A JS script automatic generation method and system suitable for a honkai NEXT simulator
By automatically generating JS scripts in the HarmonyOS NEXT simulator, parsing shared library files, and monitoring function calls in real time, the problems of function offset recognition errors and symbol failures in traditional scripts in the HarmonyOS system are solved, enabling efficient function-level testing and data analysis.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-12-03
- Publication Date
- 2026-03-24
Smart Images

Figure CN121255156B_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of simulator data processing technology, and in particular to a method and system for automatically generating JS scripts suitable for the HarmonyOS NEXT simulator. Background Technology
[0002] In the development of software testing and dynamic analysis technologies, automated script generation has gradually become a key means to improve testing efficiency and the accuracy of behavior tracking. JavaScript scripts are lightweight programming codes that can automatically execute tasks in specific runtime environments (such as the HarmonyOS NEXT emulator), such as dynamically intercepting function calls or collecting performance data. Early automated scripts mostly relied on manual writing or recording, primarily applied to general Linux and Android systems, generating test scripts through function symbol resolution and API mapping. However, traditional solutions generally rely on fixed ELF file structures and standard runtime interfaces. When the system architecture migrates to the HarmonyOS NEXT platform, due to its independent distributed kernel and dynamic shared library loading mechanism, traditional symbol resolution methods cannot correctly identify the loading base address and function offset relationship of shared libraries, causing function call instructions in the generated scripts to fail. Furthermore, the HarmonyOS NEXT system differs fundamentally from the Android system in terms of API interface access, security authentication, and memory mapping strategies, making it difficult for existing methods to achieve function-level interception and real-time behavior sampling. At the script execution level, traditional Python or Shell scripts lack compatibility with the HarmonyOS runtime injection interface, failing to meet the real-time monitoring needs of high-frequency function calls. Summary of the Invention
[0003] Based on this, it is necessary for the present invention to provide a method and system for automatically generating JS scripts applicable to the HarmonyOS NEXT simulator, so as to solve at least one of the above-mentioned technical problems.
[0004] To achieve the above objectives, a method for automatically generating JS scripts suitable for the HarmonyOS NEXT simulator includes the following steps:
[0005] Step S1: Start the HarmonyOS NEXT simulator environment, load the preset JS script template, and obtain the target method list from the preset API interface collection;
[0006] Step S2: Call the preset injection tool to parse the shared library files in the HarmonyOS NEXT simulator runtime environment, export the function symbol table of the shared library files, and extract the address of the target function corresponding to the target method list;
[0007] Step S3: Determine the entry point, parameter types, return value types, and stack information of the target function based on its address, forming a function information set;
[0008] Step S4: Map the function information set to the preset JS script template to automatically generate a JS script containing the target function call logic;
[0009] Step S5: Dynamically load the JS script in the HarmonyOS NEXT simulator, and use the injection tool to intercept the function of the target process, collect function call behavior data in real time, and determine the detailed function information.
[0010] Preferably, the present invention also provides a JS script automatic generation system suitable for the HarmonyOS NEXT simulator, used to execute the above-described JS script automatic generation method suitable for the HarmonyOS NEXT simulator, wherein the JS script automatic generation system suitable for the HarmonyOS NEXT simulator includes:
[0011] The simulator initialization module is used to start the HarmonyOS NEXT simulator environment, load the preset JS script template, and obtain the target method list from the preset API interface collection.
[0012] The function symbol resolution module is used to call the preset injection tool to parse the shared library files in the HarmonyOS NEXT simulator runtime environment, export the function symbol table of the shared library files, and extract the address of the target function corresponding to the target method list;
[0013] The function information construction module is used to determine the entry point, parameter types, return value types, and stack information of the target function based on the target function address, forming a function information set;
[0014] The script auto-generation module is used to map function information sets to preset JS script templates and automatically generate JS scripts containing target function call logic.
[0015] The dynamic interception and acquisition module is used to dynamically load JavaScript scripts in the HarmonyOS NEXT simulator and intercept functions of the target process through injection tools. It collects function call behavior data in real time and determines detailed function information. This invention, by achieving automatic generation and dynamic loading of JavaScript scripts in the HarmonyOS NEXT simulator environment, enables accurate identification of target functions, script self-adaptation, and real-time monitoring even under significant differences in the underlying system architecture, thereby significantly improving the completeness and accuracy of the testing and analysis process. This method effectively solves the problems of function offset recognition errors and symbol failures in the HarmonyOS NEXT system by establishing an independent function symbol resolution and address calculation mechanism tailored to the runtime characteristics of HarmonyOS NEXT. By establishing a one-to-one function mapping relationship with the official API interface list, it achieves precise synchronization between script logic and system function call behavior, ensuring the integrity of test coverage. By generating a structured function information set containing function entry points, parameters, return values, and stack information, the generated script possesses traceable, verifiable, and extensible logical characteristics. During the dynamic loading phase, the injection tool supports real-time interception and behavior collection of target process functions, outputting timestamps, parameter values, and return content during function calls, providing a complete behavioral data foundation for performance analysis, security detection, and anomaly tracking. Simultaneously, this method establishes a templated script generation system, enabling scripts to automatically adapt to emulator versions and shared library updates without manual modification of function addresses or parameter definitions, significantly reducing script maintenance costs. In summary, this method achieves a closed-loop fusion of automated script generation and runtime behavior collection in the HarmonyOS NEXT simulation environment, improving the accuracy of function-level testing, the real-time nature of data analysis, and system compatibility. Attached Figure Description
[0016] Other features, objects, and advantages of the invention will become more apparent from the following detailed description of non-limiting embodiments with reference to the accompanying drawings:
[0017] Figure 1 This is a flowchart illustrating the steps of an automatic JS script generation method applicable to the HarmonyOS NEXT simulator according to the present invention.
[0018] Figure 2 This invention uses a HarmonyOS NEXT simulator JS script to automatically generate a system architecture diagram.
[0019] Figure 3 This is a schematic diagram of a module for a system property simulation system automatically generated by JS scripts for the HarmonyOS NEXT simulator according to the present invention. Detailed Implementation
[0020] The technical method of the present invention will now be clearly and completely described with reference to the accompanying drawings. Obviously, the described embodiments are only some, not all, of the embodiments of the present invention. All other embodiments obtained by those skilled in the art based on the embodiments of the present invention without inventive effort are within the scope of protection of the present invention.
[0021] Furthermore, the accompanying drawings are merely illustrative of the invention and are not necessarily drawn to scale. The same reference numerals in the drawings denote the same or similar parts, and therefore repeated descriptions of them will be omitted. Some block diagrams shown in the drawings are functional entities and do not necessarily correspond to physically or logically independent entities. These functional entities can be implemented in software, in one or more hardware modules or integrated circuits, or in different network and / or processor methods and / or microcontroller methods.
[0022] It should be understood that although the terms "first," "second," etc., may be used herein to describe various units, these units should not be limited by these terms. These terms are used merely to distinguish one unit from another. For example, without departing from the scope of the exemplary embodiments, a first unit may be referred to as a second unit, and similarly, a second unit may be referred to as a first unit. The term "and / or" as used herein includes any and all combinations of one or more of the associated listed items.
[0023] To achieve the above objectives, please refer to Figures 1 to 3 This invention provides a method for automatically generating JS scripts suitable for the HarmonyOS NEXT simulator, the method comprising the following steps:
[0024] Step S1: Start the HarmonyOS NEXT simulator environment, load the preset JS script template, and obtain the target method list from the preset API interface collection;
[0025] Step S2: Call the preset injection tool to parse the shared library files in the HarmonyOS NEXT simulator runtime environment, export the function symbol table of the shared library files, and extract the address of the target function corresponding to the target method list;
[0026] Step S3: Determine the entry point, parameter types, return value types, and stack information of the target function based on its address, forming a function information set;
[0027] Step S4: Map the function information set to the preset JS script template to automatically generate a JS script containing the target function call logic;
[0028] Step S5: Dynamically load the JS script in the HarmonyOS NEXT simulator, and use the injection tool to intercept the function of the target process, collect function call behavior data in real time, and determine the detailed function information.
[0029] Of particular importance, step S1 includes:
[0030] Configure the corresponding emulator image and system root directory according to the HarmonyOS NEXT system version number to be tested, and complete the initialization and startup of the HarmonyOS NEXT emulator environment;
[0031] Load preset JS script templates from the preset template resource library according to the test scenario category. The test scenario categories include functional testing, performance testing, and security testing.
[0032] Access a pre-defined set of API interfaces in the emulator runtime environment. This set is stored in the form of a manifest file. Filter and obtain a list of target methods based on the interface name, module, and permission level declared in the manifest file.
[0033] In this embodiment of the invention, the test management module first receives the HarmonyOS NEXT system version number, and then retrieves the corresponding version image file and system root directory package from the system image storage directory / data / emulator / images / based on the version number. The image file has the extension .img, and the root directory package has the extension .rootfs. After successful retrieval, the module calls emulator-launch --image= via the command-line interface. <path>--rootfs= <path>The emulator instance is started with `--mem=4096 --cpu=4`, and the "boot completed" flag in the startup log is monitored to confirm initialization completion. After successful startup, the corresponding subdirectories are read from the template resource library path ` / data / templates / ` according to the test scenario category. "Functional testing" corresponds to the directory `func / `, "Performance testing" to `perf / `, and "Security testing" to `sec / `. Each type of template file is named in the format `template_`. <type>The .js template file content is loaded into the memory cache and stored in UTF-8 format. Subsequently, the script control module accesses the preset API interface collection manifest file / system / api / api_manifest.json in the simulator runtime environment. The manifest file fields include api_name, module, and permission_level. The system filters interface entries with permission level field values of 1 or 2 according to predefined filtering rules, and matches the corresponding module fields according to the test scenario category, extracts the target method list, and writes it into the method index table.
[0034] Preferably, step S2 includes:
[0035] The pre-defined injection tool is invoked to read the memory space of the currently running process in the emulator, identify all loaded shared library files, and create a list of shared library files.
[0036] A convenient list of shared library files is generated, and the function symbol table information for each shared library file is exported to construct a function symbol dataset.
[0037] Retrieve the function entries in the function symbol dataset that correspond to the target method list, establish a one-to-one correspondence between method names and function symbols, and form a function mapping table;
[0038] The relative addresses of each function in the function mapping table are parsed using injection tools, and the actual addresses of the functions at runtime are determined by combining the loading base address of the shared library file in the simulator, and then compiled into a target function address set.
[0039] In this embodiment of the invention, the injection tool attaches to the target process within the HarmonyOS NEXT emulator. The attachment is performed using the ptrace attachment interface or the process memory access interface process_vm_readv / / proc / <pid> / mem read permission request process. Then read / proc / <pid>The contents of the / maps file are used to parse the process's virtual address space mapping table.
[0040] parse / proc / <pid>When parsing ` / maps`, the parsing rule is to split by line and separate fields by whitespace characters. The focus is on reading the starting and ending addresses of the mapping range, permission identifiers, and the mapped file paths. Only mapped file paths ending in ".so" and containing "r" in their permissions are retained as candidate shared library file entries. The maximum number of candidates is limited to 1024; if this number is exceeded, they are sorted by starting address, and the first 1024 entries are truncated to control resource consumption.
[0041] For each mapped path in the shared library file list, file reading is performed. The disk image file header is read and the ELF file header structure is parsed to locate the segment table and section table offsets. A binary stream reading interface is used to parse fields such as e_ident, e_type, e_phoff, e_shoff, e_shentsize, and e_shnum in Little-Endian format.
[0042] Structure parsing templates are used for 32-bit and 64-bit ELF formats respectively; when e_type is ET_DYN, it is marked as a relocatable shared library; the section table traversal is limited to a maximum of 512 section table entries; the length of the string table section name is limited to 4096 bytes.
[0043] Based on the symbol table section index extracted from S2-B, the .dynsym section is traversed according to the symbol table entry structure, and the st_name, st_info, st_other, st_shndx, st_value, and st_size fields of each entry are read; at the same time, the corresponding symbol name string is read from the .dynstr section.
[0044] The symbol table traversal retains only entries with symbol binding type GLOBAL or WEAK (i.e., the high 4 bits of st_info are 1 or 2) and symbol type FUNC (the low 4 bits of st_info are 2); the symbol name length is limited to 256 bytes; when the shared library is unsigned (symbol table is empty), the backup byte signature matching process is triggered (see S2-C-alternative).
[0045] When the function symbol dataset is empty or the target symbol is not matched, binary byte signature matching technology is used. The injection tool extracts feature segments from the shared library disk image (by default, it extracts the first 4096 bytes of the .text section and samples 256 bytes per 4KB block), and performs sliding window matching on the predefined byte sequence signature of each target API.
[0046] The signature matching uses the longest common subsequence byte matching, with a threshold of 80% similarity; the matching window step size is 1 byte; when multiple candidate addresses are matched, they are sorted by the frequency of address occurrence and the score of conformity with the target method calling convention, and the top 3 candidate addresses are taken as candidate function entries.
[0047] Using the list of target methods as the search index, perform exact matching by symbol name in the function symbol dataset; if an exact match fails, perform extended search by matching the suffix of the symbol name (underscore, name mangling rules) and matching regardless of lowercase / uppercase; if no match is found and there are alternative entries, adopt the alternative entries and record the matching type as "signature inference".
[0048] The matching priority rule is: exact match Name Modifier Matching Signature inference; when the same target method corresponds to multiple matching items, the one with the highest matching score is retained. The score calculation consists of symbol name similarity (accounting for 60%) and the memory executable permission verification result of the candidate address (accounting for 40%). The lower limit of the score threshold is set to 0.6 (value range 0~1).
[0049] Using the load base address of each mapped entry in the shared library file list output by S2-A as the base, the runtime actual address is calculated according to the following formula: Runtime actual address = Load base address + Relative address offset. The load base address is determined by / proc / <pid>Retrieve the starting address field of the range for the same path mapping row in / maps.
[0050] When the ELF dynamic section contains a DT_RELA or DT_REL relocation table, the injection tool parses the relocation table and performs r_offset and r_addend operations on each relocation entry to adjust the relative address offset. The address calculation process uses 64-bit unsigned integer operations to prevent overflow. If the offset value exceeds the mapping range, it is marked as an address error and logged. The address calculation error tolerance is 0 bytes.
[0051] The target function address set is validated using the following steps: Validation items include whether the address falls within the executable mapping range of the corresponding shared library, the boundary relationship between the address and symbol size, and whether the matching score threshold is met. Mapping items that do not meet any of the validation items are marked as "requires manual review" and written to the error log table.
[0052] Executable mapping range determination uses / proc / <pid>The permissions field in / maps must contain "x"; the symbol size limit is checked as: relative offset + st_size. Mapping interval end address - load base address. The log table fields are minimized to: target method name, check item, checksum, and expected value.
[0053] Preferably, step S3 includes:
[0054] The injection tool locates the address of the target function within the simulator, and the corresponding assembly instruction sequence is loaded into the parsing buffer. The instructions in the parsing buffer identify the start and end boundaries of the function, forming a function entry information set.
[0055] Based on the function entry information set, the parameter passing path of the function's instruction structure is analyzed, and the parameter sources of register parameter passing, stack parameter passing and memory indirect parameter passing are extracted respectively, and a parameter description set is generated.
[0056] By using injection tools to trace the return path of functions, identify the return register or return memory region, infer the data type and storage method of the return value, and form a return value description set;
[0057] Based on the function entry information set and return value description set, extract stack change data during function call, identify the local variable area, the storage register area and the return address area, and form a stack structure set;
[0058] A function information set is constructed and output based on the function entry information set, parameter description set, return value description set, and stack structure set.
[0059] In this embodiment of the invention, the injection tool starts from the address of the target function and uses the process memory read interface (preferably process_vm_readv; alternatively / proc / ). <pid>The ` / mem` command captures a continuous byte stream and writes it to the parsing buffer. The read window is fixed at 4096 bytes; when the target function's initial instruction sequence indicating the subroutine boundary has not been fully identified, reading continues in increments of 2048 bytes, with a maximum cumulative read limit of 65536 bytes to prevent infinite expansion.
[0060] The parsing buffer is stored in Little-Endian format. Byte streams are fed into the disassembler (example engine: Capstone, architecture parameter set to ARM64 or AArch64). The disassembler decodes instruction by instruction, with a maximum length of 4 bytes per instruction. The maximum number of instructions in the decoding process is limited to 16384. If this number is exceeded, it is marked as a parsing overflow and logged.
[0061] Based on the disassembled instruction sequence, deterministic rules are applied to identify the start and end points of functions, forming a set of function entry information.
[0062] Identification rules (specifically limited to ARM64 architecture):
[0063] Function start determination: The first occurrence of a function attribute sequence is a stack pointer adjustment (e.g., stp x29, x30, [sp, #-X]! or mov x29, sp or sub sp, sp, #Y) or an explicit link register save instruction; if no such sequence exists, the given address is used as the starting point and marked "no standard leading".
[0064] Function termination determination: The function is considered terminated when a ret instruction or blr xN is encountered and the return address is consistent with the calling convention; if no termination instruction is encountered at the end of the parsing window, the last read address is used as the boundary and marked as "truncation boundary".
[0065] The maximum local function length is limited to 65536 bytes; if the boundary detection exceeds this limit, the process will be interrupted and an exception will be logged.
[0066] Using the function entry information set as the boundary, scan the caller-callee parameter passing convention symbols within the function and construct a parameter description set.
[0067] Register parameter passing identification rules (ARM64 explicit constraint): The first eight integer parameters are located in register sequences x0 to x7; the first eight floating-point parameters are located in register sequences v0 to v7. The parsing steps are as follows: Read the register usage pattern at the function entry point (using the register read interface of the injection tool, such as ptrace(PTRACE_GETREGS)); compare the register value at the entry point with subsequent instructions; if the register value is directly loaded as a parameter register or passed to the calling instruction through a register in several subsequent instructions, it is determined to be register parameter passing. The observation window for register parameter passing determination is the first 32 instructions or the first 256 bytes.
[0068] Stack parameter passing identification rules: Identify the pairing relationship between writes to stack addresses (e.g., the str instruction writes [sp, #offset]) and read operations on stack offsets (e.g., ldr) in the instruction sequence, and merge parameter items in ascending order of stack offset. Stack alignment is constrained to 16-byte alignment; the maximum stack frame depth is limited to 8192 bytes, and if an offset exceeds the boundary, it is marked as a stack out-of-bounds exception.
[0069] Memory indirect parameter passing identification rules: Identify memory access patterns that use registers as pointer base addresses and access them with offsets (e.g., ldr x0, [x1, #offset]) and record the relationship between that register and the subsequent instruction passed to it as indirect parameter passing. The indirect parameter passing resolution window is the same as that for register parameter passing.
[0070] Parameter description set fields and limitations: parameter number, source type (register / stack / memory indirection), source name (e.g., x0, sp+0x20, [x1+0x10]), data width limit (8, 16, 32, 64 bits), data width inference order by default: instruction operation width. Context invocation convention The readable length of the mapped memory bytes. The maximum number of parameters is limited to 32.
[0071] The injection tool uses the return instruction at the end of the function as a reference to read the return register, the register state before the return, and the write operations to memory before the return, forming a return value description set.
[0072] The state of the registers is sampled within a range of instructions before and after the function's end boundary (16 instructions backward and 8 instructions forward); the priority of the return register is determined as x0 (integer / pointer) and v0 (floating point). If the return register is assigned a value before returning and the assignment source is a memory read or calculation result, it is classified according to the source type.
[0073] Return value type determination rules: If the returned register value falls within the address range of the mapped memory area and that address corresponds to a valid readable segment, then the return type is marked as "pointer"; if the returned register value is between 0 and... If the range is not specified and does not point to a mapped region, the return type is marked as "integer"; if the return register interacts with the floating-point register and the floating-point register is used more frequently than a set threshold (20%), the return type is marked as "floating-point". The data type size is limited to 8 / 16 / 32 / 64 bits.
[0074] By combining the function entry information set with the return path identification results, the stack changes during function calls are compared and analyzed to form a stack structure set.
[0075] Within the parsing buffer, identify stack pointer adjustment instructions (such as sub sp, sp, #N and add sp, sp, #N) and calculate the base address of the local variable area; identify register save instructions (such as stp x19, x20, [sp, #M]) and record the offset of the saved register area and the register number; identify the return address save area and the push mode of the call chain. The total stack frame size is limited to a maximum of 8192 bytes.
[0076] Field definitions: Local variable area (start offset, length), register storage area (register list, offset), return address area (offset, address check segment).
[0077] Integrate the function entry information set, parameter description set, return value description set, and stack structure set to construct a function information set and perform consistency verification.
[0078] Construct fields: function name (from the function mapping table in S2), address (actual runtime address), start and end boundaries, calling convention identifier (e.g., AAPCS64), parameter description set, return value description set, stack structure set, and authentication identifier (inferred from symbol table metadata or signature).
[0079] The total number of bytes of parameters is within the stack frame range; the number of registers used does not exceed the set of architecture registers; the return value register is consistent with the return value description; if any check fails, the mapping entry is marked as "to be reviewed" and the check exception type is recorded.
[0080] Preferably, step S4 includes:
[0081] Establish a correspondence between the function names, authentication identifiers, and information addresses in the function information set and the function placeholder fields in the JS script template to form a template mapping table;
[0082] Extract the parameter description set and return value description set from the function information set according to the template mapping table, write the parameter name, data type, passing method and return value structure into the corresponding position of the template, and generate a template instance containing complete call parameter definition;
[0083] Read the stack structure set and function entry information, insert stack trace and function entry identifier code snippets, and build runtime monitoring logic code snippets in the template instance;
[0084] Insert the call statement and return value encapsulation statement of the target function based on the function address and calling convention in the template instance, and generate a script logic body with a complete function call path;
[0085] Integrate template instances and script logic into a JS script file.
[0086] In this embodiment of the invention, the script generation module calls the file reading interface (standard I / O library functions fopen and fread) to load a preset JS script template file into a memory buffer. The template file uses UTF-8 encoding format, and function placeholder fields within the template are identified in double curly braces (e.g., ...). , , ).
[0087] The function name field in the function information set is the same as that in the template. Placeholder comparison; authentication identifier field and Placeholder comparison; function address field and Placeholder matching. The matching method is line-by-line scanning and matching. Placeholder matching uses exact matching rules and is case-sensitive.
[0088] The total number of placeholders in the template must not exceed 512; the length of a single line is limited to 2048 characters. After the template file is loaded, it is stored in a character array with a length not exceeding 256KB.
[0089] The script generation module reads the template mapping table and locates the template. and The corresponding position index. Then, the parameter description set and return value description set are extracted from the function information set.
[0090] The parameter descriptor set fields include parameter name, data type, passing method, data width, and source register or stack offset; the return value descriptor set fields include return register, return data type, and return width. Each parameter definition is converted into a JS variable declaration statement, with the format: var paramN = read_ <type>( <source> ); where N is the parameter index, <type>It is a data type (one of six: int8, int16, int32, int64, float, double). <source> Describes a register or stack offset.
[0091] The return value definition is converted to: var ret = cast_ <type>(result_value);, <type>Taken from the return value description set.
[0092] The maximum number of parameters for a single function is 32; the maximum length of a single line for a variable declaration statement is 128 characters.
[0093] The script generation module extracts the stack structure set and function entry information from the function information set, and parses the offset relationships between the local variable area, the storage register area, and the return address area. Based on these offset relationships, runtime monitoring logic code is inserted into the specified positions in the template instance.
[0094] The stack tracing logic is implemented as a JavaScript function, with the function name fixed as `trace_stack()`. This function calls the injection tool's API `read_mem(address, length)` to capture a stack memory snapshot. The stack read range is limited to the first 1024 bytes offset upwards from the value of the sp register at the function entry point. The function entry identifier is inserted as a comment and in log output, formatted as `console.log("Enter function")`.<FUNC_NAME> at<FUNC_ADDR> ");
[0095] The script generation module reads the function address and calling convention fields from the second version of the template instance, and inserts the target function call statement and return encapsulation statement according to the calling convention.
[0096] The calling statement format is fixed as: var result_value = call_native(<FUNC_ADDR> ,[param1, param2, ..., paramN]);
[0097] The `call_native` function is the function call interface provided by the injection tool; parameters are passed in array form, and the order is consistent with the parameter descriptor set.
[0098] The return statement is fixed as: console.log("Return from...")<FUNC_NAME> : " + ret);
[0099] The script will append a return value to the `write_log` statement.<FUNC_NAME> , ret); so that the behavior acquisition module can read it.
[0100] Call address<FUNC_ADDR> Output in hexadecimal string format, with a uniform length of 8 digits. If the length is insufficient, pad with leading zeros.
[0101] The script generation module integrates the second version of the template instance and the script logic body into a complete script file by replacing placeholders.
[0102] The integration process involves replacing each item sequentially according to its index position in the template mapping table. Placeholder replacement uses string positioning and does not allow fuzzy regular expression matching. After integration, the script file will be named with the .js extension and the filename format will be auto_func_.<FUNC_NAME> .js.
[0103] The total file length must not exceed 512KB; the maximum number of statements in a function body is 1024 lines; all variable declarations must be placed at the beginning of the file and must not be duplicated.
[0104] The script generation module performs integrity checks on the generated JS script files.
[0105] Check if the placeholder replacement is complete; check if the variable names are duplicated; check if the number of parameter declarations matches the function information set record.
[0106] The verification results are written to a log file in JSON format, with fields including script name, number of successful replacements, number of unreplaced replacements, and check status (Pass / Fail).
[0107] Of particular importance is the process of reading the stack structure set and function entry information, inserting stack trace and function entry identifier code snippets, and constructing runtime monitoring logic code snippets within the template instance, including:
[0108] Read the stack structure set from the function information set, and insert stack trace code snippets into the JS script template to record stack pointer changes and memory read / write operations based on the size of the local variable area and the offset of the return address area identified therein.
[0109] Read the function entry information set from the function information set, obtain the entry address and authentication identifier of the target function, and insert a function entry identifier code snippet before the function call logic in the template instance to record the function call event and its entry address in the log;
[0110] Runtime monitoring logic is constructed by combining stack trace code snippets and function entry point identifier code snippets in a template instance.
[0111] In this embodiment of the invention, the script generation module first reads the stack structure set fields from the function information set. These fields include the size of the local variable area (in bytes), the offset of the stored register area, and the offset of the return address area. Based on the size of the local variable area, the stack read range is calculated as stack_range = local_var_size + 64 bytes. A stack trace code snippet is then inserted before the function call logic in the JS script template. The code content is: calling the injection tool interface read_mem(sp - stack_range, stack_range) and outputting it to the log function write_log("SP_TRACE", hex_data), where sp is the current stack pointer register value and hex_data is the read hexadecimal stack content. Subsequently, the function entry information set is read, the entry address and authentication identifier of the target function are extracted, the entry address is formatted as an eight-digit hexadecimal string, and a function entry identifier code snippet is inserted before the function call statement in the template instance. The code structure is console.log("[CALL_EVENT]FUNC=" + func_name + " ADDR=" + func_addr + " AUTH=" + Finally, the script generation module combines the two code snippets in the calling logic area of the template instance in sequence, and appends a real-time monitoring logic code block after the stack trace code snippet. The code block includes timestamp recording, thread ID reading, and stack change comparison logic when the function returns, in order to build a complete runtime monitoring logic area. The combined result is then written into the final template instance and saved as an executable JS script file.
[0112] Preferably, step S5, dynamically loading the JS script in the HarmonyOS NEXT simulator, includes:
[0113] The injection tool starts and runs an instance in the HarmonyOS NEXT emulator, loads a JS script file, maps the script to the memory space of the target process, and forms a script instance.
[0114] In this embodiment of the invention, the injection tool initiates a process access permission request to the target process by calling ptrace(PTRACE_ATTACH, pid, NULL, NULL) or by attaching through a process management interface; subsequently, it reads the target process's thread list from / proc / <pid> / task and record the main thread ID.
[0115] ptrace has a timeout limit of 5000 milliseconds for appending; if appending fails, it logs the error code and returns error status code -1.
[0116] The injection tool invokes a remote memory allocation interface within the target process, using the mmap system call to allocate contiguous readable and writable memory pages in the target process's address space. Call parameters: addr = 0, length = round_up(script_length, 4096), prot = PROT_READ | PROT_WRITE, flags = MAP_PRIVATE | MAP_ANONYMOUS, fd = -1, offset = 0.
[0117] page_size = 4096; alloc_size = ((script_length + page_size - 1) / page_size) page_size (integer rounded up). The maximum script length is limited to 524288 bytes (512KB); if script_length > 524288, allocation is refused and an error code is returned.
[0118] The injection tool reads the contents of a JavaScript file (UTF-8) locally, calculates the checksum (CRC32), and then uses `process_vm_writev` to write the script byte stream to the remote_buf_addr address of the target process. The write block size is limited to 4096 bytes, the write timeout is 200 milliseconds per block, and the total write timeout is 10000 milliseconds.
[0119] After writing is complete, process_vm_readv is called to read alloc_size bytes from remote_buf_addr and calculate the CRC32 of the read byte stream; the CRC32 before writing and after reading are compared, and if they are consistent, the write verification is marked as passed; the CRC32 calculation uses the standard polynomial 0xEDB88320, the initial value is 0xFFFFFFFF, and the result is XORed with 0xFFFFFFFF.
[0120] The injection tool writes a minimal loader binary segment to the target process (via `process_vm_writev`). This loader segment is responsible for setting memory permissions and calling existing embedded JS runtime interfaces within the target process or calling `dlopen` to load runtime libraries. Subsequently, a script instance description structure is allocated to the target process. The structure fields are fixed as follows: `instance_id` (u32), `script_addr` (u64), `script_size` (u32), `crc32` (u32), `state` (u8), and `entry_symbol_addr` (u64). The structure size is limited to 64 bytes, aligned to 8 bytes.
[0121] The loader calls mmap to modify the write area permissions to PROT_READ | PROT_EXEC or PROT_READ | PROT_WRITE | PROT_EXEC, and then calls the runtime initialization interface init_runtime(remote_buf_addr,script_length). The loader call uses remote function call technology to save and restore the original registers. The instance_id is assigned sequentially by the injection tool, starting from 1 and reaching a maximum of 1024.
[0122] The injection tool writes a script instance table entry into the target process, sets `instance_struct.state = 1` (loaded but not activated), and then calls `mprotect` to set the permissions of the `script_addr` region to `PROT_READ` | `PROT_EXEC` (if required at runtime), or keeps it `PROT_READ` | `PROT_WRITE` for immediate modification. The `mprotect` parameter is `page-aligned`, and its size is set to `alloc_size`.
[0123] The mprotect call times out in 2000 milliseconds; if the permission request returns an error, the state is set to 254 (permission error) and the error code is logged.
[0124] The injection tool periodically reads the `instance_struct` (via `process_vm_readv`) outside the attached process, verifies that the fields `script_addr` and `script_size` match the `crc32`, and calls the runtime interface to check the activity of the script entry point (if `entry_symbol_addr` is not 0, a probe call is initiated against `entry_symbol_addr`). The probe call uses a short-time isolated thread context switching scheme, with a timeout limit of 500 milliseconds.
[0125] Health determination rules: If the read-back CRC32 matches the local CRC32 and the probe call returns 0, then set state = 2 (activated); if the probe times out or returns a non-zero value, then keep state = 1 and write last_error_code.
[0126] Preferably, in step S5, the injection tool intercepts the function of the target process, collects function call behavior data in real time, and determines detailed function information, including:
[0127] The injection tool establishes function interception hooks in the script instance, maps the hook addresses to the target function address set, constructs a hook table, and writes it to the memory mapping area of the running instance;
[0128] When the target process triggers a function call event, the hook function is activated, and the function entry address, parameter values, and return register contents are sampled into the acquisition buffer to form the raw call data.
[0129] The injection tool reads raw call data from the collection buffer, extracts function names, call timestamps, parameter lists, return values, and stack snapshots, and generates a function call behavior dataset.
[0130] The script instance identifies the authentication identifier, parameter types, return value types, and stack structure of the corresponding function based on the function call behavior dataset, forming a detailed function information set.
[0131] In this embodiment of the invention, the injection tool assigns a hook item to each target function in the target function address set and writes a hook table structure into the memory area of the script instance.
[0132] The hook table is stored in a dedicated memory page following the script instance description structure, page-aligned, with a page size of 4096 bytes. Each hook item has a fixed structure (32 bytes) with the following fields: func_id (u32), target_addr (u64), trampoline_addr (u64), flags (u8), and reserved (7 bytes). The maximum number of hook items is limited to 1024; if the number of target functions exceeds this limit, the first 1024 items are truncated according to priority. Each trampoline_addr points to the entry point of the trampoline code segment written by the injection tool, and the size of the trampoline code segment does not exceed 1024 bytes. The trampoline code segment is written using process_vm_writev; after writing is complete, mprotect is called to set the permissions of the corresponding memory page to PROT_READ | PROT_EXEC.
[0133] Address and code modification rules: The jump overwrite length N bytes is limited to 16 bytes; to ensure the integrity of the replaced machine code, the injection tool first uses instruction length parsing (disassembler, such as Capstone) to determine the original instruction bytes to be saved, saves them as the original preamble (saved_prologue), and then writes the machine code that branches unconditionally to trampoline at the target address.
[0134] The injection tool replaces the leading instruction at the beginning of each target function with an unconditional branch instruction that jumps to the corresponding trampoline and writes the status bit of the corresponding entry in the hook table.
[0135] Before writing, `mprotect` is called to set the permissions of the page containing the target function to `PROT_READ` | `PROT_WRITE` | `PROT_EXEC`; after writing, the permissions are restored to the original. The `mprotect` call has a timeout of 2000 milliseconds. The original preamble (saved_prologue) is first copied to the injection tool's management area, and then jump instructions (e.g., AArch64:b) are written.<trampoline_addr> (Encoding format); if the original preamble length is less than 16 bytes, pad it to 16 bytes using NOP to ensure alignment. Use memory barriers and atomic operations (atomic store) to set the corresponding flags field in the hook table to 1 (activate).
[0136] When the target process triggers the intercepted function, the CPU jumps to the trampoline. The trampoline writes the function entry context and stack snapshot to the acquisition buffer in the target process, and then jumps back to the original logic to complete the original function call.
[0137] The set of saved registers includes: integer registers x0 to x7, floating-point registers v0 to v7, sp, lr, and pc. The saved area is aligned to 8 bytes, and the size of a single save area is limited to 256 bytes.
[0138] The stack snapshot size is limited to 512 bytes, read sequentially from the current sp address to higher addresses, and does not exceed the smaller of the length of the local variable area declared in the stack structure set of the original function stack frame or 512 bytes. Memory reads use process_vm_writev to write the snapshot to the circular area of the acquisition buffer. The timestamp is obtained in nanoseconds (64-bit ns) using clock_gettime(CLOCK_MONOTONIC). Write the record header fields: seq(u64), func_id(u32), thread_id(u32), timestamp_ns(u64), pre_regs
[16] 8]. The maximum size of a single record is 4096 bytes. To avoid write conflicts, the acquisition buffer uses a dual-pointer approach with a producer index (prod_idx) and a consumer index (cons_idx), and pointer updates are performed using 64-bit atomic addition. During writing, the write offset is first atomically obtained, then the record is written atomically, and finally a checksum bit (record_ready = 1) is set at the end of the record. The write timeout threshold is 500 milliseconds.
[0139] After the original function executes and returns, the trampoline wrapper captures a snapshot of the return register and return stack at the return point, and writes the return information to the latter half of the same record or a separate record (post-call), and then restores the register and the return main logic.
[0140] Post-processing data acquisition items include return register x0 (integer / pointer) or v0 (floating-point), return register width (8 / 4 bytes), return register value, and return stack snapshot (maximum 256 bytes). The post-call write order guarantees the same sequence number as the pre-call; the sequence number is assigned by trampoline during the pre-call and written to record.seq. If an internal function exception causes a non-normal return path to be taken, trampoline must write the status code to record.last_error in the exception handling branch and set the record.exception_flag flag to 1. The exception branch write timeout is 300 milliseconds.
[0141] The injection tool uses process_vm_readv outside the process to read ready records in the acquisition buffer in batches, parses the fields and saves them as a set of structured function call behavior data records.
[0142] The maximum batch size for reading is 256 records or 1MB of data, whichever comes first. Read timeout is 2000 milliseconds.
[0143] The order of parsed fields is strictly as follows: seq, func_id, thread_id, timestamp_ns, pre_regs, pre_stack_snapshot, post_regs, post_stack_snapshot, exception_flag, last_error.
[0144] Map x0 to x7 in `pre_regs` to parameters 1 to 8; if the Nth item in the parameter descriptor set originates from the stack, extract the corresponding byte from `pre_stack_snapshot` by offset and convert it to a numerical value according to the data width. Floating-point parameters are extracted from v0 to v7 and parsed according to IEEE-754 format. If x0 in `post_regs` points to an address that falls within the shared library mapping area of the script instance (S2's ` / proc / `), then... <pid>If the output is in / maps, the return type is marked as "pointer"; if v0 in post_regs is non-zero and the floating-point register usage frequency is higher than 20%, it is marked as "floating-point". The width of the numerical value is aligned with the width field of the return value description set. Each parsed record is converted to JSON format (no more than 8KB per record), and the fields include: func_name, func_id, timestamp_iso8601 (UTC, format YYYY-MM-DDTHH:MM:SS.nnnnnnnnnZ, converted from timestamp_ns), thread_id, params[], ret_value, pre_stack_hex, post_stack_hex, exception_flag.
[0145] The script instance compares the behavior dataset with the previously generated function information set and fills in missing fields to generate a detailed function information set.
[0146] If the function information set contains an authentication identifier field that matches the `func_name` field in the behavior dataset, it is used directly; otherwise, the authentication identifier of an entry with a matching score higher than 0.75 in the function mapping table is used as the filler. For each parameter, the performance statistics of the values at the same parameter position in the behavior samples are calculated (sample size). (Effected at 5 PM) If more than 80% of the sample values are addresses pointing to mapped memory regions, the parameter type is marked as "pointer"; if the frequency of floating-point registers in the sample values exceeds 60%, it is marked as "floating-point"; the rest are marked as "integer". The return value type confirmation rules are the same as the parameter type rules, and a confidence score is recorded (a function of the number of samples and the consistency rate: confidence score = consistency rate). min(1, log10(sample_count) / 2)). Perform pattern matching on the offsets of pre_stack_hex and post_stack_hex, mark the repeated offsets as local variables or saved register areas, and correct the offsets by comparing them with the original stack structure set.
[0147] Preferably, the method further includes:
[0148] When an update to the target function or a change in the version of a shared library file is detected, the function address is automatically re-analyzed and the JS script is regenerated to ensure that the script is synchronized and adapted to the simulator environment.
[0149] In this embodiment of the invention, the injection tool periodically scans / proc / during the operation of the HarmonyOS NEXT simulator. <pid>The / maps file reads the loading paths and mapping base addresses of all shared library files and calculates verification information for the files corresponding to the paths.
[0150] The monitoring period is limited to 3000 milliseconds; the verification method uses SHA256 hashing, which calculates the hash value of the first 4096 bytes of the shared library file; the calculation process reads a fixed-length byte stream through the standard I / O interface fread, and then calls the built-in hash function module to complete the compression and XOR operation; the hash result is saved to the shared library status table, and the fields include: library path, load base address, hash value, and timestamp; if the hash value is found to be inconsistent with the previous record, the status of the library file is marked as "modified", and the update time is recorded.
[0151] When a change flag exists in the shared library status table, the function mapping management module reads the previously generated function mapping table and compares it with the contents of the function symbol table in the changed library.
[0152] The injection tool's `dl_iterate_phdr` interface is invoked to enumerate the symbol table header address of the modified library; the comparison method is to read the symbol name string (fixed length, not exceeding 128 bytes) and calculate the 16-bit CRC check value; if the number of symbols changes or the CRC of any symbol differs from the previous record, the function address is re-analyzed; the re-analysis trigger condition is the number of symbols changed. 1. Or the cumulative number of hash changes exceeds 3.
[0153] The function address reanalysis module calls the address resolution interface of the injection tool based on FunctionChangeList to recalculate the runtime address of the changed function.
[0154] The address is calculated as actual_addr = base_addr + symbol_offset; base_addr is derived from / proc / <pid> / maps reads; symbol_offset is provided by the st_value field in the ELF symbol table; if the target function is an indirectly derived function (i.e., jumped through the PLT table), the PLT entry is parsed, and the PLT offset is limited to 4-byte alignment; the analysis results are written to a new target function address set. The maximum number of functions that can be re-analyzed each time is 512; the address resolution timeout is 2000 milliseconds.
[0155] After UpdatedFunctionAddressSet is generated, the script generation module re-executes the template mapping, parameter insertion, and call logic construction process in S4.
[0156] The template file name remains the same as the old version, and the file name format is: auto_func_<FUNC_NAME> .js; During the template instance generation phase, the replaced fields include , After generation, the data is written to the cache directory / data / tmp / js_autogen / , and then the verification module is called to perform SHA256 verification. If the verification result is consistent and the generation timestamp is later than the old version file, a file replacement operation is performed: the rename() function is called to overwrite the old file path with the new file; during the replacement operation, the script instance's state field is set to 3 (suspended state), and it is restored to 2 (active state) after the replacement is completed.
[0157] The maximum number of script files generated in each round is 1024; the write time for a single file shall not exceed 3000 milliseconds.
[0158] The injection tool's monitoring thread maintains a periodic check mechanism, determining whether to enter the regeneration process based on the shared library status table and function change list.
[0159] The monitoring thread runs at a fixed interval of 3 seconds; when two consecutive hash changes are detected, regeneration is triggered immediately without waiting for the cycle to end; during the regeneration process, new hook registration is prohibited, and the flags field of the hook table is uniformly set to 0; after the update is completed, the hook table is reactivated and the data collection buffer is restored to its write state.
[0160] Preferably, step S3 further includes:
[0161] When collecting function call behavior data in real time, the actual collected stack pointer changes, parameter memory layout and stack structure set are compared and verified.
[0162] If there is a deviation, the stack structure set is dynamically calibrated based on the currently collected function call behavior data, and the calibrated result is updated to the function information set.
[0163] In this embodiment of the invention, the injection tool reads the ready-to-use raw complete call records from the acquisition buffer (see S5-I / J), and extracts the following fields from each record: func_id, thread_id, timestamp_ns, pre_stack_snapshot, post_stack_snapshot, pre_regs, post_regs, and params_source (from the parameter descriptor set). The extracted data is then byte-order corrected and written to a temporary sample buffer.
[0164] The maximum batch read size is 256 records; the maximum number of records retained in the sample buffer is 4096 bytes; the byte order is Little-Endian; the numerical parsing is based on the data width specified in the parameter description set (8, 4, 2, 1 bytes).
[0165] For each sample in SampleSet, based on the parameter offset recorded in the stack structure set of the function information set, the byte at the predetermined offset is read from pre_stack_snapshot and parsed into a value. The address or value is matched with the parameter source value indicated in the parameter description set (if the source is a register, the corresponding register value in pre_regs is taken). At the same time, the address validity of pointer-type parameters is verified in the process mapping table.
[0166] The read offset is calculated as the starting offset of the local variable area in the stack structure set plus `param_offset`; the offset unit is bytes; `offset + data_width` must be verified before offset parsing. `pre_stack_snapshot.length`; if it exceeds the limit, mark the sample as "out-of-bounds sample". Pointer validity verification passed / proc / <pid>The ` / maps` query determines an address within a mapped region if the pointer value falls within any mapped region and the region's permissions contain "r". For each parameter, the measured deviation value is recorded: delta = observed_address_offset - expected_offset (unit: bytes, can be negative).
[0167] After accumulating a certain number of DeltaSet samples, a statistic is calculated for each parameter of each function to determine whether calibration is triggered. The statistic includes the sample count N and the mean deviation. (in bytes), median deviation m, standard deviation Pointer efficiency P (the proportion of mapped internal address samples). The determination rule for triggering calibration is based on a clearly defined numerical threshold.
[0168] For entries in CalibrationCandidates, the offset values of the corresponding parameters in the stack structure set are updated using a smoothing correction method, and written to the versioned record of the function information set. The correction uses a weighted smoothing formula to avoid abrupt changes.
[0169] The existing offset value is denoted as old_offset; the sample mean deviation is... Smoothing weight W_s = 4 (constant); New offset is calculated as: new_offset = round( (old_offset W_s + (old_offset + ) 1) / (W_s + 1)), where rounded to the nearest integer byte. If |new_offset - old_offset| < 2 bytes, no update is written; only the most recent deviation statistics are recorded in the function information set. Otherwise, an update transaction is generated: update item records offset_old, offset_new, and applied_ts are generated, and the .param_offset field in the stack structure set within the function information set is replaced with new_offset. The update transaction is committed atomically: first, a snapshot of the new information set is constructed in local memory and its consistency is verified (the relationship between the total number of parameter bytes and the stack frame size). After verification, the original record is overwritten with the version number incremented by 1; the version number has an upper limit of... -1; if the version number overflows, rollback will be performed and an error log will be written. After the update, the update transaction will be written to the ChangeLog, with the following fields: func_id, param_index, old_offset, new_offset, μ, σ, N, applied_ts, and operator_id (operator_id is the identifier of the injection tool instance). The ChangeLog uses an append file format, and the length of a single log entry will not exceed 512 bytes.
[0170] Preferably, it also includes behavioral analysis:
[0171] A baseline library of normal behavior is pre-stored. The baseline library defines the parameter value range, call frequency threshold and return value set of key functions under normal conditions.
[0172] The real-time generated function call behavior dataset is compared with a normal behavior baseline library;
[0173] When a parameter value is detected to be out of range, the call frequency exceeds the threshold, or the return value is abnormal, an exception event is generated, and a complete snapshot of the call context at the time of the exception is recorded.
[0174] In this embodiment of the invention, during controlled operation, at least 100 call samples (sample count N_base=100) for each key function are collected in batches from the collection buffer. For each sample, the following are extracted: parameter value, call timestamp, return value, thread ID, and pre / post stack snapshot.
[0175] For each numerical parameter, calculate the minimum value (min), maximum value (max), mean value (mean), and standard deviation (std) (std uses an unbiased estimate); for each enumerated / discrete parameter, calculate the occurrence set AllowedSet (keeping at most the first 256 different values); for the return value, create an AllowedReturnSet (keeping at most the first 256 different return values or return mode signatures); calculate the threshold F_thresh for the call frequency: count the number of calls per minute within the baseline sample time range, and take the 95th percentile as the threshold (i.e., the threshold is the 95th percentile of the number of calls per minute in the sample).
[0176] The injection tool will read the function call behavior dataset (JSON records) output by S5-K / S5-L one by one and route it to the corresponding baseline file by func_name.
[0177] Numerical parameter: If param_value < min or param_value > max, it is determined as "numerical out-of-bounds"; at the same time, calculate Z-score = (param_value - mean) / std (if std = 0, then compare the absolute difference |param_value - mean| with the threshold 4); if |Z-score| < 4, it is marked as high deviation.
[0178] Enumeration / discrete parameter: If param_value is not in AllowedSet and AllowedSet.size > 1, it is determined as "abnormal discrete value".
[0179] Pointer type parameter: If the baseline is marked as "pointer", then for the parameter value in the sub-sample in / proc / <pid>The ` / maps` function verifies that the pointer is a mapped internal address; if the pointer is invalid, it is judged as "pointer invalid".
[0180] Output: Write the validation result of a single sample to a temporary comparison record, including the fields: param_checks[{index, status, metric (e.g., Z-score)}] and overall_param_status.
[0181] The processing time for a single comparison must not exceed 50 milliseconds; the maximum batch size is 256 records.
[0182] A sliding time window method is adopted, with a window length W_time = 60 seconds and a step size S_time = 10 seconds; a circular counting buffer is maintained for each func_name to record the call count per second in seconds.
[0183] At any given time point, the call rate (Unit: calls / sec), converted to calls_per_minute = Rate 60.
[0184] If calls_per_minute > freq_threshold_calls_per_minute (F_thresh from the corresponding baseline file), then it is determined as "frequency abnormal".
[0185] Output: Frequency comparison results (fields: func_name, window_start_ts, window_end_ts, calls_count, calls_per_minute, threshold, freq_status).
[0186] Each function maintains a fixed length of 60 integers in its circular buffer, with a maximum limit of 2048 functions to be tracked.
[0187] The sample return value is compared with the baseline AllowedReturnSet; if AllowedReturnSet.size=0, the return value comparison is skipped (assuming that the function has not created a return sample set); if the return value is not in the set, it is judged as "return value abnormal".
[0188] If the returned value is a pointer or a structure, first extract the returned memory signature (e.g., the hexadecimal digest of the first 16 bytes) based on the return value description set in the function information set, and then perform an exact match with the returned signature set stored in the baseline; if they are different, an anomaly is determined.
[0189] Output: Return value comparison record (fields: func_name, ret_value, ret_status).
[0190] The signature calculation time for each return value shall not exceed 10 milliseconds; the signature length is limited to a 16-byte digest.
[0191] An abnormal behavior event is generated if any of the following conditions are met:
[0192] Any parameter is judged as "numerical out of bounds", "discrete value abnormal" or "pointer illegal"; or the frequency is judged as "frequency abnormal"; or the return value is judged as "return value abnormal".
[0193] After an event is generated, it is written to the event queue (local message queue capacity 1024). If the same func_name generates the same trigger_type within a debounce window D = 5 seconds, it is merged into a single event. The merging rule is to update the timestamp and append trigger_details.
[0194] After writing, the CRC32 of the event file is calculated and written to the event index database (lightweight key-value pairs, fields: event_id, func_name, detected_ts, trigger_type, file_path, crc32). The index file path / data / anomaly / index.db is in append log format, and a single index record cannot exceed 512 bytes.
[0195] The event log is used for review or automatic playback modules, and serves as the calibration trigger condition for S3 and the reference input for script regeneration in S4 (the regeneration process is triggered when the number of out-of-bounds param exceeds the threshold 3 times or the frequency of abnormality accumulates to more than 5 times).
[0196] Please see Figure 2 This document showcases the architecture of the HarmonyOS NEXT simulator's automatic JS script generation system, comprising five main processes: S1 Environment Initialization, including "starting the simulator environment," "loading the JS script template," and "obtaining the target method list," and outputting the "method list"; S2 Shared Library Parsing, including "parsing .so files," "exporting the function symbol table," and "extracting the target function address," and outputting the "function address"; S3 Function Feature Analysis, including "disassembling the instruction sequence," "analyzing parameters / return values," and "extracting the stack structure," and outputting the "function information set"; S4 Script Generation, including "parameter mapping," "inserting monitoring logic," and "generating the JS script file," and outputting the "JS script"; and S5 Dynamic Interception and Behavior Acquisition, including "script injection dynamic loading," "function interception Hook mechanism," and "behavior acquisition real-time monitoring." The core components are listed: the HarmonyOS NEXT simulator, described as the "target process runtime environment"; the injection tool, described as the "ptrace / process_vm memory read / write interface"; the disassembler engine, described as "Capstone (ARM64) instruction parsing"; and the behavior data output, described as "function call log / anomaly detection."
[0197] Please see Figure 3 The present invention also provides a JS script automatic generation system suitable for the HarmonyOS NEXT simulator, used to execute the above-mentioned JS script automatic generation method suitable for the HarmonyOS NEXT simulator. The JS script automatic generation system 100 suitable for the HarmonyOS NEXT simulator includes:
[0198] The simulator initialization module 101 is used to start the HarmonyOS NEXT simulator environment, load the preset JS script template, and obtain the target method list from the interface collection corresponding to the preset API.
[0199] The function symbol resolution module 102 is used to call a preset injection tool to parse the shared library files in the HarmonyOS NEXT simulator runtime environment, export the function symbol table of the shared library files, and extract the address of the target function corresponding to the target method list;
[0200] The function information construction module 103 is used to determine the entry position, parameter type, return value type and stack information of the target function based on the address of the target function, and form a function information set;
[0201] The script auto-generation module 104 is used to map the function information set with the preset JS script template and automatically generate a JS script containing the target function call logic.
[0202] The dynamic interception and acquisition module 105 is used to dynamically load JS scripts in the HarmonyOS NEXT emulator, and intercept functions of the target process through injection tools, collect function call behavior data in real time, and determine detailed function information. Therefore, the embodiments should be considered exemplary and non-limiting in all respects. The scope of the invention is not limited by the foregoing description, and all changes falling within the meaning and scope of equivalents in the application are intended to be included within the scope of the invention.
[0203] The above description is merely a specific embodiment of the present invention, enabling those skilled in the art to understand or implement the invention. Various modifications to these embodiments will be readily apparent to those skilled in the art, and the general principles defined herein may be implemented in other embodiments without departing from the spirit or scope of the invention. Therefore, the present invention is not to be limited to the embodiments shown herein, but is to be accorded the widest scope consistent with the principles and novel features of the invention herein.< / pid> < / pid> < / pid> < / pid> < / pid> < / pid> < / type> < / type> < / type> < / type> < / pid> < / pid> < / pid> < / pid> < / pid> < / pid> < / type> < / path> < / path>
Claims
1. A method for automatically generating JS scripts for the HarmonyOS NEXT simulator, characterized in that, Includes the following steps: Step S1: Start the HarmonyOS NEXT simulator environment, load the preset JS script template, and obtain the target method list from the preset API interface collection; Step S2: Call the preset injection tool to parse the shared library files in the HarmonyOS NEXT simulator runtime environment, export the function symbol table of the shared library files, and extract the address of the target function corresponding to the target method list; Step S3: Determine the entry point, parameter types, return value types, and stack information of the target function based on its address, forming a function information set; Step S4: Map the function information set to the preset JS script template to automatically generate a JS script containing the target function call logic; Step S4 includes: Establish a correspondence between the function names, authentication identifiers, and information addresses in the function information set and the function placeholder fields in the JS script template to form a template mapping table; Extract the parameter description set and return value description set from the function information set according to the template mapping table, write the parameter name, data type, passing method and return value structure into the corresponding position of the template, and generate a template instance containing complete call parameter definition; Read the stack structure set and function entry information, insert stack trace and function entry identifier code snippets, and build runtime monitoring logic code snippets in the template instance; Insert the call statement and return value encapsulation statement of the target function based on the function address and calling convention in the template instance, and generate a script logic body with a complete function call path; Integrate template instances and script logic into a JS script file; Step S5: Dynamically load the JS script in the HarmonyOS NEXT simulator, and use an injection tool to intercept functions in the target process, collect function call behavior data in real time, and determine detailed function information; Step S5 involves using an injection tool to intercept functions in the target process, collect function call behavior data in real time, and determine detailed function information, including: The injection tool establishes function interception hooks in the script instance, maps the hook addresses to the target function address set, constructs a hook table, and writes it to the memory mapping area of the running instance; When the target process triggers a function call event, the hook function is activated, and the function entry address, parameter values, and return register contents are sampled into the acquisition buffer to form the raw call data. The injection tool reads raw call data from the collection buffer, extracts function names, call timestamps, parameter lists, return values, and stack snapshots, and generates a function call behavior dataset. The script instance identifies the authentication identifier, parameter types, return value types, and stack structure of the corresponding function based on the function call behavior dataset, forming a detailed function information set.
2. The method for automatically generating JS scripts for the HarmonyOS NEXT simulator according to claim 1, characterized in that, Step S2 includes: The pre-defined injection tool is invoked to read the memory space of the currently running process in the emulator, identify all loaded shared library files, and create a list of shared library files. A convenient list of shared library files is generated, and the function symbol table information for each shared library file is exported to construct a function symbol dataset. Retrieve the function entries in the function symbol dataset that correspond to the target method list, establish a one-to-one correspondence between method names and function symbols, and form a function mapping table; The relative addresses of each function in the function mapping table are parsed using injection tools, and the actual addresses of the functions at runtime are determined by combining the loading base address of the shared library file in the simulator, and then compiled into a target function address set.
3. The method for automatically generating JS scripts for the HarmonyOS NEXT simulator according to claim 1, characterized in that, Step S3 includes: The injection tool locates the address of the target function within the simulator, and the corresponding assembly instruction sequence is loaded into the parsing buffer. The instructions in the parsing buffer identify the start and end boundaries of the function, forming a function entry information set. Based on the function entry information set, the parameter passing path of the function's instruction structure is analyzed, and the parameter sources of register parameter passing, stack parameter passing and memory indirect parameter passing are extracted respectively, and a parameter description set is generated. By using injection tools to trace the return path of functions, identify the return register or return memory region, infer the data type and storage method of the return value, and form a return value description set; Based on the function entry information set and return value description set, extract stack change data during function call, identify the local variable area, the storage register area and the return address area, and form a stack structure set; A function information set is constructed and output based on the function entry information set, parameter description set, return value description set, and stack structure set.
4. The method for automatically generating JS scripts for the HarmonyOS NEXT simulator according to claim 1, characterized in that, Step S5, dynamically loading JS scripts in the HarmonyOS NEXT simulator, includes: The injection tool starts and runs an instance in the HarmonyOS NEXT emulator, loads a JS script file, maps the script to the memory space of the target process, and forms a script instance.
5. The method for automatically generating JS scripts for the HarmonyOS NEXT simulator according to any one of claims 1 to 4, characterized in that, The method further includes: When an update to the target function or a change in the version of a shared library file is detected, the function address is automatically re-analyzed and the JS script is regenerated to ensure that the script is synchronized and adapted to the simulator environment.
6. The method for automatically generating JS scripts for the HarmonyOS NEXT simulator according to claim 3, characterized in that, Step S3 also includes: When collecting function call behavior data in real time, the actual collected stack pointer changes, parameter memory layout and stack structure set are compared and verified. If there is a deviation, the stack structure set is dynamically calibrated based on the currently collected function call behavior data, and the calibrated result is updated to the function information set.
7. The method for automatically generating JS scripts for the HarmonyOS NEXT simulator according to claim 1, characterized in that, It also includes behavioral analysis: A baseline library of normal behavior is pre-stored. The baseline library defines the parameter value range, call frequency threshold and return value set of key functions under normal conditions. The real-time generated function call behavior dataset is compared with a normal behavior baseline library; When a parameter value is detected to be out of range, the call frequency exceeds the threshold, or the return value is abnormal, a behavior exception event is generated, and a complete call context snapshot is recorded at the time the exception occurs.
8. A JavaScript automatic generation system suitable for the HarmonyOS NEXT simulator, characterized in that, The system for automatically generating JS scripts for the HarmonyOS NEXT simulator as described in claim 1, wherein the JS script generation system for the HarmonyOS NEXT simulator comprises: The simulator initialization module is used to start the HarmonyOS NEXT simulator environment, load the preset JS script template, and obtain the target method list from the preset API interface collection. The function symbol resolution module is used to call the preset injection tool to parse the shared library files in the HarmonyOS NEXT simulator runtime environment, export the function symbol table of the shared library files, and extract the address of the target function corresponding to the target method list; The function information construction module is used to determine the entry point, parameter types, return value types, and stack information of the target function based on the target function address, forming a function information set; The script auto-generation module is used to map function information sets to preset JS script templates and automatically generate JS scripts containing target function call logic. The dynamic interception and collection module is used to dynamically load JS scripts in the HarmonyOS NEXT simulator, and intercept the functions of the target process through injection tools to collect function call behavior data in real time and determine detailed function information.
Citation Information
Patent Citations
Shared library file simulation method and device, computer equipment and storage medium
CN111666586A
Analysis method and device of called library function, computer equipment and storage medium
CN117130929A