Array subscript out-of-bounds checking and protection method and system based on st language
Patent Information
- Application Number
- CN202610909511.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-06-23
- Publication Date
- 2026-10-16
AI Technical Summary
基于现有的ST语言程序数据内存分配与代码编译转换的方案无法实现控制程序运行时的内存越界检查与保护
(1)本发明所提供的ST程序数组元素运行时越界操作的检测与保护方法,相比现有的编译期静态内存越界检测方法,新增了动态检测数组的下标访问是否越界,同时兼顾了ST逻辑的转换低复杂度,采用了相似的偏移地址计算形式,避免了嵌套逻辑。此外,本发明中的异常抛出逻辑可以快速终止对异常地址的强制访问,避免对非预期地址的写入,从而能够有效保障控制器内存的正确性。
Smart Images

Figure CN122924784A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the technical field of industrial control, and in particular to the conversion and compilation of ST language control programs for industrial control configuration software, specifically a method and system for array subscript out-of-bounds checking and protection based on ST language. Background Technology
[0002] ST language can be used to write control programs for DCS controllers. During the configuration of a DCS system, the control program written in ST language is compiled into a binary file and then downloaded to the controller along with the program's initial data values. This process can be broken down into the following two main steps.
[0003] The first step is memory allocation for program data. In this step, the system allocates memory space for program variables (including arrays) in the data area of the controller memory. The specific allocation includes the starting offset address of the variable and the size of the storage space.
[0004] The second step is the compilation and conversion of the code. This step consists of two sub-stages: first, the program written in ST language is converted into C language code; then, the C language code is compiled into a binary file that the controller can execute.
[0005] The two steps above together constitute the complete process of compiling and converting a control program written in ST language into a binary file.
[0006] In the ST language, simple data type variables (such as integer, floating-point, and boolean types) and structure type variables composed of simple types have fixed memory sizes. The size of array objects, however, is specified by the user when writing the ST program.
[0007] In existing program data memory allocation schemes, the ST compiler directly allocates a contiguous block of memory for the array based on its size (i.e., the size of a single array element multiplied by the number of array elements). In the C code converted from ST code, the array elements are accessed and manipulated through the array's starting offset address in memory (i.e., pointer) and the array's index.
[0008] The size of an array is known at compile time, so static out-of-bounds checks can be performed on array subscript operations by analyzing the syntax tree of the ST code. Specifically, when the subscript used to access an array is a constant expression, the ST compiler can detect whether the array subscript access is out of bounds. For example, for constant subscript expressions of the form A
[15] , B[3,11], A[5+3], out-of-bounds checks can be performed during the compilation phase.
[0009] However, static checks are powerless to detect memory out-of-bounds operations during program execution. For example, when accessing array element A[x], the value of the array index variable x can only be determined at runtime. Therefore, static checks cannot confirm whether the index x of A[x] exceeds the bounds of array A during compile time. Once an array out-of-bounds access occurs, it may modify the memory values at other addresses in the data area, leading to serious consequences such as errors in control logic execution, accidental data tampering, or even abnormal controller operation. Summary of the Invention
[0010] To address the aforementioned problems, the present invention aims to provide a method and system for array index out-of-bounds checking and protection based on the ST language. Existing ST language program data memory allocation and code compilation methods cannot effectively control memory out-of-bounds checks and protection during program execution. This invention aims to improve upon this by adding dynamic array index checking during runtime during code compilation. Before accessing an array, it pre-checks whether the accessed array index is within a valid range, thus preventing unexpected problems caused by out-of-bounds access.
[0011] The above-mentioned objective of this invention is achieved through the following technical solutions: A method for array subscript out-of-bounds checking and protection based on ST language, including the following steps: S1: During the process of compiling the control program written in ST language into an executable binary file of the controller, the syntax tree of the ST code is traversed to identify the access nodes of array elements; S2: For the identified array element access node, generate code to call the subscript offset address conversion function. The subscript offset address conversion function receives at least the program identifier, the subscript values of each dimension of the array, and the maximum number of elements in each dimension as input parameters. S3: Inside the subscript offset address conversion function, perform a dimension check: if the subscript value of any dimension exceeds the maximum number of elements in the corresponding dimension, terminate the execution of the current control program and throw an exception; otherwise, calculate the offset address of the array element relative to the first address of the array and return. S4: Access the array element based on the returned offset address, combined with the array's starting address and the data type length.
[0012] Further, in step S1, the syntax tree of the ST code is traversed to identify array element access nodes, specifically: Perform a depth-first traversal of the abstract syntax tree of the ST code, and determine the type of each node during the traversal: if the current node is an array element access node, mark it as the target node to be converted; for each marked array element access node, perform the following information extraction operation: Retrieve the basic data type of the array elements from the type information of the node, including integer, floating-point, boolean, or user-defined structure types; From the array declaration symbol table associated with the node, obtain the maximum number of elements in each dimension of the array, as well as the lower and upper bounds of each dimension; Recursively parse the child nodes of the node, extract the subscript expressions of each dimension used when accessing the array elements, and distinguish whether each subscript expression is a constant expression including numeric constants and constant arithmetic operations or a variable expression including variables, input parameters, and function calls. Record the position information of each subscript expression in the syntax tree, which will be used to generate the corresponding function call parameters later; Furthermore, for multidimensional arrays, the subscript expressions of the first dimension, the second dimension, and so on up to the Nth dimension are extracted in sequence according to the dimension order when the array is declared, and their corresponding dimension size information is extracted to form an ordered sequence of dimension-subscript pairs, which are used in step S2 to generate the subscript offset address conversion function.
[0013] Further, in step S2, for the identified array element access nodes, code is generated to call the subscript offset address conversion function. The subscript offset address conversion function receives at least the program identifier, the subscript values of each dimension of the array, and the maximum number of elements in each dimension as input parameters, specifically: Obtain the unique identifier of the current control program from the current compilation context. This identifier is assigned by the compiler when the control program is compiled and is used to uniquely identify the program instance when the controller is running. The subscript expressions of each dimension extracted in step S1 are processed one by one: if the subscript expression is a constant expression, the value of the constant is directly passed as a parameter in the generated function call parameters; if the subscript expression is a variable expression, the corresponding variable reading instruction is generated and the value of the variable at runtime is passed as a parameter. The maximum number of elements in each dimension of the array, known during the compilation phase, is directly embedded as a constant into the parameter list of the function call. These constant values are determined at compile time and do not require runtime calculation. The actual parameter list for the function call is organized in the following fixed order: the first parameter is the program identifier of the current controlling program; the second parameter to the Nth plus one parameter are the first dimension subscript expression, the second dimension subscript expression, and so on up to the Nth dimension subscript expression; the Nth plus two parameter to the second Nth plus one parameter are the maximum number of elements in the first dimension, the maximum number of elements in the second dimension, and so on up to the maximum number of elements in the Nth dimension. The function call code is directly inserted into the original array element access position, replacing the original direct offset calculation logic.
[0014] Furthermore, in step S3, inside the subscript offset address conversion function, a dimension check is performed applicable to arrays of any dimension, specifically: The total number of dimensions of the array is obtained based on the array declaration information. Following the dimension order declared in the array declaration, the index value of each dimension is checked sequentially from the first dimension to the last. For the currently checked dimension, the actual input index value corresponding to that dimension is compared with the maximum number of elements in that dimension, and simultaneously compared with the lower bound of that dimension. If the actual index value is greater than or equal to the maximum number of elements in that dimension, or if the actual index value is less than the lower bound of that dimension, then the dimension index is considered out of bounds. Once an out-of-bounds index is detected in any dimension, the checks of all subsequent dimensions are immediately stopped, and the out-of-bounds handling logic is triggered. Only when the index values of all dimensions are within the valid range of their respective dimensions is the dimension check considered passed, and the offset address calculation step continues.
[0015] Furthermore, in step S3, if the index value of any dimension exceeds the maximum number of elements in the corresponding dimension, the execution of the current control program is terminated and an exception is thrown, specifically: Immediately interrupt the execution flow of the current control program, preventing all subsequent instructions in the program that have not yet been executed from continuing to run; call the program stop function preset in the controller runtime environment. This function takes the unique program identifier of the current control program as input parameter. After execution, it causes the program instance to enter the terminated state and no longer participate in the controller's periodic task scheduling. Upon terminating program execution, an array index out-of-bounds exception is thrown. This exception includes the following information: the program identifier where the out-of-bounds error occurred, the specific location where the out-of-bounds error occurred, the out-of-bounds index value, and its corresponding dimension range. The process of throwing the exception includes: recording the out-of-bounds error information in the controller's system log in a structured format, with the log entry containing a timestamp, error type, and complete out-of-bounds context data; simultaneously, actively reporting the exception information to the host computer operator station through the communication channel between the controller and the host computer operator station to prompt the operator to check the ST program logic. After the program stops and an exception is thrown, any read or write operations to out-of-bounds memory addresses are prohibited to ensure the integrity of other data areas in the controller's memory is not compromised.
[0016] Further, in step S3, the offset address of the array element relative to the starting address of the array is calculated and returned, specifically as follows: Obtain the total number of dimensions of the array and determine the storage order type of the array elements in memory, which includes two methods: row-major storage and column-major storage. Following the storage order of the array, the index values of each dimension are linearly combined and calculated. The specific method is as follows: For each dimension of the array, calculate the product of the index value of that dimension and the maximum number of elements in all dimensions after that dimension; then sum the product values of all dimensions to obtain the total linear offset. If the storage order is row-major, the processing order of dimensions is consistent with the dimension order when the array is declared. That is, the first dimension is the outermost layer and the last dimension is the innermost layer. When calculating, the index value of the first dimension is multiplied by the product of the maximum number of elements in all dimensions after the first dimension, the index value of the second dimension is multiplied by the product of the maximum number of elements in all dimensions after the second dimension, and so on, until the index value of the last dimension is directly added to itself. If the storage order is column-major, then the dimension processing order is the reverse of the dimension order when the array is declared, that is, the last dimension is the outermost layer and the first dimension is the innermost layer, and the dimension range multiplied by the subscript value of each dimension is adjusted accordingly. The calculated bus offset is returned as the offset address of the array element relative to the first address of the array, for use in subsequent memory access steps.
[0017] Further, in step S4, the array elements are accessed based on the returned offset address, combined with the array's starting address and the data type length, specifically as follows: Obtain the data type of the array elements and the length of memory bytes occupied by that data type from the array declaration information; The array's starting address is used as the starting memory address, which is determined and recorded in the symbol table during the compilation phase; Perform memory address calculation: Multiply the offset address returned in step S3 by the data type length of the array element to obtain a byte offset; then add the byte offset to the starting address of the array to obtain the precise memory address of the target array element. Here, the offset address is a logical offset in terms of the number of elements, which is converted into a physical offset in terms of bytes by multiplying by the data type length. The calculated target memory address is converted into a pointer to the data type of the array element to ensure that subsequent read and write operations on this address are performed with the correct data width; The pointer is used to perform read or write operations on array elements. Throughout the process, since step S3 has already completed the dimension out-of-bounds check, the memory address accessed in step S4 must be within the legal memory area allocated to the array and will not interfere with other data areas.
[0018] An ST-language-based array subscript bounds checking and protection system for implementing the ST-language-based array subscript bounds checking and protection method described above includes: The syntax traversal module is used to traverse the syntax tree of ST code and identify array element access nodes during the process of compiling control programs written in ST language into executable binary files of the controller. The code generation module is used to generate code that calls the subscript offset address conversion function for the identified array element access node. The subscript offset address conversion function receives at least the program identifier, the subscript values of each dimension of the array, and the maximum number of elements in each dimension as input parameters. The out-of-bounds detection module is used to perform a dimension check inside the subscript offset address conversion function: if the subscript value of any dimension exceeds the maximum number of elements in the corresponding dimension, the execution of the current control program is terminated and an exception is thrown; otherwise, the offset address of the array element relative to the first address of the array is calculated and returned. The memory access module is used to access array elements based on the returned offset address, combined with the array's starting address and the data type length.
[0019] A computer device, characterized in that it includes a memory and one or more processors, wherein the memory stores computer code, and when the computer code is executed by the one or more processors, causes the one or more processors to perform the method as described above.
[0020] A computer-readable storage medium, characterized in that the computer-readable storage medium stores computer code, which, when executed, is performed as described above.
[0021] Compared with the prior art, the present invention has at least one of the following beneficial effects: (1) The method for detecting and protecting ST program array elements from out-of-bounds operation provided by this invention, compared with the existing compile-time static memory out-of-bounds detection method, adds dynamic detection of whether the array index access is out of bounds, while taking into account the low complexity of ST logic conversion, adopting a similar offset address calculation form, and avoiding nested logic. In addition, the exception throwing logic in this invention can quickly terminate the forced access to the exception address, avoid writing to unexpected addresses, and thus effectively ensure the correctness of the controller memory.
[0022] (2) This invention implements dimension checking logic uniformly in the subscript offset address conversion function, eliminating the need to repeatedly write checking code at each array access position in the ST code, reducing the complexity of code generation, and improving the reliability and consistency of runtime checking.
[0023] (3) The present invention adopts an early exit mechanism, that is, once any dimension index is detected to be out of bounds, the program execution is terminated immediately and an exception is thrown, and the subsequent dimension checks and offset address calculations are no longer executed, thereby reducing the waste of controller running time due to invalid calculations and improving the efficiency of runtime detection.
[0024] (4) This invention is compatible with array structures of any dimension, including one-dimensional arrays, two-dimensional arrays and arrays of higher dimensions, and the same set of checking functions can be applied to array access scenarios of different dimensions without modification, which has good versatility and scalability.
[0025] (5) By recording the error information of array subscript out of bounds to the system log and actively reporting it to the host computer operator station, the present invention enables operators to quickly locate the error code in the ST program, which is convenient for debugging and maintenance, and improves the diagnostics and maintainability of the industrial control system.
[0026] (6) The present invention immediately prohibits read and write operations on illegal memory addresses after an out-of-bounds event, effectively preventing other variables or data areas from being accidentally tampered with due to array out-of-bounds events, ensuring the correct execution of other control logic in the controller, and enhancing the robustness of the entire control system. Attached Figure Description
[0027] Figure 1 This is the overall flowchart of the array subscript out-of-bounds checking and protection method based on ST language of the present invention; Figure 2 This is a diagram showing the overall structure of the array subscript out-of-bounds checking and protection system based on the ST language of this invention. Detailed Implementation
[0028] To make the objectives, technical solutions, and advantages of the embodiments of this application clearer, the technical solutions of the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of this application, not all embodiments. Based on the embodiments of this application, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of this application.
[0029] Those skilled in the art will understand that, unless specifically stated otherwise, the singular forms “a,” “an,” “the,” and “the” used herein may also include the plural forms. It should be further understood that the term “comprising” as used in this specification means the presence of the stated features, integers, steps, operations, elements, and / or components, but does not exclude the presence or addition of one or more other features, integers, steps, operations, elements, components, and / or groups thereof.
[0030] The technical solution of this invention is specifically applied to the VisualField software in the OMC system. This software, as an industrial automation configuration tool, is responsible for editing, compiling, downloading, and debugging ST language control programs.
[0031] To facilitate understanding of the technical solutions involved in this invention, the relevant terms are defined and explained below: (1) DCS system: Distributed control system used for process control and industrial automation. The DCS system monitors, controls and manages industrial production processes through components such as controllers, I / O modules, and operator stations. The method of this invention runs in the controller of the DCS system to protect the memory safety of its control program during execution.
[0032] (2) ST Language: A structured text programming language, it is one of the programming languages supported by the IEC 61131-3 standard. ST Language uses high-level syntax structures (such as assignment statements, conditional statements, loop statements, etc.), and is suitable for writing complex control logic. This invention provides runtime out-of-bounds checks and protection for array element access operations in ST Language.
[0033] (3) Array: A data object that organizes several elements of the same type in a sequence. In the ST language, an array can be a one-dimensional or multi-dimensional structure, and its size is specified by the user when writing the program. The core object protected by this invention is the array defined in the ST language.
[0034] (4) Array index: A numerical identifier used to distinguish each element in an array object. For example, a one-dimensional array A contains 3 elements, with indices 0, 1, and 2. The corresponding array element is accessed through its index in the program. This invention requires a validity check on each accessed index value.
[0035] (5) Out of bounds: An error occurs when an array object is operated on using an index that is less than the lower bound of the number of array elements or greater than the upper bound of the number of array elements. For example, if an array object contains 3 elements, the valid range of its index is 0 to 2. Accessing an index less than 0 or greater than 2 is considered out of bounds. Out-of-bounds access may cause data at other addresses in the controller's memory to be modified incorrectly, or even cause abnormal controller operation. This invention aims to detect and prevent such out-of-bounds operations.
[0036] (6) Controller: The controller in the DCS system is responsible for collecting data from the field, performing control logic operations, outputting control commands to I / O devices, and interacting with the host computer operator station. As part of the controller's runtime environment, the method of this invention dynamically checks the legality of array index access during the execution of the ST program by the controller, and immediately terminates program execution when an out-of-bounds error occurs to prevent the spread of errors.
[0037] This invention discloses a method for preventing array out-of-bounds operations during runtime in the process of compiling an ST language program into an executable binary file for a controller. Specifically, after the control program written in ST language is compiled into an executable binary file for the controller, the method dynamically checks array index accesses during the actual execution of the binary file by the controller, thereby preventing array out-of-bounds operations. Runtime array out-of-bounds detection and protection effectively prevents memory address out-of-bounds access caused by human errors in ST program writing (such as using subscript variables outside the array's declared range), avoiding a series of problems, including: ST logic not executing as expected by the programmer, and even serious consequences such as controller malfunctions, crashes, or accidental data corruption.
[0038] The technical solution of the present invention will be described below through specific embodiments: First Embodiment like Figure 1 As shown, this embodiment provides a method for array subscript out-of-bounds checking and protection based on the ST language, including the following steps: S1: During the process of compiling the control program written in ST language into an executable binary file of the controller, the syntax tree of the ST code is traversed to identify the access nodes of array elements.
[0039] In this embodiment, step S1 specifically includes: Perform a depth-first traversal of the abstract syntax tree of the ST code, and determine the type of each node during the traversal: if the current node is an array element access node, mark it as the target node to be converted; for each marked array element access node, perform the following information extraction operation: Retrieve the basic data type of the array elements from the type information of the node, including integer, floating-point, boolean, or user-defined structure types; From the array declaration symbol table associated with the node, obtain the maximum number of elements in each dimension of the array, as well as the lower and upper bounds of each dimension; Recursively parse the child nodes of the node, extract the subscript expressions of each dimension used when accessing the array elements, and distinguish whether each subscript expression is a constant expression including numeric constants and constant arithmetic operations or a variable expression including variables, input parameters, and function calls. Record the position information of each subscript expression in the syntax tree, which will be used to generate the corresponding function call parameters later; Furthermore, for multidimensional arrays, the subscript expressions of the first dimension, the second dimension, and so on up to the Nth dimension are extracted in sequence according to the dimension order when the array is declared, and their corresponding dimension size information is extracted to form an ordered sequence of dimension-subscript pairs, which are used in step S2 to generate the subscript offset address conversion function.
[0040] In step S1 of this embodiment, performing a depth-first traversal of the abstract syntax tree of the ST code and identifying array element access nodes essentially establishes the necessary data foundation for subsequent runtime out-of-bounds checks. Specifically, this step completes two core tasks: first, extracting the array's metadata from the syntax tree nodes and symbol table, including data type, upper and lower bounds of each dimension, and the expression form of each dimension's subscript; second, organizing this metadata into an ordered sequence of dimension-subscript pairs. The reason for distinguishing between constant expressions and variable expressions is that constant subscripts can be directly evaluated at compile time, while variable subscripts must be dynamically passed in as function parameters during runtime. This distinction helps the compiler choose an appropriate parameter passing strategy when generating code. Furthermore, recursively parsing child nodes and recording position information ensures that even if the subscript expression contains complex nested operations or function calls, its syntactic structure can be accurately extracted, thus allowing the original subscript calculation logic to be fully restored during subsequent code generation. Through the above information extraction and serialization processing, step S1 provides complete and standardized input data for generating the unified subscript offset address conversion function call code in step S2, avoiding the loss of array dimension structural information during the conversion process.
[0041] S2: For the identified array element access node, generate code to call the subscript offset address conversion function. The subscript offset address conversion function receives at least the program identifier, the subscript values of each dimension of the array, and the maximum number of elements in each dimension as input parameters.
[0042] In this embodiment, step S2 specifically includes: Obtain the unique identifier of the current control program from the current compilation context. This identifier is assigned by the compiler when the control program is compiled and is used to uniquely identify the program instance when the controller is running. The subscript expressions of each dimension extracted in step S1 are processed one by one: if the subscript expression is a constant expression, the value of the constant is directly passed as a parameter in the generated function call parameters; if the subscript expression is a variable expression, the corresponding variable reading instruction is generated and the value of the variable at runtime is passed as a parameter. The maximum number of elements in each dimension of the array, known during the compilation phase, is directly embedded as a constant into the parameter list of the function call. These constant values are determined at compile time and do not require runtime calculation. The actual parameter list for the function call is organized in the following fixed order: the first parameter is the program identifier of the current controlling program; the second parameter to the Nth plus one parameter are the first dimension subscript expression, the second dimension subscript expression, and so on up to the Nth dimension subscript expression; the Nth plus two parameter to the second Nth plus one parameter are the maximum number of elements in the first dimension, the maximum number of elements in the second dimension, and so on up to the maximum number of elements in the Nth dimension. The function call code is directly inserted into the original array element access position, replacing the original direct offset calculation logic.
[0043] In step S2 of this embodiment, the core task is to convert the array access information extracted in step S1 into call code for the subscript offset address translation function. The ingenious design of this step lies in the fact that it does not explicitly insert checking statements at the ST language level. Instead, during the compilation and conversion stage, it replaces the expression that directly calculates the offset address with a call to a general checking function through code generation. This replacement strategy preserves the structural integrity of the original ST program while seamlessly integrating runtime out-of-bounds detection capabilities.
[0044] Specifically, step S2 first obtains the unique identifier of the control program. This identifier is the basis for the controller to distinguish multiple program instances during runtime, ensuring that when multiple control programs exist simultaneously, out-of-bounds exceptions can be accurately associated with the erroneous source program. Secondly, for the subscript expression of each dimension, it distinguishes between constant and variable cases: constant expressions have their values determined at compile time, so they are directly embedded in function call parameters, avoiding repeated calculations at runtime; variable expressions generate corresponding value fetching instructions, ensuring that the real-time subscript value can be obtained at runtime. This differentiated processing ensures both flexibility and optimized runtime efficiency.
[0045] Furthermore, step S2 directly embeds the maximum number of elements in each dimension of the array into the function parameter list as a constant. The advantage of this approach is that this dimensional information is completely determined during the compilation phase, eliminating the need for dynamic reading at runtime, thus reducing memory access overhead and preventing check failures due to accidental modification of the dimensional information. Finally, function call code is generated according to a fixed parameter order, directly replacing the original offset calculation logic. This ensures that the array access path in the converted C code or binary file naturally carries a "protective layer" of out-of-bounds checks. The entire process is completely transparent to the ST language writer, requiring no manual intervention, significantly reducing security protection costs in industrial control program development.
[0046] S3: Inside the subscript offset address conversion function, perform a dimension check: if the subscript value of any dimension exceeds the maximum number of elements in the corresponding dimension, terminate the execution of the current control program and throw an exception; otherwise, calculate the offset address of the array element relative to the first address of the array and return.
[0047] In step S3, inside the subscript offset address conversion function, a dimension check is performed applicable to arrays of any dimension, specifically: The total number of dimensions of the array is obtained based on the array declaration information. Following the dimension order declared in the array declaration, the index value of each dimension is checked sequentially from the first dimension to the last. For the currently checked dimension, the actual input index value corresponding to that dimension is compared with the maximum number of elements in that dimension, and simultaneously compared with the lower bound of that dimension. If the actual index value is greater than or equal to the maximum number of elements in that dimension, or if the actual index value is less than the lower bound of that dimension, then the dimension index is considered out of bounds. Once an out-of-bounds index is detected in any dimension, the checks of all subsequent dimensions are immediately stopped, and the out-of-bounds handling logic is triggered. Only when the index values of all dimensions are within the valid range of their respective dimensions is the dimension check considered passed, and the offset address calculation step continues.
[0048] In step S3, if the index value of any dimension exceeds the maximum number of elements in the corresponding dimension, the execution of the current control program is terminated and an exception is thrown, specifically: Immediately interrupt the execution flow of the current control program, preventing all subsequent instructions in the program that have not yet been executed from continuing to run; call the program stop function preset in the controller runtime environment. This function takes the unique program identifier of the current control program as input parameter. After execution, it causes the program instance to enter the terminated state and no longer participate in the controller's periodic task scheduling. Upon terminating program execution, an array index out-of-bounds exception is thrown. This exception includes the following information: the program identifier where the out-of-bounds error occurred, the specific location where the out-of-bounds error occurred, the out-of-bounds index value, and its corresponding dimension range. The process of throwing the exception includes: recording the out-of-bounds error information in the controller's system log in a structured format, with the log entry containing a timestamp, error type, and complete out-of-bounds context data; simultaneously, actively reporting the exception information to the host computer operator station through the communication channel between the controller and the host computer operator station to prompt the operator to check the ST program logic. After the program stops and an exception is thrown, any read or write operations to out-of-bounds memory addresses are prohibited to ensure that the integrity of other data areas in the controller's memory is not compromised.
[0049] In step S3, the offset address of the array element relative to the starting address of the array is calculated and returned, specifically: Obtain the total number of dimensions of the array and determine the storage order type of the array elements in memory, which includes two methods: row-major storage and column-major storage. Following the storage order of the array, the index values of each dimension are linearly combined and calculated. The specific method is as follows: For each dimension of the array, calculate the product of the index value of that dimension and the maximum number of elements in all dimensions after that dimension; then sum the product values of all dimensions to obtain the total linear offset. If the storage order is row-major, the processing order of dimensions is consistent with the dimension order when the array is declared. That is, the first dimension is the outermost layer and the last dimension is the innermost layer. When calculating, the index value of the first dimension is multiplied by the product of the maximum number of elements in all dimensions after the first dimension, the index value of the second dimension is multiplied by the product of the maximum number of elements in all dimensions after the second dimension, and so on, until the index value of the last dimension is directly added to itself. If the storage order is column-major, then the dimension processing order is the reverse of the dimension order when the array is declared, that is, the last dimension is the outermost layer and the first dimension is the innermost layer, and the dimension range multiplied by the subscript value of each dimension is adjusted accordingly. The calculated bus offset is returned as the offset address of the array element relative to the first address of the array, for use in subsequent memory access steps.
[0050] In step S3 of this embodiment, the subscript offset address conversion function undertakes the dual responsibility of runtime out-of-bounds detection and offset address calculation. The design of this function fully embodies the principles of "detection first, safe termination, and accurate conversion".
[0051] First, regarding dimension checking, the function obtains the total number of dimensions based on the array's declaration information and checks each index value sequentially according to the declared dimension order. The checking logic not only determines whether the index exceeds the upper bound of the maximum number of elements but also whether it is less than the lower bound of the dimension, thus comprehensively covering all out-of-bounds cases. To improve runtime efficiency, once any dimension out-of-bounds is detected, the checking of subsequent dimensions is immediately stopped, employing an early exit mechanism to avoid invalid calculations. This sequential dimension-by-dimensional checking method corresponds to the way the array is organized in memory, ensuring the comprehensiveness of out-of-bounds detection.
[0052] Secondly, regarding exception handling, once an out-of-bounds access is detected, the function immediately interrupts the execution flow of the current control program, calls the program stop function in the controller runtime environment, and causes the program instance to enter a terminated state, no longer participating in the controller's periodic task scheduling. Simultaneously, the thrown exception carries rich information, including the program identifier, the out-of-bounds location, the out-of-bounds index value, and its corresponding dimension range. This information is structured and recorded in the system log and proactively reported to the host computer operator station, providing strong support for operators to quickly locate errors in the ST program. Most importantly, after completing the program stop and exception throwing, the function explicitly prohibits any read or write operations on the out-of-bounds memory address. This protection measure fundamentally prevents out-of-bounds access from polluting other data areas in the controller's memory, ensuring the memory safety of the entire control system.
[0053] Finally, regarding offset address calculation, the function only executes the calculation if the indices of all dimensions are within the valid range. The calculation process fully considers the array's storage order in memory, including two common methods: row-major and column-major storage. For row-major storage, the calculation is performed in a linear combination according to the dimension declaration order, that is, the first dimension's index is multiplied by the product of the maximum number of elements in all dimensions after the first dimension, and so on, finally accumulating to obtain the offset in units of the number of elements. For column-major storage, the dimension processing order is adjusted in reverse. This design allows the method to seamlessly adapt to the array storage strategies adopted by different compilers or controller platforms, exhibiting good platform compatibility.
[0054] Through the close cooperation of the three sub-steps of dimension checking, abnormal termination, and offset calculation, step S3 completes the necessary legality verification and address translation work with minimal runtime overhead while ensuring array access security, laying a solid foundation for secure memory access in step S4.
[0055] S4: Access the array element based on the returned offset address, combined with the array's starting address and the data type length.
[0056] In this embodiment, step S4 specifically includes: Obtain the data type of the array elements and the length of memory bytes occupied by that data type from the array declaration information; The array's starting address is used as the starting memory address, which is determined and recorded in the symbol table during the compilation phase; Perform memory address calculation: Multiply the offset address returned in step S3 by the data type length of the array element to obtain a byte offset; then add the byte offset to the starting address of the array to obtain the precise memory address of the target array element. Here, the offset address is a logical offset in terms of the number of elements, which is converted into a physical offset in terms of bytes by multiplying by the data type length. The calculated target memory address is converted into a pointer to the data type of the array element to ensure that subsequent read and write operations on this address are performed with the correct data width; The pointer is used to perform read or write operations on array elements. Throughout the process, since step S3 has already completed the dimension out-of-bounds check, the memory address accessed in step S4 must be within the legal memory area allocated to the array and will not interfere with other data areas.
[0057] In step S4 of this embodiment, the final array element memory access operation is performed. The core of this step is to convert the logical offset returned in step S3 (in terms of the number of elements) into a physical memory address (in terms of bytes), and then perform the read / write operation using the correct data type pointer. Since step S3 has already performed strict out-of-bounds checks on all dimensions of the index, step S4 can safely perform address calculation and memory access without needing to repeat the verification.
[0058] Specifically, step S4 first obtains the data type and memory length in bytes of the array elements from the array declaration information. The array's starting address serves as the initial memory address, which is determined and recorded in the symbol table during the compilation phase and is considered statically known information. Next, address translation is performed: the logical offset returned in step S3 is multiplied by the data type length to obtain the byte offset; then, the array's starting address is added to this byte offset to obtain the precise memory address of the target array element. This translation process must be multiplied by the data type length because the offset calculated in step S3 only represents the number of elements counted from the first element of the array, while the controller memory is byte-addressed, thus requiring scaling based on the number of bytes occupied by each element.
[0059] After obtaining the precise memory address, step S4 casts this address to a pointer to the data type of the array element. This casting ensures that subsequent memory read and write operations are performed with the correct data width. For example, for four-byte integer data, memory will be accessed in units of four bytes, avoiding data truncation or alignment errors caused by data width mismatch. Finally, the array element read or write operation is performed through this pointer.
[0060] It is particularly noteworthy that, since step S3 has already completed a full dimension out-of-bounds check, the memory address accessed in step S4 will definitely be within the legal memory region allocated by the compiler for the array, and will not exceed the bounds of other variables or data segments. This design of "separating checks and accesses" ensures both security and avoids repeatedly performing boundary checks on each memory access, thus achieving a good balance between security and execution efficiency during controller operation.
[0061] Second Embodiment This embodiment uses a two-dimensional array as an example to illustrate the array runtime out-of-bounds access detection method described in this invention, and compares it with existing methods, as follows: In existing methods, the ST statement for accessing array elements by index is translated into C code, which then accesses the array elements directly using the format "array starting address + index offset". If the index offset is not constant, this approach may lead to runtime memory out-of-bounds access.
[0062] Based on the array dimension information provided by the aforementioned array object memory model, the method in this paper adjusts the address offset, originally derived from "subscript offset," to a subscript offset address translation function when traversing array element nodes in the ST code compilation process. Simultaneously, the subscript offset address translation function implements array offset out-of-bounds checking logic and offset address translation logic.
[0063] Taking a two-dimensional array as an example, the original logic for accessing array elements is as follows: *((DataType*)( (Byte*)BaseAddr + DataTypeLength * (index1*Dim1 +index2))) Here, DataType represents the array's data type, BaseAddr represents the address of the first element of the array, DataTypeLength represents the length corresponding to the array's data type, index1 represents the first index of the accessed array element, index2 represents the second index of the accessed data element, and Dim1 represents the maximum number of elements in the first dimension of the array.
[0064] The logic for accessing array elements using the subscript offset address conversion function is as follows: *((DataType*)( (Byte*)BaseAddr + DataTypeLength *GetArrayOffset(PorgID, index1, index2, Dim1, Dim2))) Here, DataType represents the array's data type, BaseAddr represents the address of the first element of the array, DataTypeLength represents the length corresponding to the array's data type, GetArrayOffset is the function for converting index offset to address, PorgID represents the ID of the control program, index1 represents the first index of the accessed array element, index2 represents the second index of the accessed data element, Dim1 represents the maximum number of elements in the first dimension of the array, and Dim1 represents the maximum number of elements in the second dimension of the array.
[0065] The logic of the offset address conversion function GetArrayOffset is as follows: INT GetArrayOffset(INT PorgID, INT index1, INT index2, INT dim1, INTdim2) { / / Note: Dimension check if(index1>= dim1 || index2>= dim2) { StopProgram(PorgID); Error? } / / Note: Offset address calculation return index1*dim1 + index2; } The dimension checking logic checks that the access range of each array index does not exceed the maximum number of elements in that dimension. If any dimension exceeds its valid range, the execution of the current program is immediately terminated, and an error exception is thrown to prevent subsequent logic from continuing. Offset address calculation returns the offset address of the accessed element after the dimension check finds no exceptions.
[0066] Third Embodiment like Figure 2 As shown, this embodiment provides an ST-language-based array subscript out-of-bounds checking and protection system for executing the ST-language-based array subscript out-of-bounds checking and protection method as described in the first embodiment, comprising: The syntax traversal module is used to traverse the syntax tree of ST code and identify array element access nodes during the process of compiling control programs written in ST language into executable binary files of the controller. The code generation module is used to generate code that calls the subscript offset address conversion function for the identified array element access node. The subscript offset address conversion function receives at least the program identifier, the subscript values of each dimension of the array, and the maximum number of elements in each dimension as input parameters. The out-of-bounds detection module is used to perform a dimension check inside the subscript offset address conversion function: if the subscript value of any dimension exceeds the maximum number of elements in the corresponding dimension, the execution of the current control program is terminated and an exception is thrown; otherwise, the offset address of the array element relative to the first address of the array is calculated and returned. The memory access module is used to access array elements based on the returned offset address, combined with the array's starting address and the data type length.
[0067] A computer-readable storage medium stores computer code that, when executed, performs the methods described above. Those skilled in the art will understand that all or part of the steps in the various methods of the above embodiments can be implemented by a program instructing related hardware. This program can be stored in a computer-readable storage medium, which may include: read-only memory (ROM), random access memory (RAM), a magnetic disk, or an optical disk, etc.
[0068] The above description is merely a preferred embodiment of the present invention. The scope of protection of the present invention is not limited to the above embodiments. All technical solutions falling within the scope of the present invention's concept are within the scope of protection of the present invention. It should be noted that for those skilled in the art, any improvements and modifications made without departing from the principles of the present invention should also be considered within the scope of protection of the present invention.
[0069] The technical features of the above embodiments can be combined in any way. For the sake of brevity, not all possible combinations of the technical features in the above embodiments are described. However, as long as there is no contradiction in the combination of these technical features, they should be considered to be within the scope of this specification.
[0070] It should be noted that the above embodiments can be freely combined as needed. The above description is only a preferred embodiment of the present invention. It should be pointed out that for those skilled in the art, several improvements and modifications can be made without departing from the principle of the present invention, and these improvements and modifications should also be considered within the scope of protection of the present invention.
Claims
1. A method for array subscript out-of-bounds checking and protection based on ST language, characterized in that, Includes the following steps: S1: During the process of compiling the control program written in ST language into an executable binary file of the controller, the syntax tree of the ST code is traversed to identify the access nodes of array elements; S2: For the identified array element access node, generate code to call the subscript offset address conversion function. The subscript offset address conversion function receives at least the program identifier, the subscript values of each dimension of the array, and the maximum number of elements in each dimension as input parameters. S3: Inside the subscript offset address conversion function, perform a dimension check: if the subscript value of any dimension exceeds the maximum number of elements in the corresponding dimension, terminate the execution of the current control program and throw an exception; otherwise, calculate the offset address of the array element relative to the first address of the array and return. S4: Access the array element based on the returned offset address, combined with the array's starting address and the data type length.
2. The array subscript out-of-bounds checking and protection method based on ST language according to claim 1, characterized in that, In step S1, the syntax tree of the ST code is traversed to identify array element access nodes, specifically: Perform a depth-first traversal of the abstract syntax tree of the ST code, and determine the type of each node during the traversal: if the current node is an array element access node, mark it as the target node to be converted; for each marked array element access node, perform the following information extraction operation: Retrieve the basic data type of the array elements from the type information of the node, including integer, floating-point, boolean, or user-defined structure types; From the array declaration symbol table associated with the node, obtain the maximum number of elements in each dimension of the array, as well as the lower and upper bounds of each dimension; Recursively parse the child nodes of the node, extract the subscript expressions of each dimension used when accessing the array elements, and distinguish whether each subscript expression is a constant expression including numeric constants and constant arithmetic operations or a variable expression including variables, input parameters, and function calls. Record the position information of each subscript expression in the syntax tree, which will be used to generate the corresponding function call parameters later; Furthermore, for multidimensional arrays, the subscript expressions of the first dimension, the second dimension, and so on up to the Nth dimension are extracted in sequence according to the dimension order when the array is declared, and their corresponding dimension size information is extracted to form an ordered sequence of dimension-subscript pairs, which are used in step S2 to generate the subscript offset address conversion function.
3. The array subscript out-of-bounds checking and protection method based on ST language according to claim 1, characterized in that, In step S2, for the identified array element access nodes, code is generated to call the subscript offset address conversion function. The subscript offset address conversion function receives at least the program identifier, the subscript values of each dimension of the array, and the maximum number of elements in each dimension as input parameters. Specifically: Obtain the unique identifier of the current control program from the current compilation context. This identifier is assigned by the compiler when the control program is compiled and is used to uniquely identify the program instance when the controller is running. The subscript expressions of each dimension extracted in step S1 are processed one by one: if the subscript expression is a constant expression, the value of the constant is directly passed as a parameter in the generated function call parameters; If the subscript expression is a variable expression, then a corresponding variable read instruction is generated, and the value of the variable at runtime is passed as a parameter. The maximum number of elements in each dimension of the array, known during the compilation phase, is directly embedded as a constant into the parameter list of the function call. These constant values are determined at compile time and do not require runtime calculation. The actual parameter list for a function call is organized in the following fixed order: the first parameter is the program identifier of the currently controlling program; The second parameter to the Nth plus one parameter are the first dimension subscript expression, the second dimension subscript expression, and so on up to the Nth dimension subscript expression, respectively; the Nth plus two parameter to the second Nth plus one parameter are the maximum number of elements in the first dimension, the maximum number of elements in the second dimension, and so on up to the maximum number of elements in the Nth dimension, respectively. This function call code is directly inserted into the original array element access position, replacing the original direct offset calculation logic.
4. The array subscript out-of-bounds checking and protection method based on ST language according to claim 1, characterized in that, In step S3, inside the subscript offset address conversion function, a dimension check is performed applicable to arrays of any dimension, specifically: The total number of dimensions of the array is obtained based on the array declaration information. Following the dimension order declared in the array declaration, the index value of each dimension is checked sequentially from the first dimension to the last. For the currently checked dimension, the actual input index value corresponding to that dimension is compared with the maximum number of elements in that dimension, and simultaneously compared with the lower bound of that dimension. If the actual index value is greater than or equal to the maximum number of elements in that dimension, or if the actual index value is less than the lower bound of that dimension, then the dimension index is considered out of bounds. Once an out-of-bounds index is detected in any dimension, the checks of all subsequent dimensions are immediately stopped, and the out-of-bounds handling logic is triggered. Only when the index values of all dimensions are within the valid range of their respective dimensions is the dimension check considered passed, and the offset address calculation step continues.
5. The array subscript out-of-bounds checking and protection method based on ST language according to claim 1, characterized in that, In step S3, if the index value of any dimension exceeds the maximum number of elements in the corresponding dimension, the execution of the current control program is terminated and an exception is thrown, specifically: Immediately interrupt the execution flow of the current control program, preventing all subsequent instructions in the program that have not yet been executed from continuing to run; call the program stop function preset in the controller runtime environment. This function takes the unique program identifier of the current control program as input parameter. After execution, it causes the program instance to enter the terminated state and no longer participate in the controller's periodic task scheduling. Upon terminating program execution, an array index out-of-bounds exception is thrown. This exception includes the following information: the program identifier where the out-of-bounds error occurred, the specific location where the out-of-bounds error occurred, the out-of-bounds index value, and its corresponding dimension range. The process of throwing the exception includes: recording the out-of-bounds error information in the controller's system log in a structured format, with the log entry containing a timestamp, error type, and complete out-of-bounds context data; simultaneously, actively reporting the exception information to the host computer operator station through the communication channel between the controller and the host computer operator station to prompt the operator to check the ST program logic. After the program stops and an exception is thrown, any read or write operations to out-of-bounds memory addresses are prohibited to ensure the integrity of other data areas in the controller's memory is not compromised.
6. The array subscript out-of-bounds checking and protection method based on ST language according to claim 1, characterized in that, In step S3, the offset address of the array element relative to the starting address of the array is calculated and returned, specifically: Obtain the total number of dimensions of the array and determine the storage order type of the array elements in memory, which includes two methods: row-major storage and column-major storage. Following the storage order of the array, the index values of each dimension are linearly combined and calculated. The specific method is as follows: For each dimension of the array, calculate the product of the index value of that dimension and the maximum number of elements in all dimensions after that dimension; then sum the product values of all dimensions to obtain the total linear offset. If the storage order is row-major, the processing order of dimensions is consistent with the dimension order when the array is declared. That is, the first dimension is the outermost layer and the last dimension is the innermost layer. When calculating, the index value of the first dimension is multiplied by the product of the maximum number of elements in all dimensions after the first dimension, the index value of the second dimension is multiplied by the product of the maximum number of elements in all dimensions after the second dimension, and so on, until the index value of the last dimension is directly added to itself. If the storage order is column-major, then the dimension processing order is the reverse of the dimension order when the array is declared, that is, the last dimension is the outermost layer and the first dimension is the innermost layer, and the dimension range multiplied by the subscript value of each dimension is adjusted accordingly. The calculated bus offset is returned as the offset address of the array element relative to the first address of the array, for use in subsequent memory access steps.
7. The array subscript out-of-bounds checking and protection method based on ST language according to claim 1, characterized in that, In step S4, the array element is accessed based on the returned offset address, combined with the array's starting address and the data type length. Specifically: Obtain the data type of the array elements and the length of memory bytes occupied by that data type from the array declaration information; The array's starting address is used as the starting memory address, which is determined and recorded in the symbol table during the compilation phase; Perform memory address calculation: Multiply the offset address returned in step S3 by the data type length of the array element to obtain a byte offset; then add the byte offset to the starting address of the array to obtain the precise memory address of the target array element. Here, the offset address is a logical offset in terms of the number of elements, which is converted into a physical offset in terms of bytes by multiplying by the data type length. The calculated target memory address is converted into a pointer to the data type of the array element to ensure that subsequent read and write operations on this address are performed with the correct data width; The pointer is used to perform read or write operations on array elements. Throughout the process, since step S3 has already completed the dimension out-of-bounds check, the memory address accessed in step S4 must be within the legal memory area allocated to the array and will not interfere with other data areas.
8. An ST-language-based array subscript bounds checking and protection system for executing the ST-language-based array subscript bounds checking and protection method as described in any one of claims 1-7, characterized in that, include: The syntax traversal module is used to traverse the syntax tree of ST code and identify array element access nodes during the process of compiling control programs written in ST language into executable binary files of the controller. The code generation module is used to generate code that calls the subscript offset address conversion function for the identified array element access node. The subscript offset address conversion function receives at least the program identifier, the subscript values of each dimension of the array, and the maximum number of elements in each dimension as input parameters. The out-of-bounds detection module is used to perform a dimension check inside the subscript offset address conversion function: if the subscript value of any dimension exceeds the maximum number of elements in the corresponding dimension, the execution of the current control program is terminated and an exception is thrown; otherwise, the offset address of the array element relative to the first address of the array is calculated and returned. The memory access module is used to access array elements based on the returned offset address, combined with the array's starting address and the data type length.
9. A computer device, characterized in that, The device includes a memory and one or more processors, wherein the memory stores computer code that, when executed by the one or more processors, causes the one or more processors to perform the method as described in any one of claims 1 to 7.
10. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores computer code, and when the computer code is executed, the method as described in any one of claims 1 to 7 is performed.