Repository navigation
added support for hooking class initializers - #403
mnalmahmud wants to merge 14 commits into
Conversation
|
@oleavr kindly have a look at this if you get time. |
|
@oleavr any updates mate? |
|
Thanks for this, and sorry for the wait! It's a really well researched PR. Since it was opened, #344 has landed. That reworks the test harness and restores class initialization in Could you rebase it onto
Please also keep commit subjects within 50 columns, in imperative mood, and leave out source comments. The commit messages are a great place for the reasoning you have in the PR description. One thing I'm still weighing is |
I will look into this as soon as possible, mate. |
c485bca to
b48221e
Compare
Replace the dummy field lookup restored in a342d5e with a lookup of Object.hashCode(). FindMethodJNI() begins by calling EnsureInitialized(), and every class inherits Object.hashCode(), which FindClassMethod() finds by walking the superclass chain, so the lookup succeeds without raising a NoSuchFieldError. Older ART versions where FindInterfaceMethodWithSignature() does not fall back to java.lang.Object, primitive classes, and classes whose <clinit> throws still return null with a pending exception after initialization is attempted, so clear the pending exception when getMethodId() returns null. https://android.googlesource.com/platform/art/+/refs/heads/main/runtime/jni/jni_internal.cc
ART's ManagedStack::TaggedTopQuickFrame uses two tag bits
(kTaggedJniSpMask = 0x3: bit 0 for GenericJNI frames and bit 1 for
JitJNI frames). Mask both bits when untagging the linked top quick
frame pointer.
On Android 5.x (API <= 22), quick frames store the method as a 32-bit
compressed StackReference<mirror::ArtMethod> rather than a full
pointer, so read a 32-bit slot there to support 64-bit Android 5.x.
https://android.googlesource.com/platform/art/+/refs/heads/main/runtime/managed_stack.h
https://android.googlesource.com/platform/art/+/refs/tags/android-5.1.1_r1/runtime/stack.h
model_new()'s three branches disagreed on constructors. The JVMTI branch added every method GetClassMethods() reports, exposing <init> and <clinit> under their raw names so wrapper['<init>'] resolved them as regular methods and crashed. The ART branch skipped everything carrying kAccConstructor, and the reflection fallback uses getDeclaredMethods(), which never reports constructors. Drop constructors in the JVMTI branch so all three branches agree that constructors are not members. Instance constructors are resolved independently by $new and $init. Fixes frida-packages#384
f1b3ee4 to
774aaa1
Compare
Ensure ART method hooks remain active without requiring the declaring class to be initialized before installing the hook: - Rewrite ExecuteNterpWithClinitImpl to art_quick_resolution_trampoline when hooking uninitialized static methods so Nterp does not branch directly into unhooked ExecuteNterpImpl once initialization starts. - Hook C++ artQuickResolutionTrampoline (resolved by symbol or via the call target in art_quick_resolution_trampoline) instead of replacing the method at art_quick_resolution_trampoline entry. Save thread and sp on entry and, on leave, clear any stale top_quick_frame_ still pointing to sp and roll back any nterp entrypoint installed during EnsureInitialized() before redirecting hooked methods to quick_to_interpreter_bridge or quick_generic_jni_trampoline. - Intercept Instrumentation::UpdateMethodsCode, UpdateMethodsCodeImpl, ClassLinker::VerifyClass, ClassLinker::InitializeClass, and ClassLinker::FixupStaticTrampolines across exports and symbols (excluding split .cold/.part/.isra/.constprop clones) so verification and static trampoline fixups across Android 15+ hidden/ThinLTO builds cannot clobber hooked access flags or quick entrypoints. - In ArtMethodMangler.revert(), avoid restoring pre-init trampolines (art_quick_resolution_trampoline or ExecuteNterpWithClinitImpl) once the declaring class has initialized, preserving post-init quickCode and jniCode so API 26-29 does not loop forever in art_quick_resolution_trampoline.
Drop unused Method::jmethod_id symbol entries that are absent in Temurin JDK 8 builds. Check the optional UseCompiler flag before invoking code cache sweeps so reverting methods under -Xint does not hang waiting on a sweeper thread that HotSpot never starts. On JDK 8 (which lacks NMethodSweeper::force_sweep()), look up the optional NMethodSweeper::_sweep_started flag and claim it inside a safepoint instead of checking _should_sweep == 0. In OpenJDK 8, _should_sweep stays set to 1 while compiler threads are idle, so checking _should_sweep skipped sweep_code_cache() indefinitely. Also use Int64.add() and Int64.compare() when tracking traversal counts.
Expose <clinit> as $clinit on class wrappers, alongside $init and $new, so a class' static initialization can be intercepted, inspected, or skipped. Unlike $init, $clinit is a plain Method rather than a MethodDispatcher, as a class has at most one class initializer and its signature is always ()V. Add MethodType.ClassInitializer at 1 (shifting Constructor, Static, and Instance) in both lib/class-factory.js and index.d.ts. Resolve the method ID from ClassModel rather than GetStaticMethodID() (which calls EnsureInitialized(), triggering the initializer we want to hook) or Java reflection (which never exposes <clinit>). Keep it in Model::class_initializer rather than the members hash table so it does not surface in ownKeys() and get resolved through makeMethodFromSpec(), which would invoke java.lang.reflect.Method methods on a Constructor returned by ToReflectedMethod(). Report $clinit in Java.enumerateMethods() on both ART and JVM, mirroring $init.
Stop initializing classes in Java.use() so callers can hook $clinit, constructors, instance methods, or static methods before the class initializer runs. Initialize lazily only where JNI itself skips class initialization because ClassModel bypassed GetStaticFieldID() and GetStaticMethodID(): - Field.prototype.value getter and setter initialize the class before reading or writing a STATIC_FIELD since GetStatic*Field() and SetStatic*Field() perform no initialization check (leaving static field metadata inspection non-initializing). - methodPrototype.invoke() initializes the class before invoking a STATIC_METHOD from JavaScript since CallStatic*Method() performs no initialization check (NewObjectV() for $new() already initializes the class natively in ART, HotSpot, and Dalvik).
Collect <init> jmethodIDs in ClassModel across JVMTI, ART, and Dalvik and reflect them via ToReflectedMethod() instead of calling Class.getDeclaredConstructors() followed by FromReflectedMethod() in makeConstructor(). On OpenJDK HotSpot, jni_FromReflectedMethod unconditionally initializes the declaring class, so accessing $init to hook a constructor prematurely ran <clinit>.
On HotSpot, jni_FindClass() passes init=true down to
find_class_from_class_loader(), so Java.use() ran <clinit> before the
caller could install a hook on $clinit.
Resolve classes through Class.forName(name, false, loader) instead,
normalizing slash-delimited names to dot form. Because that loads
without linking and JVMTI GetClassMethods() fails with
JVMTI_ERROR_CLASS_NOT_PREPARED on an unlinked class, invoke
Class.getDeclaredMethods() first to link the class without initializing
it. Use the same path for custom ClassLoader lookups in
makeLoaderClassHandleGetter().
Match jni_FindClass()'s class loader lookup by taking the loader of the
topmost Java frame on the calling thread via JVMTI GetStackTrace(),
GetMethodDeclaringClass(), and GetClassLoader(), falling back to the
system class loader when there is no Java frame, and avoiding
DeleteLocalRef() when the caller was loaded by the bootstrap class
loader (NULL).
Implement ensureClassInitialized() via Object.hashCode(), mirroring ART:
jni_GetMethodID() calls klass->initialize() before the lookup, with
interfaces needing the pending exception cleared afterwards.
https://github.com/openjdk/jdk/blob/master/src/hotspot/share/prims/jni.cpp
Cover class initializer hooking and deferred class initialization: - Hooking $clinit and invoking the original from the replacement - Replacing $clinit without invoking the original - Enumerating $clinit via Java.enumerateMethods() - Throwing when accessing $clinit on a class without a class initializer - Hooking $init and instance methods without triggering <clinit> - Hooking static methods without triggering <clinit>, preserving JLS ordering (<clinit> before the hooked static method) and keeping hooks active across subsequent invocations - Hooking both $clinit and a static method on the same class - Invoking static methods, calling $new(), and accessing static fields directly from JavaScript on lazily wrapped classes - Hooking a static method invoked from inside its own class's <clinit> - Reverting a static method hook installed before <clinit> via script unload
Parse Frida script JSON messages in runner.c using json-glib (already linked via libfrida-gumjs.a) instead of org.json in Script.java, and fail fast with an explicit IllegalStateException on script message timeout. This ensures uniform payload serialization across Android and HotSpot JVM (matching string, boolean, number, array, object, and null values) without depending on Android's built-in org.json implementation.
Bring the Android test runner, Makefiles, and GitHub Actions workflow up to date for modern Android API levels and improve reliability: - Clamp APP_PLATFORM in test/Application.mk to the NDK's maximum supported API level from meta/platforms.json and handle major.minor API levels across test/Application.mk and test/Makefile for platform paths, sysroot, and d8 --min-api. - Implement multi-handler sigchain support in test/runner.c so ART's implicit null-check and stack-overflow fault handlers are dispatched and chained properly to any previous signal handler. - Install a 64-bit Linux GumMemoryHooks allocator in test/runner.c that probes a 64 MiB window before mapping Stalker slabs, working around gum_data_slab_new() NULL dereferences on Android API 35-36 (frida/frida-gum#793), and call Stalker.unfollow() before send() in MethodTest.callCanBeTraced() so teardown is not traced into extra slabs. - Expand the CI matrix to API levels 26-36 with fail-fast disabled, auto-detect the latest installed build-tools directory, remove the stale x86 exclusion, and cache downloaded test dependencies. - Rebuild build/frida-java-bridge.js whenever bridge sources change, deploy once in `make check` using `adb push --sync` with an explicit libartpalette.so prerequisite, use atomic `curl -fsSL` downloads (with Maven Central for hamcrest-core), pass `-o` to `unzip`, fix watch quoting and LD_PRELOAD, dump scoped crash/warning logcat since the test start timestamp on failure, and allow filtering test classes via TestRunner args.
Run the test suite on HotSpot JVM in addition to Android ART across supported LTS releases (JDK 8, 11, and 17): - Extend test/runner.c to launch HotSpot via JNI_CreateJavaVM on non-Android platforms, guarding Android-only sigchain and AttachCurrentThread differences with #ifdef __ANDROID__, fixing destroy_weak_ref's GDestroyNotify signature for OpenJDK jni.h, converting script sources via GetStringChars + g_utf16_to_utf8 (since HotSpot GetStringUTFChars emits Modified UTF-8 for surrogate pairs like the ESM package header), and deferring script-load completion to a G_PRIORITY_LOW idle callback so pending Script.nextTick() hook installations finish before new Script() returns. - Add TestRunner.isAndroid() and TestRunner.getAndroidApiLevel() so ClassRegistryTest and MethodTest compile and run on HotSpot without android.jar, selecting Android-only suites (ClassCreationTest and PerformTest) only on Android. - Rename Android Makefile/CI targets, variables, and build outputs symmetrically (build-android, deploy-android, run-android, watch-android, debug-android, check-android, check-android-gdb, develop-android, android, tests-android.dex) alongside HotSpot targets (build-jvm, run-jvm, watch-jvm, debug-jvm, check-jvm, check-jvm-gdb, develop-jvm, jvm) and update README.md accordingly. - Add a `jvm` matrix job on ubuntu-latest with Temurin JDK 8, 11, and 17 running `make check-jvm` (both interpreter and JIT modes).
Upgrade GitHub Actions to their Node 24 releases (actions/checkout@v7, actions/setup-node@v7, actions/setup-java@v6, and actions/cache@v6) across both workflows, and modernize the linting workflow to Node 22 with JavaScript syntax (`node --check`) and TypeScript declaration (`tsc --noEmit`) verification. Set explicit timeout-minutes on all CI jobs (30m for android, 15m for jvm, 10m for lint) so hung runs fail promptly instead of blocking for GitHub Actions' 6-hour default.
774aaa1 to
0fb4298
Compare
Added support for hooking class initializers
Expose
<clinit>as$cliniton class wrappers, alongside$initand$new, so aclass' static initialization can be intercepted, inspected or skipped:
As a class is only ever initialized once, the hook must be installed before anything
touches the class. Resolving
<clinit>through JNI would defeat that:GetStaticMethodID()goes throughFindMethodJNI(), which begins by callingEnsureInitialized(), and would therefore run the very initializer we are about tohook. Java reflection is no help either, as
<clinit>is exposed by neithergetDeclaredMethods()norgetDeclaredConstructors(), which is how$initand$newresolve their method IDs. The ID is therefore taken from
ClassModel, which enumeratesmethods without going through method resolution.
Unlike
$init,$clinitis a plainMethodrather than aMethodDispatcher, as aclass has at most one class initializer and its signature is always
()V, leavingnothing to dispatch on.
Class model
model_new()'s three branches disagreed on constructors. The JVMTI branch added everymethod
GetClassMethods()reports, so<init>and<clinit>became members undertheir raw names, reachable as
wrapper['<init>']; the ART branch dropped everythingcarrying
kAccConstructor; the reflection fallback usesgetDeclaredMethods(), whichnever reports constructors at all. All three now agree that constructors are not
members. Instance ones are dropped, as
$newand$initresolve them independentlyand need the signatures only reflection provides.
The class initializer is kept in
Model::class_initializerrather than in the membershash table, and read back through the new
model_find_class_initializer(). Putting itin the table would surface it in
model_list(), which backs the wrapper Proxy'sownKeys()trap, and asgetOwnPropertyDescriptor()reports every member asenumerable,
Object.entries()on a wrapper would resolve it throughmakeMethodFromSpec(). That callsToReflectedMethod(), which yields aConstructorfor
<clinit>, and would then invokejava.lang.reflect.Methodmethods on it.The ART branch identifies
<clinit>asIsConstructor() && IsStatic(), matchingArtMethod::IsClassInitializer(), and names it without consulting ART for the samereason.
Java.enumerateMethods()now reports$clinitinstead of skipping it,mirroring how
<init>is reported as$init.https://android.googlesource.com/platform/art/+/refs/heads/main/runtime/art_method.h
Class initialization
Java.use()no longer initializes the class; that now happens when a static field isfirst read or an implementation is installed. ART rewrites the quick entrypoint of
every static method of a class as that class becomes initialized, via
ClassLinker::FixupStaticTrampolines(), andArtMethodMangler.replace()snapshotsquickCodewhen the hook is installed, so hooking a static method of anot-yet-initialized class would leave the mangler holding an entrypoint ART replaces
moments later, silently bypassing the hook. Initializing at hook time preserves that
ordering while leaving classes that are merely wrapped alone.
CLASS_INITIALIZER_METHODis exempt, as forcing initialization is precisely whathooking it is meant to intercept.
https://android.googlesource.com/platform/art/+/refs/heads/main/runtime/class_linker.cc
ensureClassInitialized()had not initialized anything since 7983e81, which replacedits dummy field lookup with
getClassName()to avoid theNoSuchFieldErrorit had toclear afterwards. The exception was noise, but the lookup was the mechanism:
FindFieldJNI()begins by callingEnsureInitialized(), andgetClassName()reachesnothing of the sort. Resolve
Object.hashCode()instead, which every class inheritsand
FindClassMethod()finds by walking the superclass chain. Interfaces are the oneexception, as
FindInterfaceMethodWithSignature()searches only their declared andsuperinterface methods; they are initialized all the same, before the lookup fails.
https://android.googlesource.com/platform/art/+/refs/heads/main/runtime/jni/jni_internal.cc
Invocation
ClassLinker::InitializeClass()runs the initializer throughArtMethod::Invoke()rather than from a call site. That function hands over to the interpreter — running the
DEX bytecode straight from the code item, never consulting the quick entrypoint the
mangler patched — whenever the calling thread is forced to interpret, and dispatches
through the entrypoint otherwise. Hooking a class initializer therefore took effect
only when ART happened to pick the latter branch, which varies with the API level and
the compiler filter. Every other method has bytecode or quick call sites that stay
instrumented;
<clinit>has only this one.ArtMethod::Invoke()is therefore instrumented as well, swapping in the replacementmethod, which is native and thus not eligible for interpretation, putting the call back
onto the quick path. It needs a stack check written for the stack it actually sees: the
fragment is pushed after the hook has run, so the one in
find_replacement_method_from_quick_code()does not hold, and a class initializerre-entered through
this.$clinit()recursed until the stack ran out. Our own JNIreplacement stub is on top precisely when the hook is invoking the original, so compare
against it directly, masking the tag bit off the top of the stack the way
ManagedStack::GetTopQuickFrame()does. The comparison is per-method, leaving areplacement free to invoke some other hooked method and still reach that method's hook.
The deoptimization APIs are the other caller of this hook and were exposed to the same
recursion, so they get the fix too.
https://android.googlesource.com/platform/art/+/refs/heads/main/runtime/art_method.cc
HotSpot
$clinitwas enumerable on the JVM but never hookable:jni_FindClass()passesinit=truedown tofind_class_from_class_loader(), soJava.use()ran theinitializer before the caller could install anything.
Resolve through
Class.forName(name, false, loader)instead. That loads withoutinitializing, but stops short of linking too, and JVMTI will not enumerate the members
of a class that has yet to be prepared:
GetClassMethods()fails withJVMTI_ERROR_CLASS_NOT_PREPARED, andmodel_new()ignores the return value, leavingit to walk and free a count and array it never wrote. Ask for the declared methods
first, as
JVM_GetClassDeclaredMethods()links the class without initializing it.jni_FindClass()takes its loader from the topmost Java frame on the calling thread,falling back to the system one when the thread has none, so
Class.forName()has to betold the same or classes only a custom loader can see would stop resolving from inside
a hook.
getCallerClassLoader()works it out withGetStackTrace(),GetMethodDeclaringClass()andGetClassLoader(), none of which need a capability.jvm.js'sensureClassInitialized()was an empty function, which no longer holds nowthat
Java.use()leaves the class alone: every static field would read back itsdefault.
jni_GetMethodID()callsklass->initialize()before the lookup, so the trickART uses ports over unchanged, down to interfaces needing the pending exception cleared
afterwards.
https://github.com/openjdk/jdk/blob/master/src/hotspot/share/prims/jni.cpp
Tests
ClassInitializerTestcovers hooking a class initializer, replacing it, invoking theoriginal from the replacement, enumeration, and the class that has none. The harness
needed repairs to run at all on newer API levels: the runner gives ART back its signal
handlers instead of stubbing out libsigchain, script code is spliced into the bundle
rather than appended to it, a script that never replies fails with its own error and a
logcat dump instead of timing out silently, and
APP_PLATFORMis clamped to what theNDK actually ships. The test matrix extends to Android 16, dropping x86 in favour of
x86_64 throughout.