Everything that leaves the pure Kotlin/Java world: native shared libraries (.so), the JNI boundary, cross-boundary refs and exceptions, and the modern Android packaging constraints (16 KB pages, split APKs, App Bundles).
Pair with kotlin-performance for measuring native-call overhead, smali-dex-patching for offensive patching of the managed side, and mobile-technique for auditing shipped native code.
The JVM (ART) and native code share a process but different memory managers, exception systems, and reference tracking.
Every call across the boundary has cost (~25–100 ns even for @CriticalNative) — batch and design coarse APIs, not chatty ones.
Native code owns local references valid within one JNI call and global references valid until explicitly deleted. Losing track of either leaks or crashes.
The GC cannot pause a thread running native code — long native work blocks the whole runtime's GC cycle.
One process contains one ART instance; multiple .so files load into the same address space and can call each other freely.
Skips locking; body cannot access this from arbitrary heap without care
@CriticalNative
~25 ns
Removes JNIEnv* and jclass params; must be static, primitive-only args, cannot call back into JVM
On Android 12+ the compiled managed→native call for @CriticalNative is nearly free — worth the constraints for hot paths. See references/fast-critical-native.md.
Android 15+ devices can boot with 16 KB kernel pages for improved performance.
All .so files for arm64-v8a and x86_64 (the 64-bit ABIs) must have LOAD segments aligned to 16 KB.
AGP 8.5.1+ with NDK r28+ handles ELF and zip alignment automatically (AGP 9.0 defaults to NDK r28c, 28.2.13676358). Older combos (AGP 8.3–8.5, NDK r26–r27) compile aligned .so but may misalign the APK zip entries — see references/16kb-page-size.md for the version matrix. NDK r26 and older need manual linker flags:cmake
# CMakeLists.txt for older toolchainstarget_link_options(mylib PRIVATE "-Wl,-z,max-page-size=16384" "-Wl,-z,common-page-size=16384")
Verify per-.so:bash
llvm-readelf -lW libmylib.so | grep -E "LOAD" | awk '{ print $NF }'# Expect Align = 0x4000 for each LOAD segment on 64-bit ABIs
Third-party AARs must also comply — check every .so in build/intermediates/merged_native_libs/.
Code must not assume PAGE_SIZE = 4096. Query at runtime via sysconf(_SC_PAGESIZE) or getpagesize().
Full workflow with automation tools: references/16kb-page-size.md.
System.loadLibrary("native_crypto") looks for libnative_crypto.so in the APK's lib/<abi>/ folder.
System.load("/absolute/path.so") loads from arbitrary path — used for dynamic feature modules and (offensively) for injected libraries.
Runtime.getRuntime().load*() are aliases.
Compressed .so files (android:extractNativeLibs="true") are the legacy default; modern AAPT2/AGP defaults to uncompressed for direct mmap from APK (faster load, no disk copy). Verify with zipinfo -v app.apk | grep "\.so" — flags should show "stored" not "deflated" for optimal load.
Multiple .so files can depend on each other; use System.loadLibrary in dependency order or Java_com_example_NativeCrypto_encrypt will fail at first call because the dependency isn't loaded.
Local refs — automatically freed at JNI method return. Table starts at 512 entries (newer ART grows it, up to 8192); when full the JVM aborts with LocalReferenceTable overflow — the abort message prints the actual max=.
Explicitly env->DeleteLocalRef(obj) inside long loops.
Use PushLocalFrame(capacity) / PopLocalFrame(nullptr) for scoped batches.
Global refs — survive across JNI calls. Free with env->DeleteGlobalRef(g). Every global ref must be paired with a delete or it leaks until process exit.
Weak global refs — GC can collect the referent; check with IsSameObject(weakRef, nullptr) before use.
Never store a JNIEnv* — it's per-thread. Store JavaVM* and call AttachCurrentThread from other threads.
Threads created in native code (pthread_create) that call back into Java must attach: vm->AttachCurrentThread(&env, nullptr); detach in a cleanup handler via DetachCurrentThread.
Full patterns: references/jni-refs-and-exceptions.md.
After every JNI call that can throw (CallXxxMethod, NewObject, FindClass, GetFieldID, ...), check with env->ExceptionCheck().
Native functions cannot call additional JNI functions with a pending exception (except a small allowlist: DeleteLocalRef, ExceptionClear, ...). Doing so aborts with JNI DETECTED ERROR IN APPLICATION.
Handle by either propagating (return early — the Kotlin caller sees the exception) or clearing (env->ExceptionClear() — silently swallow, discouraged).
Native code cannot throw C++ exceptions across the JNI boundary — they trigger abort(). Wrap C++ code in try { } catch (const std::exception& e) { env->ThrowNew(env->FindClass("java/lang/RuntimeException"), e.what()); }.
Ship libmylib.so.debug (via AGP packaging { jniLibs { keepDebugSymbols += "**/lib*.so" } } for local, or upload debug symbols to Play Console for production).
Set CMake to Release with debug info: -DCMAKE_BUILD_TYPE=RelWithDebInfo. Strip separately for shipping.
Include callers of native methods in the Baseline Profile (see kotlin-performance/references/baseline-and-startup-profiles.md) — ART pre-compiles the caller side, reducing transition overhead.
Explicit RegisterNatives at JNI_OnLoad avoids name-based lookup at first call (faster) and hides method names from strings output.
For hot paths that would otherwise pay the JNI transition per element, batch: pass a whole array + length once, not one element at a time.
Prefer GetPrimitiveArrayCritical / ReleasePrimitiveArrayCritical for zero-copy access to primitive arrays — but cannot call JNI or block during the critical region.
CPU affinity: sched_setaffinity is available on Android for pinning to big cores. Rarely worth it, but valid for realtime audio/video threads.
Offensive angle covered in depth by mobile-technique/references/android-ipc-attack-surface.md and the reversing-technique skill:
unzip -j app.apk 'lib/arm64-v8a/*.so' -d libs/
llvm-nm -D libmylib.so | grep Java_ — lists JNI-exported symbols; the class/method mapping is in the name.
objdump -d libmylib.so | less or Ghidra for structural analysis.
Native anti-analysis: check for ptrace self-attach, read /proc/self/status | grep TracerPid, JNI reflection to hide method registration. Frida hooks work at the native symbol boundary.
references/jni-refs-and-exceptions.md — local vs global refs, PushLocalFrame, ExceptionCheck after every fallible call, JavaVM* thread attach, common LocalReferenceTable overflow diagnosis; load when writing or debugging JNI implementation code
references/fast-critical-native.md — @FastNative / @CriticalNative optimization, restrictions, DIY annotation classes (missing from public SDK), RegisterNatives binding, when the win is real; load when a native call is on a hot path measured at > 1 M ops/sec
references/16kb-page-size.md — compliance workflow, CMake/ndk-build flags, verification tools (android-16kb-validator, llvm-readelf), third-party AAR audit, Play deadline; load when the app has any native code and targets API 35+
references/native-crashes-and-debugging.md — tombstone anatomy, ndk-stack, addr2line, LLDB attach for on-device debugging, ASan/UBSan setup, Play Console symbol upload; load when triaging a native crash or setting up sanitizers
references/rust-jni.md — cargo-ndk + jni-rs workflow, safe wrapper patterns, catch_unwind for panic containment, cross-build for all ABIs, 16 KB alignment; load when embedding a Rust library or evaluating Rust for a new native module
references/native-memory-and-crashes.md — native heap allocation tracking (libc.debug.malloc), LeakSanitizer setup, JNI ref leaks (not visible in Java heap dump), dumpsys meminfo native section triage; load when investigating native memory growth or OOM in a native module