This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: android-16kb-page-size-alignment-standard-android-15-kmp-1-727

Android 15 / KMP 16KB Page Size Native Memory-Mapping Alignment Standard

Enforces strict 16KB memory page boundary alignment across all native binaries (.so shared objects), JNI bridge interfaces, POSIX mmap allocations, and direct ByteBuffers. Android 15 introduces support for 16KB physical page sizes on ARM64 kernels, making unaligned ELF load segments and legacy 4KB-aligned mmap calls fatal causes of SIGBUS and SIGSEGV runtime aborts.

Prohibited Anti-Pattern: Compiling with legacy 4KB ELF max-page-size or hardcoding 4096-byte alignment in POSIX mmap and direct buffer calculations.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Android 15 / KMP 16KB Page Size Native Memory-Mapping Alignment Standard - Enforces strict 16KB memory page boundary alignment across all native binaries (.so shared objects), JNI bridge interfaces, POSIX mmap allocations, and direct ByteBuffers. Android 15 introduces support for 16KB physical page sizes on ARM64 kernels, making unaligned ELF load segments and legacy 4KB-aligned mmap calls fatal causes of SIGBUS and SIGSEGV runtime aborts.
globs: **/CMakeLists.txt, **/*.cmake, **/build.gradle.kts, **/*.cpp, **/*.c, **/*.h, **/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/android-16kb-page-size-alignment-standard-android-15-kmp-1-727"
---

# Android 15 / KMP 16KB Page Size Native Memory-Mapping Alignment Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Compiling with legacy 4KB ELF max-page-size or hardcoding 4096-byte alignment in POSIX mmap and direct buffer calculations.

## System Constraints
You are a Principal Systems Engineer and Mobile Security Architect enforcing Android 15 and Kotlin Multiplatform 16KB page size alignment standards. Mandate that all native compiler flags, linker scripts, direct memory buffers, and POSIX mmap boundaries strictly conform to dynamic page sizing and 16KB ELF max-page-size invariants to prevent fatal SIGBUS/SIGSEGV crashes on modern ARM64 kernels.

## Strict Guidelines
- Engineers MUST configure Android NDK linkers with `-Wl,-z,max-page-size=16384` for all arm64-v8a and x86_64 native targets in CMakeLists.txt and build.gradle.kts.
- Engineers MUST NOT hardcode `4096`, `PAGE_SIZE`, or 4KB bitwise masks (`~0xFFF`) when mapping file descriptors via `mmap` or calculating byte buffer offsets.
- Engineers MUST dynamically query page size at runtime via `sysconf(_SC_PAGESIZE)` in C/C++ or `Os.sysconf(OsConstants._SC_PAGESIZE)` in Kotlin/Java before calculating memory offsets.
- Engineers MUST ensure third-party prebuilt shared libraries (.so) bundled in AARs or KMP distributions pass validation with the Android SDK `check_elf_alignment.sh` tool.
- Engineers MUST enforce that all JNI direct memory allocations (`NewDirectByteBuffer` or `posix_memalign`) align base pointers and capacity sizes to integer multiples of the runtime system page size.

## Bad vs Good Implementations
### CMakeLists.txt ELF Linker Alignment

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting the linker flag causes Clang/LLD on older NDKs to align ELF segment program headers to 4096 bytes (4KB), causing Android 15 ARM64 16KB kernels to immediately reject and fail dlopen() with a segmentation fault.
```cmake
# Legacy CMake configuration defaulting to 4KB page alignment
cmake_minimum_required(VERSION 3.22.1)
project(native_engine)

add_library(native_engine SHARED engine.cpp)
target_link_libraries(native_engine android log)
```

#### Production Standard (Correct)
> **Standard**: Explicitly passing `-Wl,-z,max-page-size=16384` ensures ELF loadable segment alignments are mapped to 16KB boundaries, preserving compatibility on both 4KB and 16KB kernel configurations.
```cmake
# Modern Android 15+ compatible configuration enforcing 16KB max page alignment
cmake_minimum_required(VERSION 3.22.1)
project(native_engine)

add_library(native_engine SHARED engine.cpp)

# Enforce 16KB ELF load segment alignment for 64-bit architectures
if(ANDROID_ABI STREQUAL "arm64-v8a" OR ANDROID_ABI STREQUAL "x86_64")
    target_link_options(native_engine PRIVATE "-Wl,-z,max-page-size=16384")
endif()

target_link_libraries(native_engine android log)
```

### C++ POSIX mmap Memory-Mapping

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Masking offsets against 4096 produces offsets not aligned to 16384 on 16KB kernels. Calling mmap with an unaligned offset fails immediately with EINVAL.
```cpp
#include <sys/mman.h>
#include <unistd.h>

void* map_file_buffer(int fd, size_t offset, size_t length) {
    // ANTI-PATTERN: Hardcoded 4KB page assumptions
    const size_t PAGE_SIZE_4K = 4096;
    size_t aligned_offset = offset & ~(PAGE_SIZE_4K - 1);
    return mmap(nullptr, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, aligned_offset);
}
```

#### Production Standard (Correct)
> **Standard**: Queries dynamic page size via `sysconf(_SC_PAGESIZE)` to properly calculate alignment masks at runtime, handling 4KB, 16KB, or 64KB kernels safely.
```cpp
#include <sys/mman.h>
#include <unistd.h>
#include <cstdint>

void* map_file_buffer(int fd, size_t offset, size_t length) {
    // Retrieve runtime page size dynamically
    const long page_size = sysconf(_SC_PAGESIZE);
    if (page_size <= 0) {
        return MAP_FAILED;
    }
    
    const size_t mask = static_cast<size_t>(page_size - 1);
    const size_t aligned_offset = offset & ~mask;
    const size_t page_delta = offset - aligned_offset;
    
    return mmap(nullptr, length + page_delta, PROT_READ | PROT_WRITE, MAP_SHARED, fd, aligned_offset);
}
```

### Kotlin Multiplatform / Android JNI Direct Buffer Allocation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Allocating direct byte buffers under the assumption of 4KB pages breaks when native C/C++ code attempts to mprotect or map this buffer using the host kernel's actual 16KB boundary.
```kotlin
import java.nio.ByteBuffer

class SharedMemoryRegion(val size: Long) {
    fun allocateAlignedBuffer(): ByteBuffer {
        // ANTI-PATTERN: Hardcoded 4KB alignment assumption
        val pageSize = 4096
        val alignedSize = ((size + pageSize - 1) / pageSize) * pageSize
        return ByteBuffer.allocateDirect(alignedSize.toInt())
    }
}
```

#### Production Standard (Correct)
> **Standard**: Uses `Os.sysconf(OsConstants._SC_PAGESIZE)` to resolve dynamic page size from the underlying OS kernel, ensuring direct buffers match native virtual memory boundaries.
```kotlin
import android.system.Os
import android.system.OsConstants
import java.nio.ByteBuffer

class SharedMemoryRegion(val size: Long) {
    fun allocateAlignedBuffer(): ByteBuffer {
        val pageSize = Os.sysconf(OsConstants._SC_PAGESIZE).coerceAtLeast(4096)
        val alignedSize = ((size + pageSize - 1) / pageSize) * pageSize
        return ByteBuffer.allocateDirect(alignedSize.toInt())
    }
}
```

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 / KMP 16KB Page Size Native Memory-Mapping Alignment Standard

Android 15 / KMP 16KB Page Size Native Memory-Mapping Alignment Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict 16KB memory page boundary alignment across all native binaries (.so shared objects), JNI bridge interfaces, POSIX mmap allocations, and direct ByteBuffers. Android 15 introduces support for 16KB physical page sizes on ARM64 kernels, making unaligned ELF load segments and legacy 4KB-aligned mmap calls fatal causes of SIGBUS and SIGSEGV runtime aborts. 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: Compiling with legacy 4KB ELF max-page-size or hardcoding 4096-byte alignment in POSIX mmap and direct buffer calculations. 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 DriftCompiling with legacy 4KB ELF max-page-size or hardcoding 4096-byte alignment in POSIX mmap and direct buffer calculations.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 configure Android NDK linkers with `-Wl,-z,max-page-size=16384` for all arm64-v8a and x86_64 native targets in CMakeLists.txt and build.gradle.kts.

Engineers MUST configure Android NDK linkers with `-Wl,-z,max-page-size=16384` for all arm64-v8a and x86_64 native targets in CMakeLists.txt and build.gradle.kts.

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 hardcode `4096`, `PAGE_SIZE`, or 4KB bitwise masks (`~0xFFF`) when mapping file descriptors via `mmap` or calculating byte buffer offsets.

Engineers MUST NOT hardcode `4096`, `PAGE_SIZE`, or 4KB bitwise masks (`~0xFFF`) when mapping file descriptors via `mmap` or calculating byte buffer offsets.

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 dynamically query page size at runtime via `sysconf(_SC_PAGESIZE)` in C/C++ or `Os.sysconf(OsConstants._SC_PAGESIZE)` in Kotlin/Java before calculating memory offsets.

Engineers MUST dynamically query page size at runtime via `sysconf(_SC_PAGESIZE)` in C/C++ or `Os.sysconf(OsConstants._SC_PAGESIZE)` in Kotlin/Java before calculating memory offsets.

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

Engineers MUST ensure third-party prebuilt shared libraries (.so) bundled in AARs or KMP distributions pass validation with the Android SDK `check_elf_alignment.sh` tool.

Engineers MUST ensure third-party prebuilt shared libraries (.so) bundled in AARs or KMP distributions pass validation with the Android SDK `check_elf_alignment.sh` tool.

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

Engineers MUST enforce that all JNI direct memory allocations (`NewDirectByteBuffer` or `posix_memalign`) align base pointers and capacity sizes to integer multiples of the runtime system page size.

Engineers MUST enforce that all JNI direct memory allocations (`NewDirectByteBuffer` or `posix_memalign`) align base pointers and capacity sizes to integer multiples of the runtime system page size.

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 / KMP 16KB Page Size Native Memory-Mapping Alignment Standard critical for AI coding assistants?

Enforces strict 16KB memory page boundary alignment across all native binaries (.so shared objects), JNI bridge interfaces, POSIX mmap allocations, and direct ByteBuffers. Android 15 introduces support for 16KB physical page sizes on ARM64 kernels, making unaligned ELF load segments and legacy 4KB-aligned mmap calls fatal causes of SIGBUS and SIGSEGV runtime aborts. 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 (Compiling with legacy 4KB ELF max-page-size or hardcoding 4096-byte alignment in POSIX mmap and direct buffer calculations.) 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