This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-native-gc-cinterop-concurrency-boundary

KMP 2.1 Native GC Safe C-Pointer Concurrency and StableRef Lifecycle

Enforces strict memory ownership boundaries when bridging raw C-interop pointers and Kotlin objects across coroutine thread boundaries in Kotlin Multiplatform 2.1+ Native targets. Prohibits untracked COpaquePointer sharing and unpinned Native GC heap object access across worker dispatchers to prevent use-after-free panics and segmentation faults on iOS runtimes.

Prohibited Anti-Pattern: Passing naked C pointers or dereferencing untracked Kotlin Native heap references across background dispatchers and the main thread loop

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP 2.1 Native GC Safe C-Pointer Concurrency and StableRef Lifecycle - Enforces strict memory ownership boundaries when bridging raw C-interop pointers and Kotlin objects across coroutine thread boundaries in Kotlin Multiplatform 2.1+ Native targets. Prohibits untracked COpaquePointer sharing and unpinned Native GC heap object access across worker dispatchers to prevent use-after-free panics and segmentation faults on iOS runtimes.
globs: **/*.native.kt, **/*.ios.kt, **/*.apple.kt, **/interop/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-native-gc-cinterop-concurrency-boundary"
---

# KMP 2.1 Native GC Safe C-Pointer Concurrency and StableRef Lifecycle

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Passing naked C pointers or dereferencing untracked Kotlin Native heap references across background dispatchers and the main thread loop

## System Constraints
You are a Principal Engineer enforcing Kotlin Multiplatform 2.1 Native GC Concurrency Boundaries. Mandate strict object pinning via StableRef, explicit linear ownership handoff via atomic references, and complete RAII-scoped lifecycle management for native pointers crossing coroutine contexts. Strictly disallow dereferencing raw Native pointers or capturing C-interop memory inside asynchronous blocks without deterministic disposal semantics.

## Strict Guidelines
- Engineers MUST ALWAYS pin Kotlin objects passing into foreign C libraries or non-Kotlin threads using StableRef.create() and guarantee symmetric cleanup via StableRef.dispose().
- Engineers MUST NOT cross coroutine dispatchers (e.g., Dispatchers.Default to Dispatchers.Main) while retaining unmanaged foreign memory without wrapping it in an AtomicReference or thread-safe envelope.
- Code SHOULD enforce RAII idioms using useContents, memScoped, or customized AutoCloseable wrappers to prevent raw pointer retention outside execution blocks.
- Services MUST ensure that C callback function pointers (staticCFunction) transfer ownership into StableRef<T>.asCPointer() and reconstruct target references on the receiving thread via StableRef.fromCPointer(ptr).get().
- Components NEVER bridge raw C pointers across Dispatchers.IO or Dispatchers.Default without explicit ref-count management or ownership handoff, averting use-after-free conditions caused by concurrent Native GC cycles.

## Bad vs Good Implementations
### Safe StableRef bridging across Native Worker Dispatchers to Main Thread

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accessing COpaquePointer on a background thread without establishing ownership semantics or verifying memory allocation lifetime causes use-after-free if the native source buffer deallocates. Furthermore, capturing native memory across a context-switch without StableRef pinning or safe copy causes runtime segmentation faults under Kotlin Native's concurrent GC.
```kotlin
import kotlinx.coroutines.*
import kotlinx.cinterop.*

class DataConsumer {
    // ANTI-PATTERN: Leaking raw C-interop memory and raw Kotlin reference across threads
    // Native GC can collect the underlying Kotlin instance or free native memory mid-dispatch
    fun processAsync(rawPtr: COpaquePointer, onComplete: (String) -> Unit) {
        CoroutineScope(Dispatchers.Default).launch {
            val nativeData = rawPtr.reinterpret<ByteVar>().toKString() // Danger: unpinned native memory
            withContext(Dispatchers.Main) {
                onComplete(nativeData) // Closure leaks unmanaged state into main runloop
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Uses StableRef to pin the Kotlin callback, safely transmits its pointer across dispatch boundaries using an AtomicReference, and deterministically invokes dispose() on the receiver thread inside a finally block to eliminate memory leaks and use-after-free crashes.
```kotlin
import kotlinx.coroutines.*
import kotlinx.cinterop.*
import kotlin.concurrent.AtomicReference

class DataConsumer {
    // PRODUCTION FIX: Pin Kotlin payload via StableRef, perform explicit thread-safe handoff and RAII disposal
    fun processAsync(rawPayload: String, onComplete: (String) -> Unit) {
        val stableRef = StableRef.create(onComplete)
        val rawPtr = stableRef.asCPointer()
        val holder = AtomicReference<COpaquePointer?>(rawPtr)

        CoroutineScope(Dispatchers.Default).launch {
            try {
                val processed = "Processed: $rawPayload"
                withContext(Dispatchers.Main) {
                    val targetPtr = holder.getAndSet(null)
                    if (targetPtr != null) {
                        val recoveredRef = StableRef.fromCPointer<(String) -> Unit>(targetPtr)
                        try {
                            recoveredRef.get().invoke(processed)
                        } finally {
                            recoveredRef.dispose() // Guaranteed disposal after execution
                        }
                    }
                }
            } catch (t: Throwable) {
                // Ensure memory leak prevention on coroutine cancellation or error
                val targetPtr = holder.getAndSet(null)
                targetPtr?.let { StableRef.fromCPointer<(String) -> Unit>(it).dispose() }
                throw t
            }
        }
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP 2.1 Native GC Safe C-Pointer Concurrency and StableRef Lifecycle

KMP 2.1 Native GC Safe C-Pointer Concurrency and StableRef Lifecycle defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory ownership boundaries when bridging raw C-interop pointers and Kotlin objects across coroutine thread boundaries in Kotlin Multiplatform 2.1+ Native targets. Prohibits untracked COpaquePointer sharing and unpinned Native GC heap object access across worker dispatchers to prevent use-after-free panics and segmentation faults on iOS runtimes. 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: Passing naked C pointers or dereferencing untracked Kotlin Native heap references across background dispatchers and the main thread loop 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 DriftPassing naked C pointers or dereferencing untracked Kotlin Native heap references across background dispatchers and the main thread loopCritical
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 pin Kotlin objects passing into foreign C libraries or non-Kotlin threads using StableRef.create() and guarantee symmetric cleanup via StableRef.dispose().

Engineers MUST ALWAYS pin Kotlin objects passing into foreign C libraries or non-Kotlin threads using StableRef.create() and guarantee symmetric cleanup via StableRef.dispose().

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 cross coroutine dispatchers (e.g., Dispatchers.Default to Dispatchers.Main) while retaining unmanaged foreign memory without wrapping it in an AtomicReference or thread-safe envelope.

Engineers MUST NOT cross coroutine dispatchers (e.g., Dispatchers.Default to Dispatchers.Main) while retaining unmanaged foreign memory without wrapping it in an AtomicReference or thread-safe envelope.

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 RAII idioms using useContents, memScoped, or customized AutoCloseable wrappers to prevent raw pointer retention outside execution blocks.

Code SHOULD enforce RAII idioms using useContents, memScoped, or customized AutoCloseable wrappers to prevent raw pointer retention outside execution blocks.

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 ensure that C callback function pointers (staticCFunction) transfer ownership into StableRef<T>.asCPointer() and reconstruct target references on the receiving thread via StableRef.fromCPointer(ptr).get().

Services MUST ensure that C callback function pointers (staticCFunction) transfer ownership into StableRef<T>.asCPointer() and reconstruct target references on the receiving thread via StableRef.fromCPointer(ptr).get().

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 bridge raw C pointers across Dispatchers.IO or Dispatchers.Default without explicit ref-count management or ownership handoff, averting use-after-free conditions caused by concurrent Native GC cycles.

Components NEVER bridge raw C pointers across Dispatchers.IO or Dispatchers.Default without explicit ref-count management or ownership handoff, averting use-after-free conditions caused by concurrent Native GC cycles.

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 2.1 Native GC Safe C-Pointer Concurrency and StableRef Lifecycle critical for AI coding assistants?

Enforces strict memory ownership boundaries when bridging raw C-interop pointers and Kotlin objects across coroutine thread boundaries in Kotlin Multiplatform 2.1+ Native targets. Prohibits untracked COpaquePointer sharing and unpinned Native GC heap object access across worker dispatchers to prevent use-after-free panics and segmentation faults on iOS runtimes. 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 (Passing naked C pointers or dereferencing untracked Kotlin Native heap references across background dispatchers and the main thread loop) 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