Skip to content

feat: Add support for hooking class initializers ($clinit) - #424

Open
mnalmahmud wants to merge 9 commits into
frida-packages:mainfrom
mnalmahmud:clinit-hooking
Open

mnalmahmud wants to merge 9 commits into
frida-packages:mainfrom
mnalmahmud:clinit-hooking

Conversation

@mnalmahmud

@mnalmahmud mnalmahmud commented Nov 20, 2026 •

Copy link
Copy Markdown

Summary

Adds support for hooking Java class initializers (<clinit>) via the $clinit property on class wrappers on both Android ART and HotSpot JVM, and defers class initialization during Java.use() so scripts can hook $clinit (and static/constructor methods) before <clinit> runs.

Related PRs (each independent on main):

Commits

  1. android: Initialize classes via Object.hashCode()
    • Trigger class initialization in ensureClassInitialized() via GetMethodID(classRef, "hashCode", "()I") instead of probing a nonexistent field x.
  2. android: Fix quick frame method lookup
    • Mask the two low tag bits (~3) on ManagedStack::top_quick_frame_ and read 32-bit ArtMethod* slots on API ≤ 22 in find_replacement_method_from_quick_code.
  3. class-model: Exclude constructors from members
    • Exclude <init> (and <clinit>) when enumerating regular members in ClassModel.
  4. android: Keep method hooks across class init
    • Preserve method hooks installed before <clinit> runs across ART's class initialization and code-update paths:
      • Hook artQuickResolutionTrampoline (with fallback stub disassembly when the C++ helper is not exported), Instrumentation::UpdateMethodsCode, and ClassLinker::FixupStaticTrampolines / UpdateClassAfterCharArrayInit / InitializeClass lifecycle hooks.
      • Unify hooked quick entrypoint restoration via resolve_hooked_quick_entrypoint() and an intercepted_codes table so hooks survive Android 15+ ThinLTO inlined UpdateMethodsCode AOT installs as well as API 26–29 trampoline paths.
      • Guard kAccNterpEntryPointFastPathFlag behind artNterpEntryPoint !== null.
  5. Add support for hooking class initializers
    • Add MethodType.ClassInitializer = 1 (updating index.d.ts with $clinit documentation and MethodType enum values) and wire $clinit hooking through ClassFactory / ClassModel / android.js / env.js.
  6. class-factory: Defer class init from Java.use()
    • Use non-initializing lookup in Java.use() so obtaining a class wrapper does not eagerly execute <clinit>, initializing lazily on first static field/method/constructor access instead.
  7. class-factory: Avoid class init in makeConstructor
    • Avoid triggering class initialization while building constructor wrappers during Java.use().
  8. jvm: Support hooking class initializers
    • Add <clinit> hooking support in the HotSpot JVM backend (lib/jvm.js and lib/jvmti.js), including non-initializing class lookup via Class.forName(name, false, loader) + Class.getDeclaredMethods() and deferred initialization via Object.hashCode().
  9. tests: Add ClassInitializerTest
    • Add ClassInitializerTest covering $clinit interception, original invocation, replacement, skipping, exception handling, hooking static methods/constructors before <clinit>, lazy initialization semantics of Java.use(), and classes without <clinit>.

Verification

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 mnalmahmud changed the title Add support for hooking class initializers ($clinit) feat: Add support for hooking class initializers ($clinit) Nov 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant