Repository navigation
feat: Add support for hooking class initializers ($clinit) - #424
Open
mnalmahmud wants to merge 9 commits into
Open
mnalmahmud wants to merge 9 commits into
mnalmahmud wants to merge 9 commits into
Conversation
This was referenced Nov 20, 2026
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
Ensure method hooks installed before a class is initialized survive verification, class initialization, and static trampoline fixups: - Replace Nterp-with-clinit quick entrypoints with quickResolutionTrampoline when hooking uninitialized static methods, and recognize both ClassLinker and libart trampoline addresses. - Intercept artQuickResolutionTrampoline (resolving the C++ callee from the assembly stub if stripped) so hooked methods keep their quick hook entrypoint after resolution while clearing the stale managed top_quick_frame. - Track already-intercepted AOT entrypoints in the ART controller and unify quick entrypoint preservation across Instrumentation::UpdateMethodsCode*, ClassLinker lifecycle hooks, and resolution trampoline exits so newly installed Nterp or AOT code (including when UpdateMethodsCode is inlined under ThinLTO) does not bypass active hooks. - Update ArtMethodMangler.revert() to restore post-init quick/JNI entrypoints cleanly if a class initialized while a method was hooked, and guard kAccNterpEntryPointFastPathFlag behind artNterpEntryPoint.
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
Add tests covering Java.use() deferred initialization, $clinit hooking (with and without calling the original initializer), $clinit hook reversion, classes without a static initializer, constructors and methods hooked prior to class initialization, and throwing from a $clinit hook.
mnalmahmud
force-pushed
the
clinit-hooking
branch
from
November 20, 2026 17:43
d7ac581 to
5c3d3e4
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds support for hooking Java class initializers (
<clinit>) via the$clinitproperty on class wrappers on both Android ART and HotSpot JVM, and defers class initialization duringJava.use()so scripts can hook$clinit(and static/constructor methods) before<clinit>runs.Related PRs (each independent on
main):improve-test-infra) — Test infrastructure & CI (Android API 26–36 + HotSpot JVM runner)clinit-hooking) — Class initializer ($clinit) hooking (this PR)jvm-lts-21-25) — HotSpot LTS JDK 21 & 25 support viaVMStructsCommits
android: Initialize classes via Object.hashCode()ensureClassInitialized()viaGetMethodID(classRef, "hashCode", "()I")instead of probing a nonexistent fieldx.android: Fix quick frame method lookup~3) onManagedStack::top_quick_frame_and read 32-bitArtMethod*slots on API ≤ 22 infind_replacement_method_from_quick_code.class-model: Exclude constructors from members<init>(and<clinit>) when enumerating regular members inClassModel.android: Keep method hooks across class init<clinit>runs across ART's class initialization and code-update paths:artQuickResolutionTrampoline(with fallback stub disassembly when the C++ helper is not exported),Instrumentation::UpdateMethodsCode, andClassLinker::FixupStaticTrampolines/UpdateClassAfterCharArrayInit/InitializeClasslifecycle hooks.resolve_hooked_quick_entrypoint()and anintercepted_codestable so hooks survive Android 15+ ThinLTO inlinedUpdateMethodsCodeAOT installs as well as API 26–29 trampoline paths.kAccNterpEntryPointFastPathFlagbehindartNterpEntryPoint !== null.Add support for hooking class initializersMethodType.ClassInitializer = 1(updatingindex.d.tswith$clinitdocumentation andMethodTypeenum values) and wire$clinithooking throughClassFactory/ClassModel/android.js/env.js.class-factory: Defer class init from Java.use()Java.use()so obtaining a class wrapper does not eagerly execute<clinit>, initializing lazily on first static field/method/constructor access instead.class-factory: Avoid class init in makeConstructorJava.use().jvm: Support hooking class initializers<clinit>hooking support in the HotSpot JVM backend (lib/jvm.jsandlib/jvmti.js), including non-initializing class lookup viaClass.forName(name, false, loader)+Class.getDeclaredMethods()and deferred initialization viaObject.hashCode().tests: Add ClassInitializerTestClassInitializerTestcovering$clinitinterception, original invocation, replacement, skipping, exception handling, hooking static methods/constructors before<clinit>, lazy initialization semantics ofJava.use(), and classes without<clinit>.Verification
npm run lint,node --check index.js lib/*.js, andtsc --noEmit --lib es2022 index.d.ts.