A cross-environment clipboard high-performance intercommunication method based on double-end shadow cache

CN122884724APending Publication Date: 2026-10-09北京麟卓信息科技有限公司
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611382870.9
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-09-08
Publication Date
2026-10-09

AI Technical Summary

Technical Problem

[0003]现有技术采用的跨环境剪贴互通方式主要存在以下技术问题:一是,现有方式均依赖独立中转服务做消息转发,完整调用链路为从环境 A应用、A剪贴板服务、中转代理程序、环境B通信驱动最后到B剪贴板服务,每经过一层转发都会引入固定时延叠加,中转程序为单点瓶颈,高并发场景易出现队列阻塞、资源耗尽;二是,中转通信采用普通用户态通信通道,数据需要反复在用户空间、内核空间之间拷贝,大容量二进制素材传输耗时极高,两套环境原生数据编码、图像存储格式不兼容,每次传输都需要实时转换,显著提高了处理器占用,另外多次拷贝及格式转换双重损耗会大幅降低传输吞吐上限;三是,采用定时轮询方式检测剪贴内容是否更新,由于轮询周期固定导致同步实时性较差,持续轮询会长期占用处理器资源,由于缺少数据传输完整性校验逻辑导致大体积内容传输易出现截断、残缺粘贴;四是,两套环境拥有独立的权限判定体系,两套校验逻辑完全割裂,用户访问剪贴时需要重复确认授权导致交互体验差,权限校验采用独占锁同步导致高并发访问场景产生大量阻塞等待;五是,两套环境文件系统互相隔离导致文件类剪贴资源无法跨环境直接读取,由于媒体内容传输时需要完整解析全部标记文本导致解析耗时长,且样式、内嵌资源极易丢失,由于数据类型适配缺少轻量化预处理逻辑导致每次粘贴全量解析,性能损耗大

Benefits of technology

[0024]本发明在宿主启动阶段构建L1、L2、L3三层分级权限缓存,依据剪贴板数据类型划分普通、敏感、高敏感三类安全等级并匹配对应的缓存查询、时效与访问校验策略,同时搭建三级共享内存池,确立数据类型与内存池等级绑定规则,为共享内存块分配全局唯一块标识;宿主应用发起复制操作时,剪贴板代理过滤无效数据,有效数据经封装、校验后生成剪贴板操作上下文,结合数据敏感等级查询分级权限缓存,生成跨容器访问规则,对原始数据执行跨系统异构预处理;然后依据数据类型分配对应等级共享内存块,采用差异化写入策略写入预处理后的剪贴板数据,并按照分片策略在共享内存头部构建分块索引表,更新宿主影子缓存并向容器下发携带同步元数据的剪贴变更事件,由容器剪贴板代理维护容器影子缓存;容器应用发起粘贴请求后,容器剪贴板代理根据块标识查询影子缓存元数据,通过应用身份执行分级权限二次校验,校验通过后建立共享内存只读虚拟地址映射,原子更新共享内存访问计数与状态标识,通过虚拟地址通道、复用共享内存头部的分块索引表执行适配各类数据的差异化零拷贝读取,完成数据校验后将虚拟缓冲区地址传递至容器剪贴板服务,容器剪贴板服务将封装生成的容器原生剪贴结果对象返回给发起请求的容器应用,读取结束后递减访问引用计数、释放映射资源并向宿主回执确认信号,同步更新两端缓存,完成跨系统剪贴板数据交互流程。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122884724A_ABST
    Figure CN122884724A_ABST
Patent Text Reader

Abstract

The application discloses a cross-environment clipboard high-performance intercommunication method based on a double-end shadow cache, constructs a three-level permission cache and a three-level shared memory pool when a host is started, encapsulates clipboard data into a lightweight IPC package and sends the lightweight IPC package to a host clipboard service to generate a host native cutting object when a host application is copied, determines a sensitive level according to a data type, determines a permission mark by searching the permission cache, generates a cross-container access rule and writes the cross-container access rule into a clipboard operation context, writes data into an allocated memory block, constructs a block index table, updates the host shadow cache, and downwardly issues a clipboard change event to a container to update the container shadow cache; a container application initiates a paste request, a container clipboard agent maps a shared memory block according to the container shadow cache, and a virtual address is returned to the container clipboard service to encapsulate the virtual address into a container native cutting result object and return the container native cutting result object to an application; and after reading is completed, a reading completion confirmation is sent to the host to synchronously update a double-end cache state.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of computer software development technology, specifically relating to a high-performance cross-environment clipboard interoperability method based on dual-end shadow caching. Background Technology

[0002] For the two isolated runtime environments, the host and container, each has its own independent clipboard hosting service. For example, the host is uniformly hosted by a resident background service of the system, providing a standard entry point for reading and writing data externally. Internally, it uses a memory buffer to store clipboard content, and the text is stored using the general Unicode character encoding by default. It can only complete inter-process communication within its own environment and cannot communicate directly with another environment. The container is hosted by another set of background services of the system, using an independent cross-process communication system. It supports three native capabilities: clipboard content change monitoring, background access control, and automatic content expiration and recycling. It is completely isolated from the host's hardware, processes, and sandbox, and has no native inter-process communication channel.

[0003] The existing cross-environment clipboard communication methods have the following main technical problems: First, existing methods all rely on independent relay services for message forwarding. The complete call chain is from application A, clipboard service A, relay agent program, communication driver B, and finally clipboard service B. Each layer of forwarding introduces a fixed latency, making the relay program a single point of bottleneck. In high-concurrency scenarios, queue blocking and resource exhaustion are likely to occur. Second, the relay communication uses ordinary user-space communication channels, requiring data to be repeatedly copied between user space and kernel space. The transmission of large-capacity binary materials is extremely time-consuming. The two environments' native data encoding and image storage formats are incompatible, requiring real-time conversion for each transmission, which significantly increases processor usage. In addition, the double loss from multiple copies and format conversions will significantly reduce the transmission throughput limit. Third, the use of timed rounds The polling method for detecting whether the clipping content is updated has several drawbacks. First, the fixed polling cycle leads to poor real-time synchronization, and continuous polling consumes processor resources for extended periods. Second, the lack of data transmission integrity verification logic makes large-volume content transmission prone to truncation and incomplete pasting. Third, the two environments have independent permission determination systems with completely separate verification logic. Users need to repeatedly confirm authorization when accessing clipping, resulting in a poor user experience. The use of exclusive locks for permission verification causes significant blocking and waiting in high-concurrency scenarios. Fourth, the isolated file systems of the two environments prevent direct reading of file-based clipping resources across environments. The need to fully parse all marked text during media content transmission leads to long parsing times, and styles and embedded resources are easily lost. The lack of lightweight preprocessing logic for data type adaptation results in full parsing for each paste, causing significant performance overhead.

[0004] In summary, existing cross-environment copy-paste methods have serious performance shortcomings. The total end-to-end latency of a single complete copy-paste operation is relatively high, and the cross-environment data throughput is significantly lower than that of native single-environment copy-paste. As a result, they cannot meet the high-performance requirements of low latency, high concurrency, and large-capacity material interoperability. Summary of the Invention

[0005] In view of this, the present invention provides a high-performance cross-environment clipboard interoperability method based on dual-end shadow caching. By using a three-layer hierarchical permission caching and a three-level shared memory pool on the host side, combined with sensitivity level control, sharding indexing, cross-container shadow caching, and a shared memory read-only virtual address mapping mechanism, it realizes zero-copy cross-system interaction of heterogeneous clipboard data with permission verification between the host and the container.

[0006] This invention provides a high-performance cross-environment clipboard interoperability method based on dual-end shadow caching, which specifically includes the following steps:

[0007] When the host starts, it builds a three-level permission cache and a three-level shared memory pool, and establishes memory binding rules between data types and memory pools. When the host application triggers a copy operation, the host clipboard agent encapsulates the valid clipboard data into a lightweight IPC packet and sends it to the host clipboard service. The service parses the packet and encapsulates it into a native host cut object containing the data type, data length, and original clipboard data. The sensitivity level is determined based on the data type of the native host cut object. The three-level permission cache is retrieved according to the access verification policy corresponding to the sensitivity level to obtain the permission identifier of the container application. Cross-container access rules and permission determination methods are generated and written to the clipboard operation context. Heterogeneous data preprocessing is performed on the original clipboard data to obtain the clipboard data. Memory blocks are allocated in the memory pool according to the memory binding rules and block identifiers are generated. The memory block is mapped to the user-space virtual address of the clipboard service and loaded into the processor cache. Clipboard data is written to the memory block, and a block index table is built in the header of the memory block. The host shadow cache records synchronization metadata and management information, and sends a clipboard change event carrying synchronization metadata to the container, triggering the container clipboard agent to update the synchronization metadata to the container shadow cache.

[0008] When a container application initiates a paste request, the container clipboard agent retrieves the synchronous metadata corresponding to the block identifier from the container shadow cache and verifies the container application's permissions again. Upon successful verification, the agent maps the corresponding memory block to the virtual address space of the container clipboard agent process, increments the shared memory block access count using atomic operations, updates the memory block status identifier, and passes the virtual address to the container clipboard service. After obtaining the synchronous metadata, the container clipboard service encapsulates the virtual address into a container-native clipping result object and returns it to the container application that initiated the paste request. After the read operation is complete, the agent atomically decrements the access reference count, releases the container process's virtual address mapping resources, sends a read completion confirmation signal to the host, and synchronously updates the dual-end cache status.

[0009] Furthermore, the three-level permission cache includes L1 cache, L2 cache and L3 cache. L1 cache only stores the permission identifiers of container applications whose usage frequency is greater than the threshold. L2 cache stores the container application permission entries corresponding to the current L1 cache, as well as container application permission entries that have been removed from L1 cache but have not expired. L3 cache stores the long-term permission records of all container applications.

[0010] Furthermore, sensitivity levels and permissions are determined based on data type. Specifically: text and images are classified as ordinary level, corresponding to ordinary permissions. Access is prioritized by reading the L1 and L2 caches. If the cache is not hit, the L3 cache is queried, and the query results are synchronized to both L1 and L2 caches. The effective lifespan of cache entries corresponding to ordinary permissions is the maximum value. File Uniform Resource Locators (URIs) and rich text are classified as sensitive level, corresponding to sensitive permissions. The effective lifespan of L1 and L2 cache entries is the smaller value. If the cache expires, the L3 cache is forcibly read. After a cache hit, it is verified whether the container application is in the foreground. If it is in the background, access is denied. Custom binary data is classified as high sensitivity level, corresponding to high sensitivity permissions. Each access reads the L3 cache to verify permissions and triggers a secondary authorization pop-up for the user. High sensitivity permission records are not written to the L1 and L2 caches.

[0011] Furthermore, the host clipboard service distinguishes the type of clipboard data based on a single-byte mask marker, and performs validity checks on different data types through bitwise operations. Specifically, for text data, the data is valid if the data length is a positive integer and the first byte is a non-empty placeholder; for image data, the data is valid if the image width and height are positive integers and the pixel format identifier is the host's native image format; for file data, the data is valid if the file length meets the constraints and the starting character matches the absolute path specification; for rich text and custom binary data, the data is valid if the data length is a positive integer and the basic format identifier is compliant. When any data type validation fails, the corresponding error code is returned to the upper-layer application and the current flow record is marked as a failure.

[0012] Furthermore, the method for generating cross-container access rules and determining permissions is as follows:

[0013] For normal levels, the cache read order is to first read the L1 cache, then the L2 cache, and only if both caches are missed is the L3 cache read. After the permission record is read from the L3 cache, the L2 cache is updated synchronously, and then the L1 cache is atomically refreshed.

[0014] For sensitive levels, the cache read order is to read the L1 cache first, then the L2 cache. During the read, the timestamp is checked, and if the timeout occurs, the cache is discarded. After the cache expires, the L3 cache is read, the L2 cache is refreshed, and the L1 cache is synchronized.

[0015] If the level is high sensitivity, the L3 cache is read every time, and the permission records found are not written to the L1 or L2 cache.

[0016] Permission determination method: If the permission is marked as unauthorized, the container application will be denied access to the current clipboard data in any scenario; if the permission is marked as authorized, the container application is allowed to read the current clipboard data if it is at a normal level, allowed if it is at a sensitive level and the container application is in the foreground, and allowed after user confirmation if it is at a highly sensitive level; if the permission is marked as expired, it is equivalent to unauthorized.

[0017] Furthermore, both the host shadow cache and the container shadow cache use a two-level indexing method of hash tables and data type linked lists to store cache entries. The hash table uses the block identifier as the key to index the corresponding cache entry. The background thread completes the cache preloading, and atomic operations are used to implement access control for cache read and write.

[0018] Furthermore, the block index table is constructed as follows: text data is not split, and only a single index record is generated; image data is evenly fragmented according to the DMA hardware transfer granularity and fragment index records are generated sequentially; rich text and file URIs are split into independent fragments according to internal logical units to generate fragment index records, and each fragment is configured with independent verification information; custom binary data is dynamically fragmented into variable-length fragments to generate fragment index records.

[0019] Furthermore, after receiving a clipboard change event, the container parses the block identifier carried by the event and binds the corresponding synchronization metadata. It constructs a data reading context according to a preset priority. When a paste request triggers shared memory mapping, it reads the clipboard data. All cached entries are configured with lifecycle timeout rules and are immediately cleaned up after the timeout. The data reading context is a set of reading resources and parameters initialized by the container clipboard agent after receiving the clipboard change event. It includes pre-allocated worker thread resources, verification algorithm handles, data structures, resource placeholders, data types, and sharding strategy identifiers.

[0020] Furthermore, a differentiated zero-copy reading strategy is implemented for clipboard data of different data types. Specifically: for ordinary text, it is loaded into memory in batches sequentially using CPU vector instruction sets, and contiguous memory blocks are prefetched segment by segment according to the block index table; for ordinary images, the DMA hardware channel is reused first, and pixel data is directly transferred to the image buffer via shared memory physical pages, and CPU vector instructions are used to read it when there is no DMA hardware; for sensitive data, a segmented parallel reading mechanism is adopted, with multiple worker threads concurrently reading each segment according to the block index table, and then assembling them in an orderly manner after reading; for highly sensitive custom binary data, the target segment is read point by point according to the block index table.

[0021] Furthermore, after the container clipboard service encapsulates the virtual address into a container native clipping result object and returns it to the container application, the lazy conversion proxy intercepts the application's clipboard data access interface call. When the container application reads the clipboard data for the first time, it starts a format conversion task, determines the execution method of the task based on the access urgency, and dynamically adjusts the scheduling priority of the task based on the application thread state.

[0022] For text data, the corresponding encoding format is selected based on the data reading interface type called by the container application to complete the encoding format conversion; for image data, the image is scaled and the pixel format is fine-tuned according to the resolution required by the application; for file URIs, the virtual path is restored based on the path mapping cache, resources are dynamically mounted, and a file access interface is provided; for rich text, the visible area fragments are parsed based on the tag mapping table to complete the tag mapping conversion; for custom binary data, on-demand lazy deserialization of fields is performed and container format-compatible encapsulation is implemented; after the conversion is completed, the conversion result is stored in a lightweight conversion cache, and lock-free concurrent read and write of the cache is achieved through atomic operations.

[0023] Beneficial effects:

[0024] This invention constructs a three-tiered hierarchical permission cache (L1, L2, L3) during the host startup phase. Based on clipboard data types, it categorizes security levels into ordinary, sensitive, and highly sensitive categories, matching corresponding cache query, timeliness, and access verification strategies. Simultaneously, it establishes a three-level shared memory pool, defining data type and memory pool level binding rules, and assigning globally unique block identifiers to shared memory blocks. When the host application initiates a copy operation, the clipboard proxy filters invalid data. Valid data, after encapsulation and verification, generates a clipboard operation context. This context, combined with the data sensitivity level query of the hierarchical permission cache, generates cross-container access rules and performs cross-system heterogeneous preprocessing on the original data. Then, based on data type, it allocates corresponding level shared memory blocks, writes the preprocessed clipboard data using a differentiated write strategy, and constructs a block index table in the shared memory header according to a sharding strategy, updating the host shadow cache and... A clipboard change event carrying synchronized metadata is sent to the container, and the container clipboard agent maintains the container shadow cache. After the container application initiates a paste request, the container clipboard agent queries the shadow cache metadata based on the block identifier, performs secondary verification of hierarchical permissions through the application identity, establishes a shared memory read-only virtual address mapping after the verification is passed, atomically updates the shared memory access count and status identifier, performs differentiated zero-copy reading adapted to various types of data through the virtual address channel and reuses the block index table in the shared memory header, and passes the virtual buffer address to the container clipboard service after the data verification is completed. The container clipboard service returns the encapsulated container native clipboard result object to the container application that initiated the request. After the reading is completed, the access reference count is decremented, the mapping resources are released, and an acknowledgment signal is sent back to the host. The caches at both ends are updated synchronously, completing the cross-system clipboard data interaction process. Attached Figure Description

[0025] Figure 1 This is a flowchart illustrating a high-performance cross-environment clipboard interoperability method based on dual-end shadow caching provided by the present invention. Detailed Implementation

[0026] The present invention will be described in detail below with reference to the accompanying drawings and embodiments.

[0027] This invention provides a high-performance cross-environment clipboard interoperability method based on dual-end shadow caching. The core idea is as follows: During the host startup phase, a three-layer hierarchical permission cache (L1, L2, L3) is constructed. Based on the clipboard data type, three security levels—normal, sensitive, and highly sensitive—are defined, and corresponding cache query, validity period, and access verification strategies are matched. Simultaneously, a three-level shared memory pool is built, establishing data type and memory pool level binding rules, and a globally unique block identifier is assigned to each shared memory block. When the host application initiates a copy operation, the clipboard proxy filters invalid data. Valid data, after encapsulation and verification, generates a clipboard operation context. This context is combined with the data sensitivity level query to generate cross-container access rules, and cross-system heterogeneous preprocessing is performed on the original data. Then, shared memory blocks of the corresponding level are allocated according to the data type, and the preprocessed clipboard data is written using a differentiated write strategy. Finally, the shared memory header is updated according to a sharding strategy. A block index table is constructed, the host shadow cache is updated, and a clipboard change event carrying synchronous metadata is sent to the container. The container clipboard agent maintains the container shadow cache. After the container application initiates a paste request, the container clipboard agent queries the shadow cache metadata based on the block identifier, performs secondary verification of hierarchical permissions through the application identity, establishes a shared memory read-only virtual address mapping, atomically updates the shared memory access count and status identifier, performs differentiated zero-copy reads adapted to various types of data through the virtual address channel and the block index table of the shared memory header, and passes the virtual buffer address to the container clipboard service after data verification. The container clipboard service returns the encapsulated container native clipboard result object to the container application that initiated the request. After the read is completed, the access reference count is decremented, the mapping resources are released, and an acknowledgment signal is sent back to the host. The caches at both ends are updated synchronously, completing the cross-system clipboard data interaction process.

[0028] This invention provides a high-performance cross-environment clipboard interoperability method based on dual-end shadow caching, the processing flow of which is as follows: Figure 1 As shown, the specific steps include:

[0029] Step 1: When the host starts, a three-tiered permission cache is built from top to bottom: hardware register cache (L1 cache), clipboard process cuckoo hash cache (L2 cache), and local persistent backup cache (L3 cache). The cache is used to store the permission identifiers of each application in the container accessing clipboard data. During the system startup phase, the background preloads the permission data of high-frequency container applications to complete the L2 cache warm-up. When the L2 cache entries reach the preset capacity limit, the permission entries with the lowest access frequency and the longest expiration time are evicted. Among them, the L1 cache only stores the permission identifiers of high-frequency applications, the L2 cache stores complete entries such as permission identifiers and expiration timestamps using the application package name hash value and data type as keys, and the L3 cache stores the long-term permission records of all container applications.

[0030] Sensitivity levels and access verification strategies are categorized based on the data type of clipboard data. Text and images are classified as ordinary, corresponding to ordinary permissions. Access to them prioritizes reading the L1 and L2 caches. Only if the cache is not hit will the L3 cache be queried, and the query results will be synchronized to both L1 and L2 caches. The effective lifespan of cache entries for ordinary permissions is set to the maximum value. File Uniform Resource Locators (URIs) and rich text are classified as sensitive, corresponding to sensitive permissions. The effective lifespan of L1 and L2 cache entries for them is set to a smaller value. If the cache expires, the L3 cache is forcibly read. If the cache is hit, it is verified whether the target application is in the foreground. If the application is in the background, access is directly denied. Custom binary data is classified as highly sensitive, corresponding to highly sensitive permissions. The verification process skips the L1 and L2 caches and reads the L3 cache every time, triggering a secondary authorization pop-up for the user. Records of highly sensitive permissions are not written to the L1 and L2 caches.

[0031] A three-level shared memory pool is constructed, the data type of clipboard data is set and the memory binding rules of the memory pool level are set, and the free memory block linked list is initialized. The host memory pool generates a globally unique block identifier for each allocated shared memory block as the identity identifier of the memory block, which is used to locate shared memory resources at both ends, bind permission cache and clip operation context.

[0032] The hardware register cache uses a container application package name hash mapping and data type mask to store permission identifiers for all data types related to a certain number of container applications whose access frequency exceeds a threshold within a recently set time period. Permission identifiers include three categories: unauthorized, authorized, and expired. The process memory hash cache uses a Cuckoo hash table to store permission identifiers for all container applications whose access frequency exceeds a threshold within a recently set time period. The hash table uses a combination of the container application package name hash value and the data type enumeration value as the key, and the permission identifier, relative expiration timestamp, and data type mask as the value. Local persistent backup storage stores long-term permission identifier records for all container applications. Sensitivity levels are used to classify clipboard data for security purposes, serving as the basis for cross-system permission classification verification and controlling the access verification strategy when container applications access clipboard data.

[0033] This invention dynamically adjusts the pre-allocated capacity of each level of the three-level shared memory pool based on the real-time memory load of the system. It supports a large-page memory mechanism to reduce address translation overhead. On multi-core devices, it binds the physical pages of shared memory to the memory nodes of the processes at both ends. Simultaneously, it sets up a memory allocation compatibility adaptation layer to eliminate differences in memory management mechanisms between the two systems. The binding rules between clipboard data data types and memory pool levels are as follows: text and images are preferentially allocated to the first-level memory pool; rich text and file URIs are preferentially allocated to the second-level memory pool; and custom binary data is preferentially allocated to the third-level memory pool.

[0034] Step 2: When the host application triggers a copy operation, the host clipboard agent determines that clipboard data that is empty or has a data size greater than a threshold is invalid and returns an error code to stop the copy operation. It encapsulates valid clipboard data into a lightweight IPC transport packet containing a fixed header and the original clipboard data, and then sends the lightweight IPC transport packet to the host clipboard service. The host clipboard service parses the lightweight IPC transport packet and encapsulates it into a host native cut object. The host native cut object contains the data type, data length, and the original clipboard data. It then performs a validity check on the host native cut object. After successful validation, it initializes the clipboard operation context and saves this context in the circular buffer of the host clipboard service process.

[0035] The host clipboard service determines the corresponding sensitivity level based on the data type of the host's native clipping object. Based on the data type and sensitivity level, it retrieves the L1 cache, L2 cache, and L3 cache, queries the container application's permission identifier, generates cross-container access rules and permission determination methods corresponding to the host's native clipping object, and writes them into the clipboard operation context. It also establishes a pre-binding association between the clipboard operation context and the block identifier of the subsequently allocated shared memory block. The service performs cross-system heterogeneous data preprocessing on the raw clipboard data in the host's native clipping object to obtain clipboard data that adapts to the native data formats of both the host and container.

[0036] Heterogeneous data preprocessing refers to the normalization of raw clipboard data of various heterogeneous types, such as text, images, rich text, file URIs, and custom binary data, after the host clipboard service receives the host's native clipping object. This includes stripping the application's private encapsulation header, removing invalid bytes, aligning data boundaries, separating the valid data payload from metadata, and outputting clipboard data with a unified format for subsequent unified allocation of shared memory blocks and construction of a block index table. This preprocessing only performs data regularization and does not perform business format conversion. Business format conversion is performed by the container-side lazy conversion agent when the container application reads the data.

[0037] The lightweight IPC transport packet's fixed header includes data length, data type, and basic checksum. The circular buffer is a fixed-size array, with each buffer node containing a request ID, application package name, data type, request timestamp, operation status, and a reserved field. The reserved field stores the block identifier of the corresponding shared memory block, enabling a one-to-one binding between the clipboard operation context and memory resources.

[0038] In this invention, the access verification strategy is a global verification process template preset based on the sensitivity level of clipboard data; the cross-container access rule is a full constraint instance generated for a single clipboard session based on the access verification strategy; and the permission determination method is the specific determination execution logic extracted from the cross-container access rule for container-side permission verification.

[0039] Furthermore, the host clipboard service incorporates built-in format validation logic. It distinguishes the type of clipboard data based on single-byte mask markers and performs validity checks on different data types through bitwise operations. Specifically, for text data, data is valid if the data length is a positive integer and the first byte is a non-empty placeholder; for image data, data is valid if the image width and height are positive integers and the pixel format identifier matches the host's native image format; for file data, data is valid if the file length meets the constraints and the starting character matches the absolute path specification; for rich text and custom binary data, data is valid if the data length is a positive integer and the basic format identifier is compliant. When any data type validation fails, the corresponding error code is returned to the upper-layer application, and the current flow record is marked as failed.

[0040] Specifically, the cross-container access rules, permission determination methods, and verification results for generating the host's native cut object are as follows:

[0041] For cross-container access rules, if the level is normal, the cache reading order is to first read the L1 cache, then the L2 cache, and only read the L3 cache if both levels of cache are missed; the cache expiration time is 5 minutes for the valid lifespan of the permission entry of this type in L1 and L2; after reading the permission record from the L3 cache, the L2 cache is updated synchronously, and then the L1 cache is atomically refreshed; there is no front-end verification, no secondary authorization pop-up, and the permission is determined solely by the permission identifier of the three-level cache;

[0042] For sensitive applications, the cache read order is to read L1 cache first and then L2 cache. The effective lifespan of L1 and L2 caches is set to 2 minutes. The timestamp is verified during reading, and the cache is discarded if it expires. After the cache expires, L3 cache is forcibly read, L2 cache is refreshed and L1 cache is synchronized. Even if the permission is marked as authorized, the container application must verify whether it is in the foreground when accessing it. If it is in the background, it is directly rejected.

[0043] For high sensitivity levels, the cache reading order is to skip L1 and L2 caches and directly read L3 cache for each access. The queried permission records are not written to L1 and L2 caches. Regardless of whether the permission identifier is authorized, the container application must pop up a user secondary authorization pop-up when reading, and the data can only be returned after the user confirms.

[0044] The permission determination method defines permission flag 0 as unauthorized, meaning that the container application is denied access to the current clipboard data in any scenario; permission flag 1 as authorized, meaning that access to the current clipboard data is allowed based on the hierarchical access rules corresponding to the sensitivity level; permission flag 2 as expired authorization, which is equivalent to unauthorized access and requires the user to re-grant clipboard access permissions.

[0045] Verification results, including successful and unsuccessful verification.

[0046] Step 3: Based on the data type of the host's native clipping object, query the memory binding rules to determine the corresponding memory pool level. Allocate a cross-system shared memory block with matching capacity in the corresponding level shared memory pool. Generate a globally unique block identifier for the shared memory block as a unique identifier for both ends to identify, locate, and index the shared memory resource. Map the shared memory block to the user-mode virtual address of the clipboard service and align the memory start address according to the cache line. Load the memory block into the processor cache through the CPU prefetch instruction.

[0047] Based on the data type, a differentiated write method is selected, and the preprocessed clipboard data is written to the shared memory block. A block index table is constructed according to the corresponding sharding strategy and stored in the shared memory header. The host shadow cache is updated to record the data type, data length, data verification information, block identifier, shared memory file descriptor, cross-container access rules, permission determination method, and data validity status flags of the clipboard data. At the same time, the host system's internal management information, such as the clipboard operation context index, shared memory pool ownership information, memory reclamation control flags, and preprocessing status, is also maintained. A clipboard change event carrying synchronous metadata is sent to the container, triggering the container clipboard proxy to update the container shadow cache and store the synchronous metadata of this cross-system interaction. The container shadow cache establishes cache entries with the block identifier as the primary key, enabling subsequent paste requests to locate the target shared memory block.

[0048] Both the host shadow cache and the container shadow cache use a two-level indexing method of hash table and data type linked list to store cache entries. The hash table uses the block identifier as the key to index the corresponding cache entry. The background thread completes the cache preloading and uses atomic operations to implement access control for cache read and write.

[0049] The method for constructing the block index table according to the corresponding block segmentation strategy is as follows: text data is not split, only a single index record is generated; image data is evenly segmented according to the DMA hardware transfer granularity and block indexes are generated sequentially; rich text and file URIs are split into independent blocks based on their internal logical units, and each block is configured with independent verification information; custom binary data uses dynamically variable-length blocks, and the index supports random access to blocks; all index entries are uniformly stored in the shared memory header metadata area. After the container clipboard agent establishes a shared memory mapping, it can directly read the block index table, providing a block addressing basis for differentiated zero-copy reading. "Rich text and file URIs based on their internal logical units" refers to information fragments within the rich text and file URI clipping content that possess independent semantics, can be parsed separately, and can be used independently.

[0050] Furthermore, upon receiving a clipboard change event, the container parses the block identifier carried by the event and binds the corresponding synchronization metadata. It pre-builds a data reading context according to a preset priority. When a paste request triggers shared memory mapping, it quickly reads the clipboard data for rapid display. All cached entries are configured with lifecycle timeout rules and automatically expire and are cleaned up after the timeout. The preset priority can be set according to the data type and access frequency of the clipboard data. The data reading context is a set of reading resources and parameters pre-initialized by the container's clipboard agent after receiving a clipboard change event. It includes pre-allocated worker thread resources, verification algorithm handles, data structures, resource placeholders, data types, and sharding strategy identifiers. The context only prepares resources and does not access the block index table or clipboard data in shared memory. When a paste request triggers shared memory mapping, this context is directly reused to start the data reading process, reducing the overhead of dynamically creating resources at runtime and shortening the clipboard data display latency.

[0051] Furthermore, the host sends clipboard change events to the container through the Futex lightweight synchronization mechanism and reusable kernel event channels. The container receives the events through a lock-free event queue and processes them according to priority. Combined with load adaptive scheduling, event sequence number deduplication, double acknowledgment, and multi-level degradation strategies, the event delivery is ensured to be low-latency and lossless.

[0052] Furthermore, this invention adds an access count to the memory block header to achieve dual-end access control; the memory block is only allowed to be reclaimed after both ends have finished accessing it. A background thread periodically processes idle blocks, setting differentiated idle timeout strategies based on different levels. Idle blocks remain ready for reuse before timeout. The integrity of memory blocks is checked periodically, and abnormal blocks are isolated. When the system's idle memory resources are less than a threshold, a degradation allocation scheme is activated, and multiple memory blocks are spliced ​​together to carry large-capacity clipboard data, while reserving a high-priority allocation channel for clipboard operations. When a memory block is released, adjacent idle blocks are detected in real time and merged to reduce memory fragmentation. The memory block header is expanded to store atomic management fields such as resource mapping status identifiers, verification information, occupant markers, and access counts. An independent transmission status marker field is also set to manage the clipboard transmission process. A unified byte storage specification is adopted to adapt to both systems, and a block identifier storage field is added to the memory block header as a unique identifier for shared memory blocks used for dual-end state synchronization and resource management. The resource mapping status identifier is an atomic integer variable, including data valid, idle, data mapped, data corrupted, and mapping failed. Data valid means that the container is allowed to initiate a mapping read. Idle means that the memory block can be reallocated by the memory pool. Data mapped means that the data in the memory block has been mapped to the container's virtual address space. Data corrupted means that both ends are notified that the data is unavailable and an error process is triggered. Mapping failed means that the container mapping is abnormal and the host can prepare a subsequent retransmission mechanism.

[0053] Step 4: When a container application initiates a paste request, the container clipboard agent uses the block identifier as an index to query the synchronous metadata corresponding to the clipboard data entry in the container shadow cache. Then, based on the container application's identity and the cross-container access rules in the synchronous metadata, it performs a secondary permission check on the container application. After the permission check passes, it retrieves the target shared memory resource based on the block identifier, configures read-only shared mapping permissions and specifies an isolated address range, and maps the corresponding shared memory block to the virtual address space of the container clipboard agent process. After successful mapping, it increments the shared memory block header access count using atomic operations and updates the shared memory header status from "data valid" to "data mapped" using atomic operations, marking the current shared memory block as being in a read state. The established virtual address access channel is then used. Differentiated zero-copy read strategies are employed for clipboard data of different data types. The pre-built block index table in the shared memory header is reused to read the pre-processed clipboard data in shared memory. After reading, a lightweight data integrity check is performed. If the check is successful, the virtual buffer address corresponding to the clipboard data is passed to the container clipboard service. After obtaining the virtual buffer address, data length, and other metadata, the container clipboard service encapsulates the virtual buffer address into a container native clipping result object and returns it to the container application that initiated the paste request. The shared memory access reference count is decremented through atomic operations to release the container process's virtual address mapping and corresponding file descriptor resources. A data read completion confirmation signal is sent to the host, and the dual-end cache status is updated synchronously to complete the cross-system clipboard data read.

[0054] Specifically, the container performs a tiered permission secondary verification based on the identity of the container application and the cross-container access rules stored in the container shadow cache.

[0055] The sensitivity level of the clipboard data is determined. If it is a normal level, the L1, L2, and L3 caches are searched sequentially, and cache entries are synchronized. If it is a sensitive level, the application's foreground and background states are checked after the cache is searched. If the application is in the foreground and the permission is marked as authorized, the shared memory mapping and paste reading are allowed to continue. If the application is in the foreground and the permission is marked as unauthorized or expired, access is denied. If the application is in the background, access to clipboard data is denied, and an insufficient permission error code is returned. If it is a high sensitivity level, the L3 persistent cache is read, and the user is triggered to grant secondary authorization. The access permissions are determined by the result of the user's secondary authorization.

[0056] Specifically, a differentiated zero-copy reading strategy is implemented for clipboard data of different data types. For ordinary text, CPU vector instruction sets are used to load memory in batches sequentially, and contiguous memory blocks are prefetched segment by segment according to the block index. For ordinary images, DMA hardware channels are reused first, and pixel data is directly transferred to the image buffer via shared memory physical pages. If DMA hardware is not available, CPU vector instructions are used for reading. For sensitive data, a segmented parallel reading mechanism is adopted, with multiple worker threads concurrently reading each segment according to the block index and assembling them in an orderly manner after reading. For highly sensitive custom binary data, the target segment is read point by point according to the block index.

[0057] Furthermore, after the container clipboard service obtains the address of the clipboard data virtual buffer and encapsulates it into a container native clipping result object and returns it to the container application that initiated the paste request, a lazy transformation proxy is built to intercept the application's clipboard data access interface call, and a lightweight lazy transformation of heterogeneous data is achieved by using an access triggering mechanism.

[0058] The format conversion task is started only when the container application calls the data reading interface for the first time to read clipboard data. Depending on the urgency of the access, it can be executed synchronously or submitted to the background thread pool for asynchronous processing. The scheduling priority of the format conversion task is dynamically adjusted according to the application thread state.

[0059] Lightweight format conversion is performed based on the data type of the clipboard data. The format conversion task participates in the system CPU scheduling according to the configured scheduling priority: text data dynamically selects the corresponding encoding format according to the data reading interface type called by the container application to complete the encoding format conversion; image data is dynamically scaled and the pixel format is fine-tuned according to the resolution required by the application; file URIs complete virtual path restoration, dynamically mount resources and provide file access interface according to the path mapping cache; rich text reuse tag mapping table only parses the visible area fragment to complete tag mapping restoration; custom binary data performs on-demand field lazy deserialization and achieves container format compatible encapsulation; after the conversion is completed, the conversion result is stored in the lightweight conversion cache, and the cache is lock-free concurrently read and write through atomic operations. At the same time, a dual cache cleanup mechanism of timeout expiration and clipboard data update active expiration is configured.

[0060] The urgency of data read interface calls is categorized into urgent and non-urgent access. Urgent access scenarios include real-time image rendering and direct display of clipped content in the application UI. For urgent access calls, synchronous conversion is performed, completing the format conversion within the current calling thread. Non-urgent access scenarios include reading text, file URIs, preloading clipped information in the background, and background synchronous tasks. For these types of calls, the approach is to submit them to the background thread pool for asynchronous execution to avoid occupying the application's main thread and prevent UI lag.

[0061] The application thread state is the attribute of the thread that initiated the call, which is divided into the application UI main thread and the background worker thread. If the calling thread is the application UI main thread, it represents a real-time user interaction scenario, and the format conversion task priority is set to foreground priority; if the calling thread is the application background worker thread, the format conversion task is set to background priority. Through differentiated priority scheduling, the response speed of the user's foreground clipping interaction is prioritized, and the competition of background tasks for foreground computing power is reduced.

[0062] Example:

[0063] This embodiment employs a cross-environment clipboard high-performance interoperability method based on dual-end shadow caching provided by this invention. Using OpenHarmony as the host system and Android as the container system (hereinafter referred to as OH), innovative mechanisms such as a kernel-level Binder protocol pass-through layer, a three-level permission cache, a hierarchical shared memory pool, dual-end shadow caching, and lazy conversion of heterogeneous data are designed to eliminate core overheads such as IPC forwarding, data copying, and permission redundancy verification. This achieves low-latency, high-throughput, and high-consistency interoperability of clipboard data between the OH host and the Android container. The specific implementation process includes:

[0064] S1 and OH are used to trigger clipboard initialization.

[0065] When the S1.1 and OH applications trigger a copy operation, they call the OpenHarmony 5.0+ native clipboard modular API and use the Promise asynchronous call method provided by the interface to perform data writing, thus avoiding blocking the application UI main thread.

[0066] The modular API uses a newly added lightweight proxy class, ClipboardProxy, to perform initial data filtering: for empty data such as empty text, array buffers with zero length, and invalid file URIs, it directly returns the ERR_EMPTY_DATA error code without initiating cross-process calls; for extremely large data such as images or text exceeding 100MB, it returns the ERR_DATA_TOO_LARGE error code in advance to avoid subsequent invalid memory allocation and transmission. This lightweight proxy class, ClipboardProxy, resides in the application process and has no independent process overhead.

[0067] ClipboardProxy encapsulates the filtered valid data into lightweight IPC packets. The packet structure is designed with a fixed header of 6 bytes and variable-length raw data. The fixed header contains a 4-byte data length, a 1-byte data type, and a 1-byte basic checksum. All header fields are stored in little-endian order to adapt to the CPU's native byte order and avoid byte order conversion overhead.

[0068] S1.2 The modular API sends lightweight IPC packets to the newly added ClipboardService process. During transmission, tags natively supported by the OH IPC framework are enabled. Text data is compressed in real time using the LZ4 algorithm, while binary data is not compressed.

[0069] ClipboardService parses and encapsulates the received IPC transport packets into an OH native ClipContent object, which retains only the core fields: data type dataType, data byte length dataLength, and raw data rawData.

[0070] Upon receiving the ClipContent object, ClipboardService immediately initializes the clipboard operation context. This context is stored in a circular buffer within the ClipboardService process. The circular buffer is implemented using a fixed-size array, with each buffer node occupying only 64 bytes. It contains: a 16-byte request ID, a 32-byte application package name, a 1-byte data type, an 8-byte request timestamp, a 1-byte operation status, and a 6-byte reserved field. The operation status is indicated by 0 for initialization, 1 for validation, 2 for success, and 3 for failure.

[0071] Both write and read operations in the circular buffer are implemented using atomic pointers for lock-free access: during writes, the write pointer is updated via a Compare and Swap (CAS) operation, and during reads, pointer visibility is guaranteed, avoiding mutex lock contention common in traditional LRU caches. The clipboard operation context only records trace information and does not store the original data, preventing the context cache from consuming too much memory. Furthermore, when the buffer is full, the strategy of overwriting the oldest node is adopted, eliminating the need to trigger garbage collection and ensuring uninterrupted cache operations.

[0072] S1.3 In this embodiment, a preCheckDataValidity(ClipContent content) method is added to the custom ClipboardService to achieve fast verification of data format validity through bitwise operations.

[0073] Assign unique check bits to different data types and store them in a 1-byte checkBits variable. Specifically: text is BIT0, 0x01; images are BIT1, 0x02; file URIs are BIT2, 0x04; rich text is BIT3, 0x08; and custom binary data is BIT4, 0x10. The check bits corresponding to the data type can be quickly mapped using checkBits = content.getDataType().

[0074] Text data validation: If the bitwise operation (checkBits&0x01) == 0x01 is satisfied, it is determined to be a text type. Then, the bitwise operation (content.getDataLength()&0x80000000) == 0 determines that the data length is a positive integer. No branch judgment is needed, and non-empty can be quickly verified. At the same time, by using the condition content.getRawData().get(0) != 0x00, it can be determined that the first character is a non-empty character, completing the basic legality verification. There is no string parsing operation throughout the process.

[0075] Image data verification: If the bitwise operation (checkBits&0x02) == 0x02 is satisfied, it is determined to be an image type. Then, the first 8 bytes of rawData are read, which store the image width and height, each of which is a 4-byte uint32 type. The bitwise operation (width&0x80000000) == 0 && (height&0x80000000) == 0 can be used to determine that the width and height are positive integers to verify the size validity. At the same time, the pixel format identifier bit of the 9th byte is read. Only it is checked whether it is 0x08, which indicates RGBA_8888 format. If it is not in this format, it is directly determined as invalid data, and there is no need to parse the image metadata.

[0076] File URI verification: If the bitwise operation (checkBits&0x04) == 0x04 is satisfied, it is determined to be a file URI type. The bitwise operation (content.getDataLength()&0xFFFF0000) == 0 can be used to determine whether the byte range of the URI length conforms to the OH file URI length specification to verify the length. At the same time, the content.getRawData().get(0) == 0x2F is used to determine whether it is an absolute path. Non-absolute paths are directly determined to be invalid.

[0077] Rich text or custom binary data validation: Reuse the bitwise operation logic above, only verify that the data length is a positive integer and that the basic format identifier bit is valid, without involving content parsing.

[0078] When verification fails, ClipboardService immediately returns the corresponding error code to the application via reply.writeInt32(errorCode), such as ERR_INVALID_IMAGE_SIZE or ERR_INVALID_URI_FORMAT, and updates the clipboard operation context's operation status to 3, indicating failure, to avoid unnecessary operations such as subsequent permission verification and memory allocation, thus saving CPU and memory resources. If verification succeeds, the operation status is updated to 1, indicating verification in progress, and the process proceeds to the next permission verification step.

[0079] S2. Three-level cache optimization for cross-system permission verification: Construct a three-level permission cache architecture of registers, memory, and persistence. Combine lock-free CAS operations, data type binding verification, and cross-system atomic synchronization mechanism. Under the premise of strictly following the permission model of OpenHarmony5.0+ and Android 12+, reduce the average time of permission verification, while avoiding the overhead of duplicate authorization and lock contention.

[0080] S2.1 and L1 caches provide zero-latency access at the CPU register level.

[0081] Hardware adaptation and data layout of register caching: For ARM architecture, general-purpose registers are selected as the permission status storage area to avoid cache invalidation caused by register conflicts. The permission status of each application occupies 1 byte, such as 0 indicating unauthorized, 1 indicating authorized, and 2 indicating expired authorization. Through application package name hash mapping and data type mask, the full type permission status of the 5 most frequently used applications is stored in the registers. Each register can store permission masks of 8 data types, and the 5 registers cover a total of 40 combinations of applications and data types.

[0082] Atomic refresh mechanism for register cache: When the permission status in L2 cache is updated, the register data is updated by performing a CAS atomic operation through the newly added RegisterCacheUpdater class, avoiding dirty writes to register data caused by interruption.

[0083] Register cache invalidation determination: A 1-byte cache validity flag is stored in the register. When the system switches processes or changes permissions, the flag is cleared immediately. Subsequent permission read requests will skip the L1 cache directly to avoid access to dirty data. This invalidation determination logic has no additional time consumption.

[0084] S2.2 and L2 caches are user-space memory pools that enable low-latency hash lookups.

[0085] Cache pool data structure optimization: A new `CrossSystemPermissionCache` class has been added to `ClipboardService` in OpenHarmony, and its core storage structure uses a cuckoo hash table. The hash table key is designed as a combination of a 4-byte application package name CRC32 hash value and a 1-byte data type enumeration value, which effectively reduces memory overhead compared to the existing key combination of package name string and data type string.

[0086] The cache entries feature a refined design: each entry contains only three core fields: a 1-byte permission status, a 4-byte expiration timestamp, and a 1-byte data type mask, totaling 6 bytes. The expiration timestamp is a uint32 type, storing a relative time difference rather than an absolute time, reducing time synchronization overhead. The data type mask indicates which data types the application is authorized to use; for example, 0x03 indicates authorization for text and images.

[0087] Cache preheating and eviction strategy: When the system starts, CrossSystemPermissionCache retrieves the 10 most recently running applications and preloads their permission status from the L3 cache to the L2 cache. This process is executed in a background thread and does not affect the system startup speed. When the number of cached items reaches the limit of 50, a hybrid eviction strategy of least frequent use (LFU) and earliest expiration (LRU) is adopted. The access count of each cached item is recorded by an atomic counter, and the item with the fewest accesses and the earliest expiration time is evicted.

[0088] Lock-free CAS update mechanism: CrossSystemPermissionCache uses OH's native concurrency tools to implement atomic updates of cached items. The update process is as follows: first, the reference to the target cached item is queried through the Cuckoo Hash Table, and then the new permission status object is replaced by a CAS operation. If the replacement fails, it is retried, with a maximum of 3 retries to avoid infinite loops.

[0089] S2.3 and L3 caches provide persistent storage for secure and reliable backups.

[0090] Persistent storage solution selection: Utilizing OpenHarmony's native DataAbility combined with a lightweight key-value store, instead of a traditional database.

[0091] Storage path and permission isolation: Permission data is stored in the application's dedicated sandbox path in OH, and file permissions are set to be readable and writable only by the owner.

[0092] Delayed persistence optimization: L3 cache write operations employ a batch delayed write-back mechanism. Multiple modified data entries are temporarily stored in the cache, and once the trigger condition is met, the data is synchronized downstream in batches, reducing the performance overhead caused by frequent single writes. A write buffer in memory is maintained; when the buffer is full or at 1-second intervals, batch writes are performed via a background thread to avoid frequent I / O operations triggered by single permission updates.

[0093] S2.4, Permission verification for data type binding.

[0094] Strong correlation between permissions and data types: Based on the privacy sensitivity of different data types in the clipboard, permission levels are divided: text and images are ordinary permissions, which are valid indefinitely after authorization; file URIs and rich text are sensitive permissions, with the authorization validity period shortened to 2 minutes; custom binary data are highly sensitive permissions, which require real-time verification for each access.

[0095] Hierarchical verification logic: When reading permissions, the corresponding permission level is first obtained through the data type, and then different verification processes are executed. For ordinary permissions, the data is read first from L1 and L2 caches. If the cache is not hit, the data is read from L3 and synchronized to L2 and L1. For sensitive permissions, the validity period of L1 and L2 caches is shortened to 2 minutes. After expiration, the data is forcibly read from L3 and the cache is updated. For highly sensitive permissions, L1 and L2 caches are skipped, the data is read directly from L3 and a secondary authorization pop-up is triggered. User authorization is only executed on the first access to ensure privacy and security.

[0096] Bitwise operation optimization of the verification logic: The mapping between permission level and data type is implemented through bitmasks (normal permissions correspond to the mask 0x01, text corresponds to the mask 0x0). The permission level can be quickly determined by bitwise operation (levelMask&typeMask)!=0, avoiding the overhead of branch judgment.

[0097] S2.5 Cross-system permission atomic synchronization mechanism.

[0098] Kernel-mode optimization of the synchronization channel: The newly added clipboard_eventfd event file descriptor is reused. When the permission status on the OH side is updated, the writev() method is used to write a synchronization data packet containing a 1-byte permission synchronization flag, a 4-byte application package name hash, a 1-byte data type, and a 1-byte new permission status to the event FD.

[0099] Android-side permission cache update: The newly added ClipboardPermissionCache class in the newly added ClipboardService in the Android container listens for this event FD. After receiving the synchronization data packet, it adopts the same Cuckoo Hash Table and CAS lock-free update mechanism as the OH side to atomically update the L2 cache on the Android side, and at the same time triggers the register cache refresh to ensure that the permission status on both sides is completely consistent.

[0100] Synchronization consistency guarantee: A double confirmation mechanism is introduced. After updating the permission cache on the Android side, a 1-byte synchronization confirmation signal is returned to the OH side through the same event FD. If the OH side does not receive the confirmation within the set time, it will resend the synchronization data packet to avoid synchronization failure caused by container scheduling delay. The retry logic is only triggered in extreme scenarios and does not affect normal performance.

[0101] S2.6, Optimization of reuse of secondary permission verification on the Android side.

[0102] Permission model compatibility: Android 12+ requires background access or temporary foreground authorization to access the clipboard. The permission status on the OH side is mapped to the Android permission model: authorization on the OH side corresponds to temporary authorization on the Android side, and non-authorization on the OH side corresponds to permission denial on the Android side. Users do not need to re-authorize, which complies with the Android permission pop-up specification.

[0103] Permission verification logic reuse: The permission verification on the Android side fully reuses the three-level cache and lock-free update on the OH side. The L3 cache is loaded by reading the permission database of the Android system to ensure the consistency and security of permission verification.

[0104] S3, Heterogeneous Data Preprocessing and Premapping of Clipboard Data: Addressing the core issue of heterogeneous data formats between OpenHarmony and Android containers, a mechanism is designed to accelerate encoding using instruction sets, memory-aligned storage, segmented lazy processing, and premapping caching. Lightweight preprocessing is completed before data is written to shared memory, avoiding the high overhead of full format conversion after transmission, while ensuring that the data structure adapts to the native parsing logic of both ends.

[0105] S3.1 Accurate data type recognition.

[0106] Accelerated bitwise operations for data identification: ClipboardService calls the custom parseDataType(ClipContent content) method, directly mapping the data type through the 1-byte dataType field of the custom ClipContent object. The mapping relationship between this field and the clipboard.ContentType enumeration is fixed by a bitmask, such as 0x01 for TEXT, 0x02 for IMAGE, 0x04 for FILE_URI, etc. The type is quickly determined by bitwise operations (content.getDataType()&MASK_TYPE), avoiding branching decision chains.

[0107] Redundant filtering for type validation: For mixed-type data such as image URIs embedded in rich text, this embodiment adds the typeConflictCheck() method. It avoids misjudgment of type by using the characteristics of the first byte of the data, such as the first byte of text being a printable ASCII code, and the first byte of image data being a pixel format identifier. The validation logic only occupies a set number of CPU instructions and has no additional performance overhead.

[0108] S3.2 Text data preprocessing.

[0109] Parallel dual-encoding generation and instruction set optimization: This embodiment adds a new `TextPreEncoder` class, which is implemented in C++ and called via JNI. After reading native Android UTF-8 encoded text data, it simultaneously generates native Android UTF-16 encoded data. The encoding conversion logic is optimized based on the CPU instruction set: Under the ARM architecture, vector instructions from the NEON instruction set are reused, enabling the conversion of 16 bytes of UTF-8 data at a time, resulting in higher conversion efficiency than the Java layer implementation; under the x86 architecture, the `pcmpistri` instruction from the SSE4.2 instruction set is used to accelerate character encoding judgment, reducing the conversion time per line of text.

[0110] Dynamic chunking and index table optimization: For text longer than 10KB, an adaptive chunking algorithm is used to dynamically divide the block size based on delimiters such as newlines and spaces, avoiding semantic fragmentation caused by forced chunking. The index table adopts a compact storage structure: each block index occupies only 8 bytes, including a 4-byte starting offset and a 4-byte length, stored in the text data header, which effectively reduces memory overhead compared to a fixed-chunk index table. The index table is mapped to shared memory via mmap, allowing direct reading from the Android side without the need to rebuild the index.

[0111] Optimization of duplicate segment deduplication: This embodiment adds the `textDedup()` method. For text data longer than 50KB, it uses a sliding window and hash fingerprinting to quickly identify duplicate segments, such as consecutive repeated spaces or identical phrases. The duplicate content is replaced with the number of repetitions and the original segment index. The hash fingerprint calculation is based on the XXH32 algorithm, with a window size of 32 bytes. The deduplication logic is executed asynchronously in a background thread, without blocking the main thread's preprocessing flow, effectively reducing the amount of text data stored.

[0112] Memory-aligned storage of encoded data: UTF-8 and UTF-16 encoded data are stored in shared memory aligned to the CPU cache line size, avoiding performance loss caused by accessing across cache lines. For example, after UTF-8 data is stored, if there is less than 64 bytes of remaining space, invalid characters are padded to ensure that the starting address of UTF-16 data is an integer multiple of 64 bytes, improving cache hit rate.

[0113] S3.3 Image data preprocessing.

[0114] Copy-free reading and format adaptation of raw pixel data: Raw pixel data, such as RGBA_8888 format, is read into a shared memory buffer without intermediate memory copying. If the pixel format of the PixelMap is other types, such as RGB_565, it is quickly converted to RGBA_8888 using the NEON instruction set.

[0115] Compact storage of metadata: This embodiment introduces a new ImageMetaInfo class, employing a bit-field design to compress and store metadata: width occupies 16 bits, height occupies 16 bits, pixel format occupies 4 bits, line spacing occupies 16 bits, thumbnail identifier occupies 1 bit, and reserved bit occupies 1 bit, for a total of only 54 bits. This effectively reduces memory overhead compared to existing metadata storage. Metadata is stored in the pixel data header, and the Android side can directly read it via memcpy without parsing complex structures.

[0116] Adaptive thumbnail pre-generation: for resolutions greater than 2048 For a large image of 2048 pixels, this embodiment adds the `generateThumbnail()` method to generate a 128-pixel image during the preprocessing stage. The 128-resolution thumbnail, formatted as RGBA_8888, is stored after the metadata and before the original pixel data. Thumbnail generation uses a bilinear interpolation algorithm, optimized with the NEON instruction set to reduce generation time. On the Android side, the thumbnail can be read first for faster display, avoiding delays caused by loading the original large image.

[0117] S3.4 File URI Preprocessing.

[0118] Cross-container path mapping and caching optimization: After parsing the physical file path corresponding to the URI, a virtual path accessible by the Android container is generated. The mapping relationship is stored in a newly added CrossContainerPathCache class, implemented based on a Cuckoo Hash Table. The key is a 4-byte CRC32 hash value of the OH physical path, and the value is a virtual path with a maximum length of 64 bytes. The cache capacity is set to 100 entries, using an LRU eviction policy.

[0119] File existence and permission pre-verification: In the preprocessing stage, the existence of the file and whether it has read-only permissions are verified in advance. If the verification fails, the ERR_FILE_ACCESS_DENIED error code is returned immediately to avoid the file being found to be inaccessible after being mounted on the Android side.

[0120] Mount point pre-creation and file descriptor caching: ClipboardService pre-creates the corresponding virtual mount point in the specified directory of the Android container, avoiding the delay of dynamically creating the directory when mounting on the Android side. At the same time, the read-only file descriptors of cached files are stored in the path mapping table. The Android side can directly reuse the file descriptor to access the file, skipping the open() system call and saving time overhead.

[0121] S3.5 Rich Text Preprocessing.

[0122] The tag mapping table is binary-based: It pre-defines the mapping rules between HTML tags and Android Spanned tags. The mapping relationship is stored in a compact structure combining tag ID, Spanned type, and offset identifier, which effectively reduces loading overhead compared to text-based mapping tables. The binary library is dynamically loaded via dlopen(), reducing loading time, and is only loaded once when processing rich text for the first time.

[0123] Compressed storage of tag indexes: Only high-frequency tags within the mapping table are parsed from the rich text data. The parsing results are stored as a tag index stream. Each tag index contains a 1-byte tag ID, a 2-byte start position, and a 2-byte end position, occupying a total of 5 bytes. This effectively reduces overhead compared to storing the complete tag string. The start position is the offset relative to the current segment. The index stream is stored separately from the original rich text data. The Android side can parse the index on demand, avoiding the parsing of redundant tags.

[0124] Rich text segmentation and lazy loading: The rich text is divided into multiple segments by paragraph delimiters, with each segment having a maximum length of 4KB. Tag indices are stored independently between segments. When reading on the Android side, the segment corresponding to the currently displayed area is loaded first, and the remaining segments are loaded asynchronously as the user scrolls, avoiding excessive memory spikes caused by parsing the entire rich text at once.

[0125] S3.6 Custom binary data preprocessing.

[0126] Simplified zero-copy encoding of the Protobuf protocol: This embodiment uses a custom ClipCustomData.proto protocol with only three fields: dataType (1 byte, identifying the custom data subtype), dataLength (4 bytes, uint32 type, representing the data length), and content (variable-length byte stream). The standard Protobuf's length-delimited header and CRC checksum field are removed to reduce encoding overhead. The Protobuf encoding structure is built in a shared memory buffer, and the original data is written to the content field using memcpy, avoiding intermediate buffer copying.

[0127] Custom data type registration mechanism: This embodiment adds a new `CustomDataTypeRegistry` class, which supports third-party applications in registering serialization or deserialization functions for custom data subtypes. Registration information is stored in a global function pointer array, with array indices mapped one-to-one to the `dataType` field. At runtime, the corresponding function is called through the index, avoiding dynamic lookups and effectively reducing serialization and deserialization time.

[0128] Adaptive data compression: Compression is determined based on the entropy value of the custom data. If the entropy value is less than 0.6, such as text-based custom data, LZ4 compression is used. If the entropy value is not less than 0.6, such as encrypted data or binary streams, no compression is performed to avoid ineffective compression and increased CPU overhead. The compression logic is optimized based on the CPU instruction set.

[0129] S3.7 Unified encapsulation of preprocessed data.

[0130] Contiguous memory layout design: All preprocessed data, including metadata, index table, and raw data, are stored contiguously in shared memory to avoid cross-page access caused by fragmented storage. The storage order is uniformly set as follows: 1 byte basic check bit, 1 byte data type, metadata, index table, raw data, and 4 bytes tail checksum. The basic check bit is the XOR value of the data type and the data length, and the tail checksum is the full data check value calculated by the CRC32 algorithm to ensure data transmission integrity.

[0131] Checksum pre-computation optimization: The tail CRC32 checksum is calculated in real time when data is written to shared memory. It adopts the CRC32C algorithm accelerated by the CPU instruction set, and the calculation process is executed in parallel with the data writing process through multi-threaded pipeline operation, without adding extra time consumption. After reading data on the Android side, data integrity can be quickly verified by the checksum.

[0132] S4. Dynamic allocation and mapping of hierarchical shared memory pools: Focusing on the collaborative sharing memory between OH and Android containers, a mechanism is established that integrates dynamic hierarchical adaptation, physical page affinity binding, zero-copy FD transfer, and atomic memory management. Based on the anonymous shared memory characteristics of both ends being of the same origin, this addresses the problems of fragmented shared memory allocation, high mapping latency, and poor cross-system consistency in existing methods.

[0133] S4.1 Initialization and dynamic hierarchical optimization of shared memory pool.

[0134] The load-aware pre-allocation strategy for the three-level memory pool: Modifying the OH kernel source code, this embodiment adds the oh_android_clip_ashmem shared memory pool. The initial size and number of memory blocks in each pool are dynamically adjusted based on the real-time system memory load. For example, if the system memory utilization is less than 60%, it is considered low load; in this case, 15 blocks are pre-allocated in the first-level pool, 8 blocks in the second-level pool, and 1GB of virtual address space is reserved in the third-level pool. If the system memory utilization is between 60% and 80%, it is considered medium load; in this case, 10 blocks are pre-allocated in the first-level pool, 5 blocks in the second-level pool, and 512MB of virtual address space is reserved in the third-level pool. If the system memory utilization is greater than 80%, it is considered high load; in this case, 5 blocks are pre-allocated in the first-level pool, 3 blocks in the second-level pool, and 256MB of virtual address space is reserved in the third-level pool. System load judgment is implemented through native OH methods, and pool size adjustment is performed in a background thread without blocking the memory allocation process.

[0135] HugeTLB Adaptation and Performance Optimization: For the secondary and tertiary memory pools, the Linux kernel's HugeTLB mechanism is enabled to reduce the Translation Lookaside Buffer (TLB) miss rate. The hugetlbfs filesystem in the OH kernel is mounted to reserve dedicated large page space for the shared memory pool, avoiding contention for large page resources with other system processes.

[0136] Physical page affinity binding and NUMA architecture adaptation: For multi-core Non-Uniform Memory Access (NUMA) architecture devices, this embodiment adds the bindPhysPageToNode() method to bind physical pages of the shared memory pool to the local CPU memory node where ClipboardService and the Android container reside, avoiding latency caused by cross-node memory access. The binding logic is implemented through kernel system calls, calling the mbind interface to specify the MPOL_BIND memory policy, setting the target NUMA memory node ID, and constraining the allocation of clipboard shared memory to the corresponding NUMA memory node; if the target node runs out of memory, degraded allocation logic is executed. This optimization only applies to multi-NUM node hardware; single-node terminal devices directly perform normal memory allocation, and this is only executed once during memory pool initialization.

[0137] A cross-system adaptation layer for the buddy system is designed. To adapt to the differences between OH and the Android kernel in SLUB parameter tuning, buddy system memory domain configuration, and fragmentation management strategies, a new memory allocation cross-system adaptation layer, CrossSystemBuddyAdapter kernel module, is added. This layer shields the differences in memory management details between the two kernels and provides a unified shared memory allocation and release interface, achieving compatibility and adaptation between the two algorithms.

[0138] During memory block allocation: For business scenarios requiring large contiguous blocks of physical memory, a new memory adaptation layer is added; for large-page granularity memory requests, the SLUB object allocation path is bypassed, and the Buddy System is directly called downwards for physical page block allocation, leveraging the Buddy System's O(logN) splitting and merging capabilities to improve external fragmentation of physical pages; during memory release, after all objects within the slab have been reclaimed, the complete page block is returned to the Buddy System for block merging; the adaptation layer uses a lock-free free block linked list based on atomic pointers to manage the memory of this layer, reducing the additional overhead of the allocation and release path; this adaptation layer only applies to large memory business scenarios, while ordinary small memory object requests still use the SLUB object allocation path.

[0139] S4.2 Precise allocation and performance optimization of memory blocks.

[0140] A strong binding strategy between data types and memory blocks is implemented. A custom `AshmemAllocator` class is added to `ClipboardService` to pre-define mapping rules between data types and memory blocks, avoiding invalid allocation attempts. Specifically: for text and custom data, primary pool allocation is mandatory, disallowing the use of secondary and tertiary pool resources; for images and medium-sized text (between 10KB and 1MB), secondary pool allocation is prioritized, with dynamic expansion only when the secondary pool is full, avoiding direct use of the tertiary pool; for large data (greater than 1MB), only mmap file mapping blocks from the tertiary pool are allocated, and the mapping files are stored in the OH's temporary file system to avoid disk I / O overhead. Binding rules are fixed using a hash table, where the key is the data type and data length range, and the value is the target memory pool level, prioritizing minimizing query time and ensuring unique allocation paths.

[0141] Memory block preloading and cache line alignment: Allocated memory blocks are preloaded into the CPU cache to avoid cache misses on the first access. Simultaneously, the starting address of the memory block is forcibly aligned to a 64-byte CPU cache line size, ensuring that the allocated address is a multiple of 64 bytes, reducing the probability of cross-cache line accesses and improving memory access efficiency.

[0142] Real-time fragmentation merging of free memory blocks: The first-level pool and the second-level pool enable the free block contiguous detection mechanism. Each time a memory block is released, an atomic operation is used to check whether the adjacent memory blocks are free. If both are free, they are immediately merged into a larger block. The merged block is marked as splittable and split as needed during the next allocation.

[0143] The atomicity information in the memory block header has been expanded from the original 8-byte header to a compact 16-byte header, with added fields to ensure cross-system management consistency:

[0144] Bytes 0 to 3 are the blockId, the memory block ID, which is globally unique; Byte 4 is the status, with values ​​of 0 indicating idle, 1 indicating in transit, 2 indicating completion, and 3 indicating an error; Bytes 5 to 8 are the checkSum, the data checksum; Byte 9 is the owner, with values ​​of 1 indicating OH side occupation and 2 indicating Android side occupation, to avoid simultaneous operation on both sides; Bytes 10 to 15 are the accessCount, the access count, which is modified through atomic operations to ensure safe release.

[0145] All header fields use unsigned integer types and are stored in little-endian order to adapt to the native byte order of dual-endian CPUs, avoiding byte order conversion overhead. Furthermore, the header and data area are aligned with 64-byte cache lines, which does not affect data access performance.

[0146] S4.3 Zero-copy optimization for cross-system memory mapping.

[0147] Kernel-mode handle transfer of shared memory descriptors (FDs): A Unix domain socket is created as a clipboard_socket for cross-container communication. On the Android Container (OH) side, an ashmem shared memory region is created based on the ashmem driver to obtain the file descriptor (FD). The user-mode `sendmsg` system call encapsulates the ashmem FD into an auxiliary control message of type `SCM_RIGHTS` and sends it through the Unix domain socket. On the Android container side, `recvmsg` is called to receive the `SCM_RIGHTS` control message from the socket channel to obtain the shared memory FD. This mechanism only copies the file handle in the kernel and does not perform a user-mode copy of the business data within the shared memory. Both FDs point to the same physical memory. It relies on the Linux Unix domain socket's `SCM_RIGHTS` file descriptor transfer capability to achieve cross-container ashmem shared memory handle transfer.

[0148] Fine-grained control and security isolation of mapping permissions are implemented, setting access permissions for shared memory to achieve data security isolation: Level 1 and Level 2 pools are used for ordinary data such as text and images, with permissions set to be readable and writable on both ends, but the `owner` field in the header controls that only one end can modify at a time; Level 3 pool is used for large data and file URIs, with permissions supporting execution permissions to adapt to large file mapping; semaphore permissions are prohibited for all memory blocks to avoid security risks caused by process synchronization through shared memory; permission settings take effect through the `prot` parameter of the kernel-mode `mmap()` system call, and permission changes are recorded in OH's native security log service for easy auditing.

[0149] For cross-system mapping consistency verification, after the Android container obtains the file descriptor (FD), it calls the newly added `validateMappingConsistency(int fd, uint32_t blockId)` method in this embodiment to perform three-layer verification to ensure that the mapped memory block is legal and valid. Specifically, this includes: Verification 1, using the Android libcutils native interface `ashmem_get_size_region(int fd, uint32_t blockId)`... The `fd` method allocates the size of the ashmem memory region and compares it with the expected memory size corresponding to the `blockId` synchronously issued by the OH side. If the sizes do not match, the mapping is rejected. The second verification involves first completing the ashmem memory mmap mapping to obtain the virtual address. The business layer pre-reserves a 4-byte custom checksum field in the shared memory header, obtains the physical page frame number and calculates its hash value, and compares it with the checksum pre-written in the memory header. Due to swapping and NUMA page migration, the physical page frame number may change; this verification can serve as an auxiliary identity verification method. The third verification involves calling the `get_mempolicy` system call based on the mapped virtual address to obtain the corresponding NUMA memory node number. This number is compared with the NUMA memory node numbers on the Android container side and the OpenHarmony side to ensure that both sides are accessing physical memory belonging to the same NUMA memory node. The total time consumed by these three verification layers is minimal, does not affect mapping performance, and is only executed during the first mapping; subsequent accesses directly reuse the mapping result.

[0150] S4.4 Atomic management and delayed garbage collection mechanism for memory blocks.

[0151] Atomic update and safe release of access count: The 6-byte accessCount field in the header of the memory block is updated via CAS atomic operation to record the number of accesses on both ends. After data is written on the OH side, accessCount is incremented by 1; after data is read on the Android side, accessCount is decremented by 1; when accessCount is 0 and status is complete, memory block reclamation is triggered. This mechanism can avoid data races caused by simultaneous access on both ends and ensure that memory is released only when both ends are no longer in use, preventing dangling pointer problems caused by premature release.

[0152] Free memory block timeout reclamation and preheating reuse: This embodiment adds an IdleBlockRecycler background thread, whose priority is set to SCHED_IDLE and runs only when the system is idle. It performs timeout reclamation on free memory blocks in the first-level and second-level pools. For free blocks in the first-level pool, the timeout is set to 30 seconds, after which they are released to the kernel. If they need to be allocated later, they are recreated. For free blocks in the second-level pool, the timeout is set to 60 seconds, after which they are merged into larger blocks or released. For mmap blocks in the third-level pool, the timeout is set to 120 seconds, after which the virtual address space is released and physical memory is reclaimed through the munmap() system call. At the same time, free memory blocks are kept in a preheating state before reclamation. During this time, physical pages are not swapped to disk. If they are reallocated again in a short period of time, they can be reused directly, avoiding the overhead of recreating memory blocks.

[0153] Isolation and Repair of Damaged Memory Blocks: This embodiment adds a dual-end deployed `BlockHealthChecker` class, which periodically checks the integrity of free memory blocks, reads the checksum field in the memory block header, and compares it with the actual checksum in the data area. If they do not match, they are marked as erroneous. Memory blocks marked as erroneous are isolated to the damaged block list and are no longer allocated for use. At the same time, the `recoverBlock(int fd)` method is triggered to attempt repair through memory block backup. If repair fails, the memory blocks are permanently released. The backup mechanism is enabled in the third-level pool, but not in the first and second-level pools. This mechanism prevents data transmission errors caused by damaged memory blocks.

[0154] S4.5, memory allocation adaptation for special scenarios.

[0155] Degradation allocation strategy when memory is insufficient: In an emergency state where system memory utilization is greater than 90%, if the level 3 pool cannot allocate mmap blocks, it will automatically degrade to concatenating multiple level 2 pool blocks. For example, for a large data block of 1.5MB, one 1MB level 2 block and one 512KB dynamic level 2 block will be allocated. The concatenation relationship will be recorded through an index table. When reading data on the Android side, the data will be merged according to the index table. Degradation allocation ensures that data transmission is not interrupted, and the concatenation index table only occupies 16 bytes, including 2 block IDs and 2 offsets.

[0156] Emergency allocation channel and priority guarantee: An emergency memory allocation channel is reserved for clipboard operations, and the priority of clipboard memory allocation is set higher than that of ordinary application memory allocation to ensure that necessary memory blocks can still be allocated when system memory is tight.

[0157] S5, zero-copy data writing and dual-end shadow cache synchronization, builds a mechanism for instruction set accelerated writing, DMA transfer adaptation, incremental cache synchronization and write transaction guarantee. On the basis of allocated shared memory, it realizes data transfer from OH application to shared memory without intermediate copy, while ensuring real-time consistency of dual-end shadow cache status.

[0158] S5.1 Deep optimization of zero-copy data writing.

[0159] Accelerated writing based on instruction sets for different data types: This embodiment adds the AshmemWriter class, which is implemented in C++ and can be called via JNI. It optimizes the writing logic for different data types, reuses the pre-processed memory layout, and avoids secondary data adjustments. For text data, it uses the CPU vector instruction set for batch writing. Under the ARM architecture, it uses the NEON instruction set, with a single vector instruction processing 128 bits of data; under the x86 architecture, it uses the SSE4.2 instruction set, with a single vector instruction processing 128 bits of data.

[0160] Image pixel data: Direct Memory Access (DMA) transfer is prioritized. A dedicated DMA channel is requested to directly transfer the pixel buffer of the PixelMap to shared memory. The CPU is only responsible for initiating the transfer command and does not participate in data handling.

[0161] File URIs, rich text, and custom binary data: Direct memory address mapping is used for writing. The preprocessed application process memory region is mapped to the shared memory region through mmap. Data writing can be completed by directly modifying the shared memory address, without any data copying operation.

[0162] Proactive avoidance of copy-on-write mechanism: To prevent copy-on-write (COW) from being triggered in fork-derived child processes, causing physical page migration and implicit copying, this embodiment adds the `disableCowForRegion(intfd)` method. This method first maps the Ashmem shared memory using `mmap` to obtain the virtual address range, calls the `madvise()` system call to set the `MADV_DONTFORK` flag for this virtual address range, preventing the forked child process from inheriting this memory region; simultaneously, it calls the extended Ashmem driver interface in this embodiment to further protect against copy-on-write behavior in fork scenarios.

[0163] In the main path of cross-container shared memory, ashmem's use of MAP_SHARED mapping itself does not trigger copy-on-write; the risk of copy-on-write comes from misuse of MAP_PRIVATE private mapping or forking to create a new process.

[0164] Cache line optimization during the write process: When writing data, a write-back caching strategy is strictly followed. The clflushopt instruction (dc civac instruction on ARM architecture) ensures that the written data is flushed to the shared memory physical pages in real time, avoiding dirty data reads on the Android side due to CPU cache missynchronization. At the same time, writing is performed in blocks of 64-byte cache lines to ensure that each cache line contains only the same type of data, avoiding cache line pollution.

[0165] Large Data Segmentation and Progress Marking: For large datasets exceeding 1MB in the three-level memory pool, a segmented writing and progress marking mechanism is employed. The data is divided into multiple 64KB segments. Each time a segment is written, the write progress bit at the beginning of the memory block is updated atomically. The progress value is the ratio of the number of segments written to the total number of segments. This mechanism avoids system scheduling interruptions caused by excessively large single writes and ensures the traceability of the write process.

[0166] S5.2, Incremental synchronization mechanism for dual-end shadow cache.

[0167] The lightweight design of cached synchronization data: only core change data is synchronized. The synchronization data packet structure is optimized to a 4-byte blockId, a 1-byte data type, a 2-byte metadata length, and variable-length metadata, with a maximum of 32 bytes and a total length not exceeding 40 bytes. The metadata only includes necessary fields such as data length, checksum, thumbnail identifier, and block index count. Upon receiving the data on the Android side, these fields are directly filled into a custom ClipboardShadowCache without parsing.

[0168] Kernel-mode atomic broadcast synchronization: The clipboard_eventfd channel is reused. The OH-side ClipboardShadowCache completes synchronization through single-packet transmission and atomic acknowledgment. During the transmission phase, the sendmsg system call completes atomic message transmission: the ashmem file descriptor is encapsulated into an auxiliary control message of type SCM_RIGHTS; a lightweight synchronization data packet containing information such as blockId and expected memory size is placed in the ordinary message payload; the file descriptor and lightweight synchronization data packet are transmitted through a single system call; when using UNIX domain stream sockets, at least one byte of ordinary data is included to ensure portability; the receiving end parses the ordinary payload using recvmsg to obtain the synchronization data packet and extracts the ashmem file descriptor from the auxiliary control message. This atomic transmission logic is a new implementation in this embodiment.

[0169] Confirmation phase: After receiving the data packet, the Android side returns a 1-byte synchronization confirmation signal through the same channel, such as 0x01 indicating success, to ensure that synchronization is not lost; this mechanism relies on kernel-mode semaphores to ensure atomicity and avoid data packet loss due to process switching during synchronization.

[0170] Version number consistency check: A global version number is assigned to each blockId. The synchronization data packet carries the current version number. After receiving the data, the ClipboardShadowCache on the Android side will directly insert the blockId into the cache and associate it with the version number if there is no record of the blockId in the local cache. If there is already a record in the local cache, the cache will only be updated when the received version number is higher than the local version number to avoid old data overwriting new data. The version number is incremented through CAS atomic operation to ensure that the version numbers on both ends are strictly consistent.

[0171] S5.3, Shadow caching structure optimization and access acceleration.

[0172] The cache employs a multi-level index design: Both OH and Android's ClipboardShadowCache utilize a two-level structure of hash tables and linked lists. The first-level index is a cuckoo hash table, where key = blockId and value = cache item pointer. The second-level index consists of linked lists organized by data type, such as five lists including TEXT, IMAGE, and FILE_URI, supporting batch queries by type. Cache items use a compact structure, containing only blockId, data type, metadata pointer, version number, and access timestamp, occupying a total of 32 bytes.

[0173] The preloading mechanism for high-frequency caches: When ClipboardShadowCache starts, it reads the metadata of all allocated and unreleased memory blocks from the shared memory pool and preloads it into the cache by a background thread. After preloading, when the Android side accesses the high-frequency blockId for the first time, it does not need to wait for synchronization and can directly obtain the metadata from the cache.

[0174] Lock-free query and update: Cache query and update operations completely abandon mutex locks. OH and Android's native concurrency utility classes are used to maintain cache item pointers. During queries, pointers are obtained directly through a hash table without locking, supporting concurrent reads. During updates, pointers are replaced using CAS operations. If the replacement fails, it is retried to ensure atomicity of the update.

[0175] S5.4 Write transactions and data integrity guarantees.

[0176] The write transaction's phased state management divides the data writing process into three stages: writing in progress, writing complete, and synchronization complete. This is achieved through atomic marking of the `status` field in the memory block header: before writing begins, a CAS operation is used to change the `status` from idle to "transferring," locking the memory block; after data writing is complete, the `status` is updated to "complete," and a CRC32 checksum is written to the end; after cache synchronization confirmation, the access count on the OH side is marked as 1. Stage state changes are implemented through atomic operations, avoiding state inconsistencies caused by write interruptions.

[0177] The write interruption recovery mechanism is as follows: if a system interruption such as process scheduling or low memory reclamation occurs during the write process, the ClipboardService will determine the status of the memory block header after restarting. If the status is in transit and the checksum is invalid, the rewrite process will be triggered to reuse the original memory block and rewrite the data. If the status is complete but no synchronization confirmation has been received, the cache synchronization will be re-initiated.

[0178] Real-time parallel calculation of checksums: Data writing and CRC32 checksum calculation are performed in parallel. The CRC32C algorithm, accelerated by the CPU instruction set, updates the checksum in real time after each data segment is written, avoiding the extra time spent on separate calculations after the write is completed.

[0179] Active preheating and invalidation handling of S5.5 and Android side cache.

[0180] Cache preloading and priority sorting: After receiving the synchronization data packet on the Android side, ClipboardShadowCache automatically adds the blockId to the preloading queue in addition to updating the cache. The background thread sorts the data according to the data type priority, from high to low priority: image, text, file URI, rich text, and finally custom binary data. Preload some data such as image thumbnails and the first 1KB of text. When the user triggers paste, the preloaded data can be read directly, which effectively improves the response speed.

[0181] Cache timeout invalidation mechanism: Set a timeout period corresponding to the memory block for cached items, such as 30 seconds for the first-level pool, 60 seconds for the second-level pool, and 120 seconds for the third-level pool. After the timeout, it is marked as invalid. On the next access, a passive synchronization request is automatically sent to the OH side. After receiving the request, the OH side resynchronizes the latest metadata to ensure that the cached data is not outdated.

[0182] Fast synchronization for cache misses: If the target blockId is not found in the ClipboardShadowCache on the Android side, a cache query request is immediately sent via clipboard_eventfd. After receiving the request, the ClipboardShadowCache on the OH side returns a lightweight synchronization data packet. After receiving the packet, the Android side inserts it into the cache and performs data reading.

[0183] S6. Atomic transmission status marking and lock-free verification establish a mechanism for state machine, problem protection, layered parallel verification and dynamic timeout adaptation to ensure that after the data is written on the OH side, the transmission status of both ends is consistent and the data is not corrupted.

[0184] S6.1, Atomic state marking.

[0185] The polymorphic and refined definition of the transmission state: The transmission state flag field in the extended memory block header is a polymorphic state machine, which is compatible with the state control of the entire transmission process. The state values ​​are defined as follows: 0 indicates idle, 1 indicates write complete, 2 indicates synchronization complete, 3 indicates Android side confirmation of receipt, 4 indicates verification failure, 5 indicates state conflict, and 6 indicates timeout without confirmation. It covers all scenarios of dual-end interaction. The state switching is achieved through atomic operations, without intermediate states.

[0186] ABA problem protection for CAS operations: To avoid the ABA problem in status flags, the 4-byte version number in the memory block header is bound to the 1-byte transmission status flag field to form a composite flag of status and version number. During CAS operations, the status value and version number are verified simultaneously: the status update is only performed when the status meets expectations and the version number is consistent with the local record. After the update, the version number is atomically incremented.

[0187] The CAS strategy for dynamic retry is as follows: the status update adopts a load-aware retry mechanism instead of a fixed number of retries. When the system is under low load, such as when the CPU utilization is less than 50%, it will retry a maximum of 3 times, with an interval of 10ns between each retry. When the system is under high load, such as when the CPU utilization is not less than 50%, it will enter sleep mode through the futex system call after retrying once, so as to avoid occupying too much CPU resources.

[0188] Automatic reconciliation of state conflicts: If the OH side detects a state conflict when performing a state update, it triggers the reconciliation process by sending a state query signal through the clipboard_eventfd channel. After receiving the signal, the Android side returns the current state and version number. The OH side compares the data and performs state overwriting based on the principle of prioritizing the higher version number.

[0189] S6.2, Layered Parallel Lock-Free Verification.

[0190] Different verification algorithms are employed for different data areas to balance performance and security. Level 1 verification checks the integrity of the header: An XOR check is performed on the 16-byte header of the memory block, containing blockId, status, version number, checkSum, etc. All bytes are XORed bitwise to obtain a 1-byte checksum, which is compared with the reserved header checksum. If they do not match, the header is directly considered corrupted, requiring no further verification. Level 2 verification checks the consistency of metadata: A hash check is performed on the metadata, and the hash result is compared with the metadata hash value at the end of the metadata list to ensure that the metadata has not been tampered with. Level 3 verification checks the integrity of the data area: A CRC32C check is performed on the core data area, and the check result is compared with the CRC32C value at the end of the metadata list.

[0191] Segmented parallel verification mechanism: Reuse big data segmentation strategy, bind three-level verification with data segmentation. After each segment of data is written, the background thread synchronously executes the CRC32C verification of that segment. Finally, the total checksum is accumulated through atomic operations to avoid the high latency of centralized verification after writing.

[0192] Atomic storage of verification results: After verification is completed, the verification result is marked by CAS operation as a 1-byte extended header field, where 0 indicates no verification, 1 indicates verification passed, and 2 indicates verification failed. The result is written to the header of the memory block, and the version number is updated at the same time to ensure the consistency between the verification result and the status mark.

[0193] S6.3, Dual-state confirmation and dynamic timeout adaptation.

[0194] Structured confirmation signal design: After the OH side completes the status marking and verification, it waits for the Android side to confirm the received signal. The confirmation signal structure is optimized to a 4-byte blockId, a 1-byte status confirmation code, and a 4-byte Android side version number. The status confirmation code is such as 0x01 indicating successful reception, 0x02 indicating data corruption, and 0x03 indicating invalid metadata. The total length is 9 bytes.

[0195] Intelligent timeout adjustment mechanism: The timeout time is dynamically calculated based on historical synchronization delay. The ClipboardPerformanceMonitor class added in this embodiment records the average delay of the last 10 dual-end synchronizations. The timeout time is set to three times avgDelay to avoid misjudgment of timeout or excessive timeout caused by fixed timeout.

[0196] Tiered handling after timeout: If the OH side does not receive an acknowledgment signal within the timeout period, the following tiered handling is applied: For the first timeout, the synchronization completion status flag is immediately resent, and the listening thread on the Android side is woken up via futex_wake to avoid signal loss caused by thread sleep; For the second timeout, lightweight synchronization is triggered, which only resynchronizes the data area checksum and metadata, without retransmitting the complete data; For the third timeout, the status is marked as timeout unacknowledged, the shared memory block is released, accessCount is atomically decremented by 1, and an error log is recorded to the native logging system to avoid memory leaks.

[0197] S6.4 Error location and rapid recovery.

[0198] A refined error code system maps verification failures and status anomalies to 16 specific error codes. Each error code is stored as a 4-bit extension header, covering scenarios such as header corruption (0x01), metadata tampering (0x02), data area verification failure (0x03), unresolved status conflict (0x04), and timeout without confirmation (0x05). Each error code is bound to a specific processing strategy.

[0199] Targeted recovery mechanism: Perform differentiated recovery based on error codes to avoid the high overhead of full retries. When the header is damaged or metadata is tampered with, release the current memory block, return the ERR_CACHE_CORRUPT error code, and re-initiate the write request. When data area verification fails, only the data segment is rewritten and the verification is synchronized. When state conflicts are not resolved, force synchronization of the two-end states, and re-execute state marking after synchronization.

[0200] S6.5, lock-free memory barrier optimization.

[0201] Insert memory barrier instructions at key nodes in the verification process. Before verification begins, insert a storage barrier (sfence) to ensure that all write operations have been completed and flushed to physical memory. During verification, insert a load barrier (lfence) to ensure that the data read during verification is the latest physical memory data, rather than dirty data in the CPU cache. After verification is completed, insert a full barrier (mfence) to ensure that the verification result is marked as completed before executing subsequent status updates and event notifications.

[0202] Dual-end cache consistency guarantee: Before the Android side performs the verification, the CPU cache of the shared memory area is independently corresponding to the dc ivac instruction (ARM architecture) or clflush instruction (x86 architecture) to ensure that the latest data written by the OH side is read.

[0203] S7. Zero-copy reading and address mapping of shared memory data establishes mechanisms for on-demand mapping, acceleration by typed instruction sets, cache preloading, and segment merging, enabling the transfer of shared memory data to the Android clipboard service without intermediate copies, while ensuring address mapping security and data reading integrity.

[0204] S7.1, Optimization of secure mapping of shared memory addresses.

[0205] An on-demand mapping strategy driven by data type and data volume is adopted, mapping only the data region that needs to be read at the moment, avoiding the excessive virtual address space occupied by mapping large amounts of data in full:

[0206] For small amounts of data, such as text, file URIs, and custom data less than 10KB: the entire data is mapped to the Android process address space. The mapping is implemented through the mmap() system call, specifying the PROT_READ permission and the MAP_SHARED flag.

[0207] For large datasets, such as images and rich text files that are no less than 10KB: page-level on-demand mapping is used. The MADV_WILLNEED flag is set through the madvise() system call, and only the currently read 2MB memory page is mapped. Subsequent data is automatically loaded through kernel page faults.

[0208] Secondary verification and security isolation of mapping permissions: Before mapping, the actual permissions of the shared memory are read, and the permission verification results are compared twice. If the permissions do not match, the mapping is terminated immediately and the ERR_PERMISSION_MISMATCH error code is returned. At the same time, the mapping address range is specified by the MAP_FIXED_NOREPLACE flag, which isolates it from other address spaces of the Android application process to avoid the risk of crashes caused by address conflicts.

[0209] Atomic state binding for address mapping: After successful mapping, the shared memory block header status field is updated to "data read" via a CAS operation, and the version number is atomically incremented to ensure that the OH side is aware of the data read status in real time, avoiding duplicate writes or premature release of the memory block. If the CAS operation fails, it is retried after 10ns to ensure consistency of state binding.

[0210] S7.2, Accelerated Zero-Copy Reading by Type.

[0211] Accelerated text data reading via vector instruction set: This embodiment reuses the text block index table and memory-aligned storage structure. On the Android side, a new `AshmemReader` class is added to read data in batches using the CPU vector instruction set.

[0212] ARM architecture: Adopting the NEON instruction set, it reads 128 bits of data at a time and loads it directly into the text buffer of the Android clipboard service without encoding conversion;

[0213] x86 architecture: The movdqu instruction of the SSE4.2 instruction set reads 16 bytes at a time with a single instruction; by calling the instruction multiple times in a loop, 64 bytes of data can be loaded in batches; the instruction supports unaligned memory access and can be used with the pcmpistri instruction to quickly filter invalid padding characters.

[0214] Image data DMA channel reuse and pixel format adaptation: DMA channels are reused first, directly transferring RGBA_8888 format pixel data in shared memory to the pixel buffer of the Android Bitmap. The CPU is only responsible for initiating the transfer and format confirmation, and does not participate in data transfer. For devices without DMA support, it is downgraded to batch reading using the NEON instruction set. Simultaneously, it automatically adapts to the Android Bitmap's ARGB_8888 format, eliminating the need for pixel format conversion.

[0215] Index table reuse and merging for big data and segmented data: For segmented text, rich text, and image data, the block index table in shared memory is directly reused. Complete data reading is achieved through index table pre-reading, segmented parallel reading, and continuous memory merging: Pre-reading the index table: The index table in the header of shared memory is read quickly using memcpy; Segmented parallel reading: Two background threads are started to read data in parallel according to the index table blocks, avoiding the serial delay of single-threaded reading;

[0216] Continuous merging: The read segmented data is merged in a contiguous memory buffer of the Android process, and the merging process is optimized through memory copying.

[0217] Zero-copy pointer mapping for custom data: For modified Protobuf format custom data, the address of the shared memory data area is directly mapped to the ByteBuffer of the Android process. The Android native service ClipboardManager reads the data directly through the ByteBuffer without any copy operation.

[0218] S7.3, cache preloading and memory optimization.

[0219] Active preloading of CPU cache: Before reading data, the data is preloaded into the CPU cache using the __builtin_prefetch compiler built-in function supported by the Android NDK, specifying read permissions and locale caching strategies such as preferential storage in the L1 cache. Cache line alignment for data reading: Data is read according to the 64-byte CPU cache line size to avoid performance loss caused by accessing across cache lines.

[0220] Further avoidance of copy-on-write (COW): When sharing memory mapping, the MADV_DONTFORK flag is set through the madvise() system call to avoid triggering an implicit copy when the Android side reads the memory for the first time, ensuring that the zero-copy feature is maintained throughout the entire process.

[0221] S7.4 Error handling and safe release of resources.

[0222] Lightweight integrity check for reads: The results of the three-level checksum are reused. After reading, only a digest check is performed. For text and custom data, the XXH32 hash value of the read data is calculated and compared with the checksum at the end of the shared memory and the first 4 bytes. For images and rich text data, the total length after merging the blocks is checked against the data length in the shared memory metadata. If the checksum fails, the shared memory block is marked as corrupted, and an ERR_DATA_CORRUPT error code is returned.

[0223] Atomic release of mapped resources: After data reading is completed and verification is successful, resources are released through a double atomic operation. The accessCount of the shared memory block is atomically decremented by 1 through a CAS operation. When the count is 0, the state is marked as free. The munmap() system call is called to release the virtual address mapping of the Android process and the file descriptor at the same time. Atomic release ensures that resources are not leaked and that the memory states of both ends are consistent.

[0224] Resource reclamation in abnormal scenarios: If mapping fails or reading is interrupted, emergency reclamation is performed immediately to release the mapped virtual address space, close the shared memory FD, and prevent file descriptor leakage; the shared memory block status is marked as mapping failure and fed back to the OH side to trigger data retransmission.

[0225] Efficient data delivery for S7.5 and Android clipboard services.

[0226] Direct pointer passing and buffer reuse: Read data is delivered directly to AndroidClipboardManager via pointer passing, avoiding intermediate buffer copying. For text data, the pointer to the underlying array after reading is passed directly, and ClipboardManager binds the data without copying the array. For image data, the pixel buffer pointer of Bitmap is unbound from the shared memory data area and delivered directly to ClipboardManager.

[0227] Decoupling asynchronous callbacks from the main thread: After data delivery is complete, an asynchronous callback carrying only the blockId and the read result is sent to the main thread of the Android application through the native Android class Handler, avoiding blocking subsequent operations of the clipboard service.

[0228] Final synchronization of dual-end status: A confirmation signal indicating the completion of data reading is sent to the OH side via the clipboard_eventfd channel. This signal includes a 1-byte 0x03, a 4-byte blockId, and a 4-byte version number. Upon receiving this signal, the OH side updates its local ClipboardShadowCache status, thus completing the closed loop of dual-end data transmission.

[0229] S8 features lightweight lazy conversion and format restoration of heterogeneous data. It establishes a mechanism for access-triggered lazy conversion, acceleration by type-based instruction sets, caching of conversion results, and failure degradation. It restores pre-processed heterogeneous data in shared memory to an Android native recognizable format, while avoiding resource waste caused by premature conversion.

[0230] S8.1 Optimization of the lazy conversion triggering mechanism.

[0231] Access interception triggering: The Android native class ClipData of the Android clipboard service is encapsulated through the proxy pattern. A LazyConvertClipData proxy class is created to intercept the application's calls to data access methods such as getText() and getItemAt(intindex). The format conversion is triggered only on the first access. Unaccessed data remains in a preprocessed state to avoid meaningless conversion overhead.

[0232] Delayed execution and background scheduling: After the conversion is triggered, if the data type is non-urgent, such as text or file URI, the conversion task is submitted to the Android background thread pool and the conversion result is returned asynchronously through Handler, avoiding blocking the application's main thread; if the data is urgent, such as image data that needs to be displayed immediately, the conversion is performed in the current thread, accelerated by instruction set, balancing response speed and resource utilization.

[0233] Dynamic adjustment of conversion priority: The conversion priority is set based on the application access scenario. The application thread priority is obtained and the conversion task priority is adjusted synchronously. If the foreground application accesses an urgent request, such as clicking the paste button, the conversion task priority is set to THREAD_PRIORITY_FOREGROUND and executed first. If the background application accesses an application, such as background clipboard synchronization, the priority is set to THREAD_PRIORITY_BACKGROUND and executed when idle.

[0234] S8.2, Optimized lightweight conversion by type.

[0235] Text data encoding adaptation and lightweight conversion: Reuse dual-encoding storage structure, dynamically adapt encoding according to Android application requirements. If the application calls getText() to get text, it reads UTF-16 encoded data without conversion; if the application calls openInputStream() to get byte stream, it quickly converts UTF-16 to UTF-8 using the NEON / SSE4.2 vector instruction set; For special characters such as Emoji and Unicode extended characters, it restores them using the Android native API Character.codePointAt() method, avoiding character loss caused by encoding conversion.

[0236] Image data resolution adaptation and format fine-tuning employ a custom dual-storage structure of original images and thumbnails, as described in this embodiment, to achieve on-demand image resolution conversion. When the application calls the custom `getBitmap()` method of the proxy object, it obtains the target display's expected resolution. If the obtained original image resolution matches the expected resolution, a Bitmap object is directly constructed and returned without performing scaling conversion. If the resolution does not match, for example, if the application's display area is only 300... If the value is 300, then bilinear interpolation is used to dynamically scale the image; bilinear interpolation can be implemented by enabling filter parameters through the Android native Bitmap.createScaledBitmap interface. The image pixel binary data is stored in shared memory, and a Bitmap object is generated and returned when the delegate method is accessed.

[0237] Format fine-tuning: If the application requires RGB_565 format, Bitmap.copy is not used directly. Instead, the locked pixel buffer of Bitmap is accessed at the NDK layer, and the format conversion logic is completed under the constraints of the original memory area, reducing additional memory allocation.

[0238] File URI Path Mapping Restoration and Dynamic Mounting: The CrossContainerPathCache path mapping cache is reused to restore the Android virtual path to an accessible file resource. During the conversion, the OH physical path is quickly queried through the CRC32 hash value of the virtual path, and the OH physical path is dynamically mounted to the specified directory of the Android container. The restored URI provides an access interface to the outside world through the ClipboardFileProvider added in Android in this embodiment. Applications can read files through ContentResolver.openInputStream(uri).

[0239] Rich text tag mapping restoration and delayed parsing: The RichTextMapTable tag mapping table is reused to achieve lightweight restoration of OHHTML tags to Android Spanned format. A display area delayed parsing strategy is adopted, which only parses the rich text fragments currently displayed by the application, and does not parse fragments that are not displayed. Tag conversion is implemented through function pointer mapping. Image tags are restored to Android ImageSpan, which directly references the read Bitmap and does not require reloading.

[0240] Lazy deserialization and on-demand field parsing of custom data are implemented based on the modified Protobuf format. Only the fields that are currently needed are parsed, avoiding the overhead of full deserialization. The deserialization process uses a custom protobuf-lite library, a lightweight Android Protobuf parsing library, to avoid reflection overhead.

[0241] S8.3 Cache and reuse of conversion results.

[0242] Lightweight LRU caching design: A new ConvertResultCache class is added, which uses the Least Recently Used (LRU) caching strategy to store conversion results. The cache capacity is set to 10 entries to cover frequently accessed data. The cache item structure is: 4-byte blockId, 1-byte data type, 8-byte conversion result pointer, and 4-byte access timestamp.

[0243] Atomic updates and reads of the cache: Lock-free operations for adding, querying, and deleting cached data are achieved through AtomicReference, supporting concurrent access and avoiding repeated conversions.

[0244] The cache invalidation mechanism sets cache invalidation conditions to ensure data freshness: time-based invalidation, the timeout period for cached items is set to 30 seconds, and they are automatically deleted after the timeout; data change invalidation, if the clipboard data is updated on the OH side, the cached item with the corresponding blockId is immediately deleted via CAS operation to avoid reuse of old data.

[0245] S8.4, Compatibility and Error Handling.

[0246] Android version compatibility adaptation: Dynamically adjust the conversion logic to address format differences between different Android versions. For Android 13 and above, support the setExtras(PersistableBundle) method of ClipDescription to add metadata such as data type and resolution to adapt to new system features.

[0247] For Android 10 to Android 12 storage permission compatibility handling, after the file URI is restored, a custom Android container process with authorization capabilities grants the target application temporary read access permissions for that URI. After obtaining temporary URI authorization, the target application does not need to have READ_EXTERNAL_STORAGE storage permission to call ContentResolver.openInputStream(uri) to complete the data stream reading. Business logic needs to call revokeUriPermission() in a timely manner to reclaim the granted temporary URI permissions and prevent permission residue leaks.

[0248] For Android 9 and below, rich text conversion is downgraded to plain text, and the image format is fixed to ARGB_8888 to adapt to the limitations of lower version APIs.

[0249] A rapid degradation strategy for conversion failures: For abnormal scenarios such as data corruption or unsupported formats, differentiated degradation is performed. When text conversion fails, the original UTF-8 text is returned to ensure that the application can obtain the basic content. When image conversion fails, a pre-generated thumbnail is returned to replace the original image. When custom data deserialization fails, the original ByteBuffer byte stream is returned for application parsing to avoid complete unavailability.

[0250] Accurate error code feedback and logging: When conversion fails, an error code is returned, such as 0x01 indicating encoding conversion failure, 0x02 indicating resolution scaling failure, and 0x03 indicating URI mounting failure. This code is then passed to the application, and an error log is recorded, which includes the blockId, data type, and error reason.

[0251] S8.5 Performance optimization of the conversion process.

[0252] Accelerated instruction set for conversion operations: All conversion logic, such as encoding conversion, resolution scaling, and label mapping, is implemented in C++, reusing the NEON / SSE4.2 vector instruction set for batch data processing.

[0253] Memory-aligned storage of conversion results: The converted result data is stored aligned to 64-byte CPU cache lines to avoid performance loss caused by accessing across cache lines.

[0254] GC avoidance optimization: During the conversion process, the native memory buffer DirectByteBuffer is used to store intermediate data, avoiding GC caused by Java heap memory allocation. At the same time, the buffer is reused to reduce memory allocation overhead.

[0255] S9: Android applications trigger clipboard reading and data return, establishing a mechanism for trigger preloading, lock-free concurrent scheduling, dynamic permission verification, and multi-scenario degradation adaptation, to achieve efficient response and secure data return for Android application paste operations.

[0256] S9.1 Optimization of preloading and asynchronous response triggered by paste.

[0257] Context-based preloading is triggered by monitoring the application's running status in real time through the Android native service ActivityManagerService, and implementing preloading strategies based on foreground and background call scenarios.

[0258] For frequent clipboard pasting scenarios in foreground applications, the Android native `ClipboardManager.addPrimaryClipChangedListener()` is registered to listen for clipboard content changes. This listener only detects clipboard content modifications and cannot directly capture UI actions such as long-pressing to paste or clicking a button to paste. With system privileges, the focus state of the caller's window and controls is obtained. After a clipboard change, a memory prefetch instruction is executed to provide hardware prefetching hints, performing partial preprocessing on text and image thumbnails. The preprocessing results are stored in the custom software cache of this invention. It cannot be guaranteed that the data will reside in the CPU L1 cache. When the application calls `getPrimaryClip()`, the preprocessing results are returned from the software cache first.

[0259] For background applications accessing the clipboard, the preloading logic is not executed; when an actual access occurs, a background thread is started using Android's native HandlerThread to asynchronously complete the ashmem data reading and format restoration processing, thus avoiding preemption of foreground business resources.

[0260] Main thread zero-blocking design: The application-triggered paste call adopts a fast return and asynchronous completion mechanism. If the data has been preloaded, it directly returns a ClipData object that encapsulates the restoration result, and the main thread is not blocked. If the data has not been preloaded, it immediately returns an empty ClipData placeholder, and at the same time, it notifies the application through a Callback after the background data preparation is completed, avoiding synchronous waiting of the main thread.

[0261] S9.2 Zero-copy data return and buffer reuse.

[0262] Zero-copy return of text data: The underlying array CharSequence is reused, and the array reference is encapsulated in the ClipData.Item object by passing it directly by pointer. When the application calls getText(), it directly returns this reference without any data copying. If the application needs a byte stream, the UTF-8 encoding buffer is reused, and the buffer address is bound through FileDescriptor to return the input stream.

[0263] Pointer passing of image data and Bitmap reuse: The restored Bitmap object is marked as immutable to avoid copying caused by application modifications. When the application calls getBitmap(), it directly returns the Bitmap pointer without the need for copy() operation. If the application needs to modify the image, it reuses the original pixel buffer through Bitmap.copy().

[0264] File URIs and rich text streams are returned directly: The file URI reuses the custom ClipboardFileProvider class. When the application calls ContentResolver.openInputStream(uri), the file data in shared memory is directly encapsulated into an input stream using ParcelFileDescriptor, without intermediate file copying. For rich text, the spanned format data is encapsulated into ClipData.Item. When the application calls getText(), it returns a Spanned reference, supporting native style rendering such as bold and image embedding without secondary parsing.

[0265] Cross-process Parcelable delivery of custom data: The encapsulated Parcelable object is bound to the Item through the ClipData.Item.setParcelableData() method. When the application calls getParcelable(), it is transferred with zero copy through the Binder mechanism.

[0266] S9.3, High-concurrency scheduling and priority guarantee.

[0267] Lock-free concurrent request queue: A lock-free queue with a single producer and multiple consumers is used to cache concurrent paste requests, with a queue capacity of 64. When the application triggers a paste request, the write pointer is updated through a CAS operation and the request is added to the concurrent request queue. The background processing thread obtains the request through a volatile read pointer and completes the dequeueing.

[0268] Context-based priority scheduling: Request priorities are divided according to application scenarios and states to ensure that critical operations are responded to first. For the highest priority front-end input control pasting, such as EditText and TextView, it is directly inserted into the head of the queue and processed immediately. For the medium priority front-end non-input control pasting, such as pasting images in an image viewer, it is inserted into the middle of the queue. For the low priority background application pasting, such as cloud synchronization tools, it is inserted into the tail of the queue and processed when idle.

[0269] S9.4 Security verification and data integrity assurance.

[0270] Dynamic secondary verification of application permissions: Reuse the hierarchical permission model and perform the final permission verification before data is returned. For ordinary data, read the ClipboardPermissionCache to confirm that the application has passed the verification; for sensitive and highly sensitive data, query the application permissions in real time to confirm the application's foreground status.

[0271] Final data integrity verification: Reuse the digest of the converted CRC32C checksum, perform lightweight digest verification before returning the data. For text and custom data, compare the XXH32 hash value of the returned data with the cached digest. If they match, return the data. For images and file URIs, verify whether the data length matches the length in the metadata. If they match, return the data.

[0272] S9.5, compatibility adaptation and error handling.

[0273] Android version differentiation adaptation: Dynamically adjust the return logic to address the differences in clipboard API across different versions. For Android 13 and above, return the corresponding data according to the MIME type declared by the application. For example, if the application only declares text / plain, then no image will be returned. Adapt to the new system permission control.

[0274] For Android versions 10 to 12, it is compatible with indirect permission associations such as ACCESS_COARSE_LOCATION. If an application does not have clipboard permission but has relevant system permissions, the temporary grant of read permission is only valid once to avoid functional failure due to insufficient permissions.

[0275] For Android 9 and below, it is downgraded to the traditional ClipData format. When custom Parcelable data is not supported, it is automatically converted to a byte stream and returned to adapt to the limitations of low-version APIs.

[0276] Error scenario tiered degradation: Differentiated degradation is performed for abnormal scenarios to ensure application availability. When permissions are insufficient, empty ClipData is returned, and a Toast message is sent to the user to request clipboard access. When data is corrupted, pre-generated backup data is returned, such as plain text for text and thumbnails for images, and an error log is recorded. For concurrent conflicts, a queue retry mechanism is used to attempt recovery.

[0277] In summary, the above are merely preferred embodiments of the present invention and are not intended to limit the scope of protection of the present invention. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the scope of protection of the present invention.

Claims

1. A high-performance cross-environment clipboard interoperability method based on dual-ended shadow caching, characterized in that, Specifically, the following steps are included: When the host starts, it builds a three-level permission cache and a three-level shared memory pool, and establishes memory binding rules between data types and memory pools. When the host application triggers a copy operation, the host clipboard agent encapsulates the valid clipboard data into a lightweight IPC transport packet and sends it to the host clipboard service. The service parses the packet and encapsulates it into a native host cut object containing the data type, data length, and original clipboard data. The sensitivity level is determined based on the data type of the native host cut object. The three-level permission cache is retrieved according to the access verification policy corresponding to the sensitivity level to obtain the permission identifier of the container application. Cross-container access rules and permission determination methods are generated and written into the clipboard operation context. Heterogeneous data preprocessing is performed on the original clipboard data to obtain clipboard data; memory blocks are allocated in the memory pool according to memory binding rules and block identifiers are generated; the memory blocks are mapped to the user-mode virtual address of the clipboard service and loaded into the processor cache; clipboard data is written to the memory blocks; and a block index table is built in the header of the memory blocks. Update the host shadow cache to record synchronization metadata and management information, send a clipboard change event carrying synchronization metadata to the container, and trigger the container clipboard agent to update the synchronization metadata to the container shadow cache; When a container application initiates a paste request, the container clipboard agent retrieves the synchronous metadata corresponding to the block identifier from the container shadow cache and verifies the container application's permissions again. Upon successful verification, the agent maps the corresponding memory block to the virtual address space of the container clipboard agent process, increments the shared memory block access count using atomic operations, updates the memory block status identifier, and passes the virtual address to the container clipboard service. After obtaining the synchronous metadata, the container clipboard service encapsulates the virtual address into a container-native clipping result object and returns it to the container application that initiated the paste request. After the read operation is complete, the agent atomically decrements the access reference count, releases the container process's virtual address mapping resources, sends a read completion confirmation signal to the host, and synchronously updates the dual-end cache status.

2. The cross-environment clipboard high-performance interoperability method according to claim 1, characterized in that, The three-level permission cache includes L1 cache, L2 cache and L3 cache. L1 cache only stores the permission identifiers of container applications whose usage frequency is greater than the threshold. L2 cache stores the container application permission entries corresponding to the current L1 cache, as well as container application permission entries that have been removed from L1 cache but have not expired. L3 cache stores the long-term permission records of all container applications.

3. The cross-environment clipboard high-performance interoperability method according to claim 1, characterized in that, Sensitivity levels and permissions are determined based on data type, specifically: Text and images are classified as ordinary, corresponding to ordinary permissions. Access is first read from L1 and L2 caches. If the cache is not hit, the L3 cache is queried, and the query result is synchronized to both L1 and L2 caches. The effective lifespan of cache entries corresponding to ordinary permissions is the maximum value. File Uniform Resource Locators (URIs) and rich text are classified as sensitive, corresponding to sensitive permissions. The effective lifespan of L1 and L2 cache entries is the smaller value. If the cache expires, the L3 cache is forcibly read. After a cache hit, it is verified whether the container application is in the foreground. If it is in the background, access is denied. Custom binary data is classified as highly sensitive, corresponding to highly sensitive permissions. Each access reads the L3 cache to verify permissions and triggers a secondary authorization pop-up for the user. Highly sensitive permission records are not written to L1 and L2 caches.

4. The cross-environment clipboard high-performance interoperability method according to claim 1, characterized in that, The host clipboard service distinguishes the type of clipboard data based on a single-byte mask marker and performs validity checks on different data types through bitwise operations. Specifically, for text data, the data is valid if the data length is a positive integer and the first byte is a non-empty placeholder; for image data, the data is valid if the image width and height are positive integers and the pixel format identifier is in the host's native image format; for file data, the data is valid if the file length meets the constraints and the starting character matches the absolute path specification; for rich text and custom binary data, the data is valid if the data length is a positive integer and the basic format identifier is compliant. When any data type validation fails, the corresponding error code is returned to the upper-layer application and the current flow record is marked as failed.

5. The cross-environment clipboard high-performance interoperability method according to claim 2, characterized in that, The specific methods for generating cross-container access rules and determining permissions are as follows: For normal levels, the cache read order is to first read the L1 cache, then the L2 cache, and only if both caches are missed is the L3 cache read. After the permission record is read from the L3 cache, the L2 cache is updated synchronously, and then the L1 cache is atomically refreshed. If it is a sensitive level, the cache reading order is to read the L1 cache first and then the L2 cache. The timestamp is checked during reading, and the cache is discarded if it times out. After the cache expires, read the L3 cache, refresh the L2 cache, and synchronize the L1 cache. If the level is high sensitivity, the L3 cache is read every time, and the permission records found are not written to the L1 or L2 cache. Permission determination method: If the permission is marked as unauthorized, the container application will be denied access to the current clipboard data in any scenario; if the permission is marked as authorized, the container application is allowed to read the current clipboard data if it is at a normal level, allowed if it is at a sensitive level and the container application is in the foreground, and allowed after user confirmation if it is at a highly sensitive level; if the permission is marked as expired, it is equivalent to unauthorized.

6. The cross-environment clipboard high-performance interoperability method according to claim 1, characterized in that, Both the host shadow cache and the container shadow cache use a two-level indexing method of hash table and data type linked list to store cache entries. The hash table uses the block identifier as the key to index the corresponding cache entry. The background thread completes the cache preloading and uses atomic operations to implement access control for cache read and write.

7. The cross-environment clipboard high-performance interoperability method according to claim 1, characterized in that, The block index table is constructed as follows: text data is not split, and only a single index record is generated; image data is evenly fragmented according to the DMA hardware transfer granularity and fragment index records are generated sequentially; rich text and file URIs are split into independent fragments according to internal logical units to generate fragment index records, and each fragment is configured with independent verification information; custom binary data is dynamically fragmented into variable-length fragments to generate fragment index records.

8. The cross-environment clipboard high-performance interoperability method according to claim 1, characterized in that, After receiving a clipboard change event, the container parses the block identifier carried by the event and binds the corresponding synchronization metadata. It then constructs a data reading context according to a preset priority. When a paste request triggers shared memory mapping, it reads the clipboard data. All cached entries are configured with lifecycle timeout rules and are immediately cleaned up after the timeout. The data reading context is a set of reading resources and parameters initialized by the container clipboard agent after receiving the clipboard change event. It includes pre-allocated worker thread resources, validation algorithm handles, data structures, resource placeholders, data types, and sharding strategy identifiers.

9. The cross-environment clipboard high-performance interoperability method according to claim 1, characterized in that, Differentiated zero-copy read strategies are implemented for clipboard data of different data types. Specifically: for ordinary text, CPU vector instruction sets are used to load it into memory in batches sequentially, and contiguous memory blocks are prefetched segment by segment according to the block index table; for ordinary images, DMA hardware channels are reused first, and pixel data is directly transferred to the image buffer via shared memory physical pages. If DMA hardware is not available, CPU vector instructions are used for reading; for sensitive data, a segmented parallel read mechanism is adopted, with multiple worker threads concurrently reading each segment according to the block index table, and then assembling them in an orderly manner after reading. For highly sensitive custom binary data, the target fragment is read point-to-point based on the block index table.

10. The cross-environment clipboard high-performance interoperability method according to claim 1, characterized in that, After the container clipboard service encapsulates the virtual address into a container native clipping result object and returns it to the container application, the lazy conversion proxy intercepts the application's clipboard data access interface call. When the container application reads the clipboard data for the first time, it starts a format conversion task, determines the execution method of the task based on the access urgency, and dynamically adjusts the scheduling priority of the task based on the application thread state. For text data, the corresponding encoding format is selected based on the data reading interface type called by the container application to complete the encoding format conversion; for image data, the image is scaled and the pixel format is fine-tuned according to the resolution required by the application; for file URIs, the virtual path is restored based on the path mapping cache, resources are dynamically mounted, and a file access interface is provided; for rich text, the visible area fragments are parsed based on the tag mapping table to complete the tag mapping conversion; for custom binary data, on-demand lazy deserialization of fields is performed and container format-compatible encapsulation is implemented. After the conversion is complete, the conversion result is stored in a lightweight conversion cache, and the cache can be read and written concurrently without locks through atomic operations.