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-invariant

Android 15 16KB Page Size Alignment and Native Memory Mapping Invariant

Enforces strict 16KB (0x4000) page boundary alignment for all compiled ELF shared libraries (.so), dynamic memory mappings (mmap/mprotect), and native custom allocators. Android 15 devices running 16KB page kernels abort execution via dynamic linker failures or kernel panics if ELF segments or memory descriptors rely on legacy 4KB compile-time assumptions.

Prohibited Anti-Pattern: Hardcoded 4KB Page Sizes and Unaligned ELF Segment Linking in Android NDK Binaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Android 15 16KB Page Size Alignment and Native Memory Mapping Invariant - Enforces strict 16KB (0x4000) page boundary alignment for all compiled ELF shared libraries (.so), dynamic memory mappings (mmap/mprotect), and native custom allocators. Android 15 devices running 16KB page kernels abort execution via dynamic linker failures or kernel panics if ELF segments or memory descriptors rely on legacy 4KB compile-time assumptions.
globs: **/CMakeLists.txt, **/Android.mk, **/*.cpp, **/*.c, **/*.h, **/*.hpp, **/build.gradle, **/build.gradle.kts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/android-16kb-page-size-alignment-invariant"
---

# Android 15 16KB Page Size Alignment and Native Memory Mapping Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Hardcoded 4KB Page Sizes and Unaligned ELF Segment Linking in Android NDK Binaries

## System Constraints
You are a Principal Mobile Systems Architect and NDK Specialist enforcing Android 15 16KB page-size alignment invariants. Reject any assumption of a compile-time constant 4096-byte PAGE_SIZE. Reject any CMake, Android.mk, or linker configuration failing to pass max-page-size=16384. Verify that all mmap, mprotect, and munmap system calls query page boundaries dynamically at runtime via sysconf(_SC_PAGESIZE) or getpagesize().

## Strict Guidelines
- Engineers MUST ALWAYS pass '-Wl,-z,max-page-size=16384' to target_link_options in CMake or LOCAL_LDFLAGS in Android.mk for NDK builds below r28.
- Engineers MUST NEVER use the compile-time 'PAGE_SIZE' macro or hardcode '4096' / '0x1000' in native C/C++ memory allocation, buffer offsets, or ring buffers.
- Code MUST query the system page size dynamically at runtime using 'sysconf(_SC_PAGESIZE)' or 'getpagesize()' and cache the result atomically.
- Services MUST ensure native memory mappings via 'mmap', 'munmap', and 'mprotect' align both the starting address and length to multi-page boundaries using runtime page-size arithmetic: '(len + pageSize - 1) & ~(pageSize - 1)'.
- Components NEVER use unaligned file offsets when invoking 'mmap'; file offsets passed to 'mmap' MUST be an exact integer multiple of 'sysconf(_SC_PAGESIZE)'.
- Engineers MUST verify ELF shared library alignment using 'readelf -l <lib>.so | grep LOAD' or Android's 'check_elf_alignment.sh' script during CI verification.

## Bad vs Good Implementations
### Dynamic mmap Memory Alignment vs Legacy 4KB Hardcoded Alignment

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Hardcoding 4096 bytes or relying on the legacy PAGE_SIZE macro fails when executed on Android 15 kernels built with 16KB physical memory pages. Memory mappings and protection flags requested on sub-page boundaries trigger EINVAL errors or runtime segmentation aborts.
```cpp
#include <sys/mman.h>
#include <unistd.h>

// Fatal on Android 15 (16KB page kernels)
#define LEGACY_PAGE_SIZE 4096

void* allocate_executable_buffer(size_t payload_size) {
    // Anti-Pattern: Hardcoded 4096-byte alignment causes SIGBUS/EINVAL on 16KB kernels
    size_t aligned_size = (payload_size + LEGACY_PAGE_SIZE - 1) & ~(LEGACY_PAGE_SIZE - 1);
    void* addr = mmap(nullptr, aligned_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
    if (addr == MAP_FAILED) return nullptr;

    mprotect(addr, aligned_size, PROT_READ | PROT_EXEC);
    return addr;
}
```

#### Production Standard (Correct)
> **Standard**: Queries sysconf(_SC_PAGESIZE) dynamically at runtime, guaranteeing correct memory alignment across both legacy 4KB devices and modern 16KB Android 15+ devices.
```cpp
#include <sys/mman.h>
#include <unistd.h>
#include <cstdint>

static inline size_t get_system_page_size() {
    static const size_t cached_page_size = []() {
        long sz = sysconf(_SC_PAGESIZE);
        return (sz > 0) ? static_cast<size_t>(sz) : static_cast<size_t>(16384);
    }();
    return cached_page_size;
}

void* allocate_executable_buffer(size_t payload_size) {
    const size_t page_size = get_system_page_size();
    // Invariant: Compute bounds using dynamically detected page size
    const size_t aligned_size = (payload_size + page_size - 1) & ~(page_size - 1);

    void* addr = mmap(nullptr, aligned_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
    if (addr == MAP_FAILED) return nullptr;

    if (mprotect(addr, aligned_size, PROT_READ | PROT_EXEC) != 0) {
        munmap(addr, aligned_size);
        return nullptr;
    }
    return addr;
}
```

### CMake Native Library ELF Alignment Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Shared libraries linked with default alignment on NDK versions prior to r28 generate ELF segments aligned to 4KB (0x1000). Android 15 dynamic linkers strictly enforce 16KB (0x4000) alignment on 16KB kernels, crashing during library load.
```cmake
# CMakeLists.txt - Missing explicit max-page-size alignment
cmake_minimum_required(VERSION 3.22.1)
project(native_engine CXX)

add_library(native_engine SHARED engine.cpp)
# Anti-Pattern: Default NDK r26 and older linkers default to 4KB (0x1000) ELF alignment,
# causing Android 15 dlopen() to fail with 'libnative_engine.so has invalid page size'
```

#### Production Standard (Correct)
> **Standard**: Explicitly passing '-Wl,-z,max-page-size=16384' forces the linker to align ELF PT_LOAD segments to 16KB boundaries, ensuring backward compatibility with 4KB devices and forward compatibility with 16KB Android 15 kernels.
```cmake
# CMakeLists.txt - 16KB ELF segment alignment enforced
cmake_minimum_required(VERSION 3.22.1)
project(native_engine CXX)

add_library(native_engine SHARED engine.cpp)

# Invariant: Force 16KB ELF alignment across all target architectures
target_link_options(native_engine 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 16KB Page Size Alignment and Native Memory Mapping Invariant

Android 15 16KB Page Size Alignment and Native Memory Mapping Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces strict 16KB (0x4000) page boundary alignment for all compiled ELF shared libraries (.so), dynamic memory mappings (mmap/mprotect), and native custom allocators. Android 15 devices running 16KB page kernels abort execution via dynamic linker failures or kernel panics if ELF segments or memory descriptors rely on legacy 4KB compile-time assumptions. 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: Hardcoded 4KB Page Sizes and Unaligned ELF Segment Linking in Android NDK Binaries 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 DriftHardcoded 4KB Page Sizes and Unaligned ELF Segment Linking in Android NDK BinariesCritical
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 target_link_options in CMake or LOCAL_LDFLAGS in Android.mk for NDK builds below r28.

Engineers MUST ALWAYS pass '-Wl,-z,max-page-size=16384' to target_link_options in CMake or LOCAL_LDFLAGS in Android.mk for NDK builds below r28.

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 NEVER use the compile-time 'PAGE_SIZE' macro or hardcode '4096' / '0x1000' in native C/C++ memory allocation, buffer offsets, or ring buffers.

Engineers MUST NEVER use the compile-time 'PAGE_SIZE' macro or hardcode '4096' / '0x1000' in native C/C++ memory allocation, buffer offsets, or ring buffers.

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 query the system page size dynamically at runtime using 'sysconf(_SC_PAGESIZE)' or 'getpagesize()' and cache the result atomically.

Code MUST query the system page size dynamically at runtime using 'sysconf(_SC_PAGESIZE)' or 'getpagesize()' and cache the result atomically.

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 memory mappings via 'mmap', 'munmap', and 'mprotect' align both the starting address and length to multi-page boundaries using runtime page-size arithmetic

Services MUST ensure native memory mappings via 'mmap', 'munmap', and 'mprotect' align both the starting address and length to multi-page boundaries using runtime page-size arithmetic: '(len + 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

Components NEVER use unaligned file offsets when invoking 'mmap'

Components NEVER use unaligned file offsets when invoking 'mmap'; file offsets passed to 'mmap' MUST be an exact integer multiple of 'sysconf(_SC_PAGESIZE)'.

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

Engineers MUST verify ELF shared library alignment using 'readelf -l <lib>.so | grep LOAD' or Android's 'check_elf_alignment.sh' script during CI verification.

Engineers MUST verify ELF shared library alignment using 'readelf -l <lib>.so | grep LOAD' or Android's 'check_elf_alignment.sh' script during CI verification.

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 Alignment and Native Memory Mapping Invariant critical for AI coding assistants?

Enforces strict 16KB (0x4000) page boundary alignment for all compiled ELF shared libraries (.so), dynamic memory mappings (mmap/mprotect), and native custom allocators. Android 15 devices running 16KB page kernels abort execution via dynamic linker failures or kernel panics if ELF segments or memory descriptors rely on legacy 4KB compile-time assumptions. 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 (Hardcoded 4KB Page Sizes and Unaligned ELF Segment Linking in Android NDK Binaries) 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