Method and device for switching program running environment, embedded device and storage medium

CN123011328APending Publication Date: 2026-10-30SHENZHEN EN PLUS TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611175430.6
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-04
Publication Date
2026-10-30

AI Technical Summary

Technical Problem

[0005]本申请的主要目的在于提供一种程序运行环境的切换方法、程序运行环境的切换装置、嵌入式设备及存储介质,旨在解决现有技术引导程序向应用程序进行环境切换时,存在诊断信息丢失或配置残留的技术问题

Benefits of technology

本申请通过在全局中断保持开启的状态下对各外设执行反初始化操作,使得各外设的清理过程能够正常依赖中断完成通信行为,并在反初始化操作完成后等待预设时长以确保通信数据的最后字节已完整输出,从而在关中断之前保留了诊断信息的输出通道,避免了关键诊断信息因全局中断关闭而丢失,使得故障现场可追溯。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123011328A_ABST
    Figure CN123011328A_ABST
Patent Text Reader

Abstract

The application discloses a program running environment switching method and device, an embedded device and a storage medium, and is applied to a chip and relates to the technical field of computer control, and comprises the following steps: when a global interrupt response in the chip is in an open state, performing a reverse initialization operation on each peripheral device of the chip, and waiting for a preset time length after the reverse initialization operation is completed; in response to the end of the preset time length, closing the global interrupt response, and performing a reset cleaning operation on a target register in the chip; after the reset cleaning operation on the target register is performed, inserting a multi-layer barrier instruction, and jumping to a starting entry address of a to-be-loaded program after the last inserted barrier instruction is executed, so that the running environment is switched to the to-be-loaded program. The application improves the running reliability after the application program jumps.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of computer control technology, and in particular to a method for switching program running environments, a device for switching program running environments, an embedded device, and a storage medium. Background Technology

[0002] In embedded systems, before the bootloader switches the runtime environment to the application, it needs to clean up the processor kernel state, interrupt controller, system timers, and peripheral resources to avoid the application being affected by the hardware state configured by the bootloader (i.e., the bootloader's runtime environment) when it starts up.

[0003] When a bootloader switches the application environment, it executes operations such as disabling global interrupts, setting vector table offsets, loading the main stack pointer, and jumping in a fixed order. This has the following drawbacks: Communication behaviors that rely on interrupts (such as serial data transmission) cannot be executed correctly after global interrupts are disabled, leading to the loss of critical diagnostic information before the jump and making fault tracing impossible; some registers, such as those corresponding to system timers, have a race window between the count resetting to zero and the stop instruction during the shutdown process. The pending flag triggered by the timer resetting to zero within this race window may still remain after the timer stops; for example, the registers for processor mode and memory protection units. The bootloader modifies various configurations of these registers during operation, but these configurations are not reset before the jump, leaving residual configurations. These residual states will cause the application to encounter unexpected interrupt responses, access violations, or instruction execution anomalies during startup.

[0004] It is known that existing applications cannot start in a deterministic and clean operating environment due to the loss of diagnostic information or residual configuration, resulting in application startup failure or unpredictable running behavior, and low reliability of application operation after jump. Summary of the Invention

[0005] The main objective of this application is to provide a method, device, embedded device, and storage medium for switching program runtime environments, aiming to solve the technical problem of lost diagnostic information or residual configuration when switching the environment from a boot program to an application program.

[0006] To achieve the above objectives, this application proposes a method for switching program execution environments, applied to a chip. The method for switching program execution environments includes: With the global interrupt response inside the chip enabled, deinitialization operations are performed on each peripheral device of the chip, and a preset time is waited after the deinitialization operation is completed. In response to the end of the preset time, the global interrupt response is disabled, and a reset and cleanup operation is performed on the target register in the chip; After performing a reset and cleanup operation on the target register, a multi-layer barrier instruction is inserted. After the last inserted barrier instruction is executed, the system jumps to the startup entry address of the program to be loaded to switch to the runtime environment of the program to be loaded.

[0007] In one embodiment, the step of performing deinitialization operations on each peripheral device of the chip includes: Based on a preset list of peripheral cleanup functions, the peripheral cleanup functions corresponding to each peripheral of the chip are called sequentially to perform deinitialization operations on each peripheral of the chip.

[0008] In one embodiment, the step of sequentially calling the peripheral cleanup functions corresponding to each peripheral of the chip includes: When executing the peripheral cleanup function corresponding to the current peripheral, start a timer to monitor the execution time of the current peripheral cleanup function; If the execution time exceeds a preset time threshold, the execution of the current peripheral cleanup function will be stopped, and the peripheral cleanup function corresponding to the next peripheral will be executed.

[0009] In one embodiment, the target register includes: an interrupt enable register, an interrupt suspend register, a processor mode control register, a memory protection unit control register, a system timer control register in the chip, a reload value register and a current value register, and a suspend clear register in the system control block of the chip; The steps of performing a reset and cleanup operation on the target register in the chip include, in sequence: Write a first preset value to the interrupt enable register and the interrupt pending register to disable the interrupt function of all peripherals and clear the interrupt pending state of all peripherals. Write a second preset value to the control register, the reload value register, and the current value register to stop the system timer from counting; Write a third preset value to the suspend clear register to clear the first suspend flag corresponding to the system timer and the second suspend flag corresponding to the suspendable system call in the system control block; Write the second preset value to the processor mode control register to adjust the processor's running privilege level in the chip and select to use the main stack pointer; Write the second preset value to the memory protection unit control register to disable the memory protection unit.

[0010] In one embodiment, the target register further includes a cache control register; the step of performing a reset and cleanup operation on the target register in the chip further includes: Perform a data cleanup operation on the cache in the chip, and write the second preset value to the cache control register to disable the cache.

[0011] In one embodiment, the step of inserting a multi-layer barrier instruction after performing a reset and cleanup operation on the target register includes: After performing a reset and cleanup operation on the target register, insert the first barrier instruction; After the first barrier instruction is executed and the starting address of the vector table of the program to be loaded is written into the chip, the second barrier instruction is inserted. After the second barrier instruction is executed and the stack space required for the program to be loaded is configured for operation, the third barrier instruction is inserted.

[0012] In one embodiment, the step of writing the starting address of the vector table of the program to be loaded into the chip includes: Write the starting address of the vector table of the program to be loaded into the vector table offset register in the chip; The step of configuring the stack space required for the program to be loaded includes: The stack start address is read from the vector table of the program to be loaded and written to the main stack pointer in the chip.

[0013] Furthermore, to achieve the above objectives, this application also proposes a program execution environment switching device applied to a chip, the program execution environment switching device comprising: The deinitialization module is used to perform deinitialization operations on each peripheral device of the chip when the global interrupt response inside the chip is enabled, and wait for a preset time after the deinitialization operation is completed. The interrupt disabling module is used to disable the global interrupt response and perform a reset and cleanup operation on the target register in the chip in response to the end of the preset time. The jump module is used to insert multi-layer barrier instructions after performing a reset and cleanup operation on the target register, and after the last inserted barrier instruction is executed, jump to the startup entry address of the program to be loaded to switch to the runtime environment of the program to be loaded.

[0014] In addition, to achieve the above objectives, this application also proposes an embedded device, the embedded device comprising: a chip, the chip integrating a memory, a processor, and a computer program stored in the memory and executable on the processor, the computer program being configured to implement the steps of the program execution environment switching method described above.

[0015] In addition, to achieve the above objectives, this application also proposes a storage medium, which is a computer-readable storage medium, on which a computer program is stored, and when the computer program is executed by a processor, it implements the steps of the program execution environment switching method described above.

[0016] In addition, to achieve the above objectives, this application also provides a computer program product, which includes a computer program that, when executed by a processor, implements the steps of the program runtime environment switching method described above.

[0017] One or more technical solutions proposed in this application have at least the following technical effects: This application performs deinitialization operations on each peripheral device while keeping the global interrupt enabled, enabling the cleanup process of each peripheral device to complete communication behavior normally by relying on the interrupt. After the deinitialization operation is completed, a preset time is waited to ensure that the last byte of the communication data has been completely output. This preserves the output channel of diagnostic information before the interrupt is turned off, avoiding the loss of key diagnostic information due to the global interrupt being turned off, and making the fault scene traceable.

[0018] By performing a reset and cleanup operation on the target register in the chip after disabling global interrupts, all configurations modified during the bootloader's execution are reset to zero. For example, resetting and cleanup the register in the target register corresponding to the system timer eliminates the race window between the count resetting to zero and the stop instruction during the system timer's shutdown process, preventing unexpected interrupt responses from residual pending flags when the application starts. Similarly, resetting and cleanup the registers in the target register corresponding to the processor mode and memory protection unit eliminates residual configurations in the bootloader's runtime environment, preventing access violations or instruction execution anomalies from occurring when the application starts.

[0019] By inserting multi-layered barrier instructions after the target register reset and cleanup is completed, the synchronous constraint effect of the barrier instructions on the chip's internal pipeline and write buffer is utilized to ensure that the reset and cleanup operations of each target register are completed before the jump. This avoids the situation where the write operation is delayed in the execution of subsequent jump instructions due to the chip's internal pipeline and write buffer, thereby ensuring that the application obtains a deterministic and clean boot environment.

[0020] The technical solution of this application enables the application to start in a deterministic operating environment after the hardware state configured by the bootloader has been completely cleared. This effectively avoids the inability to trace faults due to missing diagnostic information, as well as unexpected interruption responses, access violations, or instruction execution anomalies caused by residual configurations, thereby improving the operational reliability of the application after the jump. Attached Figure Description

[0021] The accompanying drawings, which are incorporated in and form part of this specification, illustrate embodiments consistent with this application and, together with the description, serve to explain the principles of this application.

[0022] To more clearly illustrate the technical solutions in the embodiments of this application or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, for those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0023] Figure 1 A first flowchart illustrating an embodiment of the method for switching the program's operating environment in this application; Figure 2 A second flowchart is provided for an embodiment of the method for switching the program's operating environment in this application; Figure 3 A third flowchart provided for an embodiment of the method for switching the program's operating environment in this application; Figure 4 This is a schematic diagram of the module structure of the switching device for the program's operating environment in this application; Figure 5 This is a schematic diagram of the hardware operating environment involved in the switching method of the program operating environment of this application.

[0024] The purpose, features, and advantages of this application will be further explained in conjunction with the embodiments and with reference to the accompanying drawings. Detailed Implementation

[0025] It should be understood that the specific embodiments described herein are only used to explain the technical solutions of this application and are not intended to limit this application.

[0026] To better understand the technical solution of this application, a detailed description will be provided below in conjunction with the accompanying drawings and specific implementation methods.

[0027] It should be noted that the execution entity in this embodiment can be a chip, such as a GD32H737 microcontroller or an STM32H753 microcontroller; it can also be a computing service device with data processing, network communication, and program execution functions, such as a tablet computer, personal computer, or mobile phone; or it can be an embedded device capable of performing the above functions, such as an industrial charging pile, a new energy vehicle controller, or a power monitoring terminal. The following description uses a chip as an example to illustrate this embodiment and the subsequent embodiments.

[0028] Based on this, embodiments of this application provide a method for switching program execution environments, referring to... Figure 1 , Figure 1 This is a flowchart illustrating an embodiment of the method for switching the runtime environment of the program in this application.

[0029] In one feasible embodiment, the application scenario of the technical solution of this application can be: switching the program running environment of embedded devices such as industrial DC charging piles, new energy vehicle on-board controllers, power monitoring terminals, and industrial IoT gateways. The application objects can be: chips using ARM Cortex-M series processor cores, such as GD32H737, STM32H753, GD32F30x and other MCUs (Microcontroller Units).

[0030] In this embodiment, the method for switching the program running environment includes steps S1 to S3: Step S1: With the global interrupt response inside the chip enabled, perform deinitialization operations on each peripheral device of the chip, and wait for a preset time after the deinitialization operation is completed. It should be noted that when the chip is powered on, the bootloader runs first. After the bootloader completes the basic hardware configuration, application image verification and other preparations, and determines that it needs to jump to the program to be loaded, the chip begins to execute this step.

[0031] Alternatively, the chip is a complete microcontroller entity that integrates a processor core (CPU Core), memory (including Flash and RAM), interrupt controller, system timer, memory protection unit, and various communication peripheral modules.

[0032] Optionally, peripherals are on-chip peripheral function modules (i.e., peripherals can also be called peripheral modules), such as UART (Universal Asynchronous Receiver / Transmitter) controllers, CAN (Controller Area Network) controllers, GPIO (General Purpose Input / Output) controllers, etc.

[0033] Optionally, the deinitialization operation refers to restoring the control registers of each peripheral to their default state at power-on reset. Specifically, during the bootloader's execution, each peripheral is initialized and put into operation (e.g., the UART controller is configured to a specific baud rate and is in transmit-enabled state, and the CAN controller is configured to a specific communication rate and is in receive-enabled state). Before jumping to the program to be loaded, these peripherals need to be restored to their default state to avoid interference from residual operating states of the peripherals (e.g., incomplete data transmission, busy control signals, and unreleased bus occupancy) caused by the reinitialization of peripherals after the program to be loaded starts.

[0034] Optionally, the deinitialization operation is implemented by sequentially calling the corresponding peripheral cleanup functions of each peripheral. Specifically, this application embodiment provides a static callback table, which is a function pointer array of fixed capacity at compile time, used to store the cleanup function addresses of each peripheral. During the initialization phase, the bootloader of the chip provides a registration interface. After each peripheral completes its own initialization, it registers its respective peripheral cleanup function address into the static callback table by calling the registration interface. The registration interface uses weak symbol wrapping, so that the core framework code (i.e., the timing control code for scheduling timing and register operation flow) does not depend on any specific peripheral header file. When step S1 is executed, the bootloader traverses the static callback table and sequentially calls the cleanup functions of each peripheral according to the registration order, thereby completing the deinitialization operation of each peripheral. It should be noted that the deinitialization operation includes, but is not limited to: clearing the transmit buffer and receive buffer of the peripheral, clearing the interrupt pending state of the peripheral, disabling the clock enable of the peripheral, and restoring the control register of the peripheral to the default configuration when the chip is powered on and reset.

[0035] Optionally, the preset duration is a configurable time length, such as 10 milliseconds to 100 milliseconds. The preset duration is used to wait for the tail frame data in the transmit buffer and shift register of the chip's communication peripheral (e.g., a UART controller or CAN controller) to be completely output from the chip's physical communication pins. Before step S1 is executed, the bootloader may have already output pre-jump diagnostic logs or status information through the communication peripheral; the data bytes of this information may still be in the peripheral's transmit buffer and have not yet been completely transmitted. By configuring and waiting for the preset duration, it is ensured that the tail frame data of this information is completely transmitted, thereby preserving critical diagnostic records from before the jump.

[0036] Understandably, the above can be considered the first level of peripheral cleanup before disabling interrupts. After the deinitialization operation, the last data in the peripheral's transmit buffer still needs to be converted bit by bit into electrical signals by a shift register before being output from the physical pin. If interrupts are disabled or a jump is executed before all data is output, the last few diagnostic logs or communication messages will fail to reach the other device, resulting in the loss of critical information. Therefore, forcing a preset waiting time ensures that the physical layer of communication transmission is complete, thus preserving the full diagnostic output capability.

[0037] Step S2: In response to the end of the preset time, disable the global interrupt response and perform a reset and cleanup operation on the target register in the chip; It should be noted that after the preset waiting time has expired, the chip confirms that the physical layer transmission operations of all peripherals have been completed, and at this time, it performs the global interrupt disable operation.

[0038] Optionally, global interrupt response is a hardware enable switch of the CPU core inside the chip, used to control whether the processor responds to all interrupt requests from peripherals or internal devices. When global interrupt response is disabled, the processor will not pause the currently executing instruction stream to handle the interrupt service routine, regardless of how many interrupt signals are sent by peripherals.

[0039] Optionally, the target register is a collective term for a group of registers within the chip that need to be reset and cleared. Specifically, a register is a storage unit within the chip used to store control and status information. Each register consists of multiple bits, each bit representing a switch signal or status flag. The target register includes at least: an interrupt enable register, an interrupt suspend register, a processor mode control register, a memory protection unit control register, a system timer control register, a system timer reload value register, a system timer current value register, and a suspend clear register in the system control block.

[0040] Optionally, the reset and cleanup operation refers to both a reset operation and a cleanup operation. The reset operation is used to write predetermined values ​​to control registers or mode registers in the chip to disable the corresponding hardware function module or restore the processor state to the default mode. For example, writing 0 to the control register of the system timer (SysTick) disables its counting enable; writing 0 to the processor control register (CONTROL) restores the processor to privileged thread mode and uses the main stack pointer; writing 0 to the control register of the memory protection unit (MPU) disables the MPU function.

[0041] The cleanup operation is used to write to status registers, pending registers, or count registers in the chip to clear transient flags or temporary values ​​remaining during operation. For example, writing 1 to the Interrupt Clear Pending Register (ICPR) of the Nested Vector Interrupt Controller (NVIC) clears the pending status of peripheral interrupts; writing 1 to the PendST and PendSV clear bits of the Interrupt Control and Status Register (ICSR) of the System Control Block (SCB) clears the system exception pending flags; and writing 0 to the current value register (SysTick->VAL) of the system timer clears its current count value.

[0042] It should be noted that both the reset and cleanup operations are performed by directly writing to the target register, and both are executed when the global interrupt response is disabled, in order to ensure the atomicity of the operation process and avoid interference from nested interrupts.

[0043] Understandably, the above can be considered the second level of kernel and system cleanup when interrupts are disabled. This process involves sequentially resetting and cleaning the target registers without calling any interfaces that depend on interrupts or the heap. Disabling global interrupt response is to prevent interference from any peripheral interrupts during register cleanup, ensuring the atomicity and integrity of the cleanup operation and preventing nested interrupts from causing accidental modification of the register state. Performing a reset and cleanup operation on the target registers is to eliminate any non-default configurations left over from the interrupt controller, system timer, processor mode, memory protection unit, and other modules during the bootloader's execution. This restores these critical control units inside the chip to the same deterministic state as before power-on, providing a clean and predictable boot environment for the program to be loaded.

[0044] Step S3: After performing a reset and cleanup operation on the target register, a multi-layer barrier instruction is inserted. After the last barrier instruction in the multi-layer barrier instruction is executed, the program jumps to the startup entry address of the program to be loaded to switch to the runtime environment of the program to be loaded.

[0045] It should be noted that after all the reset and cleanup operations of the target register are completed, the chip needs to configure the interrupt vector table and stack space of the program to be loaded, and then execute the final jump operation.

[0046] Optionally, the program to be loaded is an application stored in the chip's flash memory, waiting to be loaded and run by the bootloader. The entry address of the program to be loaded is stored in the vector table of that program.

[0047] Optionally, the runtime environment of the program to be loaded refers to the set of configuration states of each hardware module inside the chip when the program to be loaded starts executing, including processor mode, stack pointer, interrupt vector table, enable state of each peripheral, and on / off state of memory protection unit, etc.

[0048] Optionally, a multi-layer barrier instruction is a combination of multiple barrier instructions. Barrier instructions are a special type of processor instruction used to force the processor to wait for the already executed data read / write operation to complete before executing subsequent instructions, and to clear the processor's internal prefetched instruction pipeline.

[0049] Optionally, the barrier instruction is a combination of a data synchronization barrier instruction and an instruction synchronization barrier instruction, such as the DSB (Data Synchronization Barrier) instruction and the ISB (Instruction Synchronization Barrier) instruction.

[0050] Understandably, the above can be considered the third-level barrier synchronization and jump process after interrupts are disabled. After the reset and cleanup operation is completed, the processor pipeline may still contain prefetched instructions configuring old registers. If a barrier instruction is not inserted and subsequent operations are performed directly, subsequent instructions may read register states that have not yet fully taken effect. Therefore, by inserting a barrier instruction, it is possible to ensure that the execution environment after the jump is completely determined. Finally, the jump proceeds to the entry address of the program to be loaded, that is, the entry address is read from the second word of the vector table and loaded into the program counter. From there, the processor begins to execute the first instruction of the program to be loaded, completing the switch from the bootloader's runtime environment to the program to be loaded's runtime environment.

[0051] This embodiment provides a method for switching the program execution environment. By performing deinitialization operations on each peripheral while keeping global interrupts enabled, the cleanup process of each peripheral can normally rely on interrupts to complete communication behavior. After the deinitialization operation is completed, a preset time is waited to ensure that the last byte of communication data has been completely output. This preserves the output channel for diagnostic information before disabling interrupts, preventing the loss of critical diagnostic information due to the global interrupt being disabled, and making the fault scene traceable. By performing a reset and cleanup operation on the target register in the chip after disabling global interrupts, all configurations modified during the boot program's execution are reset to zero. For example, resetting and cleanup the register corresponding to the system timer in the target register eliminates the race window between the count resetting to zero and the stop instruction during the system timer's shutdown process, preventing unexpected interrupt responses from residual pending flags when the application starts. For example, resetting and cleanup the registers corresponding to the processor mode and memory protection unit in the target register eliminates residual configurations in the boot program's execution environment, preventing access violations or instruction execution anomalies from occurring when the application starts due to residual configurations. By inserting multi-layered barrier instructions after the target register reset and cleanup are completed, the synchronization constraints of the chip's internal pipeline and write buffer are utilized to ensure that the reset and cleanup operations of each target register are completed before the jump. This avoids the situation where write operations are delayed in the execution of subsequent jump instructions due to the chip's internal pipeline and write buffer, thus guaranteeing that the application obtains a deterministic and clean boot environment. The technical solution of this application enables the application to start in a deterministic operating environment after the hardware state configured by the bootloader has been completely cleaned up. This effectively avoids untraceable faults caused by missing diagnostic information, as well as unexpected interrupt responses, access violations, or instruction execution anomalies caused by residual configurations, improving the operational reliability of the application after the jump.

[0052] In one feasible implementation, step S1 includes: Step S11: Based on the preset peripheral cleanup function list, sequentially call the peripheral cleanup functions corresponding to each peripheral of the chip to perform deinitialization operations on each peripheral of the chip.

[0053] It should be noted that when performing deinitialization operations on the various peripherals of the chip, the chip uses a pre-established list of peripheral cleanup functions for unified scheduling and execution. The peripheral cleanup function list is an array of function pointers stored in the chip's memory, with each function pointer corresponding to the entry address of a peripheral cleanup function.

[0054] Optionally, during the initialization phase of the bootloader, each peripheral in the chip registers the entry address of its corresponding peripheral cleanup function into the peripheral cleanup function list (also called the callback table).

[0055] Optionally, peripheral cleanup functions are program code segments used to restore the control register configuration of a specific peripheral module to its default state when the chip is powered on and reset. For example, the UART cleanup function writes the UART control register to its default value, disables transmit and receive enable, clears the baud rate register, and clears all interrupt enable bits; the CAN cleanup function writes the CAN controller to its default value, disables communication, and clears the receive and transmit mailboxes; the GPIO (General Purpose Input / Output) cleanup function restores the GPIO pin mode register to the default analog input mode and clears the output data register.

[0056] Optionally, sequential calling means that the chip starts from the first element of the peripheral cleanup function list, retrieves the function pointers one by one in the order of the list and jumps to execute the corresponding cleanup function. When a cleanup function is completed and returns, the next function pointer is retrieved and execution continues until all functions in the list have been executed.

[0057] Optionally, the sequential calls are to perform deinitialization operations on each peripheral of the chip, thereby restoring each peripheral to its default state. Restoring to the default state means modifying the values ​​of all control registers of the peripheral to the reset default values ​​set at the chip's factory, thus putting the peripheral in an unenabled and unconfigured idle state.

[0058] Understandably, since different chip models connect to different types and numbers of peripherals, and different products have different requirements for cleaning up peripherals, by using a pre-defined list of peripheral cleaning functions and calling them sequentially, when adding a new peripheral, you only need to register its cleaning function in the list without modifying the core framework code, thus achieving a product-extensible deinitialization mechanism.

[0059] In one feasible implementation, step S11 includes: Step A11: When executing the peripheral cleanup function corresponding to the current peripheral, start a timer to monitor the execution time of the current peripheral cleanup function; Step A12: If the execution time exceeds a preset time threshold, stop executing the current peripheral cleanup function and execute the peripheral cleanup function corresponding to the next peripheral.

[0060] It should be noted that during the sequential calling of peripheral cleanup functions, the chip starts an internal hardware or software timer before or during the execution of each peripheral cleanup function.

[0061] Optionally, the current peripheral is the peripheral corresponding to the peripheral cleanup function currently being executed in the peripheral cleanup function list.

[0062] Alternatively, the timer is a hardware or software module inside the chip used to measure time intervals.

[0063] Optionally, the monitoring execution duration refers to the timer starting to count from zero when the peripheral cleanup function begins execution. During the peripheral cleanup process, the chip periodically reads the current count value of the timer and compares it with a preset time threshold.

[0064] Optionally, the preset time threshold can be configured according to the type and importance of the current peripheral. For example, it can be configured to 10 milliseconds for the UART cleanup function, 20 milliseconds for the CAN cleanup function, and 5 milliseconds for the GPIO cleanup function.

[0065] Understandably, since the execution time of peripheral cleanup functions depends on the current state of the peripheral (e.g., the amount of data remaining in the UART transmit buffer, whether the CAN controller is currently in bus occupancy), in extreme cases, a peripheral cleanup function may not return for an extended period while waiting for hardware state changes (e.g., waiting for the transmit completion flag to be set, waiting for the bus to be released). If this peripheral cleanup function occupies the chip's internal processor execution time for a long time, it will block the entire jump process, triggering a timeout reset. Therefore, starting a timer to monitor the execution duration provides a time basis for subsequent timeout judgment and skip processing.

[0066] Additionally, it should be noted that after the timer is started in step A11, the chip continuously monitors the execution duration of the current peripheral cleanup function. When the chip detects that the timer count has exceeded a preset time threshold, it determines that the current peripheral cleanup function has timed out.

[0067] Optionally, stopping the execution of the current peripheral cleanup function means that the chip no longer waits for the current cleanup function to continue running, but forces it to return from the current cleanup function. For example, by setting a global flag in the timer interrupt service routine, the current peripheral cleanup function checks the global flag at the beginning of each loop. If the global flag is set, it immediately performs the return operation.

[0068] Optionally, after stopping the execution of the current peripheral cleanup function, the chip records the timeout event of the current peripheral cleanup function to the fault storage area in the chip. The fault storage area is a storage area in the chip's memory used to store information about abnormal events, such as a backup register or a segment of non-volatile memory in the chip. For example, the recorded content of the timeout event includes information such as the timestamp of the timeout, the peripheral type identifier of the timeout, and the difference between the actual execution time and the preset time threshold.

[0069] Optionally, executing the peripheral cleanup function corresponding to the next peripheral means that after the chip stops the currently timed-out peripheral cleanup function, it moves the call pointer to the next element in the peripheral cleanup function list and jumps to execute the peripheral cleanup function pointed to by that next element. For example, if the currently executing peripheral cleanup function is the Nth peripheral cleanup function in the list, when the Nth peripheral cleanup function times out, the chip updates the current execution position to the (N+1)th peripheral cleanup function and then starts executing the (N+1)th peripheral cleanup function.

[0070] Optionally, after the chip skips the timed-out peripheral cleanup function, the skipped peripheral will retain its current state and will not be cleaned up again. That is, the peripheral may still be in the working state configured by the bootloader, but since the chip will disable the interrupt function of all peripherals in the subsequent step S2, the peripheral will not cause interrupt interference even though it is in the working state, and its potential impact on the application is limited to an acceptable range.

[0071] Understandably, by stopping the execution of a single peripheral cleanup function in the event of a timeout and continuing to process subsequent peripherals, the jump process will not be permanently stuck due to the abnormal state of a single peripheral, ensuring the robustness of the jump process against single points of failure. Furthermore, after the timeout event is recorded in the fault storage area, the diagnostic information from the previous jump can be retrieved by reading this fault storage area after the loader starts, providing data support for fault localization.

[0072] For example, such as Figure 2 As shown, the specific process of the chip performing deinitialization operations on each peripheral in sequence based on a preset list of peripheral cleanup functions includes the following steps: The chip first reads the total number (or total number) of peripheral cleanup functions from the preset peripheral cleanup function list. Then, the chip checks whether the number of currently called peripheral cleanup functions is less than the total number of peripheral cleanup functions. If the number of currently called functions is less than the total number (i.e., there are still unexecuted peripheral cleanup functions in the peripheral cleanup function list), the chip starts a timer and then executes the currently called peripheral cleanup function, while the timer monitors the execution time of the currently called peripheral cleanup function.

[0073] During execution, the chip checks for timeouts: if the execution time of the current peripheral cleanup function exceeds a preset time threshold, it is determined that the current peripheral cleanup function has timed out. The chip logs this and skips the current peripheral cleanup function, then proceeds to execute the next peripheral cleanup function. If no timeout occurs, the next peripheral cleanup function is executed directly.

[0074] After cleaning up the current peripheral, the chip moves the call pointer to the next element in the peripheral cleanup function list and then returns to the loop check step. This process repeats until all peripheral cleanup functions in the list have been executed.

[0075] After all peripheral cleanup functions have been executed, wait for a preset time to ensure that the last frame data of the communication peripheral has been output at the physical layer and to ensure that key diagnostic information is not lost. After the preset time has elapsed, the deinitialization phase will be completed.

[0076] Based on the above embodiments of this application, in another embodiment of this application, the same or similar content as the above embodiments can be referred to the above description, and will not be repeated hereafter. Based on this, the target register includes: an interrupt enable register, an interrupt suspend register, a processor mode control register, a memory protection unit control register, a control register for the system timer in the chip, a reload value register, a current value register, and a suspend clear register in the system control block of the chip; step S2 includes, in sequence: Step S21: Write a first preset value to the interrupt enable register and the interrupt pending register to disable the interrupt function of all peripherals and clear the interrupt pending state of all peripherals. Step S22: Write a second preset value to the control register, the reload value register, and the current value register to stop the system timer from counting. Step S23: Write a third preset value to the suspend clear register to clear the first suspend flag corresponding to the system timer and the second suspend flag corresponding to the suspendable system call in the system control block; Step S24: Write the second preset value to the processor mode control register to adjust the processor running permission level in the chip and select to use the main stack pointer; Step S25: Write the second preset value to the memory protection unit control register to disable the memory protection unit.

[0077] It should be noted that after disabling global interrupt response, although the chip no longer responds to any interrupt requests, the interrupt enable and interrupt pending bits within each peripheral module still retain the state configured during the bootloader's execution. To ensure that the interrupt system can be reinitialized according to the configuration of the program to be loaded after startup, the chip needs to clear all these residual interrupt configurations.

[0078] Optionally, the interrupt enable register is a set of registers in the Nested Vectored Interrupt Controller (NVIC) used to control the enable status of each peripheral interrupt channel. Each peripheral interrupt channel corresponds to a bit in the interrupt enable register. When the bit is 1, the interrupt function of the peripheral is used normally (i.e., it is in the enabled state), and the processor will respond to the interrupt when the peripheral generates an interrupt request; when the bit is 0, the interrupt function of the peripheral is disabled, and the interrupt request generated by the peripheral is masked by hardware.

[0079] Optionally, the interrupt suspend register is a set of registers in the nested vector interrupt controller used to record whether each peripheral interrupt channel is in a suspended state. Each peripheral interrupt channel corresponds to a bit in this register. When the bit is 1, it indicates that the peripheral has generated an interrupt request but has not yet been processed by the processor; when the bit is 0, it indicates that the peripheral has no pending interrupt request.

[0080] Optionally, the first preset value is a predetermined binary value written into the interrupt enable register and the interrupt pending register. Optionally, the first preset value can be a binary value of all 1s. The chip sets all bits in the interrupt enable register to 1, thereby disabling all enabled interrupt channels in batches; the chip sets all bits in the interrupt pending register to 1, thereby clearing all pending interrupt requests in batches, that is, all bits with a value of 1 in the register are automatically reset to 0 by hardware.

[0081] Optionally, the chip iterates through all the interrupt channels supported by the nested vector interrupt controller and writes the first preset value to the interrupt enable register and interrupt pending register corresponding to each channel in sequence.

[0082] Understandably, clearing all peripheral interrupts is to prevent unexpected responses to peripheral interrupts configured by the bootloader after the program to be loaded starts; clearing all peripheral interrupt pending states is to prevent residual unhandled interrupt requests from being triggered immediately after global interrupts are re-enabled, causing the execution flow of the program to be loaded to be interrupted by unexpected interrupts. Both operations together ensure that the interrupt controller state at the start of the program to be loaded is consistent with the state after the chip is powered on and reset.

[0083] It should also be noted that during the bootloader's execution, the system timer is typically configured to generate periodic interrupts to provide the operating system's heartbeat or precise timing. If the system timer is not stopped before the jump, it will continue to generate periodic interrupts after the program to be loaded starts.

[0084] Optionally, the system timer is a 24-bit decrementing counter hardware module inside the chip core.

[0085] Optionally, the system timer includes the following three registers: a control register (SysTick ControlRegister) used to control the system timer's enable state, clock source selection, and interrupt generation enable; a reload value register (SysTick Reload Value Register) used to store the initial value of the timer's decrement counter. When the current value register decrements to 0, the system timer hardware automatically reloads the value in the reload value register into the current value register to start a new round of decrement counting; and a current value register (SysTick Current Value Register) used to store the current count value of the system timer. The chip can read this current value register to obtain the current counting progress, and writing any value to this current value register will clear it to zero.

[0086] Optionally, the second preset value is a predetermined binary value written into the above three registers. Optionally, the second preset value is 0. After the chip writes 0 to the control register, the enable bit in the control register is cleared, and the system timer stops counting down; after the chip writes 0 to the reload value register, the reload value is cleared; after the chip writes 0 to the current value register, the current count value is cleared.

[0087] Understandably, the system timer's control register, reload value register, and current value register control the timer's start / stop, counting period, and current progress, respectively. When all three are written to 0, the system timer is completely stopped and no more interrupt events are generated, thus providing a clean initial state for the program to be loaded to reconfigure the system timer.

[0088] It should also be noted that after the system timer stops, the execution of the "stop system timer counting" instruction by the chip and the system timer hardware count reaching zero may occur around the same clock cycle, potentially setting the system timer's pending flag in the hardware logic. Furthermore, during the bootloader's execution, a suspendable system call (Pendable Supervisory Call) may be triggered by software, and its pending flag may remain set. If these two pending flags are not cleared, when the global interrupt is re-enabled after the loaded program starts, these pending flags will be recognized as valid interrupt requests by the interrupt controller, triggering the corresponding interrupt service routine and causing the loaded program to be interrupted by unexpected system anomalies.

[0089] Optionally, the suspend clear register is the Interrupt Control and State Register (ICSR) in the System Control Block (SCB). This suspend clear register contains multiple bits, some of which are used to read the suspend status of various system exceptions, and other bits are used to write commands to clear the corresponding suspend flag.

[0090] Optionally, the third preset value is a predetermined binary value written to the suspend clear register. Optionally, the third preset value is 1 only on specific bits, and the remaining bits are 0. For example, bit 25 of the third preset value is 1, which corresponds to the clear command of the system timer suspend flag. When the chip writes 1 to this bit, the hardware logic automatically clears the first suspend flag (bit 26) corresponding to the system timer; bit 27 of the third preset value is 1, which corresponds to the clear command of the suspend flag of the suspendable system call. When the chip writes 1 to this bit, the hardware logic automatically clears the second suspend flag (bit 28) corresponding to the suspendable system call. The first suspend flag is the interrupt request status bit corresponding to the system timer. When this flag is 1, it indicates that the system timer has generated an interrupt request that has not yet been processed. The second suspend flag is the interrupt request status bit corresponding to the suspendable system call. A suspendable system call (PendSV) is a system exception triggered by software by writing a 1 to a specific bit in the interrupt control and status register. It is usually used for task context switching in real-time operating systems. When the second suspend flag is 1, it means that the suspendable system call has been triggered but has not yet been executed.

[0091] Understandably, writing the third preset value to the suspend clear register is a clearing operation. Its purpose is to close the race window between "system timer stop" and "system timer hardware reset and suspend flag set", ensuring that the flag is forcibly cleared after this step is completed, regardless of whether the suspend flag is set by hardware, thus fundamentally eliminating the possibility of "ghost interrupts".

[0092] It's also important to note that during bootloader execution, to ensure the security of its own code, the processor in the chip can switch from the default privileged mode to non-privileged mode (user mode), or from using the Main Stack Pointer (MSP) to using the Process Stack Pointer (PSP). If these mode settings are not reset, the program to be loaded will use the bootloader's mode configuration after startup, which may cause instructions requiring privileged access levels in the program to fail to execute, or cause memory access errors due to the use of an incorrect stack pointer.

[0093] Optionally, the processor mode control register is the CONTROL register in the chip core. This register contains two control bits: the first bit controls the current privilege level of the processor. When this bit is 0, the processor runs in privileged mode, can execute all instructions and access all protected memory areas; when this bit is 1, the processor runs in non-privileged mode, and some privileged instructions and protected memory areas cannot be accessed. The second bit controls which stack pointer the processor is currently using. When this bit is 0, the processor uses the main stack pointer; when this bit is 1, the processor uses the process stack pointer. The main stack pointer is the default stack pointer used by the processor after power-on reset, typically used for operating system kernel code and interrupt service routines; the process stack pointer is typically used for application thread code. The second preset value is a predetermined binary value written to the processor mode control register. Optionally, the second preset value is 0. After the chip writes 0 to the processor mode control register, the first bit is cleared, and the processor returns to privileged mode; the second bit is cleared, and the processor returns to using the main stack pointer.

[0094] Understandably, writing 0 to the processor mode control register ensures that the processor is in the same running state as after the chip is powered on and reset when the program to be loaded starts, i.e., privileged mode and using the main stack pointer. This guarantees that the program to be loaded assumes the same processor privilege level and stack pointer as the chip reset default value.

[0095] It should also be noted that during bootloader execution, to isolate its own code and data from accidental modification by applications, the chip's Memory Protection Unit (MPU) may be configured with several memory region access rules. If these memory region access rules are not cleared, when the loaded program accesses certain storage regions after startup, it may trigger a hardware malfunction of the Memory Protection Unit, causing the program to crash.

[0096] Optionally, the memory protection unit is a hardware module inside the chip core, used to divide physical memory regions and set independent access permissions for each region, such as allowing reading but not writing, disallowing code execution, or completely prohibiting access. The memory protection unit control register is a register used to control the overall enable state of the memory protection unit. When the enable bit of the control register is 1, the memory protection unit is in the working state, and memory access requests will undergo permission checks; when the enable bit of the control register is 0, the memory protection unit is disabled, and all memory access requests will not undergo permission checks.

[0097] Optionally, the second preset value is a predetermined binary value written to the memory protection unit control register. Optionally, the second preset value is 0. After the chip writes 0 to the memory protection unit control register, the enable bit in the control register is cleared, the memory protection unit is disabled, and all pre-configured memory area access rules become invalid.

[0098] Understandably, disabling the memory protection unit means that memory access is no longer restricted by the permission rules set by the bootloader, and the program to be loaded can freely access all the storage areas it needs, thus avoiding startup failures caused by memory protection unit permission conflicts.

[0099] In this embodiment, step S21 is executed first, writing a first preset value to the interrupt enable register and the interrupt pending register to disable all peripheral interrupts and clear all peripheral interrupt pending states. This step is executed first because peripheral interrupts are the most active source of asynchronous events before the jump, and they need to be completely masked and cleared before any subsequent register operations to avoid interference from residual peripheral interrupt pending states during the execution of subsequent steps. Next, step S22 is executed, stopping the system timer and clearing all three related registers to zero. Stopping the system timer is placed after clearing peripheral interrupts because the system timer itself is also a periodic interrupt source, and its operation is independent of peripheral interrupts. Cutting off all peripheral interrupt sources before stopping the system timer ensures that there are no unmasked peripheral interrupts remaining before stopping the timer, allowing the timer stopping operation to be completed in a clean interrupt environment. Next, step S23 is executed, writing a third preset value to the pending clear register to clear the first pending flag corresponding to the system timer and the second pending flag corresponding to the pending system call. This step needs to be placed after stopping the system timer because a race window may exist between the instruction to stop the system timer and the timer hardware count reaching zero: if the hardware count reaches zero just as the stop instruction is being executed, the pending flag will be set by the hardware. Performing the operation to clear the pending flag after stopping the timer closes this race window and ensures the pending flag is forcibly cleared. If the clearing operation is placed before the stop operation, the stop operation may trigger the pending flag to be set again, causing the clearing to fail. Step S24 is executed after clearing all interrupt and exception pending flags, writing a second preset value to the processor mode control register and resetting the processor's privilege level and stack pointer selection. This step is placed after clearing system timers and system exception pending flags because processor mode switching does not depend on any interrupt or timer state, but to ensure that the mode switching action itself is not interrupted by any residual pending exceptions, it needs to be executed after confirming that all pending flags have been cleared. Step S25 is executed last, writing a second preset value to the memory protection unit control register and disabling the memory protection unit. This step is placed at the end of the entire reset and cleanup sequence because after disabling the memory protection unit, all subsequent memory accesses no longer undergo permission checks. Placing the disabling operation before the jump, combined with the first barrier instruction in step S3, can reduce the risk of access uncertainty caused by pipeline prefetching or write buffers during the time window when the memory protection unit is disabled.

[0100] In summary, steps S21 to S25 are as follows: first clear the peripheral interrupt source, then stop the periodic interrupt source, then clear the system abnormal suspension, then reset the processor mode, and finally disable memory protection before jumping. This step-by-step reset and cleanup ensures that after the chip completes this implementation, the interrupt controller, system timer, system abnormal state, processor mode configuration, and memory protection unit are all in a definite and predictable default state.

[0101] In one feasible implementation, the target register further includes a cache control register; step S2 includes: Step S26: Perform a data cleanup operation on the cache in the chip, and write the second preset value to the cache control register to disable the cache.

[0102] It's important to note that in chips with caches, such as those using a Cortex-M7 core and including instruction and data caches, read and write operations to memory during bootloader execution may temporarily store some data in the cache before it's written back to physical memory. Simultaneously, the cache may retain outdated copies of the bootloader code segment and data. If caching is not performed before the jump, when the loader starts and accesses physical memory, it may read outdated data from the cache, or write data to physical memory and find that the cache still contains copies of the data from the bootloader's execution, leading to data inconsistency.

[0103] Alternatively, a cache is a high-speed memory hardware module inside the chip core used to accelerate memory access, located between the processor core and physical memory.

[0104] Optionally, the cache control register is a register used to control the cache enable state and operating mode. When the enable bit of the cache control register is 1, the cache is active, and the processor's read and write operations on memory will pass through the cache; when the enable bit of the cache control register is 0, the cache is disabled, and the processor's read and write operations on memory will directly access physical memory.

[0105] Optionally, data cleanup refers to forcibly writing modified but not yet written-back dirty data from the cache back to physical memory. For example, when the chip performs a write operation, data may first be written to the cache, and the corresponding cache line is marked as "dirty data." During the data cleanup operation, the chip iterates through each cache line, checks the "dirty data" flag of each line, and if the flag is 1, writes the data in that cache line back to physical memory, then clears the "dirty data" flag.

[0106] Optionally, the second preset value is a predetermined binary value written to the cache control register. Optionally, the second preset value is 0. After the chip writes 0 to the cache control register, the enable bit in the control register is cleared, the cache is disabled, and all subsequent memory access requests directly access physical memory through the cache.

[0107] Understandably, performing data cleanup before disabling caching ensures that modified data in the cache is not lost and has been fully written to physical memory. Disabling caching ensures that all memory accesses after the program starts directly operate on physical memory, avoiding reading outdated copies of data from the cache. The combination of these two measures ensures that the cache state at program startup is consistent with the state after the chip's power-on reset, eliminating the uncertainty caused by residual cache data on program execution.

[0108] Based on the above embodiments of this application, in another embodiment of this application, the same or similar content as the above embodiments can be referred to the above description, and will not be repeated hereafter. Based on this, step S3 includes: Step S31: After performing a reset and cleanup operation on the target register, insert a first barrier instruction; It should be noted that the reset and cleanup operation of the target register in step S2 involves multiple write operations, including writing to the interrupt enable register, interrupt suspend register, system timer control register, reload value register and current value register, suspend clear register, processor mode control register, and memory protection unit control register. These write operations are transmitted to the address space of each target register internally via the bus. Due to the existence of write buffers and multi-level bus architecture within the chip, there is a certain time delay in the completion of the write operations.

[0109] Optionally, when the first barrier instruction is executed, it forces the processor to suspend the decoding and execution of subsequent instructions, waiting for all currently executed data read / write operations to complete transmission and for the processor to receive a write completion response from the target register before the first barrier instruction is considered complete. Optionally, the first barrier instruction is a combination of a data synchronization barrier instruction and an instruction synchronization barrier instruction. When the chip executes the data synchronization barrier instruction, it waits for all incomplete write operations in the write buffer to complete transmission; when the chip executes the instruction synchronization barrier instruction, it clears the prefetched instruction pipeline inside the processor, forcing the processor to re-fetch subsequent instructions from memory.

[0110] Alternatively, the first barrier instruction may be inserted after the memory protection unit is disabled.

[0111] Understandably, reset and cleanup operations require all writes to multiple registers to take effect before subsequent operations can proceed. Without inserting a first barrier instruction, subsequent instructions might begin execution before some registers have been written to, leading to write operations being overwritten or reading register states that haven't been updated. By inserting a first barrier instruction after performing a reset and cleanup operation on the target register, it ensures that all write results from the reset and cleanup operation are globally effective after the barrier instruction has been executed, providing a deterministic hardware state for subsequent operations.

[0112] Step S32: After the first barrier instruction is executed and the starting address of the vector table of the program to be loaded is written into the chip, the second barrier instruction is inserted. It should be noted that after the first barrier instruction is executed, the chip confirms that the write results of all reset and cleanup operations have taken effect globally. Subsequently, the chip needs to point the interrupt response to the program to be loaded, that is, tell the chip's processor to look up the entry address of the corresponding interrupt service routine in the interrupt vector table of the program to be loaded when a subsequent interrupt occurs. Writing the starting address of the vector table of the program to be loaded can be achieved by writing the starting address of the vector table of the program to be loaded.

[0113] Optionally, writing the starting address of the vector table of the program to be loaded refers to writing the starting storage address of the interrupt vector table of the program to be loaded in the chip's memory to the vector table offset register in the chip. The vector table offset register is a register used to store the starting address of the currently used interrupt vector table. When the processor responds to an interrupt, it reads the address from this register, adds the offset corresponding to the interrupt number, and calculates the entry address of the interrupt service routine. The starting address of the vector table is the starting storage location of the interrupt vector table of the program to be loaded in the chip's memory. This table stores the initial value of the main stack pointer and the entry addresses of each interrupt service routine sequentially at fixed offsets.

[0114] Optionally, the second barrier instruction is also a combination of a data synchronization barrier instruction and an instruction synchronization barrier instruction. After the operation of writing to the starting address of the vector table is completed, the chip immediately executes the second barrier instruction. This second barrier instruction forces the processor to wait for the write operation to the starting address of the vector table to complete and become globally visible, and then clears the prefetched instruction pipeline within the processor.

[0115] Understandably, the value written to the vector table offset register needs to be fully effective before any subsequent interrupt responses. If an interrupt occurs before the write operation is complete, the processor will read the entry address from the old interrupt vector table, causing a jump to the wrong interrupt service routine. Furthermore, the processor may have already prefetched the instructions corresponding to the old interrupt vector table addresses; if the instruction synchronization barrier instruction is not executed to clear the pipeline, these prefetched old instructions will continue to be executed. By inserting a second barrier instruction after writing the vector table start address of the program to be loaded, it is ensured that the write to the vector table start address is globally visible, and that there are no prefetched instructions corresponding to the old addresses in the processor pipeline, thus guaranteeing that all subsequent interrupt responses point to the interrupt vector table of the program to be loaded.

[0116] Step S33: After the second barrier instruction is executed and the stack space required for the program to be loaded is configured for operation, a third barrier instruction is inserted.

[0117] It should be noted that after the second barrier instruction is executed, the chip confirms that the starting address of the vector table of the program to be loaded has been written and is globally effective. Subsequently, the chip needs to configure the stack space required for the program to be loaded to run.

[0118] Optionally, configuring the stack space required for execution refers to reading the stack start address from the vector table of the program to be loaded and writing that stack start address into the main stack pointer in the chip. The first 32-bit word in the vector table stores the stack start address, which is the starting position of a memory region pre-allocated by the program to be loaded, used to store temporary data such as local variables, function parameters, and return addresses during function calls. The main stack pointer is a register inside the processor used to point to the top of the current stack. When the chip executes a function call instruction, it pushes the return address onto the stack memory pointed to by the main stack pointer and then decrements the main stack pointer; when the function returns, it pops the return address from the stack memory pointed to by the main stack pointer and then increments the main stack pointer.

[0119] Optionally, the third barrier instruction is also a combination of the data synchronization barrier instruction and the instruction synchronization barrier instruction. After the operation of writing to the main stack pointer is completed, the chip immediately executes the third barrier instruction. This third barrier instruction forces the processor to wait for the main stack pointer write operation to complete and become globally visible, and then clears the prefetched instruction pipeline within the processor.

[0120] It is understandable that the value written to the main stack pointer register needs to be fully effective before subsequent jump operations are executed. If the main stack pointer write operation is not completed before the chip executes a jump instruction, and a function call occurs during the execution of the program after the jump, the processor will access the stack memory using the not-yet-updated main stack pointer, leading to stack operation errors. By inserting a third barrier instruction after writing to the main stack pointer, it can be ensured that the main stack pointer write is globally visible, thereby guaranteeing that the processor uses the correct stack space of the program to be loaded after the jump, avoiding stack access exceptions caused by an outdated stack pointer.

[0121] In one feasible implementation, the step of writing the starting address of the vector table of the program to be loaded into the chip includes: Write the starting address of the vector table of the program to be loaded into the vector table offset register in the chip; The step of configuring the stack space required for the program to be loaded includes: The stack start address is read from the vector table of the program to be loaded and written to the main stack pointer in the chip.

[0122] It should be noted that the vector table offset register and the main stack pointer are internal registers used by the chip to store the base address of the vector table and the top address of the stack, respectively. During the compilation and linking stage, the starting address of the vector table and the starting address of the stack in the program to be loaded are determined and written into the binary file of the program to be loaded. Before the chip executes this step, the binary file of the program to be loaded is already stored in the chip's flash memory, and the chip accesses the location of the vector table in the binary file through pointers or address offsets.

[0123] Optionally, the vector table offset register is a 32-bit register internal to the chip, and its value is directly related to the entry address of the interrupt service routine calculated when the processor responds to an interrupt. The chip writes the starting address of the vector table into the vector table offset register, that is, the address value is transferred as data through the internal bus and stored in the physical memory unit of the vector table offset register.

[0124] Optionally, the chip reads the stack start address from the vector table of the program to be loaded. This means that the chip reads the data stored at the first 32-bit memory unit starting from the beginning of the vector table of the program to be loaded into the processor's internal general-purpose register through a memory read instruction, and then writes the data to the main stack pointer register through a write instruction.

[0125] Understandably, writing to the vector table offset register causes the processor's interrupt response to point to the vector table of the program to be loaded, ensuring that the correct entry address can be found after a subsequent interrupt occurs; writing to the main stack pointer allows the processor to use the stack space pre-allocated by the program to be loaded, ensuring the correctness of function calls and local variable storage after a jump. Together, these two constitute the basic execution environment necessary for the program to be loaded to run.

[0126] For example, to help understand the implementation flow of the program runtime environment switching method obtained by combining this embodiment with the above embodiments, please refer to... Figure 3 The three-level execution flow of the program runtime environment switching method in this application is divided into three stages: peripheral cleanup before interrupts are disabled, kernel and system cleanup after interrupts are disabled, and barrier synchronization and jump.

[0127] Level 1: Before disabling interrupts, the chip performs peripheral cleanup. First, it reads a pre-defined list of peripheral cleanup functions. Based on this list, it calls the corresponding cleanup function for each peripheral in turn, performing deinitialization operations on peripherals such as UART, CAN, and GPIO, restoring them to their reset default state. During this cleanup process, the chip starts a timer to monitor the execution time of each peripheral cleanup function. If a timeout occurs, it logs the process and skips that peripheral, continuing to the next one. After all peripheral cleanup functions have been executed, the chip waits for a preset time to ensure the complete output of the physical layer tail frame data of the communication peripherals, avoiding the loss of diagnostic information.

[0128] Level 2: Disable interrupts and clean up the kernel and system. After a preset duration, the chip first disables global interrupt response to ensure the atomicity of subsequent register cleanup operations. After disabling global interrupts, the chip performs the following register reset and cleanup operations in sequence: writes a first preset value to the interrupt enable register and interrupt suspend register to disable the interrupt function of all peripherals and clear the suspended state; writes a second preset value to the system timer control register, reload value register, and current value register to stop the system timer counting and clear it; writes a third preset value to the suspend clear register in the system control block to clear the system timer suspend flag (first suspend flag) and the suspendable system call suspend flag (second suspend flag) and close the race window; writes a second preset value to the processor mode control register to restore the processor to privileged thread mode and use the main stack pointer; writes a second preset value to the memory protection unit control register to disable the memory protection unit.

[0129] Level 3: Barrier Synchronization and Jump. After completing the kernel and system reset cleanup, the chip inserts multiple barrier instructions before the jump to ensure the operation is globally effective: First, the first barrier instruction is executed to ensure that the reset cleanup write results of all target registers are globally effective; the starting address of the vector table of the program to be loaded is written to the vector table offset register, and the second barrier instruction is executed immediately to ensure that the new vector table base address is globally visible and clears the old instruction pipeline prefetched by the processor; the stack starting address is read from the vector table of the program to be loaded and written to the main stack pointer (configuring the stack space), and the third barrier instruction is executed immediately to ensure that the stack pointer update is globally effective; after all the above multiple barrier instructions have been executed, the jump is finally made to the boot entry address of the program to be loaded, completing the deterministic switch from the bootloader runtime environment to the program to be loaded runtime environment.

[0130] It should be noted that the above examples are only for understanding this application and do not constitute a limitation on the switching method of the program running environment of this application. Based on this technical concept, more simple transformations can be made, such as the interaction and combination of various embodiments, all of which are within the protection scope of this application.

[0131] This application also provides a device for switching program execution environments, please refer to... Figure 4 Applied to chips, the program execution environment switching device includes: The deinitialization module 10 is used to perform deinitialization operations on each peripheral device of the chip, and wait for a preset time after the deinitialization operation is completed; The interrupt disabling module 20 is used to disable the global interrupt response inside the chip and perform a reset and cleanup operation on the target register in the chip in response to the end of the preset time. The jump module 30 is used to insert multi-layer barrier instructions after performing a reset and cleanup operation on the target register, and after the last barrier instruction in the multi-layer barrier instructions is executed, jump to the start entry address of the program to be loaded, so as to switch to the running environment of the program to be loaded.

[0132] Optionally, the deinitialization module 10 is used to sequentially call the peripheral cleanup functions corresponding to each peripheral of the chip based on a preset peripheral cleanup function list, so as to perform deinitialization operations on each peripheral of the chip.

[0133] Optionally, the deinitialization module 10 is used to start a timer to monitor the execution duration of the current peripheral cleanup function when executing the peripheral cleanup function corresponding to the current peripheral. If the execution time exceeds a preset time threshold, the execution of the current peripheral cleanup function will be stopped, and the peripheral cleanup function corresponding to the next peripheral will be executed.

[0134] Optionally, the interrupt disable module 20 is used to write a first preset value to the interrupt enable register and the interrupt pending register to disable the interrupt function of all peripherals and clear the interrupt pending state of all peripherals. Write a second preset value to the control register, the reload value register, and the current value register to stop the system timer from counting; Write a third preset value to the suspend clear register to clear the first suspend flag corresponding to the system timer and the second suspend flag corresponding to the suspendable system call in the system control block; Write the second preset value to the processor mode control register to adjust the processor's running privilege level in the chip and select to use the main stack pointer; Write the second preset value to the memory protection unit control register to disable the memory protection unit.

[0135] Optionally, the interrupt disabling module 20 is used to perform data cleanup operations on the cache in the chip and write the second preset value to the cache control register to disable the cache.

[0136] Optionally, the jump module 30 is configured to insert a first barrier instruction after performing a reset and cleanup operation on the target register; After the first barrier instruction is executed and the starting address of the vector table of the program to be loaded is written into the chip, the second barrier instruction is inserted. After the second barrier instruction is executed and the stack space required for the program to be loaded is configured for operation, the third barrier instruction is inserted.

[0137] Optionally, the jump module 30 is used to write the starting address of the vector table of the program to be loaded into the vector table offset register in the chip; Optionally, the jump module 30 is used to read the stack start address from the vector table of the program to be loaded and write it into the main stack pointer in the chip.

[0138] The program runtime environment switching device provided in this application, employing the program runtime environment switching method in the above embodiments, can solve the technical problem of lost diagnostic information or residual configuration when switching the environment from a boot program to an application program. Compared with the prior art, the beneficial effects of the program runtime environment switching device provided in this application are the same as those of the program runtime environment switching method provided in the above embodiments, and other technical features in the program runtime environment switching device are the same as those disclosed in the methods of the above embodiments, and will not be repeated here.

[0139] This application provides an embedded device, which includes: a chip integrating at least one processor; and a memory communicatively connected to the at least one processor; wherein the memory stores instructions executable by the at least one processor, which are executed by the at least one processor to enable the at least one processor to execute the program execution environment switching method in the first embodiment described above.

[0140] The following is for reference. Figure 5 It shows a schematic diagram of the structure of a chip suitable for implementing the embodiments of this application. Figure 5 The chip shown is merely an example and should not impose any limitation on the functionality and scope of use of the embodiments of this application.

[0141] like Figure 5 As shown, the chip may include a processing device 1001 (e.g., a central processing unit, a graphics processing unit, etc.), which can perform various appropriate actions and processes according to a program stored in read-only memory 1002 or a program loaded from storage device 1003 into random access memory 1004. Random access memory 1004 also stores various programs and data required for chip operation. The processing device 1001, read-only memory 1002, and random access memory 1004 are interconnected via bus 1005. Input / output interface 1006 is also connected to the bus. Typically, the following systems can be connected to input / output interface 1006: input devices 1007 including, for example, touchscreens, touchpads, keyboards, mice, image sensors, microphones, accelerometers, gyroscopes, etc.; output devices 1008 including, for example, liquid crystal displays (LCDs), speakers, vibrators, etc.; storage devices 1003 including, for example, magnetic tape, hard disks, etc.; and communication devices 1009. Communication device 1009 allows the embedded device to communicate wirelessly or wiredly with other devices to exchange data.

[0142] Specifically, according to the embodiments disclosed in this application, the processes described above with reference to the flowcharts can be implemented as computer software programs. For example, embodiments disclosed in this application include a computer program product comprising a computer program carried on a computer-readable medium, the computer program containing program code for performing the methods shown in the flowcharts. In such embodiments, the computer program can be downloaded and installed from a network via a communication device, or installed from storage device 1003, or installed from read-only memory 1002. When the computer program is executed by processing device 1001, it performs the functions defined in the methods of the embodiments disclosed in this application.

[0143] The embedded device provided in this application, employing the program runtime environment switching method in the above embodiments, can solve the technical problem of lost diagnostic information or residual configuration when switching the environment from the boot program to the application program in the prior art. Compared with the prior art, the beneficial effects of the embedded device provided in this application are the same as those of the program runtime environment switching method provided in the above embodiments, and other technical features of this embedded device are the same as those disclosed in the method of the previous embodiment, and will not be repeated here.

[0144] It should be understood that the various parts disclosed in this application can be implemented using hardware, software, firmware, or a combination thereof. In the description of the above embodiments, specific features, structures, materials, or characteristics can be combined in any suitable manner in one or more embodiments or examples.

[0145] The above description is merely a specific embodiment of this application, but the scope of protection of this application is not limited thereto. Any variations or substitutions that can be easily conceived by those skilled in the art within the scope of the technology disclosed in this application should be included within the scope of protection of this application. Therefore, the scope of protection of this application should be determined by the scope of the claims.

[0146] This application provides a computer-readable storage medium having computer-readable program instructions (i.e., a computer program) stored thereon, the computer-readable program instructions being used to execute the program execution environment switching method in the above embodiments.

[0147] The computer-readable storage medium provided in this application may be, for example, a USB flash drive, but is not limited to, electrical, magnetic, optical, electromagnetic, infrared, or semiconductor systems or devices, or any combination thereof. More specific examples of computer-readable storage media may include, but are not limited to: electrical connections having one or more wires, portable computer disks, hard disks, random access memory (RAM), read-only memory (ROM), erasable programmable read-only memory (EPROM or flash memory), optical fiber, portable compact disk read-only memory (CD-ROM), optical storage devices, magnetic storage devices, or any suitable combination thereof. In this embodiment, the computer-readable storage medium may be any tangible medium containing or storing a program that can be used by or in conjunction with an instruction execution system or device. The program code contained on the computer-readable storage medium may be transmitted using any suitable medium, including but not limited to: wires, optical cables, RF (Radio Frequency), etc., or any suitable combination thereof.

[0148] The aforementioned computer-readable storage medium may be included in an embedded device or may exist independently without being assembled into an embedded device.

[0149] Computer program code for performing the operations of this application can be written in one or more programming languages ​​or a combination thereof, including object-oriented programming languages ​​such as Java, Smalltalk, and C++, and conventional procedural programming languages ​​such as the "C" language or similar programming languages. The program code can be executed entirely on the user's computer, partially on the user's computer, as a standalone software package, partially on the user's computer and partially on a remote computer, or entirely on a remote computer or server. In cases involving remote computers, the remote computer can be connected to the user's computer via any type of network—including a Local Area Network (LAN) or a Wide Area Network (WAN)—or can be connected to an external computer (e.g., via the Internet using an Internet service provider).

[0150] The flowcharts and block diagrams in the accompanying drawings illustrate the architecture, functionality, and operation of possible implementations of systems, methods, and computer program products according to various embodiments of this application. In this regard, each block in a flowchart or block diagram may represent a module, segment, or portion of code containing one or more executable instructions for implementing a specified logical function. It should also be noted that in some alternative implementations, the functions indicated in the blocks may occur in a different order than those indicated in the drawings. For example, two consecutively indicated blocks may actually be executed substantially in parallel, and they may sometimes be executed in reverse order, depending on the functions involved. It should also be noted that each block in the block diagrams and / or flowcharts, and combinations of blocks in the block diagrams and / or flowcharts, can be implemented using a dedicated hardware-based system that performs the specified function or operation, or using a combination of dedicated hardware and computer instructions.

[0151] The modules described in the embodiments of this application can be implemented in software or hardware. The names of the modules do not necessarily limit the functionality of the unit itself.

[0152] The readable storage medium provided in this application is a computer-readable storage medium that stores computer-readable program instructions (i.e., a computer program) for executing the above-described method for switching program runtime environments. This solves the technical problem of lost diagnostic information or residual configuration when a bootloader switches environments to an application program. Compared with the prior art, the beneficial effects of the computer-readable storage medium provided in this application are the same as the beneficial effects of the program runtime environment switching method provided in the above embodiments, and will not be repeated here.

[0153] This application also provides a computer program product, including a computer program that, when executed by a processor, implements the steps of the program runtime environment switching method described above.

[0154] The computer program product provided in this application can solve the technical problem of lost diagnostic information or residual configuration when switching the environment from a bootloader to an application program. Compared with the prior art, the beneficial effects of the computer program product provided in this application are the same as the beneficial effects of the program running environment switching method provided in the above embodiments, and will not be repeated here.

[0155] The above description is only a part of the embodiments of this application and does not limit the patent scope of this application. All equivalent structural transformations made under the technical concept of this application and using the contents of the specification and drawings of this application, or direct / indirect applications in other related technical fields, are included in the patent protection scope of this application.

Claims

1. A method for switching program execution environments, characterized in that, When applied to chips, the method for switching the program execution environment includes: With the global interrupt response inside the chip enabled, deinitialization operations are performed on each peripheral device of the chip, and a preset time is waited after the deinitialization operation is completed. In response to the end of the preset time, the global interrupt response is disabled, and a reset and cleanup operation is performed on the target register in the chip; After performing a reset and cleanup operation on the target register, a multi-layer barrier instruction is inserted. After the last inserted barrier instruction is executed, the system jumps to the startup entry address of the program to be loaded to switch to the runtime environment of the program to be loaded.

2. The method as described in claim 1, characterized in that, The steps of performing deinitialization operations on each peripheral device of the chip include: Based on a preset list of peripheral cleanup functions, the peripheral cleanup functions corresponding to each peripheral of the chip are called sequentially to perform deinitialization operations on each peripheral of the chip.

3. The method as described in claim 2, characterized in that, The step of sequentially calling the peripheral cleanup functions corresponding to each peripheral of the chip includes: When executing the peripheral cleanup function corresponding to the current peripheral, start a timer to monitor the execution time of the current peripheral cleanup function; If the execution time exceeds a preset time threshold, the execution of the current peripheral cleanup function will be stopped, and the peripheral cleanup function corresponding to the next peripheral will be executed.

4. The method as described in claim 1, characterized in that, The target registers include: an interrupt enable register, an interrupt suspend register, a processor mode control register, a memory protection unit control register, a system timer control register in the chip, a reload value register, a current value register, and a suspend clear register in the system control block of the chip; The steps of performing a reset and cleanup operation on the target register in the chip include, in sequence: Write a first preset value to the interrupt enable register and the interrupt pending register to disable the interrupt function of all peripherals and clear the interrupt pending state of all peripherals. Write a second preset value to the control register, the reload value register, and the current value register to stop the system timer from counting; Write a third preset value to the suspend clear register to clear the first suspend flag corresponding to the system timer and the second suspend flag corresponding to the suspendable system call in the system control block; Write the second preset value to the processor mode control register to adjust the processor's running privilege level in the chip and select to use the main stack pointer; Write the second preset value to the memory protection unit control register to disable the memory protection unit.

5. The method as described in claim 4, characterized in that, The target register further includes a cache control register; the step of performing a reset and cleanup operation on the target register in the chip further includes: Perform a data cleanup operation on the cache in the chip, and write the second preset value to the cache control register to disable the cache.

6. The method as described in claim 1, characterized in that, The step of inserting multi-layer barrier instructions after performing a reset and cleanup operation on the target register includes: After performing a reset and cleanup operation on the target register, insert the first barrier instruction; After the first barrier instruction is executed and the starting address of the vector table of the program to be loaded is written into the chip, the second barrier instruction is inserted. After the second barrier instruction is executed and the stack space required for the program to be loaded is configured for operation, the third barrier instruction is inserted.

7. The method as described in claim 6, characterized in that, The step of writing the starting address of the vector table of the program to be loaded into the chip includes: Write the starting address of the vector table of the program to be loaded into the vector table offset register in the chip; The step of configuring the stack space required for the program to be loaded includes: The stack start address is read from the vector table of the program to be loaded and written to the main stack pointer in the chip.

8. A device for switching program execution environments, characterized in that, Applied to chips, the program execution environment switching device includes: The deinitialization module is used to perform deinitialization operations on each peripheral device of the chip when the global interrupt response inside the chip is enabled, and wait for a preset time after the deinitialization operation is completed. The interrupt disabling module is used to disable the global interrupt response and perform a reset and cleanup operation on the target register in the chip in response to the end of the preset time. The jump module is used to insert multi-layer barrier instructions after performing a reset and cleanup operation on the target register, and after the last inserted barrier instruction is executed, jump to the startup entry address of the program to be loaded to switch to the runtime environment of the program to be loaded.

9. An embedded device, characterized in that, The embedded device includes: a chip, the chip integrating a memory, a processor, and a computer program stored in the memory and executable on the processor, the computer program being configured to implement the steps of the method for switching program execution environments as described in any one of claims 1 to 7.

10. A storage medium, characterized in that, The storage medium is a computer-readable storage medium, and a computer program is stored on the storage medium. When the computer program is executed by a processor, it implements the steps of the method for switching the program running environment as described in any one of claims 1 to 7.