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

Android 15 16KB Memory Page Alignment Invariants for Native NDK Toolchains

Android 15 introduces support for 16KB physical memory page sizes on ARM64 hardware, shifting away from the legacy 4KB page assumption. Shared libraries (.so) built with native NDK toolchains that fail to align ELF segments (PT_LOAD) to 16KB boundaries will trigger immediate dynamic linker crashes (dlopen failures) and SIGSEGV faults at runtime. Engineers must enforce strict 16KB linker alignment in CMake/ndk-build configurations, eliminate hardcoded 4KB page assumptions in native mmap/mprotect invocations, and ensure vendor prebuilts pass verification.

Prohibited Anti-Pattern: Compiling NDK native libraries with legacy 4KB ELF segment alignment or hardcoding 4096-byte offsets in mmap calls

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Android 15 16KB Memory Page Alignment Invariants for Native NDK Toolchains - Android 15 introduces support for 16KB physical memory page sizes on ARM64 hardware, shifting away from the legacy 4KB page assumption. Shared libraries (.so) built with native NDK toolchains that fail to align ELF segments (PT_LOAD) to 16KB boundaries will trigger immediate dynamic linker crashes (dlopen failures) and SIGSEGV faults at runtime. Engineers must enforce strict 16KB linker alignment in CMake/ndk-build configurations, eliminate hardcoded 4KB page assumptions in native mmap/mprotect invocations, and ensure vendor prebuilts pass verification.
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-15-16kb-page-alignment-ndk-guardrail"
---

# Android 15 16KB Memory Page Alignment Invariants for Native NDK Toolchains

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Compiling NDK native libraries with legacy 4KB ELF segment alignment or hardcoding 4096-byte offsets in mmap calls

## System Constraints
You are a Principal Software Architect enforcing Android 15 16KB Memory Page Alignment invariants. Dynamic linkers on Android 15 running on 16KB kernels reject ELF shared objects whose segment alignment (p_align) is less than 0x4000 (16384 bytes). You must enforce compiler and linker flags across CMake, ndk-build, and Gradle, mandate dynamic runtime page size queries (sysconf(_SC_PAGESIZE) or getpagesize()) over hardcoded 4096-byte constants, and reject non-compliant prebuilt binaries.

## Strict Guidelines
- Engineers MUST ALWAYS pass `-Wl,-z,max-page-size=16384` to linker flags for all ARM64 targets in CMake (`target_link_options`), `Android.mk` (`LOCAL_LDFLAGS`), or AGP external native build configurations.
- Engineers MUST ALWAYS query physical memory page size at runtime using `sysconf(_SC_PAGESIZE)` or `getpagesize()` instead of referencing macros like `PAGE_SIZE` or literal `4096` in C/C++ native source.
- Engineers MUST NOT hardcode `4096`, `0x1000`, or bitmasks such as `~(0xFFF)` when calculating offsets, ring buffer capacities, or addresses for `mmap()`, `mprotect()`, or `posix_memalign()`.
- Engineers MUST audit and verify all third-party prebuilt dynamic libraries (`.so`) using `llvm-objdump -p <lib>.so | grep -A 1 LOAD` to ensure `align 2**14` (0x4000) or higher before vendoring.
- AGP build scripts MUST configure `packagingOptions.jniLibs.useLegacyPackaging = false` to avoid unaligned compressed shared libraries within the final APK container.

## Bad vs Good Implementations
### CMake Linker Alignment Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting explicit max-page-size on NDK releases prior to r27 causes lld/gold to emit PT_LOAD segments aligned to 4KB (0x1000). On Android 15 16KB kernels, the dynamic linker refuses to load the library, throwing an unsatisfied linker error.
```cmake
# Anti-Pattern: Defaults to NDK toolchain legacy default (4KB ELF alignment)
cmake_minimum_required(VERSION 3.22.1)
project(native_engine LANGUAGES CXX)

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

#### Production Standard (Correct)
> **Standard**: Explicitly passing `-Wl,-z,max-page-size=16384` instructs the linker to set PT_LOAD segment alignment to 0x4000 (16KB), guaranteeing safe execution on both 4KB and 16KB page size devices.
```cmake
# Production Invariant: Explicitly enforce 16KB max-page-size across target architectures
cmake_minimum_required(VERSION 3.22.1)
project(native_engine LANGUAGES CXX)

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

# Enforce 16KB ELF 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()
```

### Dynamic Memory Page Boundary Calculation in C++

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using 4096 bytes or hardcoded bitmasks will fail alignment constraints on 16KB pages. If mprotect or custom pointer math relies on a 4KB granularity, it triggers EINVAL or SIGSEGV on Android 15 16KB systems.
```cpp
// Anti-Pattern: Hardcoded 4KB page size assumptions
#include <sys/mman.h>
#include <unistd.h>

#define PAGE_SIZE_4K 4096

void* allocate_aligned_buffer(size_t size) {
    // Hardcoded mask assumes 4096-byte boundaries
    size_t aligned_size = (size + PAGE_SIZE_4K - 1) & ~(PAGE_SIZE_4K - 1);
    void* addr = mmap(nullptr, aligned_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    return addr;
}
```

#### Production Standard (Correct)
> **Standard**: Calling `sysconf(_SC_PAGESIZE)` dynamically adapts the mask calculation to the active kernel page size (16384 bytes on 16KB devices and 4096 bytes on legacy devices), preventing misaligned syscall errors.
```cpp
// Production Invariant: Dynamic page-size resolution via sysconf
#include <sys/mman.h>
#include <unistd.h>
#include <cstdint>

void* allocate_aligned_buffer(size_t size) {
    const size_t pageSize = static_cast<size_t>(sysconf(_SC_PAGESIZE));
    const size_t pageMask = pageSize - 1;
    
    // Dynamically align allocation to host physical page size (4KB or 16KB)
    size_t aligned_size = (size + pageMask) & ~pageMask;
    void* addr = mmap(nullptr, aligned_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    return addr;
}
```

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 Memory Page Alignment Invariants for Native NDK Toolchains

Android 15 16KB Memory Page Alignment Invariants for Native NDK Toolchains defines an industrial-grade behavioral standard for mobile engineering. Android 15 introduces support for 16KB physical memory page sizes on ARM64 hardware, shifting away from the legacy 4KB page assumption. Shared libraries (.so) built with native NDK toolchains that fail to align ELF segments (PT_LOAD) to 16KB boundaries will trigger immediate dynamic linker crashes (dlopen failures) and SIGSEGV faults at runtime. Engineers must enforce strict 16KB linker alignment in CMake/ndk-build configurations, eliminate hardcoded 4KB page assumptions in native mmap/mprotect invocations, and ensure vendor prebuilts pass verification. 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 native libraries with legacy 4KB ELF segment alignment or hardcoding 4096-byte offsets in mmap calls 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 native libraries with legacy 4KB ELF segment alignment or hardcoding 4096-byte offsets in mmap callsCritical
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 for all ARM64 targets in CMake (`target_link_options`), `Android.mk` (`LOCAL_LDFLAGS`), or AGP external native build configurations.

Engineers MUST ALWAYS pass `-Wl,-z,max-page-size=16384` to linker flags for all ARM64 targets in CMake (`target_link_options`), `Android.mk` (`LOCAL_LDFLAGS`), or AGP external native build configurations.

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 query physical memory page size at runtime using `sysconf(_SC_PAGESIZE)` or `getpagesize()` instead of referencing macros like `PAGE_SIZE` or literal `4096` in C/C++ native source.

Engineers MUST ALWAYS query physical memory page size at runtime using `sysconf(_SC_PAGESIZE)` or `getpagesize()` instead of referencing macros like `PAGE_SIZE` or literal `4096` in C/C++ native source.

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 hardcode `4096`, `0x1000`, or bitmasks such as `~(0xFFF)` when calculating offsets, ring buffer capacities, or addresses for `mmap()`, `mprotect()`, or `posix_memalign()`.

Engineers MUST NOT hardcode `4096`, `0x1000`, or bitmasks such as `~(0xFFF)` when calculating offsets, ring buffer capacities, or addresses for `mmap()`, `mprotect()`, or `posix_memalign()`.

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 audit and verify all third-party prebuilt dynamic libraries (`.so`) using `llvm-objdump -p <lib>.so | grep -A 1 LOAD` to ensure `align 2**14` (0x4000) or higher before vendoring.

Engineers MUST audit and verify all third-party prebuilt dynamic libraries (`.so`) using `llvm-objdump -p <lib>.so | grep -A 1 LOAD` to ensure `align 2**14` (0x4000) or higher before vendoring.

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

AGP build scripts MUST configure `packagingOptions.jniLibs.useLegacyPackaging = false` to avoid unaligned compressed shared libraries within the final APK container.

AGP build scripts MUST configure `packagingOptions.jniLibs.useLegacyPackaging = false` to avoid unaligned compressed shared libraries within the final APK container.

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 Memory Page Alignment Invariants for Native NDK Toolchains critical for AI coding assistants?

Android 15 introduces support for 16KB physical memory page sizes on ARM64 hardware, shifting away from the legacy 4KB page assumption. Shared libraries (.so) built with native NDK toolchains that fail to align ELF segments (PT_LOAD) to 16KB boundaries will trigger immediate dynamic linker crashes (dlopen failures) and SIGSEGV faults at runtime. Engineers must enforce strict 16KB linker alignment in CMake/ndk-build configurations, eliminate hardcoded 4KB page assumptions in native mmap/mprotect invocations, and ensure vendor prebuilts pass verification. 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 native libraries with legacy 4KB ELF segment alignment or hardcoding 4096-byte offsets in mmap calls) 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