This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-ffi-struct-alignment-and-memory-pinning-guardrail

Bun 1.2 FFI C-ABI Struct Alignment and Non-Moving Memory Pinning Standard

Mandates strict C-ABI layout alignment calculations and deterministic memory pinning when exchanging zero-copy pointers between Bun 1.2 (JavaScriptCore) and native Rust/C libraries. Prevents engine panics, ARM64 bus errors (SIGBUS), and heap corruption resulting from JSC garbage collection compaction or misaligned struct boundaries.

Prohibited Anti-Pattern: Passing packed GC-managed buffers without host alignment padding or lifetime guarantees to native FFI pointers.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 FFI C-ABI Struct Alignment and Non-Moving Memory Pinning Standard - Mandates strict C-ABI layout alignment calculations and deterministic memory pinning when exchanging zero-copy pointers between Bun 1.2 (JavaScriptCore) and native Rust/C libraries. Prevents engine panics, ARM64 bus errors (SIGBUS), and heap corruption resulting from JSC garbage collection compaction or misaligned struct boundaries.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-ffi-struct-alignment-and-memory-pinning-guardrail"
---

# Bun 1.2 FFI C-ABI Struct Alignment and Non-Moving Memory Pinning Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Passing packed GC-managed buffers without host alignment padding or lifetime guarantees to native FFI pointers.

## System Constraints
You are a Principal Software Architect enforcing C-ABI compliance and memory pinning invariants under Bun 1.2 Native FFI. JavaScriptCore (JSC) aggressively allocates and sweeps heap objects; passing dynamic TypedArrays directly to native libraries (Rust #[repr(C)], C structs) can cause silent heap corruption, SIGSEGV, or SIGBUS when JSC performs GC cycles or when struct fields violate 4-byte or 8-byte scalar alignment rules. Mandate explicit offset calculations matching target architecture alignment, non-relocatable buffer management, and deterministic ownership boundaries across the FFI bridge.

## Strict Guidelines
- Engineers MUST ALWAYS calculate explicit struct member padding matching the host platform's C-ABI natural alignment (e.g., 64-bit pointers and integers must align to 8-byte boundaries).
- Engineers MUST NOT pass ephemeral or locally scoped ArrayBuffers across asynchronous FFI boundaries without retaining an explicit reference to the backing buffer on the JavaScript root set to prevent JSC garbage collection.
- Code SHOULD verify platform endianness and use DataView with explicit little-endian parameters when preparing struct payloads for foreign function interfaces.
- Services MUST ensure native allocations (malloc/Rust Box) passed into Bun are freed strictly by their corresponding native destructor, never by JSC engine GC.
- Components NEVER cast raw arbitrary memory addresses to pointers without bounds and null-pointer checks prior to invoking native FFI symbols.

## Bad vs Good Implementations
### C-ABI Struct Packing and Memory Pinning Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The layout violates C-ABI alignment requirements (a 64-bit integer following a 32-bit integer must have 4 bytes of padding on 64-bit platforms). Additionally, the ArrayBuffer is allocated in local scope without anchoring to the root set, rendering it vulnerable to garbage collection and pointer invalidation before the microtask executes.
```typescript
import { dlopen, FFIType, ptr } from 'bun:ffi';

// Rust expects: #[repr(C)] struct Request { id: u32, timestamp: u64, active: bool }
const { symbols } = dlopen('libnative.so', {
  process_request: { args: [FFIType.ptr], returns: FFIType.void },
});

export async function sendTelemetry(id: number, timestamp: bigint, active: boolean) {
  // Anti-Pattern: packed sequential bytes ignoring 64-bit C-ABI padding rules (u32 needs 4-byte pad before u64).
  // Anti-Pattern: Uint8Array is GC-eligible and may be swept or relocated during async operations.
  const raw = new Uint8Array(4 + 8 + 1);
  const view = new DataView(raw.buffer);
  view.setUint32(0, id, true);
  view.setBigUint64(4, timestamp, true); // Misaligned write on 4-byte offset: triggers UB/SIGBUS in native code
  view.setUint8(12, active ? 1 : 0);

  // Passing raw pointer without retaining buffer reference or accounting for alignment
  queueMicrotask(() => {
    symbols.process_request(ptr(raw));
  });
}
```

#### Production Standard (Correct)
> **Standard**: Calculates exact struct alignment and padding offsets corresponding to the host 64-bit C-ABI. Anchors the underlying ArrayBuffer in an active set to prevent JSC GC compaction from invalidating pointer addresses during execution.
```typescript
import { dlopen, FFIType, ptr } from 'bun:ffi';

// Target C-ABI: #[repr(C)] struct Request { id: u32, _pad: u32, timestamp: u64, active: u8, _pad2: [u8; 7] }
// Total Struct Size = 24 bytes, 8-byte aligned.
const STRUCT_CONFIG = {
  SIZE_BYTES: 24,
  OFFSET_ID: 0,
  OFFSET_TIMESTAMP: 8, // Properly aligned to 8-byte boundary
  OFFSET_ACTIVE: 16,
} as const;

const { symbols } = dlopen('libnative.so', {
  process_request: { args: [FFIType.ptr], returns: FFIType.void },
});

// Pinning anchor to prevent JSC GC sweeps during pending asynchronous foreign executions
const pinnedBuffers = new Set<ArrayBuffer>();

export function sendTelemetry(id: number, timestamp: bigint, active: boolean): void {
  const buffer = new ArrayBuffer(STRUCT_CONFIG.SIZE_BYTES);
  const view = new DataView(buffer);

  // Deterministic little-endian writes respecting C-ABI padding
  view.setUint32(STRUCT_CONFIG.OFFSET_ID, id, true);
  view.setBigUint64(STRUCT_CONFIG.OFFSET_TIMESTAMP, timestamp, true);
  view.setUint8(STRUCT_CONFIG.OFFSET_ACTIVE, active ? 1 : 0);

  // Pin buffer in the GC root registry
  pinnedBuffers.add(buffer);
  const bufferPtr = ptr(buffer);

  try {
    symbols.process_request(bufferPtr);
  } finally {
    // Safely unpin after synchronous native dispatch completes
    pinnedBuffers.delete(buffer);
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 FFI C-ABI Struct Alignment and Non-Moving Memory Pinning Standard

Bun 1.2 FFI C-ABI Struct Alignment and Non-Moving Memory Pinning Standard defines an industrial-grade behavioral standard for backend engineering. Mandates strict C-ABI layout alignment calculations and deterministic memory pinning when exchanging zero-copy pointers between Bun 1.2 (JavaScriptCore) and native Rust/C libraries. Prevents engine panics, ARM64 bus errors (SIGBUS), and heap corruption resulting from JSC garbage collection compaction or misaligned struct boundaries. 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 packed GC-managed buffers without host alignment padding or lifetime guarantees to native FFI pointers. 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 packed GC-managed buffers without host alignment padding or lifetime guarantees to native FFI pointers.Critical
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 calculate explicit struct member padding matching the host platform's C-ABI natural alignment (e.g., 64-bit pointers and integers must align to 8-byte boundaries).

Engineers MUST ALWAYS calculate explicit struct member padding matching the host platform's C-ABI natural alignment (e.g., 64-bit pointers and integers must align to 8-byte boundaries).

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 ephemeral or locally scoped ArrayBuffers across asynchronous FFI boundaries without retaining an explicit reference to the backing buffer on the JavaScript root set to prevent JSC garbage collection.

Engineers MUST NOT pass ephemeral or locally scoped ArrayBuffers across asynchronous FFI boundaries without retaining an explicit reference to the backing buffer on the JavaScript root set to prevent JSC 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.
3

Code SHOULD verify platform endianness and use DataView with explicit little-endian parameters when preparing struct payloads for foreign function interfaces.

Code SHOULD verify platform endianness and use DataView with explicit little-endian parameters when preparing struct payloads for foreign function interfaces.

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 native allocations (malloc/Rust Box) passed into Bun are freed strictly by their corresponding native destructor, never by JSC engine GC.

Services MUST ensure native allocations (malloc/Rust Box) passed into Bun are freed strictly by their corresponding native destructor, never by JSC engine GC.

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 cast raw arbitrary memory addresses to pointers without bounds and null-pointer checks prior to invoking native FFI symbols.

Components NEVER cast raw arbitrary memory addresses to pointers without bounds and null-pointer checks prior to invoking native FFI symbols.

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 Bun 1.2 FFI C-ABI Struct Alignment and Non-Moving Memory Pinning Standard critical for AI coding assistants?

Mandates strict C-ABI layout alignment calculations and deterministic memory pinning when exchanging zero-copy pointers between Bun 1.2 (JavaScriptCore) and native Rust/C libraries. Prevents engine panics, ARM64 bus errors (SIGBUS), and heap corruption resulting from JSC garbage collection compaction or misaligned struct boundaries. 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 packed GC-managed buffers without host alignment padding or lifetime guarantees to native FFI pointers.) 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.

1 Rule in Stack

Bun