Skip to content

added support for hooking class initializers - #403

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

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

Conversation

@mnalmahmud

@mnalmahmud mnalmahmud commented Aug 7, 2026 •

Copy link
Copy Markdown

Added support for hooking class initializers

Expose <clinit> as $clinit on class wrappers, alongside $init and $new, so a
class' static initialization can be intercepted, inspected or skipped:

const Foo = Java.use('com.example.Foo');
Foo.$clinit.implementation = function () {
    this.$clinit();
};

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 through FindMethodJNI(), which begins by calling
EnsureInitialized(), and would therefore run the very initializer we are about to
hook. Java reflection is no help either, as <clinit> is exposed by neither
getDeclaredMethods() nor getDeclaredConstructors(), which is how $init and $new
resolve their method IDs. The ID is therefore taken from ClassModel, which enumerates
methods without going through method resolution.

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, leaving
nothing to dispatch on.

Class model

model_new()'s three branches disagreed on constructors. The JVMTI branch added every
method GetClassMethods() reports, so <init> and <clinit> became members under
their raw names, reachable as wrapper['<init>']; the ART branch dropped everything
carrying kAccConstructor; the reflection fallback uses getDeclaredMethods(), which
never reports constructors at all. All three now agree that constructors are not
members. Instance ones are dropped, as $new and $init resolve them independently
and need the signatures only reflection provides.

The class initializer is kept in Model::class_initializer rather than in the members
hash table, and read back through the new model_find_class_initializer(). Putting it
in the table would surface it in model_list(), which backs the wrapper Proxy's
ownKeys() trap, and as getOwnPropertyDescriptor() reports every member as
enumerable, Object.entries() on a wrapper would resolve it through
makeMethodFromSpec(). That calls ToReflectedMethod(), which yields a Constructor
for <clinit>, and would then invoke java.lang.reflect.Method methods on it.

The ART branch identifies <clinit> as IsConstructor() && IsStatic(), matching
ArtMethod::IsClassInitializer(), and names it without consulting ART for the same
reason. Java.enumerateMethods() now reports $clinit instead 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 is
first 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(), and ArtMethodMangler.replace() snapshots
quickCode when the hook is installed, so hooking a static method of a
not-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_METHOD is exempt, as forcing initialization is precisely what
hooking 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 replaced
its dummy field lookup with getClassName() to avoid the NoSuchFieldError it had to
clear afterwards. The exception was noise, but the lookup was the mechanism:
FindFieldJNI() begins by calling EnsureInitialized(), and getClassName() reaches
nothing of the sort. Resolve Object.hashCode() instead, which every class inherits
and FindClassMethod() finds by walking the superclass chain. Interfaces are the one
exception, as FindInterfaceMethodWithSignature() searches only their declared and
superinterface 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 through ArtMethod::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 replacement
method, 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 initializer
re-entered through this.$clinit() recursed until the stack ran out. Our own JNI
replacement 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 a
replacement 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

$clinit was enumerable on the JVM but never hookable: jni_FindClass() passes
init=true down to find_class_from_class_loader(), so Java.use() ran the
initializer before the caller could install anything.

Resolve through Class.forName(name, false, loader) instead. That loads without
initializing, but stops short of linking too, and JVMTI will not enumerate the members
of a class that has yet to be prepared: GetClassMethods() fails with
JVMTI_ERROR_CLASS_NOT_PREPARED, and model_new() ignores the return value, leaving
it 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 be
told the same or classes only a custom loader can see would stop resolving from inside
a hook. getCallerClassLoader() works it out with GetStackTrace(),
GetMethodDeclaringClass() and GetClassLoader(), none of which need a capability.

jvm.js's ensureClassInitialized() was an empty function, which no longer holds now
that Java.use() leaves the class alone: every static field would read back its
default. jni_GetMethodID() calls klass->initialize() before the lookup, so the trick
ART 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

ClassInitializerTest covers hooking a class initializer, replacing it, invoking the
original 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_PLATFORM is clamped to what the
NDK actually ships. The test matrix extends to Android 16, dropping x86 in favour of
x86_64 throughout.

@mnalmahmud mnalmahmud changed the title Add support for hooking class initializers added support for hooking class initializers Aug 7, 2026
@mnalmahmud

Copy link
Copy Markdown
Author

@oleavr kindly have a look at this if you get time.

@mnalmahmud

Copy link
Copy Markdown
Author

@oleavr any updates mate?

@oleavr

oleavr commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

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 ensureClassInitialized(), so this now conflicts with main in several places.

Could you rebase it onto main and split it into separate commits? Roughly:

  1. ensureClassInitialized() via Object.hashCode(). This is a nice improvement over the NoSuchFieldError approach that Fix the test suite and restore class initialization #344 brought back, and I'd like to land it first.
  2. Making the class model's three branches agree on constructors. This also covers Fix for Process crash on accessing object["<init>"] with JVMTI available #385.
  3. $clinit hooking, including the ArtMethod::Invoke() instrumentation and its recursion check.
  4. The HotSpot changes.
  5. Any test/CI changes still needed on top of Fix the test suite and restore class initialization #344.

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 Java.use() no longer initializing the class, as that changes when app code runs for existing scripts. Having it in its own commit would make that easier to evaluate.

@mnalmahmud

Copy link
Copy Markdown
Author

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 ensureClassInitialized(), so this now conflicts with main in several places.

Could you rebase it onto main and split it into separate commits? Roughly:

1. `ensureClassInitialized()` via `Object.hashCode()`. This is a nice improvement over the `NoSuchFieldError` approach that [Fix the test suite and restore class initialization #344](https://github.com/frida-packages/frida-java-bridge/pull/344) brought back, and I'd like to land it first.

2. Making the class model's three branches agree on constructors. This also covers [Fix for Process crash on accessing object["<init>"] with JVMTI available #385](https://github.com/frida-packages/frida-java-bridge/pull/385).

3. `$clinit` hooking, including the `ArtMethod::Invoke()` instrumentation and its recursion check.

4. The HotSpot changes.

5. Any test/CI changes still needed on top of [Fix the test suite and restore class initialization #344](https://github.com/frida-packages/frida-java-bridge/pull/344).

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 Java.use() no longer initializing the class, as that changes when app code runs for existing scripts. Having it in its own commit would make that easier to evaluate.

I will look into this as soon as possible, mate.

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 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.
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.

2 participants