This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-swift-export-memory-pinning-guardrail

KMP Swift-Export Binary ABI Memory-Pinning and Lifecycle Synchronization

Enforces strict memory-pinning invariants and lifecycle reference consistency across the Kotlin/Native and Swift Binary ABI boundary. Guarantees that asynchronous Swift ARC invocations and Kotlin Native GC cycles do not produce dangling pointers, premature deallocations, or heap corruption during interop bridge operations.

Prohibited Anti-Pattern: Dangling Pointer De-synchronization via Unpinned Raw Pointers or Unmanaged Swift-Export Interop Transfers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Swift-Export Binary ABI Memory-Pinning and Lifecycle Synchronization - Enforces strict memory-pinning invariants and lifecycle reference consistency across the Kotlin/Native and Swift Binary ABI boundary. Guarantees that asynchronous Swift ARC invocations and Kotlin Native GC cycles do not produce dangling pointers, premature deallocations, or heap corruption during interop bridge operations.
globs: **/iosMain/**/*.kt, **/nativeMain/**/*.kt, **/swiftExport/**/*.kt, **/*Bridge*.kt, **/*Export*.kt, iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-memory-pinning-guardrail"
---

# KMP Swift-Export Binary ABI Memory-Pinning and Lifecycle Synchronization

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Dangling Pointer De-synchronization via Unpinned Raw Pointers or Unmanaged Swift-Export Interop Transfers

## System Constraints
You are a Principal Mobile Systems Architect and Binary ABI Specialist enforcing the KMP Swift-Export Binary ABI Memory-Pinning Guardrail. Mandate that any native memory buffers, unmanaged object pointers, or asynchronous callback continuations crossing the Kotlin/Native and Swift ARC boundary are explicitly pinned with StableRef or usePinned blocks, and deterministically balanced against Swift ARC deinitialization hooks to eliminate memory corruption and SIGSEGV panics.

## Strict Guidelines
- Engineers MUST ALWAYS wrap Kotlin object instances passed as raw pointer handles into Swift with StableRef.create() and explicitly release them via dispose() inside the corresponding Swift deinit.
- Engineers MUST NOT pass raw CPointer or direct buffer memory addresses across thread boundaries without enclosing the execution within an active usePinned block or StableRef lifecycle scope.
- Code SHOULD enforce bidirectional lifetime binding where Swift wrapper classes conform to explicit destruction semantics (e.g., native deinit triggering Kotlin teardown) rather than relying on non-deterministic garbage collection.
- Services MUST validate that native memory regions shared via Swift-Export buffers are pinned prior to scheduling asynchronous background work via GCD or Swift Concurrency Tasks.
- Components NEVER expose unpinned Kotlin ByteArray or primitive arrays directly to Swift as raw pointers; engineers must pin arrays and extract the pinned head pointer using addressOf(0).

## Bad vs Good Implementations
### Bridging Kotlin Shared State to Swift via StableRef and Explicit ARC Disposal

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin Native's concurrent garbage collector does not track unmanaged raw pointers or unpinned references retained only by Swift ARC. If Kotlin triggers a GC cycle while Swift holds or schedules operations on this pointer, the object is reclaimed, producing EXC_BAD_ACCESS (SIGSEGV) when Swift dereferences it.
```kotlin
// CRITICAL DEFECT: Passing raw Kotlin reference address without GC pinning
package com.example.interop

import kotlinx.cinterop.COpaquePointer

class DataStreamChannel(val channelId: String) {
    fun deliverPayload(data: ByteArray) {
        // Emits payload to native layer
    }
}

// Anti-pattern: Object can be collected by Kotlin GC while Swift holds the raw pointer
@OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
fun exportStreamChannelUnsafe(channel: DataStreamChannel): COpaquePointer? {
    // DANGEROUS: Type cast or address extraction without StableRef root registration
    // Swift ARC knows nothing of Kotlin GC roots; Kotlin GC sweeps channel mid-flight
    return null // Represents passing unpinned or unmanaged raw reference
}
```

#### Production Standard (Correct)
> **Standard**: StableRef.create(channel) pins the Kotlin object into the GC root set, preventing premature reclamation while Swift ARC holds the unmanaged pointer. Exposing an explicit releaseStreamChannel function ensures that Swift's deinit safely disposes of the StableRef, maintaining ABI consistency without memory leaks or SIGSEGVs.
```kotlin
// PRODUCTION STANDARD: Pinning lifecycle via StableRef with deterministic Swift deinit disposal
package com.example.interop

import kotlinx.cinterop.COpaquePointer
import kotlinx.cinterop.StableRef
import kotlinx.cinterop.asStableRef

class DataStreamChannel(val channelId: String) {
    fun deliverPayload(data: ByteArray) {
        // Emits payload to native layer
    }
}

@OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
fun exportStreamChannel(channel: DataStreamChannel): COpaquePointer {
    // Pin the Kotlin reference as an active GC root
    val stableRef = StableRef.create(channel)
    return stableRef.asCPointer()
}

@OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
fun releaseStreamChannel(opaquePointer: COpaquePointer) {
    // Deterministically unpin reference when Swift ARC invokes deinit
    val stableRef = opaquePointer.asStableRef<DataStreamChannel>()
    stableRef.dispose()
}
```

### Asynchronous Memory Buffer Sharing via usePinned

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin's GC may compact memory or move array allocations during garbage collection cycles. Handing off an unpinned byte buffer address across the Swift-Export boundary allows the underlying memory address to become invalid or point to disparate heap metadata.
```kotlin
// CRITICAL DEFECT: Passing raw ByteArray memory to Swift async callback without pinning
package com.example.interop

import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.CValuesRef
import kotlinx.cinterop.ByteVar

@OptIn(ExperimentalForeignApi::class)
fun processBufferUnsafe(buffer: ByteArray, onComplete: (Int) -> Unit) {
    // Anti-pattern: Buffer is unpinned; Kotlin GC can relocate ByteArray during compaction
    // Swift worker thread reading memory at this raw offset will read corrupted memory
    val rawPtr = buffer.toString() // Simulating unpinned memory handoff
    onComplete(buffer.size)
}
```

#### Production Standard (Correct)
> **Standard**: The usePinned extension pins the ByteArray in memory, ensuring that its physical address remains fixed and resistant to GC compaction while Swift or native C functions consume the memory via addressOf(0). Once the block scope exits, the pinned handle is automatically released.
```kotlin
// PRODUCTION STANDARD: Pinning memory buffer before C/Swift ABI address extraction
package com.example.interop

import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.usePinned
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.ByteVar

@OptIn(ExperimentalForeignApi::class)
fun processBufferPinned(
    buffer: ByteArray,
    externalConsumer: (CPointer<ByteVar>, Int) -> Unit
) {
    // Guarantees array address immobility throughout foreign invocation
    buffer.usePinned { pinned ->
        val rawAddress: CPointer<ByteVar> = pinned.addressOf(0)
        externalConsumer(rawAddress, buffer.size)
    }
    // Buffer is automatically unpinned here after native consumption terminates
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP Swift-Export Binary ABI Memory-Pinning and Lifecycle Synchronization

KMP Swift-Export Binary ABI Memory-Pinning and Lifecycle Synchronization defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory-pinning invariants and lifecycle reference consistency across the Kotlin/Native and Swift Binary ABI boundary. Guarantees that asynchronous Swift ARC invocations and Kotlin Native GC cycles do not produce dangling pointers, premature deallocations, or heap corruption during interop bridge operations. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Dangling Pointer De-synchronization via Unpinned Raw Pointers or Unmanaged Swift-Export Interop Transfers Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftDangling Pointer De-synchronization via Unpinned Raw Pointers or Unmanaged Swift-Export Interop TransfersCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS wrap Kotlin object instances passed as raw pointer handles into Swift with StableRef.create() and explicitly release them via dispose() inside the corresponding Swift deinit.

Engineers MUST ALWAYS wrap Kotlin object instances passed as raw pointer handles into Swift with StableRef.create() and explicitly release them via dispose() inside the corresponding Swift deinit.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT pass raw CPointer or direct buffer memory addresses across thread boundaries without enclosing the execution within an active usePinned block or StableRef lifecycle scope.

Engineers MUST NOT pass raw CPointer or direct buffer memory addresses across thread boundaries without enclosing the execution within an active usePinned block or StableRef lifecycle scope.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code SHOULD enforce bidirectional lifetime binding where Swift wrapper classes conform to explicit destruction semantics (e.g., native deinit triggering Kotlin teardown) rather than relying on non-deterministic garbage collection.

Code SHOULD enforce bidirectional lifetime binding where Swift wrapper classes conform to explicit destruction semantics (e.g., native deinit triggering Kotlin teardown) rather than relying on non-deterministic garbage collection.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST validate that native memory regions shared via Swift-Export buffers are pinned prior to scheduling asynchronous background work via GCD or Swift Concurrency Tasks.

Services MUST validate that native memory regions shared via Swift-Export buffers are pinned prior to scheduling asynchronous background work via GCD or Swift Concurrency Tasks.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER expose unpinned Kotlin ByteArray or primitive arrays directly to Swift as raw pointers

Components NEVER expose unpinned Kotlin ByteArray or primitive arrays directly to Swift as raw pointers; engineers must pin arrays and extract the pinned head pointer using addressOf(0).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is KMP Swift-Export Binary ABI Memory-Pinning and Lifecycle Synchronization critical for AI coding assistants?

Enforces strict memory-pinning invariants and lifecycle reference consistency across the Kotlin/Native and Swift Binary ABI boundary. Guarantees that asynchronous Swift ARC invocations and Kotlin Native GC cycles do not produce dangling pointers, premature deallocations, or heap corruption during interop bridge operations. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Dangling Pointer De-synchronization via Unpinned Raw Pointers or Unmanaged Swift-Export Interop Transfers) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

KMP