/*
 * examples/inert-sample/jni/inert_stub.c
 *
 * =========================================================================
 * INERT TEACHING SAMPLE - chapter 69. THIS IS NOT MALWARE.
 *
 * This file compiles to libinertstub.so. It contains a constructor, a
 * JNI_OnLoad, one dynamically registered method and one statically named
 * export, and every one of them writes a line to logcat and returns. There
 * is no decryption, no anti-debugging, no ptrace, no maps scan, no mprotect,
 * no dlopen of a second stage, and no network code of any kind.
 *
 * It exists so that the native-surface section of ../../scripts/apk-triage.py
 * has something real to report, and so that lab 01 can walk a genuine
 * .init_array entry rather than an imagined one.
 * =========================================================================
 *
 * WHY THE NATIVE SIDE IS NOT OPTIONAL IN THIS DISCIPLINE
 *
 * Chapter 15 states the ordering and this file demonstrates it:
 *
 *     dlopen("libinertstub.so")
 *        -> the dynamic linker processes relocations
 *        -> DT_INIT runs, then every DT_INIT_ARRAY entry in order
 *        -> dlopen RETURNS
 *        -> ART looks up "JNI_OnLoad" with dlsym and calls it
 *        -> System.loadLibrary() returns to Java
 *
 * Everything in the third line happens BEFORE any Java code can observe the
 * library at all. A Frida script that attaches to a running process, or that
 * hooks JNI_OnLoad, has already missed it. That is why chapter 15 insists on
 * spawn-gating and on hooking android_dlopen_ext rather than JNI_OnLoad.
 *
 * A constructor is written in C as:
 *
 *     __attribute__((constructor)) static void f(void) { ... }
 *
 * and the compiler emits a pointer to f into the .init_array section. There
 * is nothing clever about it; it is the standard C mechanism that runs
 * static C++ constructors. It becomes an analysis problem only because the
 * window it runs in is invisible to most tooling.
 *
 * THE OTHER THING THIS FILE DEMONSTRATES: DYNAMIC REGISTRATION
 *
 * There are two ways a Java native method reaches C:
 *
 *   1. STATIC. The C function is named Java_<pkg>_<Class>_<method> and the
 *      runtime finds it by dlsym at first call. The name is in the ELF
 *      dynamic symbol table, so `llvm-nm -D` or elf-inspect.py lists it and
 *      you know the mapping without running anything.
 *
 *   2. DYNAMIC. JNI_OnLoad calls RegisterNatives() with a table of
 *      {name, signature, function pointer}. The function can be `static` and
 *      therefore ABSENT from the dynamic symbol table entirely. Nothing on
 *      disk records which Java method it serves.
 *
 * Chapters 15, 51 and 52 all name RegisterNatives as the same blind spot for
 * the same reason: a static reading of the ELF cannot recover the mapping.
 * The only reliable recovery is to hook art::JNI::RegisterNatives at runtime
 * (52's blindspot-recorder.js does exactly this) or to read the argument
 * table out of JNI_OnLoad by hand in a disassembler.
 *
 * This file registers ONE method dynamically and exports ONE statically, so
 * that the reader can run both readings against the same library and see the
 * gap for themselves. That comparison is lab 01, step 6.
 *
 * BUILD
 *   Built by ../build.sh when an NDK is present. Skipped, with a message,
 *   when it is not - the rest of the sample builds and analyses fine
 *   without it, and the triage tool then reports "no native libraries",
 *   which is itself a result worth seeing.
 */

#include <jni.h>
#include <android/log.h>
#include <string.h>

#define TAG "CH69-INERT"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)

/*
 * Runs from .init_array, before dlopen returns, before JNI_OnLoad.
 * A hostile constructor would: ptrace(PTRACE_TRACEME) to occupy the tracer
 * slot, read /proc/self/status for TracerPid, scan /proc/self/maps for
 * "frida", or mprotect a data page executable and jump into decrypted code.
 * This one prints a sentence.
 */
__attribute__((constructor))
static void ch69_init_array_entry(void)
{
    LOGI("native: .init_array entry ran. This is BEFORE dlopen returned and "
         "BEFORE JNI_OnLoad. Nothing else happens here.");
}

/*
 * Statically named export. Discoverable with:
 *     llvm-nm -D --defined-only libinertstub.so | grep Java_
 *     python3 ../../15-Native-Code/scripts/elf-inspect.py libinertstub.so --dynsyms
 */
JNIEXPORT jstring JNICALL
Java_com_pentest_ch69_inert_NativeProbe_staticallyNamed(JNIEnv *env, jclass clazz)
{
    (void) clazz;
    LOGI("native: staticallyNamed() - resolved by dlsym on its mangled name.");
    return (*env)->NewStringUTF(env,
        "statically named export: the ELF dynamic symbol table records this");
}

/*
 * Dynamically registered. `static`, so it does NOT appear in the dynamic
 * symbol table. Nothing on disk connects it to a Java method name.
 */
static jstring ch69_dynamically_registered(JNIEnv *env, jclass clazz)
{
    (void) clazz;
    LOGI("native: dynamicallyRegistered() - bound by RegisterNatives, "
         "invisible to a static symbol dump.");
    return (*env)->NewStringUTF(env,
        "dynamically registered: only RegisterNatives knows this mapping");
}

static const JNINativeMethod kMethods[] = {
    { "dynamicallyRegistered", "()Ljava/lang/String;",
      (void *) ch69_dynamically_registered },
};

JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM *vm, void *reserved)
{
    JNIEnv *env = NULL;
    jclass cls;

    (void) reserved;

    LOGI("native: JNI_OnLoad entered. The .init_array entry above already ran.");

    if ((*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6) != JNI_OK) {
        return JNI_ERR;
    }

    cls = (*env)->FindClass(env, "com/pentest/ch69/inert/NativeProbe");
    if (cls == NULL) {
        /* The class is optional in this sample; the library is still loadable
           and its symbols are still worth dumping. Clear the pending
           exception so the runtime is not left in an error state. */
        (*env)->ExceptionClear(env);
        LOGI("native: NativeProbe class absent, skipping RegisterNatives.");
        return JNI_VERSION_1_6;
    }

    if ((*env)->RegisterNatives(env, cls, kMethods,
                                (jint) (sizeof(kMethods) / sizeof(kMethods[0]))) < 0) {
        LOGI("native: RegisterNatives failed.");
        return JNI_ERR;
    }

    LOGI("native: RegisterNatives bound 1 method. Nothing else was done.");
    return JNI_VERSION_1_6;
}
