This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: android-ndk-16kb-page-alignment-memory-fence

Android 15 NDK 16KB Page Alignment and Dynamic Memory Fence Architecture

Enforces 16KB ELF segment alignment and dynamic runtime page-size querying for Android 15 compatibility across native C/C++, Rust, and Kotlin Multiplatform binaries. Prevents fatal SIGBUS and SIGSEGV memory faults by forbidding hardcoded 4KB assumptions, static PAGE_SIZE macros, and misaligned mmap/mprotect boundaries.

Prohibited Anti-Pattern: Hardcoding 4KB Page Sizes or Omitting 16KB Linker Flags Causing Critical Android 15 Native Crashes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Android 15 NDK 16KB Page Alignment and Dynamic Memory Fence Architecture - Enforces 16KB ELF segment alignment and dynamic runtime page-size querying for Android 15 compatibility across native C/C++, Rust, and Kotlin Multiplatform binaries. Prevents fatal SIGBUS and SIGSEGV memory faults by forbidding hardcoded 4KB assumptions, static PAGE_SIZE macros, and misaligned mmap/mprotect boundaries.
globs: **/CMakeLists.txt, **/Android.mk, **/*.cpp, **/*.c, **/*.h, **/*.hpp, **/build.gradle.kts, **/build.gradle
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/android-ndk-16kb-page-alignment-memory-fence"
---

# Android 15 NDK 16KB Page Alignment and Dynamic Memory Fence Architecture

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Hardcoding 4KB Page Sizes or Omitting 16KB Linker Flags Causing Critical Android 15 Native Crashes

## System Constraints
You are a Principal Native Systems Architect enforcing strict Android 15 16KB page alignment and dynamic memory barrier guardrails. Mandate that all native C/C++, JNI, and Kotlin Multiplatform binaries dynamically evaluate memory boundaries via sysconf(_SC_PAGESIZE), configure linker max-page-size to 16384, and strictly eliminate static 4096-byte allocations.

## Strict Guidelines
- Engineers MUST ALWAYS pass `-Wl,-z,max-page-size=16384` to linker flags across all CMake, NDK build scripts, and native toolchains.
- Engineers MUST ALWAYS determine memory page boundaries dynamically at runtime using `sysconf(_SC_PAGESIZE)` or `getpagesize()` instead of compile-time `PAGE_SIZE` macros.
- Engineers MUST NOT assume 4096-byte alignment or use hardcoded bitshifts (e.g., `>> 12`) for address offset calculation and memory-mapped files.
- Code SHOULD calculate memory page alignments using bitwise arithmetic against runtime page dimensions: `(size + pageSize - 1) & ~(pageSize - 1)`.
- Native memory fences and custom pool allocators MUST align both base pointers and segment spans to the dynamic runtime page boundary prior to calling `mprotect()` or `madvise()`.

## Bad vs Good Implementations
### Native Dynamic Memory Fence Allocation & mprotect (C++)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Hardcoding 4096 bytes fails completely on Android 15 devices configured with 16KB page kernels. The `mprotect()` syscall requires the target address to be aligned to the kernel's actual page boundary; passing a non-16KB aligned address causes `EINVAL`, leading to corrupted memory fencing or crashes.
```cpp
#include <sys/mman.h>
#include <unistd.h>

// Anti-pattern: Hardcoded 4KB page size constant
constexpr size_t PAGE_SIZE_4K = 4096;

void* allocate_guarded_fence(size_t payload_size) {
    // Crashes with SIGBUS or invalid argument on 16KB kernels
    size_t aligned_size = (payload_size + PAGE_SIZE_4K - 1) & ~(PAGE_SIZE_4K - 1);
    void* buffer = mmap(nullptr, aligned_size + PAGE_SIZE_4K,
                        PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
    
    // Guard page placed assuming 4KB boundary
    void* guard_page = static_cast<char*>(buffer) + aligned_size;
    mprotect(guard_page, PAGE_SIZE_4K, PROT_NONE); // Fails alignment check if kernel runs 16KB pages
    return buffer;
}
```

#### Production Standard (Correct)
> **Standard**: Queries `sysconf(_SC_PAGESIZE)` at runtime to accommodate 4KB, 16KB, or 64KB pages dynamically. Ensures `mprotect` and `mmap` operate strictly on valid, kernel-aligned page boundaries, guaranteeing deterministic execution on Android 15.
```cpp
#include <sys/mman.h>
#include <unistd.h>
#include <cstdint>
#include <cassert>

void* allocate_guarded_fence(size_t payload_size) {
    // Production fix: Dynamically retrieve kernel page size
    const size_t dynamic_page_size = static_cast<size_t>(sysconf(_SC_PAGESIZE));
    assert((dynamic_page_size & (dynamic_page_size - 1)) == 0 && "Page size must be power of two");

    const size_t page_mask = dynamic_page_size - 1;
    const size_t aligned_payload = (payload_size + page_mask) & ~page_mask;
    const size_t total_allocation = aligned_payload + dynamic_page_size;

    void* buffer = mmap(nullptr, total_allocation, 
                        PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
    if (buffer == MAP_FAILED) {
        return nullptr;
    }

    // Guard page is strictly aligned to the true 16KB boundary
    void* guard_page = static_cast<char*>(buffer) + aligned_payload;
    if (mprotect(guard_page, dynamic_page_size, PROT_NONE) != 0) {
        munmap(buffer, total_allocation);
        return nullptr;
    }

    return buffer;
}
```

### CMake Native Linker Configuration for 16KB Alignment

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting the explicit linker flags causes the ELF program headers (`p_align`) to be emitted with 4KB segment boundaries. The Android 15 dynamic linker will refuse to load or misalign the shared library into process memory.
```cmake
# Anti-pattern: Default CMake linker settings targeting 4KB pages
cmake_minimum_required(VERSION 3.22.1)
project(native_core LANGUAGES CXX)

add_library(native_core SHARED
    src/main/cpp/native_core.cpp
)
# Missing max-page-size; ELF segments will default to 4KB alignment on NDK <= r26
```

#### Production Standard (Correct)
> **Standard**: Passes `-Wl,-z,max-page-size=16384` to the linker, guaranteeing that ELF segments are aligned to 16KB boundaries and allowing seamless backward compatibility on 4KB devices while satisfying Android 15 requirements.
```cmake
# Production fix: Mandate 16KB ELF alignment across all target ABIs
cmake_minimum_required(VERSION 3.22.1)
project(native_core LANGUAGES CXX)

add_library(native_core SHARED
    src/main/cpp/native_core.cpp
)

target_link_options(native_core PRIVATE
    "-Wl,-z,max-page-size=16384"
)
```

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: Android 15 NDK 16KB Page Alignment and Dynamic Memory Fence Architecture

Android 15 NDK 16KB Page Alignment and Dynamic Memory Fence Architecture defines an industrial-grade behavioral standard for mobile engineering. Enforces 16KB ELF segment alignment and dynamic runtime page-size querying for Android 15 compatibility across native C/C++, Rust, and Kotlin Multiplatform binaries. Prevents fatal SIGBUS and SIGSEGV memory faults by forbidding hardcoded 4KB assumptions, static PAGE_SIZE macros, and misaligned mmap/mprotect 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: Hardcoding 4KB Page Sizes or Omitting 16KB Linker Flags Causing Critical Android 15 Native Crashes 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 DriftHardcoding 4KB Page Sizes or Omitting 16KB Linker Flags Causing Critical Android 15 Native CrashesCritical
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 pass `-Wl,-z,max-page-size=16384` to linker flags across all CMake, NDK build scripts, and native toolchains.

Engineers MUST ALWAYS pass `-Wl,-z,max-page-size=16384` to linker flags across all CMake, NDK build scripts, and native toolchains.

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 ALWAYS determine memory page boundaries dynamically at runtime using `sysconf(_SC_PAGESIZE)` or `getpagesize()` instead of compile-time `PAGE_SIZE` macros.

Engineers MUST ALWAYS determine memory page boundaries dynamically at runtime using `sysconf(_SC_PAGESIZE)` or `getpagesize()` instead of compile-time `PAGE_SIZE` macros.

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

Engineers MUST NOT assume 4096-byte alignment or use hardcoded bitshifts (e.g., `>> 12`) for address offset calculation and memory-mapped files.

Engineers MUST NOT assume 4096-byte alignment or use hardcoded bitshifts (e.g., `>> 12`) for address offset calculation and memory-mapped files.

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

Code SHOULD calculate memory page alignments using bitwise arithmetic against runtime page dimensions

Code SHOULD calculate memory page alignments using bitwise arithmetic against runtime page dimensions: `(size + pageSize - 1) & ~(pageSize - 1)`.

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

Native memory fences and custom pool allocators MUST align both base pointers and segment spans to the dynamic runtime page boundary prior to calling `mprotect()` or `madvise()`.

Native memory fences and custom pool allocators MUST align both base pointers and segment spans to the dynamic runtime page boundary prior to calling `mprotect()` or `madvise()`.

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 Android 15 NDK 16KB Page Alignment and Dynamic Memory Fence Architecture critical for AI coding assistants?

Enforces 16KB ELF segment alignment and dynamic runtime page-size querying for Android 15 compatibility across native C/C++, Rust, and Kotlin Multiplatform binaries. Prevents fatal SIGBUS and SIGSEGV memory faults by forbidding hardcoded 4KB assumptions, static PAGE_SIZE macros, and misaligned mmap/mprotect 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 (Hardcoding 4KB Page Sizes or Omitting 16KB Linker Flags Causing Critical Android 15 Native Crashes) 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

Android