From ef98c46ff741f7fc1706f104b1cfca5232d4e08c Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Thu, 19 Nov 2026 17:15:40 +0600 Subject: [PATCH 01/14] 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 bcbceb37bcee04657d18c163a1f8b256d809c6dd Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Thu, 19 Nov 2026 17:16:31 +0600 Subject: [PATCH 02/14] 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 a8c29b59a12ea058a9bd7469c899ec937ad9783f Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Thu, 19 Nov 2026 15:46:53 +0600 Subject: [PATCH 03/14] 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 d8d50d3897578cc5e5f2e5417d246d053abfefcd Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 20:33:21 +0600 Subject: [PATCH 04/14] android: Keep method hooks across class init 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. --- lib/android.js | 305 ++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 277 insertions(+), 28 deletions(-) diff --git a/lib/android.js b/lib/android.js index 5010a1b..84e499c 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 | kAccNterpEntryPointFastPathFlag) >>> 0; + const cPtr = p => (p !== null) ? `((gpointer) (gsize) ${p}ULL)` : 'NULL'; + const nterpEntryPoint = cPtr(api.artNterpEntryPoint); + 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 gpointer last_seen_art_method; +extern guint32 method_offsets[2]; extern gpointer get_oat_quick_method_header_impl (gpointer method, gpointer pc); @@ -1872,6 +1897,15 @@ finalize (void) 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}; +} + gboolean is_replacement_method (gpointer method) { @@ -1913,9 +1947,7 @@ set_replacement_method (gpointer original_method, } 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 +1957,17 @@ 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]; *((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; + if (${nterpEntryPoint} != NULL && *quick_code == ${nterpEntryPoint}) + *quick_code = ${quickToInterpreterBridge}; + else if (${nterpWithClinitEntryPoint} != NULL && *quick_code == ${nterpWithClinitEntryPoint}) + *quick_code = ${quickResolutionTrampoline}; } g_mutex_unlock (&lock); @@ -2047,6 +2083,73 @@ 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 && get_replacement_method (method) != NULL) + { + gpointer * quick_code = method + method_offsets[0]; + + if (thread != NULL) + { + gpointer * top_quick_frame = thread + ${threadOffsets.managedStack} + ${managedStackOffsets.topQuickFrame}; + if (*top_quick_frame == sp) + *top_quick_frame = NULL; + } + + if (${nterpEntryPoint} != NULL && *quick_code == ${nterpEntryPoint}) + *quick_code = ${quickToInterpreterBridge}; + else if (${nterpWithClinitEntryPoint} != NULL && *quick_code == ${nterpWithClinitEntryPoint}) + *quick_code = ${quickResolutionTrampoline}; + + gum_invocation_context_replace_return_value (ic, get_hooked_quick_entrypoint (method)); + } +} + +void +on_instrumentation_update_methods_code (GumInvocationContext * ic) +{ + gpointer method, new_code; + + method = gum_invocation_context_get_nth_argument (ic, 1); + if (method == NULL || get_replacement_method (method) == NULL) + return; + + new_code = gum_invocation_context_get_nth_argument (ic, 2); + if (${nterpWithClinitEntryPoint} != NULL && new_code == ${nterpWithClinitEntryPoint}) + gum_invocation_context_replace_nth_argument (ic, 2, ${quickResolutionTrampoline}); + else if (new_code != ${quickResolutionTrampoline} && + new_code != ${artQuickResolutionTrampoline} && + new_code != ${quickToInterpreterBridge} && + new_code != ${artQuickToInterpreterBridge} && + new_code != ${quickGenericJniTrampoline} && + new_code != ${artQuickGenericJniTrampoline}) + gum_invocation_context_replace_nth_argument (ic, 2, get_hooked_quick_entrypoint (method)); +} + +void +on_synchronize_replacement_methods (GumInvocationContext * ic) +{ + synchronize_replacement_methods (); +} + void on_leave_gc_concurrent_copying_copying_phase (GumInvocationContext * ic) { @@ -2067,13 +2170,15 @@ on_leave_gc_concurrent_copying_copying_phase (GumInvocationContext * ic) const methodsSize = pointerSize; const replacementsSize = pointerSize; const lastSeenArtMethodSize = pointerSize; + const methodOffsetsSize = 8; - const data = Memory.alloc(lockSize + methodsSize + replacementsSize + lastSeenArtMethodSize); + const data = Memory.alloc(lockSize + methodsSize + replacementsSize + lastSeenArtMethodSize + methodOffsetsSize); const lock = data; const methods = lock.add(lockSize); const replacements = methods.add(methodsSize); const lastSeenArtMethod = replacements.add(replacementsSize); + const methodOffsets = lastSeenArtMethod.add(lastSeenArtMethodSize); const getOatQuickMethodHeaderImpl = api.find((pointerSize === 4) ? '_ZN3art9ArtMethod23GetOatQuickMethodHeaderEj' @@ -2084,6 +2189,7 @@ on_leave_gc_concurrent_copying_copying_phase (GumInvocationContext * ic) methods, replacements, last_seen_art_method: lastSeenArtMethod, + method_offsets: methodOffsets, get_oat_quick_method_header_impl: getOatQuickMethodHeaderImpl ?? ptr('0xdeadbeef') }); @@ -2091,11 +2197,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), + 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 +2212,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 +2246,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 +2291,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 +2349,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 +2438,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 +3968,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,7 +4009,11 @@ 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); } @@ -3810,12 +4030,41 @@ class ArtMethodMangler { } 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 be84cf7ed30720c6f91344289b068a5a72e0076a Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 20:33:42 +0600 Subject: [PATCH 05/14] jvm: Fix JDK 8 lookup and code cache sweep 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. --- lib/jvm.js | 75 +++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 58 insertions(+), 17 deletions(-) diff --git a/lib/jvm.js b/lib/jvm.js index 0319cdb..3650ebf 100644 --- a/lib/jvm.js +++ b/lib/jvm.js @@ -61,7 +61,6 @@ function _getApi () { 'Method::size': ['Method::size', 'int', ['int']], 'Method::set_native_function': ['Method::set_native_function', 'void', ['pointer', 'pointer', 'int']], 'Method::clear_native_function': ['Method::clear_native_function', 'void', ['pointer']], - 'Method::jmethod_id': ['Method::jmethod_id', 'pointer', ['pointer']], 'ClassLoaderDataGraph::classes_do': ['ClassLoaderDataGraph::classes_do', 'void', ['pointer']], 'NMethodSweeper::sweep_code_cache': ['NMethodSweeper::sweep_code_cache', 'void', []], 'OopMapCache::flush_obsolete_entries': ['OopMapCache::flush_obsolete_entries', 'void', ['pointer']] @@ -87,9 +86,17 @@ function _getApi () { }, 'NMethodSweeper::_should_sweep': function (address) { this.shouldSweep = address; + }, + 'NMethodSweeper::_sweep_started': function (address) { + this.sweepStarted = address; + }, + UseCompiler: function (address) { + this.useCompiler = address; } }, optionals: [ + 'NMethodSweeper::_sweep_started', + 'UseCompiler' ] }] // If platform is not Windows @@ -106,7 +113,6 @@ function _getApi () { // JDK < 17 _ZN6Method24restore_unshareable_infoEP6Thread: ['Method::restore_unshareable_info', 'void', ['pointer', 'pointer']], _ZN6Method11link_methodERK12methodHandleP10JavaThread: ['Method::link_method', 'void', ['pointer', 'pointer', 'pointer']], - _ZN6Method10jmethod_idEv: ['Method::jmethod_id', 'pointer', ['pointer']], _ZN6Method10clear_codeEv: function (address) { const clearCode = new NativeFunction(address, 'void', ['pointer'], nativeFunctionOptions); this['Method::clear_code'] = function (thisPtr) { @@ -232,6 +238,12 @@ function _getApi () { }, _ZN14NMethodSweeper13_should_sweepE: function (address) { this.shouldSweep = address; + }, + _ZN14NMethodSweeper14_sweep_startedE: function (address) { + this.sweepStarted = address; + }, + UseCompiler: function (address) { + this.useCompiler = address; } }, optionals: [ @@ -270,7 +282,9 @@ function _getApi () { '_ZN13InstanceKlass33create_new_default_vtable_indicesEiP10JavaThread', '_ZN13InstanceKlass33create_new_default_vtable_indicesEiP6Thread', - '_ZN14NMethodSweeper21_sweep_fractions_leftE' + '_ZN14NMethodSweeper21_sweep_fractions_leftE', + '_ZN14NMethodSweeper14_sweep_startedE', + 'UseCompiler' ] }]; @@ -541,13 +555,19 @@ function forceSweep (env) { const { fractions, shouldSweep, + sweepStarted, traversals, + useCompiler, 'NMethodSweeper::sweep_code_cache': sweep, 'NMethodSweeper::sweep_in_progress': inProgress, 'NMethodSweeper::force_sweep': force, JVM_Sleep: sleep } = getApi(); + if (useCompiler !== undefined && useCompiler.readU8() === 0) { + return; + } + if (force !== undefined) { Thread.sleep(0.05); force(); @@ -555,26 +575,47 @@ function forceSweep (env) { force(); } else { let trav = traversals.readS64(); - const endTrav = trav + 2; + const endTrav = trav.add(2); - while (endTrav > trav) { - // Force a full sweep if already in progress. - fractions.writeS32(1); - sleep(env, NULL, 50); + while (trav.compare(endTrav) < 0) { + if (sweepStarted !== undefined) { + let claimed = false; - // Check if current nmethod is set. - if (!inProgress()) { - // Force mark_active_nmethods on exit from safepoint. withJvmThread(() => { - Thread.sleep(0.05); + if (sweepStarted.readS32() === 0) { + sweepStarted.writeS32(1); + claimed = true; + } }); - } - const sweepNotAlreadyInProgress = shouldSweep.readU8() === 0; - if (sweepNotAlreadyInProgress) { - // Sanity check to not divide by 0. + if (claimed) { + try { + if (inProgress()) { + fractions.writeS32(1); + sweep(); + fractions.writeS32(0); + } + } finally { + sweepStarted.writeS32(0); + } + } else { + fractions.writeS32(1); + sleep(env, NULL, 50); + } + } else { fractions.writeS32(1); - sweep(); + sleep(env, NULL, 50); + + if (!inProgress()) { + withJvmThread(() => { + Thread.sleep(0.05); + }); + } + + if (shouldSweep.readU8() === 0) { + fractions.writeS32(1); + sweep(); + } } trav = traversals.readS64(); From 851065debabe37959b01069b392340a9c8d4ba1d Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 20:33:55 +0600 Subject: [PATCH 06/14] 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 9c4931b7159ec79cfacad6910dfc9ff0616eb68d Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Thu, 19 Nov 2026 17:44:02 +0600 Subject: [PATCH 07/14] 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 cff39defdbb5c0d78498ca1bd40db4961bfeef7c Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 16:57:37 +0600 Subject: [PATCH 08/14] 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 b277e743bf02fe242e9b416a79c2e26f3cdb198f Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Thu, 19 Nov 2026 17:45:26 +0600 Subject: [PATCH 09/14] 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 3650ebf..4996b0a 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; @@ -441,6 +442,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 ff0b4e37f09ddd58fa2850783a9d255c7ab91910 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 20:34:28 +0600 Subject: [PATCH 10/14] tests: Add ClassInitializerTest 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 - Hooking static methods without triggering , preserving JLS ordering ( 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 - Reverting a static method hook installed before via script unload --- 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" ); } From 40b32aee03d2ccc7721901dc192a8fd7736e76e9 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 20:34:47 +0600 Subject: [PATCH 11/14] tests: Parse script messages with json-glib 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. --- test/re/frida/Script.java | 29 ++++---------- test/runner.c | 79 ++++++++++++++++++++++++++++++++++----- 2 files changed, 78 insertions(+), 30 deletions(-) diff --git a/test/re/frida/Script.java b/test/re/frida/Script.java index 9fefdba..14c9332 100644 --- a/test/re/frida/Script.java +++ b/test/re/frida/Script.java @@ -5,9 +5,6 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; -import org.json.JSONException; -import org.json.JSONObject; - public class Script implements Closeable { private long handle; private LinkedBlockingQueue pending = new LinkedBlockingQueue<>(); @@ -35,29 +32,19 @@ public void close() throws IOException { public String getNextMessage() { try { - return pending.poll(5, TimeUnit.SECONDS); + String message = pending.poll(5, TimeUnit.SECONDS); + if (message == null) { + throw new IllegalStateException("timed out waiting for a message from the" + + " script; see stderr and logcat for errors raised by it"); + } + return message; } catch (InterruptedException e) { return getNextMessage(); } } - private void onMessage(String rawMessage) { - try { - JSONObject message = new JSONObject(rawMessage); - - String type = message.getString("type"); - if (type.equals("send")) { - pending.add(message.getString("payload")); - } else if (type.equals("log")) { - System.out.println(message.getString("payload")); - } else if (type.equals("error")) { - System.err.println(message.getString("stack")); - } else { - System.err.println(rawMessage); - } - } catch (JSONException e) { - e.printStackTrace(); - } + private void onMessage(String payload) { + pending.add(payload); } private native long create(String sourceCode); diff --git a/test/runner.c b/test/runner.c index 9c41e29..3382555 100644 --- a/test/runner.c +++ b/test/runner.c @@ -465,21 +465,82 @@ on_unload_ready (GObject * source_object, GAsyncResult * result, gpointer user_d static void re_frida_script_on_message (const gchar * message, GBytes * data, gpointer user_data) { - JNIEnv * env; - jweak weak_wrapper = user_data; - jobject wrapper; + JsonNode * root; + JsonObject * object; + const gchar * type; - env = frida_java_get_env (); + root = json_from_string (message, NULL); + if (root == NULL || !JSON_NODE_HOLDS_OBJECT (root)) + { + g_printerr ("%s\n", message); + if (root != NULL) + json_node_unref (root); + return; + } - (*env)->PushLocalFrame (env, 3); + object = json_node_get_object (root); + type = json_object_get_string_member_with_default (object, "type", ""); - wrapper = (*env)->NewLocalRef (env, weak_wrapper); - if (wrapper != NULL) + if (strcmp (type, "send") == 0) + { + JsonNode * payload_node; + const gchar * payload; + gchar * payload_owned = NULL; + JNIEnv * env; + jweak weak_wrapper = user_data; + jobject wrapper; + + payload_node = json_object_get_member (object, "payload"); + if (payload_node == NULL) + { + payload = "null"; + } + else if (JSON_NODE_HOLDS_VALUE (payload_node) && json_node_get_value_type (payload_node) == G_TYPE_STRING) + { + payload = json_node_get_string (payload_node); + } + else + { + payload_owned = json_to_string (payload_node, FALSE); + payload = payload_owned; + } + + env = frida_java_get_env (); + + (*env)->PushLocalFrame (env, 3); + + wrapper = (*env)->NewLocalRef (env, weak_wrapper); + if (wrapper != NULL) + { + gunichar2 * utf16; + glong utf16_len; + jstring payload_value; + + utf16 = g_utf8_to_utf16 (payload, -1, NULL, &utf16_len, NULL); + payload_value = (*env)->NewString (env, utf16, utf16_len); + g_free (utf16); + + (*env)->CallVoidMethod (env, wrapper, re_frida_script_on_message_method, payload_value); + } + + (*env)->PopLocalFrame (env, NULL); + + g_free (payload_owned); + } + else if (strcmp (type, "log") == 0) { - (*env)->CallVoidMethod (env, wrapper, re_frida_script_on_message_method, (*env)->NewStringUTF (env, message)); + g_print ("%s\n", json_object_get_string_member_with_default (object, "payload", "")); + } + else if (strcmp (type, "error") == 0) + { + g_printerr ("%s\n", json_object_get_string_member_with_default (object, "stack", message)); + } + else + { + g_printerr ("%s\n", message); } - (*env)->PopLocalFrame (env, NULL); + json_node_unref (root); } static void From 56977a37c35b6882ffb46ce74031748fef5cf10e Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 20:35:29 +0600 Subject: [PATCH 12/14] tests: Support Android API levels up to 36 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. --- .github/workflows/tests.yml | 25 +++-- Makefile | 7 +- test/Application.mk | 5 +- test/Makefile | 50 +++++++--- test/re/frida/MethodTest.java | 4 +- test/re/frida/TestRunner.java | 18 ++-- test/runner.c | 179 +++++++++++++++++++++++++++++++++- 7 files changed, 251 insertions(+), 37 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 9dbced4..f89d926 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -4,19 +4,27 @@ jobs: tests: runs-on: ubuntu-latest strategy: + fail-fast: false matrix: - api: [26, 27, 28, 29, 30, 31] + api: [26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] arch: [x86_64] - exclude: - - api: 30 - arch: x86 - - api: 31 - arch: x86 env: - ANDROID_EMULATOR_WAIT_TIME_BEFORE_KILL: 200 # Default is 20 + ANDROID_EMULATOR_WAIT_TIME_BEFORE_KILL: 200 steps: - name: Check out repo uses: actions/checkout@v4 + - name: Cache test dependencies + uses: actions/cache@v4 + with: + path: | + ~/.npm + test/build/junit.jar + test/build/hamcrest.jar + test/build/obj/local/${{ matrix.arch }}/frida-gumjs.h + test/build/obj/local/${{ matrix.arch }}/libfrida-gumjs.a + key: android-deps-${{ matrix.arch }}-${{ hashFiles('test/Makefile', 'package-lock.json', 'test/package-lock.json') }} + restore-keys: | + android-deps-${{ matrix.arch }}- - name: Enable KVM run: | echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules @@ -50,7 +58,8 @@ jobs: disable-animations: true script: >- sdkmanager "platforms;android-${{ matrix.api }}" - && PATH="$ANDROID_SDK_ROOT/build-tools/34.0.0:$PATH" + && BUILD_TOOLS_DIR="$(ls -d "$ANDROID_SDK_ROOT/build-tools/"* | sort -V | tail -n 1)" + && PATH="$BUILD_TOOLS_DIR:$PATH" ANDROID_ARCH=${{ matrix.arch }} ANDROID_ABI=${{ matrix.arch }} ANDROID_API_LEVEL=${{ matrix.api }} diff --git a/Makefile b/Makefile index 3454863..adba877 100644 --- a/Makefile +++ b/Makefile @@ -2,14 +2,15 @@ all: @echo "Nothing to build. To run the test-suite: make check" check: node_modules + $(MAKE) -C test deploy @echo "" @echo "[*] Running the test suite with optimizations disabled (interpreter mode)." @echo "" - @$(MAKE) check-run + @$(MAKE) -C test run @echo "" @echo "[*] Running the test suite with optimizations enabled." @echo "" - @$(MAKE) RUNNER_ARGS="--enable-optimizations" check-run + @$(MAKE) -C test RUNNER_ARGS="--enable-optimizations" run check-run: node_modules $(MAKE) -C test deploy @@ -30,4 +31,4 @@ clean: rm -rf node_modules $(MAKE) -C test clean -.PHONY: all check check-gdb develop clean +.PHONY: all check check-run check-gdb develop clean diff --git a/test/Application.mk b/test/Application.mk index 45ad11f..2b0d386 100644 --- a/test/Application.mk +++ b/test/Application.mk @@ -1,6 +1,9 @@ include config.mk +android_api_major := $(firstword $(subst ., ,$(ANDROID_API_LEVEL))) +ndk_max_api := $(shell sed -n 's/^[[:space:]]*"max":[[:space:]]*\([0-9]*\).*/\1/p' $(ANDROID_NDK_ROOT)/meta/platforms.json 2>/dev/null) + APP_ABI := $(ANDROID_ABI) -APP_PLATFORM := android-$(ANDROID_API_LEVEL) +APP_PLATFORM := android-$(firstword $(sort $(android_api_major) $(ndk_max_api))) APP_STL := c++_static APP_BUILD_SCRIPT := Android.mk diff --git a/test/Makefile b/test/Makefile index aff3fd2..dcc713c 100644 --- a/test/Makefile +++ b/test/Makefile @@ -2,8 +2,10 @@ include config.mk build_os_arch := $(shell uname -s | tr -s "[A-Z]" "[a-z]")-$(shell uname -m) -android_platform := android-$(ANDROID_API_LEVEL) -android_sysroot := $(ANDROID_NDK_ROOT)/platforms/$(android_platform)/arch-$(ANDROID_ARCH) +android_api_major := $(firstword $(subst ., ,$(ANDROID_API_LEVEL))) +android_platform := $(if $(wildcard $(ANDROID_SDK_ROOT)/platforms/android-$(ANDROID_API_LEVEL)/android.jar),android-$(ANDROID_API_LEVEL),$(notdir $(lastword $(sort $(wildcard $(ANDROID_SDK_ROOT)/platforms/android-$(ANDROID_API_LEVEL).*))))) +android_platform := $(if $(android_platform),$(android_platform),android-$(ANDROID_API_LEVEL)) +android_sysroot := $(ANDROID_NDK_ROOT)/platforms/android-$(android_api_major)/arch-$(ANDROID_ARCH) deploy_prefix := /data/local/tmp deploy_data_dir := $(deploy_prefix)/frida-java-bridge-tests @@ -13,28 +15,41 @@ frida_version := 17.26.3 test_sources := $(wildcard re/frida/*.java) test_classes := $(patsubst %.java,%.class,$(test_sources)) +bridge_sources := bundle.js ../index.js $(wildcard ../lib/*.js) android_jar := $(ANDROID_SDK_ROOT)/platforms/$(android_platform)/android.jar +android_deploy_files := \ + build/$(ANDROID_ABI)/runner \ + build/$(ANDROID_ABI)/libartpalette.so \ + build/tests.dex \ + build/frida-java-bridge.js + all: @echo "Available targets: deploy run" clean: rm -rf build -deploy: build/$(ANDROID_ABI)/runner build/tests.dex build/frida-java-bridge.js - adb shell "rm -rf $(deploy_data_dir) && mkdir -p $(deploy_data_dir)" - adb push $^ build/$(ANDROID_ABI)/libartpalette.so $(deploy_data_dir) +deploy: $(android_deploy_files) + adb shell "mkdir -p $(deploy_data_dir) $(deploy_cache_dir)" + adb push --sync $(android_deploy_files) $(deploy_data_dir)/ run: - adb shell "LD_PRELOAD=$(ANDROID_VM) LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(deploy_data_dir)' $(deploy_data_dir)/runner $(RUNNER_ARGS)" + @since=$$(adb shell 'date "+%m-%d %H:%M:%S.000"' | tr -d '\r'); \ + adb shell "LD_PRELOAD=$(ANDROID_VM) LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(deploy_data_dir)' $(deploy_data_dir)/runner $(RUNNER_ARGS)" || { \ + status=$$?; \ + adb logcat -d -T "$$since" -b crash || true; \ + adb logcat -d -T "$$since" -b main *:W || true; \ + exit $$status; \ + } watch: npm run watch & ./node_modules/.bin/chokidar \ build/frida-java-bridge.js \ - -c "adb push build/frida-java-bridge.js $(deploy_data_dir) \ - && adb shell 'LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(deploy_data_dir)' $(deploy_data_dir)/runner $(RUNNER_ARGS)'" + -c "adb push --sync build/frida-java-bridge.js $(deploy_data_dir)/ \ + && adb shell \"LD_PRELOAD=$(ANDROID_VM) LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(deploy_data_dir)' $(deploy_data_dir)/runner $(RUNNER_ARGS)\"" debug: build/gdb.setup adb shell "rm -f $(deploy_data_dir)/debug-socket" @@ -60,6 +75,9 @@ build/symbols.stamp: adb pull -a $(shell adb shell "ls $(ANDROID_LIBDIR)/*.so") build/symbols/$(ANDROID_LIBDIR)/; \ touch $@ +build/$(ANDROID_ABI)/libartpalette.so: build/$(ANDROID_ABI)/runner + @test -f $@ + build/$(ANDROID_ABI)/runner: runner.c artpalette.c build/obj/local/$(ANDROID_ABI)/libfrida-gumjs.a $(ANDROID_NDK_ROOT)/ndk-build \ NDK_PROJECT_PATH=$$(pwd) \ @@ -71,15 +89,17 @@ build/$(ANDROID_ABI)/runner: runner.c artpalette.c build/obj/local/$(ANDROID_ABI build/obj/local/$(ANDROID_ABI)/libfrida-gumjs.a: @mkdir -p $(@D) - curl -Ls https://github.com/frida/frida/releases/download/$(frida_version)/frida-gumjs-devkit-$(frida_version)-android-$(ANDROID_ARCH).tar.xz | tar -xJf - -C $(@D) + curl -fsSL https://github.com/frida/frida/releases/download/$(frida_version)/frida-gumjs-devkit-$(frida_version)-android-$(ANDROID_ARCH).tar.xz -o $@.tar.xz.tmp + tar -xJf $@.tar.xz.tmp -C $(@D) + rm -f $@.tar.xz.tmp build/tests.dex: build/tests.jar d8 \ --output build/tests.zip \ --classpath $(android_jar) \ - --min-api $(ANDROID_API_LEVEL) \ + --min-api $(android_api_major) \ $< - cd build && unzip tests.zip classes.dex + cd build && unzip -o tests.zip classes.dex mv build/classes.dex $@ build/tests.jar: $(test_sources) build/junit.jar build/hamcrest.jar @@ -101,13 +121,15 @@ build/tests.jar: $(test_sources) build/junit.jar build/hamcrest.jar build/junit.jar: @mkdir -p $(@D) - curl -Ls https://github.com/junit-team/junit4/releases/download/r4.12/junit-4.12.jar > $@ + curl -fsSL https://github.com/junit-team/junit4/releases/download/r4.12/junit-4.12.jar -o $@.tmp + mv $@.tmp $@ build/hamcrest.jar: @mkdir -p $(@D) - curl -Ls https://search.maven.org/remotecontent?filepath=org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar > $@ + curl -fsSL https://repo1.maven.org/maven2/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar -o $@.tmp + mv $@.tmp $@ -build/frida-java-bridge.js: node_modules +build/frida-java-bridge.js: node_modules $(bridge_sources) npm run build node_modules: package.json diff --git a/test/re/frida/MethodTest.java b/test/re/frida/MethodTest.java index f736ee6..52bf65d 100644 --- a/test/re/frida/MethodTest.java +++ b/test/re/frida/MethodTest.java @@ -208,8 +208,10 @@ public void callCanBeTraced() { "}" + "});" + - "send(returnZero.call(badger));" + + "var result = returnZero.call(badger);" + + "Stalker.unfollow();" + + "send(result);" + "Stalker.flush();"); assertEquals("0", script.getNextMessage()); assertEquals("onCallSummary", script.getNextMessage()); diff --git a/test/re/frida/TestRunner.java b/test/re/frida/TestRunner.java index 5d275cf..a95579e 100644 --- a/test/re/frida/TestRunner.java +++ b/test/re/frida/TestRunner.java @@ -4,6 +4,7 @@ import java.io.File; import java.io.FileInputStream; import java.nio.charset.StandardCharsets; +import java.util.Arrays; import org.junit.runner.JUnitCore; @@ -24,13 +25,16 @@ public static void main(String[] args, String dataDir, String cacheDir, registerClassLoader(TestRunner.class.getClassLoader()); - JUnitCore.main( - "re.frida.ClassRegistryTest", - "re.frida.MethodTest", - "re.frida.ClassCreationTest", - "re.frida.ClassInitializerTest", - "re.frida.PerformTest" - ); + String[] classes = (args.length > 1) + ? Arrays.copyOfRange(args, 1, args.length) + : new String[] { + "re.frida.ClassRegistryTest", + "re.frida.MethodTest", + "re.frida.ClassCreationTest", + "re.frida.ClassInitializerTest", + "re.frida.PerformTest" + }; + JUnitCore.main(classes); } public static String getCacheDir() { diff --git a/test/runner.c b/test/runner.c index 3382555..e7f14ce 100644 --- a/test/runner.c +++ b/test/runner.c @@ -2,11 +2,17 @@ #include #include #include +#include #include +#include +#if defined (__linux__) && defined (__LP64__) +# include +#endif #include typedef struct _CreateScriptOperation CreateScriptOperation; typedef struct _DestroyScriptOperation DestroyScriptOperation; +typedef struct _SigchainAction SigchainAction; struct _CreateScriptOperation { @@ -31,6 +37,13 @@ struct _DestroyScriptOperation GCond cond; }; +struct _SigchainAction +{ + bool (* sc_sigaction) (int, siginfo_t *, void *); + sigset_t sc_mask; + guint64 sc_flags; +}; + static void frida_java_init_vm (JavaVM ** vm, JNIEnv ** env, gboolean enable_optimizations); static void frida_java_register_test_runner_api (JNIEnv * env); static void frida_java_register_script_api (JNIEnv * env); @@ -52,8 +65,15 @@ static void re_frida_badger_native_method (JNIEnv * env, jobject self, jstring s static void destroy_weak_ref (jweak ref); +#if defined (__linux__) && defined (__LP64__) +static gpointer frida_java_allocate_memory (const GumAddressSpec * spec, gsize size, gsize alignment, + GumPageProtection prot, gpointer user_data); +#endif + static guint get_system_api_level (void); +static void on_special_signal (int signo, siginfo_t * info, void * context); + static const JNINativeMethod re_frida_test_runner_methods[] = { { "registerClassLoader", "(Ljava/lang/ClassLoader;)V", re_frida_test_runner_register_class_loader }, @@ -78,6 +98,12 @@ static jobject re_frida_test_runner_class_loader; static jmethodID re_frida_script_on_message_method; +#define MAX_SPECIAL_HANDLERS 4 + +static SigchainAction special_handlers[NSIG][MAX_SPECIAL_HANDLERS]; +static guint special_handler_count[NSIG]; +static struct sigaction previous_action[NSIG]; + int main (int argc, char * argv[]) { @@ -95,6 +121,14 @@ main (int argc, char * argv[]) gum_init_embedded (); +#if defined (__linux__) && defined (__LP64__) + { + GumMemoryHooks hooks = { 0, }; + hooks.allocate = frida_java_allocate_memory; + gum_memory_set_hooks (&hooks); + } +#endif + js_scheduler = gum_script_backend_get_scheduler (); js_context = gum_script_scheduler_get_js_context (js_scheduler); gum_script_scheduler_enable_background_thread (js_scheduler); @@ -558,6 +592,74 @@ destroy_weak_ref (jweak ref) (*env)->DeleteWeakGlobalRef (env, ref); } +#if defined (__linux__) && defined (__LP64__) + +static gpointer +frida_java_allocate_memory (const GumAddressSpec * spec, + gsize size, + gsize alignment, + GumPageProtection prot, + gpointer user_data) +{ + GumPageProtection non_exec_prot = prot & ~GUM_PAGE_EXECUTE; + gpointer mem = NULL; + + if (spec != NULL) + { + mem = gum_memory_allocate_near (spec, size, alignment, non_exec_prot); + } + else + { + const gsize window_size = 64 * 1024 * 1024; + gsize page_size = gum_query_page_size (); + gsize effective_alignment = MAX (alignment, page_size); + gsize aligned_size = GUM_ALIGN_SIZE (size, page_size); + + if (aligned_size > 0 && + aligned_size <= (window_size / 4) && + effective_alignment <= (window_size / 4) && + (effective_alignment & (effective_alignment - 1)) == 0) + { + gpointer probe = mmap (NULL, window_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (probe != MAP_FAILED) + { + guint8 * probe_start = probe; + guint8 * probe_end = probe_start + window_size; + guint8 * target = GUM_ALIGN_POINTER (guint8 *, probe_start + (window_size / 2), effective_alignment); + gpointer mapped = mmap (target, aligned_size, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + if (mapped == target) + { + munmap (probe_start, target - probe_start); + if (target + aligned_size < probe_end) + munmap (target + aligned_size, probe_end - (target + aligned_size)); + mem = mapped; + } + else + { + munmap (probe, window_size); + } + } + } + + if (mem == NULL) + mem = gum_memory_allocate (NULL, size, alignment, non_exec_prot); + } + + if (mem != NULL && prot != non_exec_prot) + { + if (!gum_try_mprotect (mem, size, prot)) + { + gum_memory_free (mem, size); + return NULL; + } + } + + return mem; +} + +#endif + static guint get_system_api_level (void) { @@ -606,13 +708,84 @@ SetSpecialSignalHandlerFn (int signal, gpointer fn) } void -AddSpecialSignalHandlerFn (int signal, gpointer sa) +AddSpecialSignalHandlerFn (int signal, SigchainAction * sa) { - /* g_print ("AddSpecialSignalHandlerFn(signal=%d)\n", signal); */ + guint count; + struct sigaction action; + + if (signal <= 0 || signal >= NSIG) + return; + + count = special_handler_count[signal]; + if (count >= MAX_SPECIAL_HANDLERS) + return; + + special_handlers[signal][count] = *sa; + special_handler_count[signal] = count + 1; + + if (count == 0) + { + memset (&action, 0, sizeof (action)); + action.sa_sigaction = on_special_signal; + action.sa_flags = SA_SIGINFO | SA_ONSTACK; + action.sa_mask = sa->sc_mask; + + sigaction (signal, &action, &previous_action[signal]); + } } void RemoveSpecialSignalHandlerFn (int signal, bool (* fn) (int, siginfo_t *, void *)) { - /* g_print ("RemoveSpecialSignalHandlerFn(signal=%d)\n", signal); */ + guint count, i; + + if (signal <= 0 || signal >= NSIG) + return; + + count = special_handler_count[signal]; + for (i = 0; i != count; i++) + { + if (special_handlers[signal][i].sc_sigaction == fn) + { + guint j; + + for (j = i + 1; j != count; j++) + special_handlers[signal][j - 1] = special_handlers[signal][j]; + + special_handler_count[signal] = count - 1; + if (count == 1) + sigaction (signal, &previous_action[signal], NULL); + return; + } + } +} + +static void +on_special_signal (int signo, siginfo_t * info, void * context) +{ + guint count, i; + struct sigaction prev; + + count = special_handler_count[signo]; + for (i = 0; i != count; i++) + { + bool (* handler) (int, siginfo_t *, void *) = special_handlers[signo][i].sc_sigaction; + if (handler != NULL && handler (signo, info, context)) + return; + } + + prev = previous_action[signo]; + if ((prev.sa_flags & SA_SIGINFO) != 0 && prev.sa_sigaction != NULL) + { + prev.sa_sigaction (signo, info, context); + return; + } + + if ((prev.sa_flags & SA_SIGINFO) == 0 && prev.sa_handler != SIG_DFL && prev.sa_handler != SIG_IGN) + { + prev.sa_handler (signo); + return; + } + + sigaction (signo, &prev, NULL); } From d9bc056bcac79f19612832c5629bf5bcc55c9d56 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 20:36:04 +0600 Subject: [PATCH 13/14] tests: Add HotSpot JVM test runner and CI 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). --- .github/workflows/tests.yml | 36 ++++++- Makefile | 49 +++++---- README.md | 46 ++++++--- test/Makefile | 142 +++++++++++++++++++-------- test/re/frida/ClassRegistryTest.java | 2 +- test/re/frida/MethodTest.java | 4 + test/re/frida/TestRunner.java | 38 +++++-- test/runner.c | 107 ++++++++++++++++++-- 8 files changed, 335 insertions(+), 89 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index f89d926..68fa860 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,7 +1,7 @@ name: tests on: [push, pull_request] jobs: - tests: + android: runs-on: ubuntu-latest strategy: fail-fast: false @@ -64,4 +64,36 @@ jobs: ANDROID_ABI=${{ matrix.arch }} ANDROID_API_LEVEL=${{ matrix.api }} ANDROID_LIBDIR=/system/${{ contains(matrix.arch, '64') && 'lib64' || 'lib' }} - make check + make check-android + + jvm: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + java: ['8', '11', '17'] + steps: + - name: Check out repo + uses: actions/checkout@v4 + - name: Set up JDK ${{ matrix.java }} + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: ${{ matrix.java }} + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - name: Cache test dependencies + uses: actions/cache@v4 + with: + path: | + test/build/junit.jar + test/build/hamcrest.jar + test/build/jvm/frida-gumjs + key: jvm-deps-${{ hashFiles('test/Makefile') }} + restore-keys: | + jvm-deps- + - name: Run JVM tests + run: make check-jvm diff --git a/Makefile b/Makefile index adba877..9a51ef4 100644 --- a/Makefile +++ b/Makefile @@ -1,28 +1,43 @@ all: - @echo "Nothing to build. To run the test-suite: make check" + @echo "Nothing to build. To run the test-suite: make check-android or make check-jvm" -check: node_modules - $(MAKE) -C test deploy +check-android: node_modules + $(MAKE) -C test deploy-android @echo "" - @echo "[*] Running the test suite with optimizations disabled (interpreter mode)." + @echo "[*] Running the Android test suite with optimizations disabled (interpreter mode)." @echo "" - @$(MAKE) -C test run + @$(MAKE) -C test run-android @echo "" - @echo "[*] Running the test suite with optimizations enabled." + @echo "[*] Running the Android test suite with optimizations enabled." @echo "" - @$(MAKE) -C test RUNNER_ARGS="--enable-optimizations" run + @$(MAKE) -C test RUNNER_ARGS="--enable-optimizations" run-android -check-run: node_modules - $(MAKE) -C test deploy - $(MAKE) -C test run +check-android-gdb: node_modules + $(MAKE) -C test deploy-android + $(MAKE) -C test debug-android -check-gdb: node_modules - $(MAKE) -C test deploy - $(MAKE) -C test debug +develop-android: node_modules + $(MAKE) -C test deploy-android + $(MAKE) -C test watch-android -develop: node_modules - $(MAKE) -C test deploy - $(MAKE) -C test watch +check-jvm: node_modules + $(MAKE) -C test build-jvm + @echo "" + @echo "[*] Running the JVM test suite with optimizations disabled (interpreter mode)." + @echo "" + @$(MAKE) -C test run-jvm + @echo "" + @echo "[*] Running the JVM test suite with optimizations enabled." + @echo "" + @$(MAKE) -C test RUNNER_ARGS="--enable-optimizations" run-jvm + +check-jvm-gdb: node_modules + $(MAKE) -C test build-jvm + $(MAKE) -C test debug-jvm + +develop-jvm: node_modules + $(MAKE) -C test build-jvm + $(MAKE) -C test watch-jvm node_modules: package.json npm install @@ -31,4 +46,4 @@ clean: rm -rf node_modules $(MAKE) -C test clean -.PHONY: all check check-run check-gdb develop clean +.PHONY: all check-android check-android-gdb develop-android check-jvm check-jvm-gdb develop-jvm clean diff --git a/README.md b/README.md index 7c391a1..3fa0f12 100644 --- a/README.md +++ b/README.md @@ -5,36 +5,60 @@ through the global named `Java`. ## Running the test-suite -### Dependencies +### Android -- Android SDK Platform-Tools >= 27.0.1 -- Android NDK r21 +#### Dependencies + +- Android SDK Platform-Tools >= 29.0.6 +- Android NDK r21+ With environment configured accordingly: ```sh $ export ANDROID_SDK_ROOT=~/Library/Android/Sdk -$ export ANDROID_NDK_ROOT=/usr/local/opt/android-ndk-r21 +$ export ANDROID_NDK_ROOT=/usr/local/opt/android-ndk-r25b ``` -### Configuration +#### Configuration - Go to `/test/config.mk` for editing the device configuration settings. -### Run +#### Run + +```sh +$ make check-android +``` + +#### Debug + +```sh +$ make check-android-gdb +``` + +#### Auto-run tests on JavaScript change + +```sh +$ make develop-android +``` + +### HotSpot JVM + +With `JAVA_HOME` pointing to a HotSpot JDK (JDK 8–17 on Linux x86_64): + +#### Run ```sh -$ make check +$ make check-jvm ``` -### Debug +#### Debug ```sh -$ make check-gdb +$ make check-jvm-gdb ``` -### Auto-run tests on JavaScript change +#### Auto-run tests on JavaScript change ```sh -$ make develop +$ make develop-jvm ``` diff --git a/test/Makefile b/test/Makefile index dcc713c..784b3d4 100644 --- a/test/Makefile +++ b/test/Makefile @@ -1,20 +1,23 @@ include config.mk build_os_arch := $(shell uname -s | tr -s "[A-Z]" "[a-z]")-$(shell uname -m) +jvm_arch := $(shell uname -m) +JAVA_HOME ?= $(shell dirname $$(dirname $$(readlink -f $$(which javac)))) +jvm_lib := $(firstword $(wildcard $(JAVA_HOME)/lib/server/libjvm.so $(JAVA_HOME)/jre/lib/amd64/server/libjvm.so)) android_api_major := $(firstword $(subst ., ,$(ANDROID_API_LEVEL))) android_platform := $(if $(wildcard $(ANDROID_SDK_ROOT)/platforms/android-$(ANDROID_API_LEVEL)/android.jar),android-$(ANDROID_API_LEVEL),$(notdir $(lastword $(sort $(wildcard $(ANDROID_SDK_ROOT)/platforms/android-$(ANDROID_API_LEVEL).*))))) android_platform := $(if $(android_platform),$(android_platform),android-$(ANDROID_API_LEVEL)) android_sysroot := $(ANDROID_NDK_ROOT)/platforms/android-$(android_api_major)/arch-$(ANDROID_ARCH) -deploy_prefix := /data/local/tmp -deploy_data_dir := $(deploy_prefix)/frida-java-bridge-tests -deploy_cache_dir := $(deploy_data_dir)/dalvik-cache +android_deploy_prefix := /data/local/tmp +android_deploy_data_dir := $(android_deploy_prefix)/frida-java-bridge-tests +android_deploy_cache_dir := $(android_deploy_data_dir)/dalvik-cache frida_version := 17.26.3 -test_sources := $(wildcard re/frida/*.java) -test_classes := $(patsubst %.java,%.class,$(test_sources)) +android_test_sources := $(wildcard re/frida/*.java) +jvm_test_sources := $(filter-out re/frida/ClassCreationTest.java re/frida/PerformTest.java,$(android_test_sources)) bridge_sources := bundle.js ../index.js $(wildcard ../lib/*.js) android_jar := $(ANDROID_SDK_ROOT)/platforms/$(android_platform)/android.jar @@ -22,57 +25,76 @@ android_jar := $(ANDROID_SDK_ROOT)/platforms/$(android_platform)/android.jar android_deploy_files := \ build/$(ANDROID_ABI)/runner \ build/$(ANDROID_ABI)/libartpalette.so \ - build/tests.dex \ + build/tests-android.dex \ build/frida-java-bridge.js all: - @echo "Available targets: deploy run" + @echo "Available targets: build-android deploy-android run-android watch-android debug-android build-jvm run-jvm watch-jvm debug-jvm" clean: rm -rf build -deploy: $(android_deploy_files) - adb shell "mkdir -p $(deploy_data_dir) $(deploy_cache_dir)" - adb push --sync $(android_deploy_files) $(deploy_data_dir)/ +build-android: $(android_deploy_files) -run: +deploy-android: build-android + adb shell "mkdir -p $(android_deploy_data_dir) $(android_deploy_cache_dir)" + adb push --sync $(android_deploy_files) $(android_deploy_data_dir)/ + +run-android: @since=$$(adb shell 'date "+%m-%d %H:%M:%S.000"' | tr -d '\r'); \ - adb shell "LD_PRELOAD=$(ANDROID_VM) LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(deploy_data_dir)' $(deploy_data_dir)/runner $(RUNNER_ARGS)" || { \ + adb shell "LD_PRELOAD=$(ANDROID_VM) LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(android_deploy_data_dir)' $(android_deploy_data_dir)/runner $(RUNNER_ARGS)" || { \ status=$$?; \ adb logcat -d -T "$$since" -b crash || true; \ adb logcat -d -T "$$since" -b main *:W || true; \ exit $$status; \ } -watch: +watch-android: npm run watch & ./node_modules/.bin/chokidar \ build/frida-java-bridge.js \ - -c "adb push --sync build/frida-java-bridge.js $(deploy_data_dir)/ \ - && adb shell \"LD_PRELOAD=$(ANDROID_VM) LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(deploy_data_dir)' $(deploy_data_dir)/runner $(RUNNER_ARGS)\"" + -c "adb push --sync build/frida-java-bridge.js $(android_deploy_data_dir)/ \ + && adb shell \"LD_PRELOAD=$(ANDROID_VM) LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(android_deploy_data_dir)' $(android_deploy_data_dir)/runner $(RUNNER_ARGS)\"" -debug: build/gdb.setup - adb shell "rm -f $(deploy_data_dir)/debug-socket" - adb push $(ANDROID_NDK_ROOT)/prebuilt/android-$(ANDROID_ARCH)/gdbserver/gdbserver $(deploy_data_dir) - adb shell "$(deploy_data_dir)/gdbserver +$(deploy_data_dir)/debug-socket $(deploy_data_dir)/runner $(RUNNER_ARGS)" & +debug-android: build/gdb-android.setup + adb shell "rm -f $(android_deploy_data_dir)/debug-socket" + adb push $(ANDROID_NDK_ROOT)/prebuilt/android-$(ANDROID_ARCH)/gdbserver/gdbserver $(android_deploy_data_dir) + adb shell "$(android_deploy_data_dir)/gdbserver +$(android_deploy_data_dir)/debug-socket $(android_deploy_data_dir)/runner $(RUNNER_ARGS)" & sleep 1 - adb forward tcp:$(DEBUG_PORT) localfilesystem:$(deploy_data_dir)/debug-socket - $(ANDROID_NDK_ROOT)/prebuilt/$(build_os_arch)/bin/gdb -x build/gdb.setup + adb forward tcp:$(DEBUG_PORT) localfilesystem:$(android_deploy_data_dir)/debug-socket + $(ANDROID_NDK_ROOT)/prebuilt/$(build_os_arch)/bin/gdb -x build/gdb-android.setup + +build-jvm: build/jvm/runner build/tests-jvm.jar build/frida-java-bridge.js + +run-jvm: + @test -n "$(jvm_lib)" || { echo "Unable to locate libjvm.so under JAVA_HOME=$(JAVA_HOME)" >&2; exit 1; } + FRIDA_JAVA_TESTS_JVM_PATH="$(jvm_lib)" build/jvm/runner $(RUNNER_ARGS) + +watch-jvm: + @test -n "$(jvm_lib)" || { echo "Unable to locate libjvm.so under JAVA_HOME=$(JAVA_HOME)" >&2; exit 1; } + npm run watch & + ./node_modules/.bin/chokidar \ + build/frida-java-bridge.js \ + -c "FRIDA_JAVA_TESTS_JVM_PATH='$(jvm_lib)' build/jvm/runner $(RUNNER_ARGS)" + +debug-jvm: + @test -n "$(jvm_lib)" || { echo "Unable to locate libjvm.so under JAVA_HOME=$(JAVA_HOME)" >&2; exit 1; } + FRIDA_JAVA_TESTS_JVM_PATH="$(jvm_lib)" gdb --args build/jvm/runner $(RUNNER_ARGS) -build/gdb.setup: build/symbols.stamp +build/gdb-android.setup: build/android-symbols.stamp ( \ - echo "set sysroot $(abspath build/symbols/)"; \ + echo "set sysroot $(abspath build/android-symbols/)"; \ echo "directory $(android_sysroot)/usr/include"; \ echo "directory $(abspath .)"; \ echo "file $(abspath build/obj/local/$(ANDROID_ABI)/runner)"; \ echo "target remote :$(DEBUG_PORT)"; \ ) > $@ -build/symbols.stamp: - rm -rf build/symbols - mkdir -p build/symbols/$(ANDROID_BINDIR)/ build/symbols/$(ANDROID_LIBDIR)/ - adb pull -a $(ANDROID_BINDIR)/linker build/symbols/$(ANDROID_BINDIR)/ - adb pull -a $(shell adb shell "ls $(ANDROID_LIBDIR)/*.so") build/symbols/$(ANDROID_LIBDIR)/; \ +build/android-symbols.stamp: + rm -rf build/android-symbols + mkdir -p build/android-symbols/$(ANDROID_BINDIR)/ build/android-symbols/$(ANDROID_LIBDIR)/ + adb pull -a $(ANDROID_BINDIR)/linker build/android-symbols/$(ANDROID_BINDIR)/ + adb pull -a $(shell adb shell "ls $(ANDROID_LIBDIR)/*.so") build/android-symbols/$(ANDROID_LIBDIR)/; \ touch $@ build/$(ANDROID_ABI)/libartpalette.so: build/$(ANDROID_ABI)/runner @@ -84,8 +106,8 @@ build/$(ANDROID_ABI)/runner: runner.c artpalette.c build/obj/local/$(ANDROID_ABI NDK_APPLICATION_MK=$$(pwd)/Application.mk \ NDK_OUT=$$(pwd)/build/obj \ NDK_LIBS_OUT=$$(pwd)/build \ - FRIDA_JAVA_TESTS_DATA_DIR=$(deploy_data_dir) \ - FRIDA_JAVA_TESTS_CACHE_DIR=$(deploy_cache_dir) + FRIDA_JAVA_TESTS_DATA_DIR=$(android_deploy_data_dir) \ + FRIDA_JAVA_TESTS_CACHE_DIR=$(android_deploy_cache_dir) build/obj/local/$(ANDROID_ABI)/libfrida-gumjs.a: @mkdir -p $(@D) @@ -93,31 +115,67 @@ build/obj/local/$(ANDROID_ABI)/libfrida-gumjs.a: tar -xJf $@.tar.xz.tmp -C $(@D) rm -f $@.tar.xz.tmp -build/tests.dex: build/tests.jar +build/jvm/runner: runner.c build/jvm/frida-gumjs/libfrida-gumjs.a + @mkdir -p $(@D) + gcc -g -Wall -Werror -pthread \ + -I$(JAVA_HOME)/include \ + -I$(JAVA_HOME)/include/linux \ + -Ibuild/jvm/frida-gumjs \ + -DFRIDA_JAVA_TESTS_DATA_DIR=\"$(abspath build)\" \ + -DFRIDA_JAVA_TESTS_CACHE_DIR=\"$(abspath build)/jvm/cache\" \ + runner.c \ + build/jvm/frida-gumjs/libfrida-gumjs.a \ + -Wl,--no-as-needed -lstdc++ -Wl,--as-needed \ + -ldl -lm -lrt -lresolv -pthread \ + -o $@ + +build/jvm/frida-gumjs/libfrida-gumjs.a: + @mkdir -p $(@D) + curl -fsSL https://github.com/frida/frida/releases/download/$(frida_version)/frida-gumjs-devkit-$(frida_version)-linux-$(jvm_arch).tar.xz -o $@.tar.xz.tmp + tar -xJf $@.tar.xz.tmp -C $(@D) + rm -f $@.tar.xz.tmp + +build/tests-android.dex: build/tests-android.jar d8 \ - --output build/tests.zip \ + --output build/tests-android.zip \ --classpath $(android_jar) \ --min-api $(android_api_major) \ $< - cd build && unzip -o tests.zip classes.dex + cd build && unzip -o tests-android.zip classes.dex mv build/classes.dex $@ -build/tests.jar: $(test_sources) build/junit.jar build/hamcrest.jar - @rm -rf build/java/ - @mkdir -p build/java/ - cd build/java/ \ +build/tests-android.jar: $(android_test_sources) build/junit.jar build/hamcrest.jar + @rm -rf build/java-android/ + @mkdir -p build/java-android/ + cd build/java-android/ \ && jar xf ../junit.jar \ && jar xf ../hamcrest.jar javac \ - -cp .:build/java/:$(android_jar) \ + -cp .:build/java-android/:$(android_jar) \ -bootclasspath $(android_jar) \ -source 1.8 \ -target 1.8 \ -Xlint:deprecation \ -Xlint:unchecked \ - $(test_sources) \ - -d build/java/ - jar cfe $@ re.frida.tests.Runner -C build/java . + $(android_test_sources) \ + -d build/java-android/ + jar cf $@ -C build/java-android . + +build/tests-jvm.jar: $(jvm_test_sources) build/junit.jar build/hamcrest.jar + @rm -rf build/java-jvm/ + @mkdir -p build/java-jvm/ + cd build/java-jvm/ \ + && jar xf ../junit.jar \ + && jar xf ../hamcrest.jar + javac \ + -cp .:build/java-jvm/ \ + -source 1.8 \ + -target 1.8 \ + -Xlint:deprecation \ + -Xlint:unchecked \ + $(jvm_test_sources) \ + -d build/java-jvm/ + jar cf $@ -C build/java-jvm . build/junit.jar: @mkdir -p $(@D) @@ -135,4 +193,4 @@ build/frida-java-bridge.js: node_modules $(bridge_sources) node_modules: package.json npm install -.PHONY: all clean deploy run watch debug +.PHONY: all clean build-android deploy-android run-android watch-android debug-android build-jvm run-jvm watch-jvm debug-jvm diff --git a/test/re/frida/ClassRegistryTest.java b/test/re/frida/ClassRegistryTest.java index 86ef175..a1c891b 100644 --- a/test/re/frida/ClassRegistryTest.java +++ b/test/re/frida/ClassRegistryTest.java @@ -26,7 +26,7 @@ public void loadedClassesCanBeEnumerated() { @Test public void classLoadersCanBeEnumerated() { - if (android.os.Build.VERSION.SDK_INT < 24) { + if (TestRunner.isAndroid() && TestRunner.getAndroidApiLevel() < 24) { return; } diff --git a/test/re/frida/MethodTest.java b/test/re/frida/MethodTest.java index 52bf65d..410b0b8 100644 --- a/test/re/frida/MethodTest.java +++ b/test/re/frida/MethodTest.java @@ -540,6 +540,10 @@ public void performNowWorks() { // Issue #271 @Test public void toStringOnOverloadedToString() { + if (!TestRunner.isAndroid()) { + return; + } + loadScript("const utf16 = Java.use('android.icu.text.UTF16');" + "send(utf16.toString());"); assertEquals("", script.getNextMessage()); diff --git a/test/re/frida/TestRunner.java b/test/re/frida/TestRunner.java index a95579e..c23aad2 100644 --- a/test/re/frida/TestRunner.java +++ b/test/re/frida/TestRunner.java @@ -27,16 +27,40 @@ public static void main(String[] args, String dataDir, String cacheDir, String[] classes = (args.length > 1) ? Arrays.copyOfRange(args, 1, args.length) - : new String[] { - "re.frida.ClassRegistryTest", - "re.frida.MethodTest", - "re.frida.ClassCreationTest", - "re.frida.ClassInitializerTest", - "re.frida.PerformTest" - }; + : isAndroid() + ? new String[] { + "re.frida.ClassRegistryTest", + "re.frida.MethodTest", + "re.frida.ClassCreationTest", + "re.frida.ClassInitializerTest", + "re.frida.PerformTest" + } + : new String[] { + "re.frida.ClassRegistryTest", + "re.frida.MethodTest", + "re.frida.ClassInitializerTest" + }; JUnitCore.main(classes); } + public static boolean isAndroid() { + try { + Class.forName("android.os.Build"); + return true; + } catch (ClassNotFoundException e) { + return false; + } + } + + public static int getAndroidApiLevel() { + try { + Class version = Class.forName("android.os.Build$VERSION"); + return version.getField("SDK_INT").getInt(null); + } catch (Exception e) { + return 0; + } + } + public static String getCacheDir() { return dataDir; } diff --git a/test/runner.c b/test/runner.c index e7f14ce..5185bce 100644 --- a/test/runner.c +++ b/test/runner.c @@ -2,22 +2,26 @@ #include #include #include -#include #include #include #if defined (__linux__) && defined (__LP64__) # include #endif -#include +#ifdef __ANDROID__ +# include +# include +#endif typedef struct _CreateScriptOperation CreateScriptOperation; typedef struct _DestroyScriptOperation DestroyScriptOperation; +#ifdef __ANDROID__ typedef struct _SigchainAction SigchainAction; +#endif struct _CreateScriptOperation { jweak wrapper; - const gchar * source_code; + gchar * source_code; gboolean done; GumScript * script; @@ -37,12 +41,14 @@ struct _DestroyScriptOperation GCond cond; }; +#ifdef __ANDROID__ struct _SigchainAction { bool (* sc_sigaction) (int, siginfo_t *, void *); sigset_t sc_mask; guint64 sc_flags; }; +#endif static void frida_java_init_vm (JavaVM ** vm, JNIEnv ** env, gboolean enable_optimizations); static void frida_java_register_test_runner_api (JNIEnv * env); @@ -56,6 +62,7 @@ static jlong re_frida_script_create (JNIEnv * env, jobject self, jstring source_ static gboolean create_script_on_js_thread (gpointer user_data); static void on_create_ready (GObject * source_object, GAsyncResult * result, gpointer user_data); static void on_load_ready (GObject * source_object, GAsyncResult * result, gpointer user_data); +static gboolean finish_create_script_on_js_thread (gpointer user_data); static void re_frida_script_destroy (JNIEnv * env, jobject self, jlong handle); static gboolean destroy_script_on_js_thread (gpointer user_data); static void on_unload_ready (GObject * source_object, GAsyncResult * result, gpointer user_data); @@ -63,16 +70,18 @@ static void re_frida_script_on_message (const gchar * message, GBytes * data, gp static void re_frida_badger_native_method (JNIEnv * env, jobject self, jstring str); -static void destroy_weak_ref (jweak ref); +static void destroy_weak_ref (gpointer data); #if defined (__linux__) && defined (__LP64__) static gpointer frida_java_allocate_memory (const GumAddressSpec * spec, gsize size, gsize alignment, GumPageProtection prot, gpointer user_data); #endif +#ifdef __ANDROID__ static guint get_system_api_level (void); static void on_special_signal (int signo, siginfo_t * info, void * context); +#endif static const JNINativeMethod re_frida_test_runner_methods[] = { @@ -98,11 +107,13 @@ static jobject re_frida_test_runner_class_loader; static jmethodID re_frida_script_on_message_method; -#define MAX_SPECIAL_HANDLERS 4 +#ifdef __ANDROID__ +# define MAX_SPECIAL_HANDLERS 4 static SigchainAction special_handlers[NSIG][MAX_SPECIAL_HANDLERS]; static guint special_handler_count[NSIG]; static struct sigaction previous_action[NSIG]; +#endif int main (int argc, char * argv[]) @@ -198,6 +209,8 @@ main (int argc, char * argv[]) return result; } +#ifdef __ANDROID__ + static void frida_java_init_vm (JavaVM ** vm, JNIEnv ** env, gboolean enable_optimizations) { @@ -235,7 +248,7 @@ frida_java_init_vm (JavaVM ** vm, JNIEnv ** env, gboolean enable_optimizations) options[1].optionString = "-verbose:gc"; options[2].optionString = "-Xcheck:jni"; options[3].optionString = "-Xdebug"; - options[4].optionString = "-Djava.class.path=" FRIDA_JAVA_TESTS_DATA_DIR "/tests.dex"; + options[4].optionString = "-Djava.class.path=" FRIDA_JAVA_TESTS_DATA_DIR "/tests-android.dex"; if (enable_optimizations) { @@ -275,6 +288,53 @@ frida_java_init_vm (JavaVM ** vm, JNIEnv ** env, gboolean enable_optimizations) } } +#else + +static void +frida_java_init_vm (JavaVM ** vm, JNIEnv ** env, gboolean enable_optimizations) +{ + const gchar * jvm_path; + void * vm_module; + jint (* create_java_vm) (JavaVM ** vm, void ** env, void * vm_args); + int n_options; + JavaVMOption * options; + JavaVMInitArgs args; + jint result; + + jvm_path = getenv ("FRIDA_JAVA_TESTS_JVM_PATH"); + if (jvm_path == NULL) + jvm_path = "libjvm.so"; + + vm_module = dlopen (jvm_path, RTLD_LAZY | RTLD_GLOBAL); + if (vm_module == NULL) + { + g_printerr ("Unable to load VM: %s\n", dlerror ()); + exit (1); + } + + create_java_vm = dlsym (vm_module, "JNI_CreateJavaVM"); + g_assert (create_java_vm != NULL); + + n_options = enable_optimizations ? 1 : 2; + options = g_new0 (JavaVMOption, n_options); + + options[0].optionString = "-Djava.class.path=" FRIDA_JAVA_TESTS_DATA_DIR "/tests-jvm.jar"; + if (!enable_optimizations) + options[1].optionString = "-Xint"; + + args.version = JNI_VERSION_1_8; + args.nOptions = n_options; + args.options = options; + args.ignoreUnrecognized = JNI_TRUE; + + result = create_java_vm (vm, (void **) env, &args); + g_assert_cmpint (result, ==, JNI_OK); + + g_free (options); +} + +#endif + static void frida_java_register_test_runner_api (JNIEnv * env) { @@ -334,7 +394,11 @@ frida_java_get_env (void) { g_assert_cmpint (result, ==, JNI_EDETACHED); +#ifdef __ANDROID__ result = (*java_vm)->AttachCurrentThread (java_vm, &env, NULL); +#else + result = (*java_vm)->AttachCurrentThread (java_vm, (void **) &env, NULL); +#endif g_assert_cmpint (result, ==, JNI_OK); } @@ -351,10 +415,15 @@ static jlong re_frida_script_create (JNIEnv * env, jobject self, jstring source_code) { CreateScriptOperation op; + const jchar * chars; + jsize length; GSource * idle_source; op.wrapper = (*env)->NewWeakGlobalRef (env, self); - op.source_code = (*env)->GetStringUTFChars (env, source_code, NULL); + chars = (*env)->GetStringChars (env, source_code, NULL); + length = (*env)->GetStringLength (env, source_code); + op.source_code = g_utf16_to_utf8 (chars, length, NULL, NULL, NULL); + (*env)->ReleaseStringChars (env, source_code, chars); op.done = FALSE; op.script = NULL; @@ -376,7 +445,7 @@ re_frida_script_create (JNIEnv * env, jobject self, jstring source_code) g_cond_clear (&op.cond); g_mutex_clear (&op.lock); - (*env)->ReleaseStringUTFChars (env, source_code, op.source_code); + g_free (op.source_code); if (op.error != NULL) { @@ -431,10 +500,25 @@ static void on_load_ready (GObject * source_object, GAsyncResult * result, gpointer user_data) { CreateScriptOperation * op = user_data; + GSource * idle_source; gum_script_load_finish (op->script, result); + idle_source = g_idle_source_new (); + g_source_set_priority (idle_source, G_PRIORITY_LOW); + g_source_set_callback (idle_source, finish_create_script_on_js_thread, op, NULL); + g_source_attach (idle_source, js_context); + g_source_unref (idle_source); +} + +static gboolean +finish_create_script_on_js_thread (gpointer user_data) +{ + CreateScriptOperation * op = user_data; + create_script_operation_notify_complete (op); + + return FALSE; } static void @@ -583,8 +667,9 @@ re_frida_badger_native_method (JNIEnv * env, jobject self, jstring str) } static void -destroy_weak_ref (jweak ref) +destroy_weak_ref (gpointer data) { + jweak ref = data; JNIEnv * env; env = frida_java_get_env (); @@ -660,6 +745,8 @@ frida_java_allocate_memory (const GumAddressSpec * spec, #endif +#ifdef __ANDROID__ + static guint get_system_api_level (void) { @@ -789,3 +876,5 @@ on_special_signal (int signo, siginfo_t * info, void * context) sigaction (signo, &prev, NULL); } + +#endif From 0fb4298f137458664b34fb3974e2776283953826 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 20:36:13 +0600 Subject: [PATCH 14/14] ci: Modernize workflows and add job timeouts 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. --- .github/workflows/linting.yml | 12 ++++++++---- .github/workflows/tests.yml | 16 +++++++++------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/.github/workflows/linting.yml b/.github/workflows/linting.yml index adc979e..26b5b15 100644 --- a/.github/workflows/linting.yml +++ b/.github/workflows/linting.yml @@ -1,12 +1,16 @@ name: linting on: [push, pull_request] jobs: - eslint: + lint: runs-on: ubuntu-latest + timeout-minutes: 10 steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 with: - node-version: 18 + node-version: 22 + cache: npm - run: npm install - run: npm run lint + - run: node --check index.js lib/*.js + - run: npx --no-install tsc --noEmit --lib es2022 index.d.ts diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 68fa860..8364fd9 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -3,6 +3,7 @@ on: [push, pull_request] jobs: android: runs-on: ubuntu-latest + timeout-minutes: 30 strategy: fail-fast: false matrix: @@ -12,9 +13,9 @@ jobs: ANDROID_EMULATOR_WAIT_TIME_BEFORE_KILL: 200 steps: - name: Check out repo - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Cache test dependencies - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: | ~/.npm @@ -31,7 +32,7 @@ jobs: sudo udevadm control --reload-rules sudo udevadm trigger --name-match=kvm - name: AVD cache - uses: actions/cache@v4 + uses: actions/cache@v6 id: avd-cache with: path: | @@ -68,25 +69,26 @@ jobs: jvm: runs-on: ubuntu-latest + timeout-minutes: 15 strategy: fail-fast: false matrix: java: ['8', '11', '17'] steps: - name: Check out repo - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Set up JDK ${{ matrix.java }} - uses: actions/setup-java@v4 + uses: actions/setup-java@v6 with: distribution: temurin java-version: ${{ matrix.java }} - name: Set up Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@v7 with: node-version: 22 cache: npm - name: Cache test dependencies - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: | test/build/junit.jar