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-16kb--422

Android 15 16KB Page Size NDK Memory Alignment Standard

Enforces 16KB (16384 bytes) ELF segment alignment and memory allocation constraints for Android NDK native libraries on Android 15+. Prevents fatal runtime SIGBUS crashes, mmap mapping failures, and dynamic linker rejections caused by legacy 4KB page assumptions on modern ARM64 and x86_64 hardware.

Prohibited Anti-Pattern: Compiling NDK Binaries with Hardcoded 4KB Max Page Size and Unaligned Native mmap Offsets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Android 15 16KB Page Size NDK Memory Alignment Standard - Enforces 16KB (16384 bytes) ELF segment alignment and memory allocation constraints for Android NDK native libraries on Android 15+. Prevents fatal runtime SIGBUS crashes, mmap mapping failures, and dynamic linker rejections caused by legacy 4KB page assumptions on modern ARM64 and x86_64 hardware.
globs: **/CMakeLists.txt, **/Android.mk, **/build.gradle, **/build.gradle.kts, **/*.cpp, **/*.c, **/*.h
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/android-16kb-page-size-alignment-standard-android-15-16kb--422"
---

# Android 15 16KB Page Size NDK Memory Alignment Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Compiling NDK Binaries with Hardcoded 4KB Max Page Size and Unaligned Native mmap Offsets

## System Constraints
You are a Principal Mobile Systems Architect enforcing the Android 15 16KB Page Size NDK Memory Alignment Standard. You must mandate 16KB page boundary alignment across all NDK build configurations (CMake, ndk-build, Gradle) and eliminate all native runtime code assuming 4096-byte pages or using PAGE_SIZE macros. You must require runtime page size queries via sysconf(_SC_PAGESIZE) or getpagesize(), prohibit hardcoded 4KB alignment offsets in mmap/munmap/mprotect calls, and verify ELF max-page-size linker flags (-Wl,-z,max-page-size=16384).

## Strict Guidelines
- Engineers MUST ALWAYS pass '-Wl,-z,max-page-size=16384' to native linker flags in CMakeLists.txt and Android.mk across all target ABIs.
- Engineers MUST NOT reference the compile-time 'PAGE_SIZE' or 'PAGE_MASK' constants from '<sys/user.h>' in Android C/C++ source code.
- Code MUST ALWAYS retrieve page sizes dynamically at runtime using 'sysconf(_SC_PAGESIZE)' or 'getpagesize()'.
- Memory mapping operations using 'mmap' MUST align target file descriptors, offsets, and buffer lengths to exact multiples of the dynamic runtime page size.
- Engineers MUST ALWAYS update the Android NDK to r27 or higher, or explicitly configure NDK r26 with 16KB alignment flags.
- Build scripts MUST NOT package prebuilt third-party '.so' binaries that contain ELF program headers aligned to 4KB (0x1000) boundaries.
- Custom memory allocators and ring buffers MUST compute memory alignment masks dynamically using 'size_t page_mask = sysconf(_SC_PAGESIZE) - 1' instead of fixed bitshifts (e.g., '1 << 12').

## Bad vs Good Implementations
### CMake Native Linker Configuration for 16KB ELF Alignment

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting the max-page-size linker flag leaves compiled ELF loadable segments aligned to 4096-byte boundaries (0x1000). Android 15 devices running with 16KB kernel pages fail to load the library via dlopen with a dynamic linker alignment error.
```cmake
# Fatal: Relies on legacy default 4KB ELF alignment, causing SIGBUS on Android 15
cmake_minimum_required(VERSION 3.22.1)
project(native_engine)

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

#### Production Standard (Correct)
> **Standard**: Explicitly instructs the lld linker to align all PT_LOAD segments to 16384 bytes (0x4000), making the resulting shared library fully compatible with both 4KB and 16KB kernel page runtimes.
```cmake
cmake_minimum_required(VERSION 3.22.1)
project(native_engine)

add_library(native_engine SHARED engine.cpp)

# Enforce 16KB ELF segment alignment across modern and legacy Android targets
target_link_options(native_engine PRIVATE "-Wl,-z,max-page-size=16384")
target_link_libraries(native_engine log)
```

### Runtime Memory Allocation and mmap Alignment in C++

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: If file_offset is aligned to 4KB or 8KB but not 16KB (e.g., 0x2000), mmap() will fail with EINVAL on a 16KB kernel, crashing native memory subsystems relying on successful mappings.
```cpp
#include <sys/mman.h>
#include <sys/user.h>
#include <unistd.h>

// Fatal: Hardcoded 4096-byte assumption fails on 16KB page systems
void* allocate_aligned_buffer(int fd, off_t file_offset, size_t length) {
    // PAGE_SIZE is either undefined or hardcoded to 4096 in legacy headers
    const size_t kPageSize = 4096;
    off_t aligned_offset = file_offset & ~(kPageSize - 1);
    return mmap(nullptr, length, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, aligned_offset);
}
```

#### Production Standard (Correct)
> **Standard**: Dynamically queries sysconf(_SC_PAGESIZE), calculates offsets and lengths according to the active page boundary (whether 4KB or 16KB), and prevents EINVAL and SIGBUS faults across all Android kernel architectures.
```cpp
#include <sys/mman.h>
#include <unistd.h>
#include <cstdint>

void* allocate_aligned_buffer(int fd, off_t file_offset, size_t length) {
    const size_t page_size = static_cast<size_t>(sysconf(_SC_PAGESIZE));
    const size_t page_mask = page_size - 1;
    
    // Align offset down to dynamic page boundary
    off_t aligned_offset = file_offset & ~static_cast<off_t>(page_mask);
    size_t adjustment = static_cast<size_t>(file_offset - aligned_offset);
    size_t aligned_length = (length + adjustment + page_mask) & ~page_mask;
    
    void* addr = mmap(nullptr, aligned_length, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, aligned_offset);
    if (addr == MAP_FAILED) {
        return nullptr;
    }
    return static_cast<char*>(addr) + adjustment;
}
```

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 16KB Page Size NDK Memory Alignment Standard

Android 15 16KB Page Size NDK Memory Alignment Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces 16KB (16384 bytes) ELF segment alignment and memory allocation constraints for Android NDK native libraries on Android 15+. Prevents fatal runtime SIGBUS crashes, mmap mapping failures, and dynamic linker rejections caused by legacy 4KB page assumptions on modern ARM64 and x86_64 hardware. 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 NDK Binaries with Hardcoded 4KB Max Page Size and Unaligned Native mmap Offsets 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 NDK Binaries with Hardcoded 4KB Max Page Size and Unaligned Native mmap OffsetsCritical
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 native linker flags in CMakeLists.txt and Android.mk across all target ABIs.

Engineers MUST ALWAYS pass '-Wl,-z,max-page-size=16384' to native linker flags in CMakeLists.txt and Android.mk across all target ABIs.

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 reference the compile-time 'PAGE_SIZE' or 'PAGE_MASK' constants from '<sys/user.h>' in Android C/C++ source code.

Engineers MUST NOT reference the compile-time 'PAGE_SIZE' or 'PAGE_MASK' constants from '<sys/user.h>' in Android C/C++ source code.

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 MUST ALWAYS retrieve page sizes dynamically at runtime using 'sysconf(_SC_PAGESIZE)' or 'getpagesize()'.

Code MUST ALWAYS retrieve page sizes dynamically at runtime using 'sysconf(_SC_PAGESIZE)' or 'getpagesize()'.

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

Memory mapping operations using 'mmap' MUST align target file descriptors, offsets, and buffer lengths to exact multiples of the dynamic runtime page size.

Memory mapping operations using 'mmap' MUST align target file descriptors, offsets, and buffer lengths to exact multiples of the dynamic runtime 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.
5

Engineers MUST ALWAYS update the Android NDK to r27 or higher, or explicitly configure NDK r26 with 16KB alignment flags.

Engineers MUST ALWAYS update the Android NDK to r27 or higher, or explicitly configure NDK r26 with 16KB alignment flags.

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

Build scripts MUST NOT package prebuilt third-party '.so' binaries that contain ELF program headers aligned to 4KB (0x1000) boundaries.

Build scripts MUST NOT package prebuilt third-party '.so' binaries that contain ELF program headers aligned to 4KB (0x1000) 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.
7

Custom memory allocators and ring buffers MUST compute memory alignment masks dynamically using 'size_t page_mask = sysconf(_SC_PAGESIZE) - 1' instead of fixed bitshifts (e.g., '1 << 12').

Custom memory allocators and ring buffers MUST compute memory alignment masks dynamically using 'size_t page_mask = sysconf(_SC_PAGESIZE) - 1' instead of fixed bitshifts (e.g., '1 << 12').

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

Enforces 16KB (16384 bytes) ELF segment alignment and memory allocation constraints for Android NDK native libraries on Android 15+. Prevents fatal runtime SIGBUS crashes, mmap mapping failures, and dynamic linker rejections caused by legacy 4KB page assumptions on modern ARM64 and x86_64 hardware. 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 NDK Binaries with Hardcoded 4KB Max Page Size and Unaligned Native mmap Offsets) 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