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

Kotlin Multiplatform 2.1 Swift Export Foreign Memory Allocation Quarantine

Enforces strict memory quarantine and deterministic buffer lifetime management across the Kotlin/Native 2.1 Swift Export boundary. Prevents silent heap corruption, double-frees, and use-after-free crashes by prohibiting raw unmanaged pointer escapes and mandating scoped pinned-buffer transfers with explicit ownership handoffs.

Prohibited Anti-Pattern: Escaping Raw CPointer or UnsafePointer Across Swift Export Boundaries Without Explicit Lifetime Pinning

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform 2.1 Swift Export Foreign Memory Allocation Quarantine - Enforces strict memory quarantine and deterministic buffer lifetime management across the Kotlin/Native 2.1 Swift Export boundary. Prevents silent heap corruption, double-frees, and use-after-free crashes by prohibiting raw unmanaged pointer escapes and mandating scoped pinned-buffer transfers with explicit ownership handoffs.
globs: shared/src/iosMain/**/*.kt, shared/src/nativeMain/**/*.kt, iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-foreign-memory-quarantine"
---

# Kotlin Multiplatform 2.1 Swift Export Foreign Memory Allocation Quarantine

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Escaping Raw CPointer or UnsafePointer Across Swift Export Boundaries Without Explicit Lifetime Pinning

## System Constraints
You are a Principal Software Architect enforcing foreign memory safety in Kotlin Multiplatform 2.1 projects utilizing Swift Export. Enforce strict isolation barriers between Swift UnsafeRawPointer allocations and Kotlin/Native GC heaps to prevent undefined behavior and heap corruption.

## Strict Guidelines
- Engineers MUST ALWAYS scope Kotlin-managed byte buffers within `usePinned { ... }` blocks when exposing pointers to Swift Export APIs.
- Engineers MUST NOT leak raw Kotlin `CPointer` or Swift `UnsafePointer` references outside their enclosing stack frame or immediate closure invocation.
- Swift clients MUST NOT retain raw pointers passed from Kotlin; data intended for persistent storage MUST be immediately copied into Swift-owned contiguous buffers (e.g., `Data(bytes:count:)`).
- Native allocations created via `kotlinx.cinterop.nativeHeap` MUST have an unambiguous, single-owner deallocation contract, guaranteed by a paired `defer { ... }` in Swift or an auto-closable quarantine wrapper in Kotlin.
- Code MUST NEVER bridge unpinned heap arrays across asynchronous or concurrent suspension points (`suspend` functions or Swift `async/await`).
- Services MUST validate byte lengths and buffer bounds prior to passing native pointers across the interop boundary to prevent foreign heap out-of-bounds writes.

## Bad vs Good Implementations
### Unpinned Pointer Escape vs. Quarantined Scoped Pinning in KMP 2.1

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Returning a raw CPointer derived from a Kotlin ByteArray without holding its pinned lifetime allows the Kotlin/Native garbage collector to invalidate or reallocate the memory while Swift attempts to read or mutate it, leading to hard-to-reproduce segmentation faults.
```kotlin
import kotlinx.cinterop.*

// ANTI-PATTERN: Returning unpinned Kotlin heap buffer pointer to Swift
class NativePayloadBridge {
    private val buffer = ByteArray(1024)

    // CRITICAL BUG: Address escapes GC control. Kotlin GC can collect or
    // relocate the underlying array, causing silent heap corruption in Swift.
    @OptIn(ExperimentalForeignApi::class)
    fun getUnsafeBufferAddress(): CPointer<ByteVar> {
        return buffer.refTo(0).getPointer(MemScope())
    }
}
```

#### Production Standard (Correct)
> **Standard**: The scoped quarantine pattern uses `usePinned` to freeze the buffer's physical address for the duration of the lambda execution, guaranteeing pointer validity while preventing unpinned addresses from escaping into unmanaged foreign contexts.
```kotlin
import kotlinx.cinterop.*

// PRODUCTION PATTERN: Scoped lifetime quarantine pattern
class NativePayloadBridge {
    private val buffer = ByteArray(1024)

    // Explicit scope prevents pointer leakage; lifetime strictly governed
    @OptIn(ExperimentalForeignApi::class)
    fun <R> withQuarantinedBuffer(block: (CPointer<ByteVar>, Int) -> R): R {
        return buffer.usePinned { pinned ->
            block(pinned.addressOf(0), buffer.size)
        }
    }
}
```

### Unmanaged Swift Pointer Bridge vs. Defensively Copied Ingestion

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing the raw pointer outside the quarantined callback introduces a use-after-free vulnerability, as the Kotlin pinning lock is released the moment the closure returns.
```swift
import Shared

// ANTI-PATTERN: Retaining raw Kotlin native pointer across async boundaries
final class AudioFrameConsumer {
    private var cachedPointer: UnsafePointer<Int8>?

    func onBufferReceived(bridge: NativePayloadBridge) {
        bridge.withQuarantinedBuffer { rawPtr, count in
            // CRITICAL BUG: Escapes the quarantine block! rawPtr is invalid
            // the microsecond withQuarantinedBuffer exits.
            self.cachedPointer = rawPtr
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: By initializing `Foundation.Data(bytes:count:)` synchronously inside the quarantined block, Swift performs a safe deep-copy of the buffer before the Kotlin pin is released, preventing any dangling pointer references.
```swift
import Foundation
import Shared

// PRODUCTION PATTERN: Immediate copy into Swift-managed ARC storage
final class AudioFrameConsumer {
    private var frameData: Data = Data()

    func onBufferReceived(bridge: NativePayloadBridge) {
        bridge.withQuarantinedBuffer { rawPtr, count in
            // Deep-copy memory within quarantine boundary into Swift Data
            self.frameData = Data(bytes: rawPtr, count: Int(count))
        }
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin Multiplatform 2.1 Swift Export Foreign Memory Allocation Quarantine

Kotlin Multiplatform 2.1 Swift Export Foreign Memory Allocation Quarantine defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory quarantine and deterministic buffer lifetime management across the Kotlin/Native 2.1 Swift Export boundary. Prevents silent heap corruption, double-frees, and use-after-free crashes by prohibiting raw unmanaged pointer escapes and mandating scoped pinned-buffer transfers with explicit ownership handoffs. 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: Escaping Raw CPointer or UnsafePointer Across Swift Export Boundaries Without Explicit Lifetime Pinning 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 DriftEscaping Raw CPointer or UnsafePointer Across Swift Export Boundaries Without Explicit Lifetime PinningCritical
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 scope Kotlin-managed byte buffers within `usePinned { ... }` blocks when exposing pointers to Swift Export APIs.

Engineers MUST ALWAYS scope Kotlin-managed byte buffers within `usePinned { ... }` blocks when exposing pointers to Swift Export APIs.

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 leak raw Kotlin `CPointer` or Swift `UnsafePointer` references outside their enclosing stack frame or immediate closure invocation.

Engineers MUST NOT leak raw Kotlin `CPointer` or Swift `UnsafePointer` references outside their enclosing stack frame or immediate closure invocation.

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

Swift clients MUST NOT retain raw pointers passed from Kotlin

Swift clients MUST NOT retain raw pointers passed from Kotlin; data intended for persistent storage MUST be immediately copied into Swift-owned contiguous buffers (e.g., `Data(bytes:count:)`).

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

Native allocations created via `kotlinx.cinterop.nativeHeap` MUST have an unambiguous, single-owner deallocation contract, guaranteed by a paired `defer { ... }` in Swift or an auto-closable quarantine wrapper in Kotlin.

Native allocations created via `kotlinx.cinterop.nativeHeap` MUST have an unambiguous, single-owner deallocation contract, guaranteed by a paired `defer { ... }` in Swift or an auto-closable quarantine wrapper in Kotlin.

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

Code MUST NEVER bridge unpinned heap arrays across asynchronous or concurrent suspension points (`suspend` functions or Swift `async/await`).

Code MUST NEVER bridge unpinned heap arrays across asynchronous or concurrent suspension points (`suspend` functions or Swift `async/await`).

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.
6

Services MUST validate byte lengths and buffer bounds prior to passing native pointers across the interop boundary to prevent foreign heap out-of-bounds writes.

Services MUST validate byte lengths and buffer bounds prior to passing native pointers across the interop boundary to prevent foreign heap out-of-bounds writes.

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 Kotlin Multiplatform 2.1 Swift Export Foreign Memory Allocation Quarantine critical for AI coding assistants?

Enforces strict memory quarantine and deterministic buffer lifetime management across the Kotlin/Native 2.1 Swift Export boundary. Prevents silent heap corruption, double-frees, and use-after-free crashes by prohibiting raw unmanaged pointer escapes and mandating scoped pinned-buffer transfers with explicit ownership handoffs. 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 (Escaping Raw CPointer or UnsafePointer Across Swift Export Boundaries Without Explicit Lifetime Pinning) 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

Kotlin