From 47c3177d612918c9fc776335cba63697f282504b Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Thu, 19 Nov 2026 17:15:40 +0600 Subject: [PATCH 1/9] android: Initialize classes via Object.hashCode() 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 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 --- lib/android.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/android.js b/lib/android.js index 70b99f1..ca98172 100644 --- a/lib/android.js +++ b/lib/android.js @@ -629,8 +629,10 @@ export function ensureClassInitialized (env, classRef) { return; } - env.getFieldId(classRef, 'x', 'Z'); - env.exceptionClear(); + const method = env.getMethodId(classRef, 'hashCode', '()I'); + if (method.isNull()) { + env.exceptionClear(); + } } function getArtVMSpec (api) { From b4438c898675628409f947ebb3874e37739861c8 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Thu, 19 Nov 2026 17:16:31 +0600 Subject: [PATCH 2/9] android: Fix quick frame method lookup 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 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 --- lib/android.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/android.js b/lib/android.js index ca98172..5010a1b 100644 --- a/lib/android.js +++ b/lib/android.js @@ -1842,6 +1842,7 @@ function notifyArtMethodHooked (method, vm) { } function makeArtController (api, vm) { + const apiLevel = getAndroidApiLevel(); const threadOffsets = getArtThreadSpec(vm).offset; const managedStackOffsets = getArtManagedStackSpec().offset; @@ -2004,8 +2005,8 @@ find_replacement_method_from_quick_code (gpointer method, if (link_managed_stack == NULL) return replacement_method; - link_top_quick_frame = GSIZE_TO_POINTER (*((gsize *) (link_managed_stack + ${managedStackOffsets.topQuickFrame})) & ~((gsize) 1)); - if (link_top_quick_frame == NULL || *link_top_quick_frame != replacement_method) + link_top_quick_frame = GSIZE_TO_POINTER (*((gsize *) (link_managed_stack + ${managedStackOffsets.topQuickFrame})) & ~((gsize) 3)); + if (link_top_quick_frame == NULL || ${(apiLevel <= 22) ? 'GSIZE_TO_POINTER (*((guint32 *) link_top_quick_frame))' : '*link_top_quick_frame'} != replacement_method) return replacement_method; return NULL; From 2968491740ad1303c554cca42784b662d65267f9 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Thu, 19 Nov 2026 15:46:53 +0600 Subject: [PATCH 3/9] class-model: Exclude constructors from members model_new()'s three branches disagreed on constructors. The JVMTI branch added every method GetClassMethods() reports, exposing and under their raw names so wrapper[''] 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 #384 --- lib/class-model.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/class-model.js b/lib/class-model.js index 28b68b0..a7c3d4d 100644 --- a/lib/class-model.js +++ b/lib/class-model.js @@ -282,7 +282,8 @@ model_new (jclass class_handle, get_method_name (jvmti, method, &name, NULL, NULL); get_method_modifiers (jvmti, method, &modifiers); - model_add_method (model, name, method, modifiers); + if (name[0] != '<') + model_add_method (model, name, method, modifiers); deallocate (jvmti, name); } From 9c146c5d54cb835578dd5afda0c3659dce76c702 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 22:48:54 +0600 Subject: [PATCH 4/9] android: Keep method hooks across class init 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. --- lib/android.js | 364 ++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 332 insertions(+), 32 deletions(-) diff --git a/lib/android.js b/lib/android.js index 5010a1b..5a12dae 100644 --- a/lib/android.js +++ b/lib/android.js @@ -320,6 +320,7 @@ function _getApi () { _ZN3art3jni12JniIdManager14DecodeMethodIdEP10_jmethodID: ['art::jni::JniIdManager::DecodeMethodId', 'pointer', ['pointer', 'pointer']], _ZN3art3jni12JniIdManager13DecodeFieldIdEP9_jfieldID: ['art::jni::JniIdManager::DecodeFieldId', 'pointer', ['pointer', 'pointer']], _ZN3art11interpreter18GetNterpEntryPointEv: ['art::interpreter::GetNterpEntryPoint', 'pointer', []], + _ZN3art11interpreter28GetNterpWithClinitEntryPointEv: ['art::interpreter::GetNterpWithClinitEntryPoint', 'pointer', []], _ZN3art7Monitor17TranslateLocationEPNS_9ArtMethodEjPPKcPi: ['art::Monitor::TranslateLocation', 'void', ['pointer', 'uint32', 'pointer', 'pointer']] }, @@ -386,6 +387,7 @@ function _getApi () { '_ZN3art3jni12JniIdManager14DecodeMethodIdEP10_jmethodID', '_ZN3art3jni12JniIdManager13DecodeFieldIdEP9_jfieldID', '_ZN3art11interpreter18GetNterpEntryPointEv', + '_ZN3art11interpreter28GetNterpWithClinitEntryPointEv', '_ZN3art7Monitor17TranslateLocationEPNS_9ArtMethodEjPPKcPi' ]) } @@ -524,6 +526,9 @@ function _getApi () { } else { temporaryApi.artNterpEntryPoint = temporaryApi.find('ExecuteNterpImpl'); } + temporaryApi.artNterpWithClinitEntryPoint = + temporaryApi['art::interpreter::GetNterpWithClinitEntryPoint']?.() ?? + temporaryApi.find('ExecuteNterpWithClinitImpl'); artController = makeArtController(temporaryApi, vm); @@ -1845,14 +1850,34 @@ function makeArtController (api, vm) { const apiLevel = getAndroidApiLevel(); const threadOffsets = getArtThreadSpec(vm).offset; const managedStackOffsets = getArtManagedStackSpec().offset; + const { artClassLinker } = api; + const removedHookFlags = (kAccFastInterpreterToInterpreterInvoke | kAccSingleImplementation | ((api.artNterpEntryPoint !== null) ? kAccNterpEntryPointFastPathFlag : 0)) >>> 0; + const cPtr = p => (p !== null) ? `((gpointer) (gsize) ${p}ULL)` : 'NULL'; + const nterpWithClinitEntryPoint = cPtr(api.artNterpWithClinitEntryPoint); + const quickToInterpreterBridge = cPtr(artClassLinker.quickToInterpreterBridgeTrampoline); + const quickGenericJniTrampoline = cPtr(artClassLinker.quickGenericJniTrampoline); + const quickResolutionTrampoline = cPtr(artClassLinker.quickResolutionTrampoline); + const artQuickToInterpreterBridge = cPtr(api.artQuickToInterpreterBridge); + const artQuickGenericJniTrampoline = cPtr(api.artQuickGenericJniTrampoline); + const artQuickResolutionTrampoline = cPtr(api.artQuickResolutionTrampoline); const code = ` #include +typedef struct _ResolutionTrampolineData ResolutionTrampolineData; + +struct _ResolutionTrampolineData +{ + gpointer thread; + gpointer * sp; +}; + extern GMutex lock; extern GHashTable * methods; extern GHashTable * replacements; +extern GHashTable * intercepted_codes; extern gpointer last_seen_art_method; +extern guint32 method_offsets[2]; extern gpointer get_oat_quick_method_header_impl (gpointer method, gpointer pc); @@ -1862,16 +1887,47 @@ init (void) g_mutex_init (&lock); methods = g_hash_table_new_full (NULL, NULL, NULL, NULL); replacements = g_hash_table_new_full (NULL, NULL, NULL, NULL); + intercepted_codes = g_hash_table_new_full (NULL, NULL, NULL, NULL); } void finalize (void) { + g_hash_table_unref (intercepted_codes); g_hash_table_unref (replacements); g_hash_table_unref (methods); g_mutex_clear (&lock); } +static gpointer +get_hooked_quick_entrypoint (gpointer method) +{ + guint32 access_flags = *((guint32 *) (method + method_offsets[1])); + return ((access_flags & ${kAccNative}) != 0) + ? ${quickGenericJniTrampoline} + : ${quickToInterpreterBridge}; +} + +static gpointer +resolve_hooked_quick_entrypoint (gpointer method, + gpointer code, + gpointer intercepted_code) +{ + if (${nterpWithClinitEntryPoint} != NULL && code == ${nterpWithClinitEntryPoint}) + return ${quickResolutionTrampoline}; + + if (code != ${quickResolutionTrampoline} && + code != ${artQuickResolutionTrampoline} && + code != ${quickToInterpreterBridge} && + code != ${artQuickToInterpreterBridge} && + code != ${quickGenericJniTrampoline} && + code != ${artQuickGenericJniTrampoline} && + (intercepted_code == NULL || code != intercepted_code)) + return get_hooked_quick_entrypoint (method); + + return code; +} + gboolean is_replacement_method (gpointer method) { @@ -1902,20 +1958,23 @@ get_replacement_method (gpointer original_method) void set_replacement_method (gpointer original_method, - gpointer replacement_method) + gpointer replacement_method, + gpointer intercepted_code) { g_mutex_lock (&lock); g_hash_table_insert (methods, original_method, replacement_method); g_hash_table_insert (replacements, replacement_method, original_method); + if (intercepted_code != NULL) + g_hash_table_insert (intercepted_codes, original_method, intercepted_code); + else + g_hash_table_remove (intercepted_codes, original_method); g_mutex_unlock (&lock); } void -synchronize_replacement_methods (guint quick_code_offset, - void * nterp_entrypoint, - void * quick_to_interpreter_bridge) +synchronize_replacement_methods (void) { GHashTableIter iter; gpointer hooked_method, replacement_method; @@ -1925,13 +1984,18 @@ synchronize_replacement_methods (guint quick_code_offset, g_hash_table_iter_init (&iter, methods); while (g_hash_table_iter_next (&iter, &hooked_method, &replacement_method)) { - void ** quick_code; + guint32 * access_flags = hooked_method + method_offsets[1]; + guint32 flags = *access_flags; + gpointer * quick_code = hooked_method + method_offsets[0]; + gpointer intercepted_code = g_hash_table_lookup (intercepted_codes, hooked_method); + gpointer updated_code; *((uint32_t *) replacement_method) = *((uint32_t *) hooked_method); + *access_flags = (flags & ~(${removedHookFlags} | (((flags & ${kAccNative}) == 0) ? ${kAccSkipAccessChecks} : 0))) | ${api.kAccCompileDontBother}; - quick_code = hooked_method + quick_code_offset; - if (*quick_code == nterp_entrypoint) - *quick_code = quick_to_interpreter_bridge; + updated_code = resolve_hooked_quick_entrypoint (hooked_method, *quick_code, intercepted_code); + if (updated_code != *quick_code) + *quick_code = updated_code; } g_mutex_unlock (&lock); @@ -1949,6 +2013,7 @@ delete_replacement_method (gpointer original_method) { g_hash_table_remove (methods, original_method); g_hash_table_remove (replacements, replacement_method); + g_hash_table_remove (intercepted_codes, original_method); } g_mutex_unlock (&lock); @@ -2047,6 +2112,90 @@ on_art_method_pretty_method (GumInvocationContext * ic) last_seen_art_method = method; } +void +on_enter_art_quick_resolution_trampoline (GumInvocationContext * ic) +{ + ResolutionTrampolineData * data = GUM_IC_GET_INVOCATION_DATA (ic, ResolutionTrampolineData); + data->thread = gum_invocation_context_get_nth_argument (ic, 2); + data->sp = gum_invocation_context_get_nth_argument (ic, 3); +} + +void +on_leave_art_quick_resolution_trampoline (GumInvocationContext * ic) +{ + ResolutionTrampolineData * data = GUM_IC_GET_INVOCATION_DATA (ic, ResolutionTrampolineData); + gpointer thread = data->thread; + gpointer * sp = data->sp; + gpointer method; + + if (gum_invocation_context_get_return_value (ic) == NULL || sp == NULL) + return; + + method = ${(apiLevel <= 22) ? 'GSIZE_TO_POINTER (*((guint32 *) sp))' : '*sp'}; + if (method != NULL) + { + gboolean is_hooked; + gpointer intercepted_code = NULL; + + g_mutex_lock (&lock); + is_hooked = g_hash_table_contains (methods, method); + if (is_hooked) + intercepted_code = g_hash_table_lookup (intercepted_codes, method); + g_mutex_unlock (&lock); + + if (is_hooked) + { + gpointer * quick_code = method + method_offsets[0]; + gpointer updated_code; + + if (thread != NULL) + { + gpointer * top_quick_frame = thread + ${threadOffsets.managedStack} + ${managedStackOffsets.topQuickFrame}; + if (*top_quick_frame == sp) + *top_quick_frame = NULL; + } + + updated_code = resolve_hooked_quick_entrypoint (method, *quick_code, intercepted_code); + if (updated_code != *quick_code) + *quick_code = updated_code; + + gum_invocation_context_replace_return_value (ic, get_hooked_quick_entrypoint (method)); + } + } +} + +void +on_instrumentation_update_methods_code (GumInvocationContext * ic) +{ + gpointer method, new_code, updated_code; + gboolean is_hooked; + gpointer intercepted_code = NULL; + + method = gum_invocation_context_get_nth_argument (ic, 1); + if (method == NULL) + return; + + g_mutex_lock (&lock); + is_hooked = g_hash_table_contains (methods, method); + if (is_hooked) + intercepted_code = g_hash_table_lookup (intercepted_codes, method); + g_mutex_unlock (&lock); + + if (!is_hooked) + return; + + new_code = gum_invocation_context_get_nth_argument (ic, 2); + updated_code = resolve_hooked_quick_entrypoint (method, new_code, intercepted_code); + if (updated_code != new_code) + gum_invocation_context_replace_nth_argument (ic, 2, updated_code); +} + +void +on_synchronize_replacement_methods (GumInvocationContext * ic) +{ + synchronize_replacement_methods (); +} + void on_leave_gc_concurrent_copying_copying_phase (GumInvocationContext * ic) { @@ -2066,14 +2215,18 @@ on_leave_gc_concurrent_copying_copying_phase (GumInvocationContext * ic) const lockSize = 8; const methodsSize = pointerSize; const replacementsSize = pointerSize; + const interceptedCodesSize = pointerSize; const lastSeenArtMethodSize = pointerSize; + const methodOffsetsSize = 8; - const data = Memory.alloc(lockSize + methodsSize + replacementsSize + lastSeenArtMethodSize); + const data = Memory.alloc(lockSize + methodsSize + replacementsSize + interceptedCodesSize + lastSeenArtMethodSize + methodOffsetsSize); const lock = data; const methods = lock.add(lockSize); const replacements = methods.add(methodsSize); - const lastSeenArtMethod = replacements.add(replacementsSize); + const interceptedCodes = replacements.add(replacementsSize); + const lastSeenArtMethod = interceptedCodes.add(interceptedCodesSize); + const methodOffsets = lastSeenArtMethod.add(lastSeenArtMethodSize); const getOatQuickMethodHeaderImpl = api.find((pointerSize === 4) ? '_ZN3art9ArtMethod23GetOatQuickMethodHeaderEj' @@ -2083,7 +2236,9 @@ on_leave_gc_concurrent_copying_copying_phase (GumInvocationContext * ic) lock, methods, replacements, + intercepted_codes: interceptedCodes, last_seen_art_method: lastSeenArtMethod, + method_offsets: methodOffsets, get_oat_quick_method_header_impl: getOatQuickMethodHeaderImpl ?? ptr('0xdeadbeef') }); @@ -2091,11 +2246,12 @@ on_leave_gc_concurrent_copying_copying_phase (GumInvocationContext * ic) return { handle: cm, + methodOffsets, replacedMethods: { isReplacement: new NativeFunction(cm.is_replacement_method, 'bool', ['pointer'], fastOptions), get: new NativeFunction(cm.get_replacement_method, 'pointer', ['pointer'], fastOptions), - set: new NativeFunction(cm.set_replacement_method, 'void', ['pointer', 'pointer'], fastOptions), - synchronize: new NativeFunction(cm.synchronize_replacement_methods, 'void', ['uint', 'pointer', 'pointer'], fastOptions), + set: new NativeFunction(cm.set_replacement_method, 'void', ['pointer', 'pointer', 'pointer'], fastOptions), + synchronize: new NativeFunction(cm.synchronize_replacement_methods, 'void', [], fastOptions), delete: new NativeFunction(cm.delete_replacement_method, 'void', ['pointer'], fastOptions), translate: new NativeFunction(cm.translate_method, 'pointer', ['pointer'], fastOptions), findReplacementFromQuickCode: cm.find_replacement_method_from_quick_code @@ -2105,6 +2261,18 @@ on_leave_gc_concurrent_copying_copying_phase (GumInvocationContext * ic) Interpreter: { doCall: cm.on_interpreter_do_call }, + QuickTrampoline: { + resolution: { + onEnter: cm.on_enter_art_quick_resolution_trampoline, + onLeave: cm.on_leave_art_quick_resolution_trampoline + } + }, + Instrumentation: { + updateMethodsCode: cm.on_instrumentation_update_methods_code + }, + ClassLinker: { + synchronize: cm.on_synchronize_replacement_methods + }, ArtMethod: { getOatQuickMethodHeader: cm.on_art_method_get_oat_quick_method_header, prettyMethod: cm.on_art_method_pretty_method @@ -2127,10 +2295,43 @@ function ensureArtKnowsHowToHandleMethodInstrumentation (vm) { } taughtArtAboutMethodInstrumentation = true; + const { offset } = getArtMethodSpec(vm); + artController.methodOffsets.writeU32(offset.quickCode); + artController.methodOffsets.add(4).writeU32(offset.accessFlags); + instrumentArtQuickEntrypoints(vm); instrumentArtMethodInvocationFromInterpreter(); instrumentArtGarbageCollection(); - instrumentArtFixupStaticTrampolines(); + instrumentArtClassLifecycle(); +} + +function findArtQuickResolutionTrampolineImpl (api) { + const symbol = api.find('artQuickResolutionTrampoline'); + if (symbol !== null) { + return symbol; + } + + const stub = api.artQuickResolutionTrampoline; + const { base, size } = api.module; + const end = base.add(size); + const { arch } = Process; + const callMnemonic = (arch === 'arm64') ? 'bl' : (arch === 'arm') ? 'blx' : 'call'; + const isThumb = (arch === 'arm') && !stub.and(1).isNull(); + + return parseInstructionsAt(stub, insn => { + const { mnemonic, operands } = insn; + if ((mnemonic !== callMnemonic && !(arch === 'arm' && mnemonic === 'bl')) || + operands.length !== 1 || operands[0].type !== 'imm') { + return null; + } + + const target = ptr(operands[0].value); + if (target.equals(insn.next) || target.compare(base) < 0 || target.compare(end) >= 0) { + return null; + } + + return (arch === 'arm' && ((mnemonic === 'bl') ? isThumb : !isThumb)) ? target.or(1) : target; + }, { limit: 64 }); } function instrumentArtQuickEntrypoints (vm) { @@ -2139,10 +2340,16 @@ function instrumentArtQuickEntrypoints (vm) { // Entrypoints that dispatch method invocation from the quick ABI. const quickEntrypoints = [ api.artQuickGenericJniTrampoline, - api.artQuickToInterpreterBridge, - api.artQuickResolutionTrampoline + api.artQuickToInterpreterBridge ]; + const resolutionTrampoline = findArtQuickResolutionTrampolineImpl(api); + if (resolutionTrampoline !== null) { + Interceptor.attach(resolutionTrampoline, artController.hooks.QuickTrampoline.resolution); + } else { + quickEntrypoints.push(api.artQuickResolutionTrampoline); + } + quickEntrypoints.forEach(entrypoint => { Memory.protect(entrypoint, 32, 'rwx'); @@ -2191,13 +2398,75 @@ function instrumentArtGarbageCollection () { return; } - const { artNterpEntryPoint, artQuickToInterpreterBridge } = api; - const quickCodeOffset = getArtMethodSpec(api.vm).offset.quickCode; - Interceptor.attach(gc, { - onLeave () { - artController.replacedMethods.synchronize(quickCodeOffset, artNterpEntryPoint, artQuickToInterpreterBridge); + Interceptor.attach(gc, { onLeave: artController.hooks.ClassLinker.synchronize }); +} + +function instrumentArtClassLifecycle () { + const api = getApi(); + const { hooks } = artController; + const art = api.module; + const exports = art.enumerateExports(); + let symbols = null; + + const findFunctions = (prefixes, seen) => { + const isMatch = entry => !entry.address.isNull() && + (entry.type === 'function' || entry.type === 'unknown') && + !/\.(?:cold|part|isra|constprop)\b/.test(entry.name) && + prefixes.some(prefix => entry.name.startsWith(prefix)); + const addresses = []; + + const collect = entries => { + for (const entry of entries) { + if (!isMatch(entry)) { + continue; + } + const key = entry.address.toString(); + if (!seen.has(key)) { + seen.add(key); + addresses.push(entry.address); + } + } + }; + + collect(exports); + if (addresses.length === 0) { + if (symbols === null) { + symbols = art.enumerateSymbols(); + } + collect(symbols); } - }); + + return addresses; + }; + + const updateSeen = new Set(); + for (const prefixes of [ + [ + '_ZN3art15instrumentation15Instrumentation17UpdateMethodsCodeEPNS_9ArtMethodEPKv', + '_ZN3art15instrumentation15Instrumentation17UpdateMethodsCodeEPNS_6mirror9ArtMethodEPKv' + ], + [ + '_ZN3art15instrumentation15Instrumentation21UpdateMethodsCodeImplEPNS_9ArtMethodEPKv', + '_ZN3art15instrumentation15Instrumentation21UpdateMethodsCodeImplEPNS_6mirror9ArtMethodEPKv' + ] + ]) { + for (const address of findFunctions(prefixes, updateSeen)) { + Interceptor.attach(address, hooks.Instrumentation.updateMethodsCode); + } + } + + const syncSeen = new Set(); + for (const prefixes of [ + ['_ZN3art11ClassLinker11VerifyClassE'], + ['_ZN3art11ClassLinker15InitializeClassE'], + ['_ZN3art11ClassLinker22FixupStaticTrampolinesE'] + ]) { + for (const address of findFunctions(prefixes, syncSeen)) { + Interceptor.attach(address, { onLeave: hooks.ClassLinker.synchronize }); + } + } + + instrumentArtFixupStaticTrampolines(); } function instrumentArtFixupStaticTrampolines () { @@ -2218,11 +2487,7 @@ function instrumentArtFixupStaticTrampolines () { return; } - const { artNterpEntryPoint, artQuickToInterpreterBridge } = api; - const quickCodeOffset = getArtMethodSpec(api.vm).offset.quickCode; - Interceptor.attach(matches[0].address, function () { - artController.replacedMethods.synchronize(quickCodeOffset, artNterpEntryPoint, artQuickToInterpreterBridge); - }); + Interceptor.attach(matches[0].address, artController.hooks.ClassLinker.synchronize); return; } @@ -3752,7 +4017,7 @@ class ArtMethodMangler { } replace (impl, isInstanceMethod, argTypes, vm, api) { - const { kAccCompileDontBother, artNterpEntryPoint } = api; + const { kAccCompileDontBother, artNterpEntryPoint, artNterpWithClinitEntryPoint } = api; this.originalMethod = fetchArtMethod(this.methodId, vm); @@ -3793,29 +4058,64 @@ class ArtMethodMangler { // of ART's next-generation interpreter and use the quick stub instead. if (artNterpEntryPoint !== null && quickCode.equals(artNterpEntryPoint)) { patchArtMethod(hookedMethodId, { - quickCode: api.artQuickToInterpreterBridge + quickCode: api.artClassLinker.quickToInterpreterBridgeTrampoline + }, vm); + } else if (artNterpWithClinitEntryPoint !== null && quickCode.equals(artNterpWithClinitEntryPoint)) { + patchArtMethod(hookedMethodId, { + quickCode: api.artClassLinker.quickResolutionTrampoline }, vm); } + let interceptedQuickCode = NULL; if (!isArtQuickEntrypoint(quickCode)) { const interceptor = new ArtQuickCodeInterceptor(quickCode); interceptor.activate(vm); this.interceptor = interceptor; + interceptedQuickCode = quickCode; } - artController.replacedMethods.set(hookedMethodId, replacementMethodId); + artController.replacedMethods.set(hookedMethodId, replacementMethodId, interceptedQuickCode); notifyArtMethodHooked(hookedMethodId, vm); } revert (vm) { - const { hookedMethodId, interceptor } = this; - - patchArtMethod(hookedMethodId, this.originalMethod, vm); + const { hookedMethodId, interceptor, originalMethod } = this; artController.replacedMethods.delete(hookedMethodId); + const api = getApi(); + const { quickResolutionTrampoline } = api.artClassLinker; + const { artQuickResolutionTrampoline, artNterpEntryPoint, artNterpWithClinitEntryPoint } = api; + const originalQuickCode = originalMethod.quickCode; + const isPreInitTrampoline = address => address.equals(quickResolutionTrampoline) || + address.equals(artQuickResolutionTrampoline) || + (artNterpWithClinitEntryPoint !== null && address.equals(artNterpWithClinitEntryPoint)); + + let restored = originalMethod; + if (isPreInitTrampoline(originalQuickCode)) { + const currentMethod = fetchArtMethod(hookedMethodId, vm); + if (!isPreInitTrampoline(currentMethod.quickCode)) { + const quickCode = (artNterpWithClinitEntryPoint !== null && + originalQuickCode.equals(artNterpWithClinitEntryPoint) && + artNterpEntryPoint !== null) + ? artNterpEntryPoint + : currentMethod.quickCode; + const accessFlags = (artNterpEntryPoint !== null && !quickCode.equals(artNterpEntryPoint)) + ? (originalMethod.accessFlags & ~kAccNterpEntryPointFastPathFlag) >>> 0 + : originalMethod.accessFlags; + restored = { + ...originalMethod, + jniCode: currentMethod.jniCode, + accessFlags, + quickCode + }; + } + } + + patchArtMethod(hookedMethodId, restored, vm); + if (interceptor !== null) { interceptor.deactivate(); From eb8d8247df911bbee76e7c26264574491724c165 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 20:33:55 +0600 Subject: [PATCH 5/9] Add support for hooking class initializers Expose 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 ). 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. --- index.d.ts | 20 ++++++++++++++--- lib/class-factory.js | 53 ++++++++++++++++++++++++++++++++++++++------ lib/class-model.js | 41 +++++++++++++++++++++++----------- 3 files changed, 91 insertions(+), 23 deletions(-) diff --git a/index.d.ts b/index.d.ts index d1ca82d..5f48b37 100644 --- a/index.d.ts +++ b/index.d.ts @@ -388,6 +388,19 @@ declare module "frida-java-bridge" { */ $init: MethodDispatcher; + /** + * The class initializer, i.e. ``, which the runtime invokes once to + * initialize the class' static state. + * + * Replace the `implementation` property to hook it. As the class is only ever + * initialized once, this must happen before anything touches it -- accessing a + * static member, or calling a static method, is enough to trigger it. Throws if + * the class has no class initializer. + * + * Not supported on Dalvik, i.e. Android < 5.0. + */ + $clinit: Method; + /** * Eagerly deletes the underlying JNI global reference without having to * wait for the object to become unreachable and the JavaScript @@ -534,9 +547,10 @@ declare module "frida-java-bridge" { // eslint-disable-next-line @definitelytyped/no-const-enum const enum MethodType { - Constructor = 1, - Static = 2, - Instance = 3, + ClassInitializer = 1, + Constructor = 2, + Static = 3, + Instance = 4, } // eslint-disable-next-line @definitelytyped/no-const-enum diff --git a/lib/class-factory.js b/lib/class-factory.js index 29c0dd0..17c7391 100644 --- a/lib/class-factory.js +++ b/lib/class-factory.js @@ -18,9 +18,10 @@ let { const kAccStatic = 0x0008; -const CONSTRUCTOR_METHOD = 1; -const STATIC_METHOD = 2; -const INSTANCE_METHOD = 3; +const CLASS_INITIALIZER_METHOD = 1; +const CONSTRUCTOR_METHOD = 2; +const STATIC_METHOD = 3; +const INSTANCE_METHOD = 4; const STATIC_FIELD = 1; const INSTANCE_FIELD = 2; @@ -235,6 +236,14 @@ export default class ClassFactory { return this[Symbol.for('c')]; } }, + [Symbol.for('ci')]: { + value: [null] + }, + $ci: { + get () { + return this[Symbol.for('ci')]; + } + }, [Symbol.for('m')]: { value: new Map() }, @@ -914,6 +923,35 @@ Object.defineProperties(Wrapper.prototype, { return this[Symbol.for('init')]; } }, + [Symbol.for('clinit')]: { + enumerable: false, + get () { + const slot = this.$ci; + + let clinit = slot[0]; + if (clinit === null) { + const classWrapper = this.$w; + const { $n: className, $f: factory } = classWrapper; + + const methodId = this.$l.findClassInitializer(); + if (methodId === null) { + throw new Error(`${className} has no class initializer`); + } + + clinit = makeMethod('$clinit', classWrapper, CLASS_INITIALIZER_METHOD, methodId, + factory._getType('void', false), [], vm.getEnv()); + slot[0] = clinit; + } + + return clinit; + } + }, + $clinit: { + enumerable: true, + get () { + return this[Symbol.for('clinit')]; + } + }, [Symbol.for('dispose')]: { enumerable: false, value () { @@ -1641,12 +1679,13 @@ function makeMethod (methodName, classWrapper, type, methodId, retType, argTypes } let callVirtually, callDirectly; - if (type === INSTANCE_METHOD) { - callVirtually = env.vaMethod(rawRetType, rawArgTypes, invocationOptions); - callDirectly = env.nonvirtualVaMethod(rawRetType, rawArgTypes, invocationOptions); - } else if (type === STATIC_METHOD) { + + if (type === CLASS_INITIALIZER_METHOD || type === STATIC_METHOD) { callVirtually = env.staticVaMethod(rawRetType, rawArgTypes, invocationOptions); callDirectly = callVirtually; + } else if (type === INSTANCE_METHOD) { + callVirtually = env.vaMethod(rawRetType, rawArgTypes, invocationOptions); + callDirectly = env.nonvirtualVaMethod(rawRetType, rawArgTypes, invocationOptions); } else { callVirtually = env.constructor(rawArgTypes, invocationOptions); callDirectly = callVirtually; diff --git a/lib/class-model.js b/lib/class-model.js index a7c3d4d..95cbbff 100644 --- a/lib/class-model.js +++ b/lib/class-model.js @@ -54,6 +54,7 @@ typedef void (* ArtPrettyMethodFunc) (StdString * result, ArtMethod * method, jb struct _Model { GHashTable * members; + jmethodID class_initializer; }; struct _EnumerateMethodsContext @@ -256,6 +257,7 @@ model_new (jclass class_handle, members = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); model->members = members; + model->class_initializer = NULL; if (jvmti != NULL) { @@ -284,6 +286,8 @@ model_new (jclass class_handle, if (name[0] != '<') model_add_method (model, name, method, modifiers); + else if (strcmp (name, "") == 0) + model->class_initializer = method; deallocate (jvmti, name); } @@ -328,9 +332,15 @@ model_new (jclass class_handle, id = elements + (i * art_api.method_size); access_flags = *(guint32 *) (id + art_api.method_offset_access_flags); + is_static = (access_flags & kAccStatic) != 0; + if ((access_flags & kAccConstructor) != 0) + { + if (is_static) + model->class_initializer = id; continue; - is_static = (access_flags & kAccStatic) != 0; + } + method = to_reflected_method (env, class_handle, id, is_static); name = call_object_method (env, method, java_api.method.get_name); name_str = get_string_utf_chars (env, name, NULL); @@ -509,6 +519,12 @@ model_find (Model * self, return g_hash_table_lookup (self->members, member); } +jmethodID +model_find_class_initializer (Model * self) +{ + return self->class_initializer; +} + gchar * model_list (Model * self) { @@ -620,7 +636,7 @@ collect_matching_class_methods (ArtClassVisitor * self, { ArtMethod * method; guint32 access_flags; - jboolean is_constructor; + jboolean is_constructor, is_static; StdString method_name = { 0, }; const gchar * bare_method_name; gchar * bare_method_name_copy = NULL; @@ -631,6 +647,7 @@ collect_matching_class_methods (ArtClassVisitor * self, access_flags = *(guint32 *) ((gpointer) method + art_api.method_offset_access_flags); is_constructor = (access_flags & kAccConstructor) != 0; + is_static = (access_flags & kAccStatic) != 0; art_api.pretty_method (&method_name, method, ctx->include_signature); bare_method_name = std_string_c_str (&method_name); @@ -641,14 +658,12 @@ collect_matching_class_methods (ArtClassVisitor * self, return_type_end = strchr (bare_method_name, ' '); name_begin = return_type_end + 1 + class_name_length + 1; - if (is_constructor && g_str_has_prefix (name_begin, "")) - goto skip_method; name = g_string_sized_new (64); if (is_constructor) { - g_string_append (name, "$init"); + g_string_append (name, is_static ? "$clinit" : "$init"); g_string_append (name, strchr (name_begin, '>') + 1); } else @@ -663,14 +678,8 @@ collect_matching_class_methods (ArtClassVisitor * self, } else { - const gchar * name_begin; - - name_begin = bare_method_name + class_name_length + 1; - if (is_constructor && strcmp (name_begin, "") == 0) - goto skip_method; - if (is_constructor) - bare_method_name = "$init"; + bare_method_name = is_static ? "$clinit" : "$init"; else bare_method_name += class_name_length + 1; } @@ -845,7 +854,7 @@ enumerate_methods_jvm (const gchar * class_query, if (strcmp (method_name, "") == 0) method_name = "$init"; else if (strcmp (method_name, "") == 0) - goto skip_method; + method_name = "$clinit"; } if (include_signature) @@ -1304,6 +1313,11 @@ export default class Model { return cm.find(this.handle, Memory.allocUtf8String(member)).readUtf8String(); } + findClassInitializer () { + const id = cm.findClassInitializer(this.handle); + return !id.isNull() ? id : null; + } + list () { const str = cm.list(this.handle); try { @@ -1410,6 +1424,7 @@ function compileModule (env) { new: new NativeFunction(cm.model_new, 'pointer', ['pointer', 'pointer', 'pointer'], reentrantOptions), has: new NativeFunction(cm.model_has, 'bool', ['pointer', 'pointer'], fastOptions), find: new NativeFunction(cm.model_find, 'pointer', ['pointer', 'pointer'], fastOptions), + findClassInitializer: new NativeFunction(cm.model_find_class_initializer, 'pointer', ['pointer'], fastOptions), list: new NativeFunction(cm.model_list, 'pointer', ['pointer'], fastOptions), enumerateMethodsArt: new NativeFunction(cm.enumerate_methods_art, 'pointer', ['pointer', 'pointer', 'bool', 'bool', 'bool'], reentrantOptions), From 8dbb04a2d0b1d5fac8613219212ca858afaf4e9e Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Thu, 19 Nov 2026 17:44:02 +0600 Subject: [PATCH 6/9] class-factory: Defer class init from Java.use() 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). --- index.d.ts | 5 +++-- lib/class-factory.js | 7 +++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/index.d.ts b/index.d.ts index 5f48b37..0cddf38 100644 --- a/index.d.ts +++ b/index.d.ts @@ -394,8 +394,9 @@ declare module "frida-java-bridge" { * * Replace the `implementation` property to hook it. As the class is only ever * initialized once, this must happen before anything touches it -- accessing a - * static member, or calling a static method, is enough to trigger it. Throws if - * the class has no class initializer. + * static member, or calling a static method, is enough to trigger it. Note that + * `Java.use()` itself deliberately does not. Throws if the class has no class + * initializer. * * Not supported on Dalvik, i.e. Android < 5.0. */ diff --git a/lib/class-factory.js b/lib/class-factory.js index 17c7391..c571a0d 100644 --- a/lib/class-factory.js +++ b/lib/class-factory.js @@ -291,8 +291,6 @@ export default class ClassFactory { try { const classHandle = h.value; - ensureClassInitialized(env, classHandle); - proto.$l = ClassModel.build(classHandle, env); } finally { h.unref(env); @@ -1830,6 +1828,9 @@ methodPrototype = Object.create(Function.prototype, { } else { borrowedHandle = receiver.$borrowClassHandle(env); jniThis = borrowedHandle.value; + if (type === STATIC_METHOD) { + ensureClassInitialized(env, jniThis); + } } let methodId; @@ -2145,6 +2146,7 @@ Object.defineProperties(Field.prototype, { } else { borrowedHandle = holder.$borrowClassHandle(env); jniThis = borrowedHandle.value; + ensureClassInitialized(env, jniThis); } const jniRetval = getValue(env.handle, jniThis, id); @@ -2176,6 +2178,7 @@ Object.defineProperties(Field.prototype, { } else { borrowedHandle = holder.$borrowClassHandle(env); jniThis = borrowedHandle.value; + ensureClassInitialized(env, jniThis); } if (!rtype.isCompatible(value)) { From de8af6e0a2443df900544e400540d497790cba8c Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 16:57:37 +0600 Subject: [PATCH 7/9] class-factory: Avoid class init in makeConstructor Collect 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 . --- lib/class-factory.js | 63 +++++++++++++--------------- lib/class-model.js | 97 +++++++++++++++++++++++++++++++++++--------- 2 files changed, 106 insertions(+), 54 deletions(-) diff --git a/lib/class-factory.js b/lib/class-factory.js index c571a0d..c3d21fc 100644 --- a/lib/class-factory.js +++ b/lib/class-factory.js @@ -1370,45 +1370,38 @@ function makeConstructor (classHandle, classWrapper, env) { const jsRetType = factory._getType(className, false); const jsVoidType = factory._getType('void', false); - const constructors = invokeObjectMethodNoArgs(env.handle, classHandle, Class.getDeclaredConstructors); - try { - const n = env.getArrayLength(constructors); - - if (n !== 0) { - for (let i = 0; i !== n; i++) { - let methodId, types; - const constructor = env.getObjectArrayElement(constructors, i); - try { - methodId = env.fromReflectedMethod(constructor); - types = invokeObjectMethodNoArgs(env.handle, constructor, Constructor.getGenericParameterTypes); - } finally { - env.deleteLocalRef(constructor); - } - - let jsArgTypes; - try { - jsArgTypes = readTypeNames(env, types).map(name => factory._getType(name)); - } finally { - env.deleteLocalRef(types); - } - - jsCtorMethods.push(makeMethod(methodName, classWrapper, CONSTRUCTOR_METHOD, methodId, jsRetType, jsArgTypes, env)); - jsInitMethods.push(makeMethod(methodName, classWrapper, INSTANCE_METHOD, methodId, jsVoidType, jsArgTypes, env)); - } - } else { - const isInterface = invokeUInt8MethodNoArgs(env.handle, classHandle, Class.isInterface); - if (isInterface) { - throw new Error('cannot instantiate an interface'); + const ctorIds = classWrapper.$l.listConstructors(); + if (ctorIds.length !== 0) { + for (const methodId of ctorIds) { + let types; + const constructor = env.toReflectedMethod(classHandle, methodId, 0); + try { + types = invokeObjectMethodNoArgs(env.handle, constructor, Constructor.getGenericParameterTypes); + } finally { + env.deleteLocalRef(constructor); } - const defaultClass = env.javaLangObject(); - const defaultConstructor = env.getMethodId(defaultClass, '', '()V'); + let jsArgTypes; + try { + jsArgTypes = readTypeNames(env, types).map(name => factory._getType(name)); + } finally { + env.deleteLocalRef(types); + } - jsCtorMethods.push(makeMethod(methodName, classWrapper, CONSTRUCTOR_METHOD, defaultConstructor, jsRetType, [], env)); - jsInitMethods.push(makeMethod(methodName, classWrapper, INSTANCE_METHOD, defaultConstructor, jsVoidType, [], env)); + jsCtorMethods.push(makeMethod(methodName, classWrapper, CONSTRUCTOR_METHOD, methodId, jsRetType, jsArgTypes, env)); + jsInitMethods.push(makeMethod(methodName, classWrapper, INSTANCE_METHOD, methodId, jsVoidType, jsArgTypes, env)); } - } finally { - env.deleteLocalRef(constructors); + } else { + const isInterface = invokeUInt8MethodNoArgs(env.handle, classHandle, Class.isInterface); + if (isInterface) { + throw new Error('cannot instantiate an interface'); + } + + const defaultClass = env.javaLangObject(); + const defaultConstructor = env.getMethodId(defaultClass, '', '()V'); + + jsCtorMethods.push(makeMethod(methodName, classWrapper, CONSTRUCTOR_METHOD, defaultConstructor, jsRetType, [], env)); + jsInitMethods.push(makeMethod(methodName, classWrapper, INSTANCE_METHOD, defaultConstructor, jsVoidType, [], env)); } if (jsInitMethods.length === 0) { diff --git a/lib/class-model.js b/lib/class-model.js index 95cbbff..358f794 100644 --- a/lib/class-model.js +++ b/lib/class-model.js @@ -53,8 +53,9 @@ typedef void (* ArtPrettyMethodFunc) (StdString * result, ArtMethod * method, jb struct _Model { - GHashTable * members; jmethodID class_initializer; + GArray * constructors; + GHashTable * members; }; struct _EnumerateMethodsContext @@ -69,6 +70,7 @@ struct _EnumerateMethodsContext struct _JavaClassApi { + jmethodID get_declared_constructors; jmethodID get_declared_methods; jmethodID get_declared_fields; }; @@ -237,7 +239,6 @@ model_new (jclass class_handle, JNIEnv * env) { Model * model; - GHashTable * members; jvmtiEnv * jvmti = java_api.jvmti; gpointer * funcs = env->functions; jmethodID (* from_reflected_method) (JNIEnv *, jobject) = funcs[7]; @@ -255,9 +256,9 @@ model_new (jclass class_handle, model = g_new (Model, 1); - members = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); - model->members = members; model->class_initializer = NULL; + model->constructors = g_array_new (FALSE, FALSE, sizeof (jmethodID)); + model->members = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); if (jvmti != NULL) { @@ -282,12 +283,16 @@ model_new (jclass class_handle, jmethodID method = methods[i]; get_method_name (jvmti, method, &name, NULL, NULL); - get_method_modifiers (jvmti, method, &modifiers); - if (name[0] != '<') - model_add_method (model, name, method, modifiers); - else if (strcmp (name, "") == 0) + if (strcmp (name, "") == 0) model->class_initializer = method; + else if (strcmp (name, "") == 0) + g_array_append_val (model->constructors, method); + else + { + get_method_modifiers (jvmti, method, &modifiers); + model_add_method (model, name, method, modifiers); + } deallocate (jvmti, name); } @@ -330,7 +335,6 @@ model_new (jclass class_handle, jint modifiers; id = elements + (i * art_api.method_size); - access_flags = *(guint32 *) (id + art_api.method_offset_access_flags); is_static = (access_flags & kAccStatic) != 0; @@ -338,6 +342,8 @@ model_new (jclass class_handle, { if (is_static) model->class_initializer = id; + else + g_array_append_val (model->constructors, id); continue; } @@ -394,6 +400,22 @@ model_new (jclass class_handle, { jobject elements; + elements = call_object_method (env, class_handle, java_api.clazz.get_declared_constructors); + n = get_array_length (env, elements); + for (i = 0; i != n; i++) + { + jobject constructor; + jmethodID id; + + constructor = get_object_array_element (env, elements, i); + id = from_reflected_method (env, constructor); + + g_array_append_val (model->constructors, id); + + delete_local_ref (env, constructor); + } + delete_local_ref (env, elements); + elements = call_object_method (env, class_handle, java_api.clazz.get_declared_methods); n = get_array_length (env, elements); for (i = 0; i != n; i++) @@ -500,6 +522,7 @@ model_add_field (Model * self, static void model_free (Model * model) { + g_array_unref (model->constructors); g_hash_table_unref (model->members); g_free (model); @@ -525,6 +548,35 @@ model_find_class_initializer (Model * self) return self->class_initializer; } +gchar * +model_list_constructors (Model * self) +{ + GString * result; + guint n, i; + + result = g_string_sized_new (64); + g_string_append_c (result, '['); + + n = self->constructors->len; + for (i = 0; i != n; i++) + { + gchar * item; + + if (i > 0) + g_string_append_c (result, ','); + + g_string_append_c (result, '"'); + item = g_strdup_printf ("0x%zx", (gsize) g_array_index (self->constructors, jmethodID, i)); + g_string_append (result, item); + g_free (item); + g_string_append_c (result, '"'); + } + + g_string_append_c (result, ']'); + + return g_string_free (result, FALSE); +} + gchar * model_list (Model * self) { @@ -849,13 +901,10 @@ enumerate_methods_jvm (const gchar * class_query, goto skip_method; method_name = method_name_value; - if (method_name[0] == '<') - { - if (strcmp (method_name, "") == 0) - method_name = "$init"; - else if (strcmp (method_name, "") == 0) - method_name = "$clinit"; - } + if (strcmp (method_name, "") == 0) + method_name = "$clinit"; + else if (strcmp (method_name, "") == 0) + method_name = "$init"; if (include_signature) { @@ -1318,6 +1367,15 @@ export default class Model { return !id.isNull() ? id : null; } + listConstructors () { + const str = cm.listConstructors(this.handle); + try { + return JSON.parse(str.readUtf8String()).map(ptr); + } finally { + cm.dealloc(str); + } + } + list () { const str = cm.list(this.handle); try { @@ -1343,7 +1401,7 @@ function compileModule (env) { const lockSize = 8; const modelsSize = pointerSize; - const javaApiSize = 7 * pointerSize; + const javaApiSize = 8 * pointerSize; const artApiSize = (10 * 4) + (5 * pointerSize); const dataSize = lockSize + modelsSize + javaApiSize + artApiSize; @@ -1354,13 +1412,13 @@ function compileModule (env) { const models = lock.add(lockSize); const javaApi = models.add(modelsSize); - const { getDeclaredMethods, getDeclaredFields } = env.javaLangClass(); + const { getDeclaredConstructors, getDeclaredMethods, getDeclaredFields } = env.javaLangClass(); const method = env.javaLangReflectMethod(); const field = env.javaLangReflectField(); let j = javaApi; [ (jvmti !== null) ? jvmti : NULL, - getDeclaredMethods, getDeclaredFields, + getDeclaredConstructors, getDeclaredMethods, getDeclaredFields, method.getName, method.getModifiers, field.getName, field.getModifiers ] @@ -1425,6 +1483,7 @@ function compileModule (env) { has: new NativeFunction(cm.model_has, 'bool', ['pointer', 'pointer'], fastOptions), find: new NativeFunction(cm.model_find, 'pointer', ['pointer', 'pointer'], fastOptions), findClassInitializer: new NativeFunction(cm.model_find_class_initializer, 'pointer', ['pointer'], fastOptions), + listConstructors: new NativeFunction(cm.model_list_constructors, 'pointer', ['pointer'], fastOptions), list: new NativeFunction(cm.model_list, 'pointer', ['pointer'], fastOptions), enumerateMethodsArt: new NativeFunction(cm.enumerate_methods_art, 'pointer', ['pointer', 'pointer', 'bool', 'bool', 'bool'], reentrantOptions), From c333b2b2e372ee7420a2b97373081d3706036feb Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Thu, 19 Nov 2026 17:45:26 +0600 Subject: [PATCH 8/9] jvm: Support hooking class initializers On HotSpot, jni_FindClass() passes init=true down to find_class_from_class_loader(), so Java.use() ran 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 --- lib/class-factory.js | 21 ++++++++++++++++++++- lib/env.js | 43 +++++++++++++++++++++++++++++++++++++++++++ lib/jvm.js | 37 +++++++++++++++++++++++++++++++++++++ lib/jvmti.js | 15 +++++++++++++++ 4 files changed, 115 insertions(+), 1 deletion(-) diff --git a/lib/class-factory.js b/lib/class-factory.js index c3d21fc..4834231 100644 --- a/lib/class-factory.js +++ b/lib/class-factory.js @@ -1,6 +1,10 @@ import Env from './env.js'; import * as android from './android.js'; -import { ensureClassInitialized as jvmEnsureClassInitialized, makeMethodMangler as jvmMakeMethodMangler } from './jvm.js'; +import { + ensureClassInitialized as jvmEnsureClassInitialized, + findClassWithoutInitializing as jvmFindClassWithoutInitializing, + makeMethodMangler as jvmMakeMethodMangler +} from './jvm.js'; import ClassModel from './class-model.js'; import LRU from './lru.js'; import mkdex from './mkdex.js'; @@ -1315,6 +1319,9 @@ function makeBasicClassHandleGetter (className) { const tid = getCurrentThreadId(); ignore(tid); try { + if (api.flavor === 'jvm') { + return jvmFindClassWithoutInitializing(env, className); + } return env.findClass(canonicalClassName); } finally { unignore(tid); @@ -1323,6 +1330,18 @@ function makeBasicClassHandleGetter (className) { } function makeLoaderClassHandleGetter (className, usedLoader, callerEnv) { + if (api.flavor === 'jvm') { + return function (env) { + const tid = getCurrentThreadId(); + ignore(tid); + try { + return env.findClassWithoutInitializing(className, usedLoader.$h); + } finally { + unignore(tid); + } + }; + } + if (cachedLoaderMethod === null) { cachedLoaderInvoke = callerEnv.vaMethod('pointer', ['pointer']); cachedLoaderMethod = usedLoader.loadClass.overload('java.lang.String').handle; diff --git a/lib/env.js b/lib/env.js index b8a5a7d..3076dc2 100644 --- a/lib/env.js +++ b/lib/env.js @@ -214,6 +214,29 @@ Env.prototype.findClass = proxy(6, 'pointer', ['pointer', 'pointer'], function ( return result; }); +Env.prototype.findClassWithoutInitializing = function (name, loader) { + const Class = this.javaLangClass(); + const nameValue = this.newStringUtf(name.replace(/\//g, '.')); + try { + const handle = this.staticVaMethod('pointer', ['pointer', 'int', 'pointer'])( + this.handle, Class.handle, Class.forName, nameValue, 0, loader); + this.throwIfExceptionPending(); + + try { + const methods = this.vaMethod('pointer', [])(this.handle, handle, Class.getDeclaredMethods); + this.throwIfExceptionPending(); + this.deleteLocalRef(methods); + } catch (e) { + this.deleteLocalRef(handle); + throw e; + } + + return handle; + } finally { + this.deleteLocalRef(nameValue); + } +}; + Env.prototype.throwIfExceptionPending = function () { const throwable = this.exceptionOccurred(); if (throwable.isNull()) { @@ -659,6 +682,8 @@ Env.prototype.javaLangClass = function () { const get = this.getMethodId.bind(this, handle); javaLangClass = { handle: register(this.newGlobalRef(handle)), + forName: this.getStaticMethodId(handle, 'forName', + '(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;'), getName: get('getName', '()Ljava/lang/String;'), getSimpleName: get('getSimpleName', '()Ljava/lang/String;'), getGenericSuperclass: get('getGenericSuperclass', '()Ljava/lang/reflect/Type;'), @@ -677,6 +702,24 @@ Env.prototype.javaLangClass = function () { return javaLangClass; }; +let systemClassLoader = null; +Env.prototype.systemClassLoader = function () { + if (systemClassLoader === null) { + const handle = this.findClass('java/lang/ClassLoader'); + try { + const getSystemClassLoader = this.getStaticMethodId(handle, 'getSystemClassLoader', + '()Ljava/lang/ClassLoader;'); + const loader = this.staticVaMethod('pointer', [])(this.handle, handle, getSystemClassLoader); + this.throwIfExceptionPending(); + systemClassLoader = register(this.newGlobalRef(loader)); + this.deleteLocalRef(loader); + } finally { + this.deleteLocalRef(handle); + } + } + return systemClassLoader; +}; + let javaLangObject = null; Env.prototype.javaLangObject = function () { if (javaLangObject === null) { diff --git a/lib/jvm.js b/lib/jvm.js index 0319cdb..69a5679 100644 --- a/lib/jvm.js +++ b/lib/jvm.js @@ -10,6 +10,7 @@ import VM from './vm.js'; const jsizeSize = 4; const { pointerSize } = Process; +const jvmtiFrameInfoSize = 16; const JVM_ACC_NATIVE = 0x0100; const JVM_ACC_IS_OLD = 0x00010000; @@ -427,6 +428,42 @@ function parseX64ThreadOffset (insn) { } export function ensureClassInitialized (env, classRef) { + const method = env.getMethodId(classRef, 'hashCode', '()I'); + if (method.isNull()) { + env.exceptionClear(); + } +} + +export function findClassWithoutInitializing (env, name) { + const loader = getCallerClassLoader(env); + try { + return env.findClassWithoutInitializing(name, (loader !== null) ? loader : env.systemClassLoader()); + } finally { + if (loader !== null && !loader.isNull()) { + env.deleteLocalRef(loader); + } + } +} + +function getCallerClassLoader (env) { + const { jvmti } = getApi(); + + const frames = Memory.alloc(jvmtiFrameInfoSize); + const numFrames = Memory.alloc(jsizeSize); + jvmti.getStackTrace(NULL, 0, 1, frames, numFrames); + if (numFrames.readS32() === 0) { + return null; + } + + const result = Memory.alloc(pointerSize); + jvmti.getMethodDeclaringClass(frames.readPointer(), result); + const klass = result.readPointer(); + try { + jvmti.getClassLoader(klass, result); + return result.readPointer(); + } finally { + env.deleteLocalRef(klass); + } } class JvmMethodMangler { diff --git a/lib/jvmti.js b/lib/jvmti.js index bcae1a8..d96b7cc 100644 --- a/lib/jvmti.js +++ b/lib/jvmti.js @@ -24,11 +24,26 @@ EnvJvmti.prototype.deallocate = proxy(47, 'int32', ['pointer', 'pointer'], funct return impl(this.handle, mem); }); +EnvJvmti.prototype.getClassLoader = proxy(57, 'int32', ['pointer', 'pointer', 'pointer'], function (impl, klass, classLoaderPtr) { + const result = impl(this.handle, klass, classLoaderPtr); + checkJniResult('EnvJvmti::getClassLoader', result); +}); + +EnvJvmti.prototype.getMethodDeclaringClass = proxy(65, 'int32', ['pointer', 'pointer', 'pointer'], function (impl, method, declaringClassPtr) { + const result = impl(this.handle, method, declaringClassPtr); + checkJniResult('EnvJvmti::getMethodDeclaringClass', result); +}); + EnvJvmti.prototype.getLoadedClasses = proxy(78, 'int32', ['pointer', 'pointer', 'pointer'], function (impl, classCountPtr, classesPtr) { const result = impl(this.handle, classCountPtr, classesPtr); checkJniResult('EnvJvmti::getLoadedClasses', result); }); +EnvJvmti.prototype.getStackTrace = proxy(104, 'int32', ['pointer', 'pointer', 'int', 'int', 'pointer', 'pointer'], function (impl, thread, startDepth, maxFrameCount, frameBuffer, countPtr) { + const result = impl(this.handle, thread, startDepth, maxFrameCount, frameBuffer, countPtr); + checkJniResult('EnvJvmti::getStackTrace', result); +}); + EnvJvmti.prototype.iterateOverInstancesOfClass = proxy(112, 'int32', ['pointer', 'pointer', 'int', 'pointer', 'pointer'], function (impl, klass, objectFilter, heapObjectCallback, userData) { const result = impl(this.handle, klass, objectFilter, heapObjectCallback, userData); checkJniResult('EnvJvmti::iterateOverInstancesOfClass', result); From 5c3d3e41f7590a27270800b2dd9bb81d08376825 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 22:49:22 +0600 Subject: [PATCH 9/9] tests: Add ClassInitializerTest 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. --- test/re/frida/ClassInitializerTest.java | 325 ++++++++++++++++++++++++ test/re/frida/TestRunner.java | 1 + 2 files changed, 326 insertions(+) create mode 100644 test/re/frida/ClassInitializerTest.java diff --git a/test/re/frida/ClassInitializerTest.java b/test/re/frida/ClassInitializerTest.java new file mode 100644 index 0000000..92aed2f --- /dev/null +++ b/test/re/frida/ClassInitializerTest.java @@ -0,0 +1,325 @@ +package re.frida; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.Test; + +import java.io.IOException; + +public class ClassInitializerTest { + public static boolean instanceTargetInitialized = false; + public static boolean staticTargetInitialized = false; + public static boolean combinedTargetInitialized = false; + public static boolean staticFieldTargetInitialized = false; + public static boolean revertableTargetInitialized = false; + + @Test + public void classInitializerCanBeHooked() { + loadScript("var Lazy = Java.use('re.frida.HookablyInitialized');" + + "Lazy.$clinit.implementation = function () {" + + "send('before');" + + "this.$clinit();" + + "send('after');" + + "};"); + + assertEquals("initialized", HookablyInitialized.greeting); + assertEquals("before", script.getNextMessage()); + assertEquals("after", script.getNextMessage()); + } + + @Test + public void classInitializerCanBeReplaced() { + loadScript("var Lazy = Java.use('re.frida.ReplaceablyInitialized');" + + "Lazy.$clinit.implementation = function () {" + + "send('skipped');" + + "};"); + + assertEquals(null, ReplaceablyInitialized.greeting); + assertEquals("skipped", script.getNextMessage()); + } + + @Test + public void classInitializerIsEnumerable() { + loadScript("Java.use('re.frida.EnumerablyInitialized');" + + "var names = [];" + + "Java.enumerateMethods('re.frida.EnumerablyInitialized!*').forEach(function (group) {" + + "group.classes.forEach(function (klass) {" + + "names = names.concat(klass.methods);" + + "});" + + "});" + + "send(names.indexOf('$clinit') !== -1 ? 'found' : names.join(','));"); + + assertEquals("found", script.getNextMessage()); + } + + @Test + public void classWithoutClassInitializerThrows() { + loadScript("var Bare = Java.use('re.frida.NeverInitialized');" + + "try {" + + "Bare.$clinit;" + + "send('no error');" + + "} catch (e) {" + + "send(e.message);" + + "}"); + + assertEquals("re.frida.NeverInitialized has no class initializer", + script.getNextMessage()); + } + + @Test + public void hookingInstanceMethodDoesNotInitializeClass() { + loadScript("var Target = Java.use('re.frida.LazyInstanceHookTarget');" + + "Target.$init.implementation = function () {" + + "send('init');" + + "this.$init();" + + "};" + + "Target.greet.implementation = function () {" + + "send('greet');" + + "return this.greet() + '!';" + + "};"); + + assertFalse(instanceTargetInitialized); + + LazyInstanceHookTarget obj = new LazyInstanceHookTarget(); + assertTrue(instanceTargetInitialized); + assertEquals("hello!", obj.greet()); + assertEquals("init", script.getNextMessage()); + assertEquals("greet", script.getNextMessage()); + } + + @Test + public void hookingStaticMethodDoesNotInitializeClass() { + loadScript("var Test = Java.use('re.frida.ClassInitializerTest');" + + "var Target = Java.use('re.frida.LazyStaticHookTarget');" + + "Target.format.implementation = function (s) {" + + "send(Test.staticTargetInitialized.value ? 'hook-after-clinit' : 'hook-before-clinit');" + + "return this.format(s) + '!';" + + "};"); + + assertFalse(staticTargetInitialized); + + assertEquals("ready:ok!", LazyStaticHookTarget.format("ok")); + assertTrue(staticTargetInitialized); + assertEquals("hook-after-clinit", script.getNextMessage()); + + assertEquals("ready:again!", LazyStaticHookTarget.format("again")); + assertEquals("hook-after-clinit", script.getNextMessage()); + } + + @Test + public void classInitializerAndStaticMethodCanBothBeHooked() { + loadScript("var Target = Java.use('re.frida.CombinedHookTarget');" + + "Target.$clinit.implementation = function () {" + + "send('clinit-before');" + + "this.$clinit();" + + "send('clinit-after');" + + "};" + + "Target.getTag.implementation = function () {" + + "send('static-hook');" + + "return this.getTag() + ':hooked';" + + "};"); + + assertFalse(combinedTargetInitialized); + + assertEquals("v1:hooked", CombinedHookTarget.getTag()); + assertTrue(combinedTargetInitialized); + assertEquals("clinit-before", script.getNextMessage()); + assertEquals("clinit-after", script.getNextMessage()); + assertEquals("static-hook", script.getNextMessage()); + + assertEquals("v1:hooked", CombinedHookTarget.getTag()); + assertEquals("static-hook", script.getNextMessage()); + } + + @Test + public void invokingStaticMethodAndConstructorFromJsInitializesClass() { + loadScript("var StaticTarget = Java.use('re.frida.JsStaticInvokeTarget');" + + "send(StaticTarget.getLabel());" + + "var CtorTarget = Java.use('re.frida.JsCtorInvokeTarget');" + + "send(CtorTarget.$new().getBase());"); + + assertEquals("static-ok", script.getNextMessage()); + assertEquals("ctor-ok", script.getNextMessage()); + } + + @Test + public void accessingStaticFieldFromJsInitializesClass() { + loadScript("var Test = Java.use('re.frida.ClassInitializerTest');" + + "var Target = Java.use('re.frida.JsStaticFieldTarget');" + + "var field = Target.greeting;" + + "send(field.fieldType + ':' + Test.staticFieldTargetInitialized.value);" + + "send(field.value);" + + "send('' + Test.staticFieldTargetInitialized.value);"); + + assertEquals("1:false", script.getNextMessage()); + assertEquals("field-ok", script.getNextMessage()); + assertEquals("true", script.getNextMessage()); + } + + @Test + public void staticMethodHookFiresWhenCalledFromClassInitializer() { + loadScript("var Target = Java.use('re.frida.StaticFromClinitTarget');" + + "Target.compute.implementation = function () {" + + "send('in-clinit');" + + "return this.compute() + 1;" + + "};"); + + assertEquals(42, StaticFromClinitTarget.value); + assertEquals("in-clinit", script.getNextMessage()); + + assertEquals(42, StaticFromClinitTarget.compute()); + assertEquals("in-clinit", script.getNextMessage()); + } + + @Test + public void revertedPreInitStaticMethodHookRunsOriginal() throws IOException { + loadScript("var Target = Java.use('re.frida.RevertableStaticHookTarget');" + + "Target.getValue.implementation = function () {" + + "return this.getValue() + ':hooked';" + + "};"); + + assertFalse(revertableTargetInitialized); + + assertEquals("v1:hooked", RevertableStaticHookTarget.getValue()); + assertTrue(revertableTargetInitialized); + + unloadScript(); + assertEquals("v1", RevertableStaticHookTarget.getValue()); + } + + private Script script = null; + + private void loadScript(String code) { + Script script = new Script(TestRunner.bundleWith( + "(function (Java) {" + + "Java.perform(function () {" + + code + + "});" + + "})(LocalJava);")); + this.script = script; + } + + private void unloadScript() throws IOException { + if (script != null) { + script.close(); + script = null; + } + } + + @After + public void tearDown() throws IOException { + unloadScript(); + } +} + +class HookablyInitialized { + public static String greeting = "initialized"; +} + +class ReplaceablyInitialized { + public static String greeting = "initialized"; +} + +class EnumerablyInitialized { + public static String greeting = "initialized"; +} + +class NeverInitialized { +} + +class LazyInstanceHookTarget { + static { + ClassInitializerTest.instanceTargetInitialized = true; + } + + public String greet() { + return "hello"; + } +} + +class LazyStaticHookTarget { + private static String prefix; + + static { + prefix = "ready:"; + ClassInitializerTest.staticTargetInitialized = true; + } + + public static String format(String value) { + return prefix + value; + } +} + +class CombinedHookTarget { + private static String tag; + + static { + tag = "v1"; + ClassInitializerTest.combinedTargetInitialized = true; + } + + public static String getTag() { + return tag; + } +} + +class JsStaticInvokeTarget { + private static String label; + + static { + label = "static-ok"; + } + + public static String getLabel() { + return label; + } +} + +class JsCtorInvokeTarget { + private static String base; + + static { + base = "ctor-ok"; + } + + public String getBase() { + return base; + } +} + +class JsStaticFieldTarget { + public static String greeting; + + static { + greeting = "field-ok"; + ClassInitializerTest.staticFieldTargetInitialized = true; + } +} + +class StaticFromClinitTarget { + public static int value; + + static { + value = compute(); + } + + public static int compute() { + return 41; + } +} + +class RevertableStaticHookTarget { + private static String value; + + static { + value = "v1"; + ClassInitializerTest.revertableTargetInitialized = true; + } + + public static String getValue() { + return value; + } +} diff --git a/test/re/frida/TestRunner.java b/test/re/frida/TestRunner.java index 8be36bf..5d275cf 100644 --- a/test/re/frida/TestRunner.java +++ b/test/re/frida/TestRunner.java @@ -28,6 +28,7 @@ public static void main(String[] args, String dataDir, String cacheDir, "re.frida.ClassRegistryTest", "re.frida.MethodTest", "re.frida.ClassCreationTest", + "re.frida.ClassInitializerTest", "re.frida.PerformTest" ); }