diff --git a/index.d.ts b/index.d.ts index d1ca82d..0cddf38 100644 --- a/index.d.ts +++ b/index.d.ts @@ -388,6 +388,20 @@ 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. 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. + */ + $clinit: Method; + /** * Eagerly deletes the underlying JNI global reference without having to * wait for the object to become unreachable and the JavaScript @@ -534,9 +548,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/android.js b/lib/android.js index 70b99f1..5a12dae 100644 --- a/lib/android.js +++ b/lib/android.js @@ -320,6 +320,7 @@ function _getApi () { _ZN3art3jni12JniIdManager14DecodeMethodIdEP10_jmethodID: ['art::jni::JniIdManager::DecodeMethodId', 'pointer', ['pointer', 'pointer']], _ZN3art3jni12JniIdManager13DecodeFieldIdEP9_jfieldID: ['art::jni::JniIdManager::DecodeFieldId', 'pointer', ['pointer', 'pointer']], _ZN3art11interpreter18GetNterpEntryPointEv: ['art::interpreter::GetNterpEntryPoint', 'pointer', []], + _ZN3art11interpreter28GetNterpWithClinitEntryPointEv: ['art::interpreter::GetNterpWithClinitEntryPoint', 'pointer', []], _ZN3art7Monitor17TranslateLocationEPNS_9ArtMethodEjPPKcPi: ['art::Monitor::TranslateLocation', 'void', ['pointer', 'uint32', 'pointer', 'pointer']] }, @@ -386,6 +387,7 @@ function _getApi () { '_ZN3art3jni12JniIdManager14DecodeMethodIdEP10_jmethodID', '_ZN3art3jni12JniIdManager13DecodeFieldIdEP9_jfieldID', '_ZN3art11interpreter18GetNterpEntryPointEv', + '_ZN3art11interpreter28GetNterpWithClinitEntryPointEv', '_ZN3art7Monitor17TranslateLocationEPNS_9ArtMethodEjPPKcPi' ]) } @@ -524,6 +526,9 @@ function _getApi () { } else { temporaryApi.artNterpEntryPoint = temporaryApi.find('ExecuteNterpImpl'); } + temporaryApi.artNterpWithClinitEntryPoint = + temporaryApi['art::interpreter::GetNterpWithClinitEntryPoint']?.() ?? + temporaryApi.find('ExecuteNterpWithClinitImpl'); artController = makeArtController(temporaryApi, vm); @@ -629,8 +634,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) { @@ -1840,16 +1847,37 @@ function notifyArtMethodHooked (method, vm) { } function makeArtController (api, vm) { + const apiLevel = getAndroidApiLevel(); const threadOffsets = getArtThreadSpec(vm).offset; const managedStackOffsets = getArtManagedStackSpec().offset; + const { artClassLinker } = api; + const removedHookFlags = (kAccFastInterpreterToInterpreterInvoke | kAccSingleImplementation | ((api.artNterpEntryPoint !== null) ? kAccNterpEntryPointFastPathFlag : 0)) >>> 0; + const cPtr = p => (p !== null) ? `((gpointer) (gsize) ${p}ULL)` : 'NULL'; + const nterpWithClinitEntryPoint = cPtr(api.artNterpWithClinitEntryPoint); + const quickToInterpreterBridge = cPtr(artClassLinker.quickToInterpreterBridgeTrampoline); + const quickGenericJniTrampoline = cPtr(artClassLinker.quickGenericJniTrampoline); + const quickResolutionTrampoline = cPtr(artClassLinker.quickResolutionTrampoline); + const artQuickToInterpreterBridge = cPtr(api.artQuickToInterpreterBridge); + const artQuickGenericJniTrampoline = cPtr(api.artQuickGenericJniTrampoline); + const artQuickResolutionTrampoline = cPtr(api.artQuickResolutionTrampoline); const code = ` #include +typedef struct _ResolutionTrampolineData ResolutionTrampolineData; + +struct _ResolutionTrampolineData +{ + gpointer thread; + gpointer * sp; +}; + extern GMutex lock; extern GHashTable * methods; extern GHashTable * replacements; +extern GHashTable * intercepted_codes; extern gpointer last_seen_art_method; +extern guint32 method_offsets[2]; extern gpointer get_oat_quick_method_header_impl (gpointer method, gpointer pc); @@ -1859,16 +1887,47 @@ init (void) g_mutex_init (&lock); methods = g_hash_table_new_full (NULL, NULL, NULL, NULL); replacements = g_hash_table_new_full (NULL, NULL, NULL, NULL); + intercepted_codes = g_hash_table_new_full (NULL, NULL, NULL, NULL); } void finalize (void) { + g_hash_table_unref (intercepted_codes); g_hash_table_unref (replacements); g_hash_table_unref (methods); g_mutex_clear (&lock); } +static gpointer +get_hooked_quick_entrypoint (gpointer method) +{ + guint32 access_flags = *((guint32 *) (method + method_offsets[1])); + return ((access_flags & ${kAccNative}) != 0) + ? ${quickGenericJniTrampoline} + : ${quickToInterpreterBridge}; +} + +static gpointer +resolve_hooked_quick_entrypoint (gpointer method, + gpointer code, + gpointer intercepted_code) +{ + if (${nterpWithClinitEntryPoint} != NULL && code == ${nterpWithClinitEntryPoint}) + return ${quickResolutionTrampoline}; + + if (code != ${quickResolutionTrampoline} && + code != ${artQuickResolutionTrampoline} && + code != ${quickToInterpreterBridge} && + code != ${artQuickToInterpreterBridge} && + code != ${quickGenericJniTrampoline} && + code != ${artQuickGenericJniTrampoline} && + (intercepted_code == NULL || code != intercepted_code)) + return get_hooked_quick_entrypoint (method); + + return code; +} + gboolean is_replacement_method (gpointer method) { @@ -1899,20 +1958,23 @@ get_replacement_method (gpointer original_method) void set_replacement_method (gpointer original_method, - gpointer replacement_method) + gpointer replacement_method, + gpointer intercepted_code) { g_mutex_lock (&lock); g_hash_table_insert (methods, original_method, replacement_method); g_hash_table_insert (replacements, replacement_method, original_method); + if (intercepted_code != NULL) + g_hash_table_insert (intercepted_codes, original_method, intercepted_code); + else + g_hash_table_remove (intercepted_codes, original_method); g_mutex_unlock (&lock); } void -synchronize_replacement_methods (guint quick_code_offset, - void * nterp_entrypoint, - void * quick_to_interpreter_bridge) +synchronize_replacement_methods (void) { GHashTableIter iter; gpointer hooked_method, replacement_method; @@ -1922,13 +1984,18 @@ synchronize_replacement_methods (guint quick_code_offset, g_hash_table_iter_init (&iter, methods); while (g_hash_table_iter_next (&iter, &hooked_method, &replacement_method)) { - void ** quick_code; + guint32 * access_flags = hooked_method + method_offsets[1]; + guint32 flags = *access_flags; + gpointer * quick_code = hooked_method + method_offsets[0]; + gpointer intercepted_code = g_hash_table_lookup (intercepted_codes, hooked_method); + gpointer updated_code; *((uint32_t *) replacement_method) = *((uint32_t *) hooked_method); + *access_flags = (flags & ~(${removedHookFlags} | (((flags & ${kAccNative}) == 0) ? ${kAccSkipAccessChecks} : 0))) | ${api.kAccCompileDontBother}; - quick_code = hooked_method + quick_code_offset; - if (*quick_code == nterp_entrypoint) - *quick_code = quick_to_interpreter_bridge; + updated_code = resolve_hooked_quick_entrypoint (hooked_method, *quick_code, intercepted_code); + if (updated_code != *quick_code) + *quick_code = updated_code; } g_mutex_unlock (&lock); @@ -1946,6 +2013,7 @@ delete_replacement_method (gpointer original_method) { g_hash_table_remove (methods, original_method); g_hash_table_remove (replacements, replacement_method); + g_hash_table_remove (intercepted_codes, original_method); } g_mutex_unlock (&lock); @@ -2002,8 +2070,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; @@ -2044,6 +2112,90 @@ on_art_method_pretty_method (GumInvocationContext * ic) last_seen_art_method = method; } +void +on_enter_art_quick_resolution_trampoline (GumInvocationContext * ic) +{ + ResolutionTrampolineData * data = GUM_IC_GET_INVOCATION_DATA (ic, ResolutionTrampolineData); + data->thread = gum_invocation_context_get_nth_argument (ic, 2); + data->sp = gum_invocation_context_get_nth_argument (ic, 3); +} + +void +on_leave_art_quick_resolution_trampoline (GumInvocationContext * ic) +{ + ResolutionTrampolineData * data = GUM_IC_GET_INVOCATION_DATA (ic, ResolutionTrampolineData); + gpointer thread = data->thread; + gpointer * sp = data->sp; + gpointer method; + + if (gum_invocation_context_get_return_value (ic) == NULL || sp == NULL) + return; + + method = ${(apiLevel <= 22) ? 'GSIZE_TO_POINTER (*((guint32 *) sp))' : '*sp'}; + if (method != NULL) + { + gboolean is_hooked; + gpointer intercepted_code = NULL; + + g_mutex_lock (&lock); + is_hooked = g_hash_table_contains (methods, method); + if (is_hooked) + intercepted_code = g_hash_table_lookup (intercepted_codes, method); + g_mutex_unlock (&lock); + + if (is_hooked) + { + gpointer * quick_code = method + method_offsets[0]; + gpointer updated_code; + + if (thread != NULL) + { + gpointer * top_quick_frame = thread + ${threadOffsets.managedStack} + ${managedStackOffsets.topQuickFrame}; + if (*top_quick_frame == sp) + *top_quick_frame = NULL; + } + + updated_code = resolve_hooked_quick_entrypoint (method, *quick_code, intercepted_code); + if (updated_code != *quick_code) + *quick_code = updated_code; + + gum_invocation_context_replace_return_value (ic, get_hooked_quick_entrypoint (method)); + } + } +} + +void +on_instrumentation_update_methods_code (GumInvocationContext * ic) +{ + gpointer method, new_code, updated_code; + gboolean is_hooked; + gpointer intercepted_code = NULL; + + method = gum_invocation_context_get_nth_argument (ic, 1); + if (method == NULL) + return; + + g_mutex_lock (&lock); + is_hooked = g_hash_table_contains (methods, method); + if (is_hooked) + intercepted_code = g_hash_table_lookup (intercepted_codes, method); + g_mutex_unlock (&lock); + + if (!is_hooked) + return; + + new_code = gum_invocation_context_get_nth_argument (ic, 2); + updated_code = resolve_hooked_quick_entrypoint (method, new_code, intercepted_code); + if (updated_code != new_code) + gum_invocation_context_replace_nth_argument (ic, 2, updated_code); +} + +void +on_synchronize_replacement_methods (GumInvocationContext * ic) +{ + synchronize_replacement_methods (); +} + void on_leave_gc_concurrent_copying_copying_phase (GumInvocationContext * ic) { @@ -2063,14 +2215,18 @@ on_leave_gc_concurrent_copying_copying_phase (GumInvocationContext * ic) const lockSize = 8; const methodsSize = pointerSize; const replacementsSize = pointerSize; + const interceptedCodesSize = pointerSize; const lastSeenArtMethodSize = pointerSize; + const methodOffsetsSize = 8; - const data = Memory.alloc(lockSize + methodsSize + replacementsSize + lastSeenArtMethodSize); + const data = Memory.alloc(lockSize + methodsSize + replacementsSize + interceptedCodesSize + lastSeenArtMethodSize + methodOffsetsSize); const lock = data; const methods = lock.add(lockSize); const replacements = methods.add(methodsSize); - const lastSeenArtMethod = replacements.add(replacementsSize); + const interceptedCodes = replacements.add(replacementsSize); + const lastSeenArtMethod = interceptedCodes.add(interceptedCodesSize); + const methodOffsets = lastSeenArtMethod.add(lastSeenArtMethodSize); const getOatQuickMethodHeaderImpl = api.find((pointerSize === 4) ? '_ZN3art9ArtMethod23GetOatQuickMethodHeaderEj' @@ -2080,7 +2236,9 @@ on_leave_gc_concurrent_copying_copying_phase (GumInvocationContext * ic) lock, methods, replacements, + intercepted_codes: interceptedCodes, last_seen_art_method: lastSeenArtMethod, + method_offsets: methodOffsets, get_oat_quick_method_header_impl: getOatQuickMethodHeaderImpl ?? ptr('0xdeadbeef') }); @@ -2088,11 +2246,12 @@ on_leave_gc_concurrent_copying_copying_phase (GumInvocationContext * ic) return { handle: cm, + methodOffsets, replacedMethods: { isReplacement: new NativeFunction(cm.is_replacement_method, 'bool', ['pointer'], fastOptions), get: new NativeFunction(cm.get_replacement_method, 'pointer', ['pointer'], fastOptions), - set: new NativeFunction(cm.set_replacement_method, 'void', ['pointer', 'pointer'], fastOptions), - synchronize: new NativeFunction(cm.synchronize_replacement_methods, 'void', ['uint', 'pointer', 'pointer'], fastOptions), + set: new NativeFunction(cm.set_replacement_method, 'void', ['pointer', 'pointer', 'pointer'], fastOptions), + synchronize: new NativeFunction(cm.synchronize_replacement_methods, 'void', [], fastOptions), delete: new NativeFunction(cm.delete_replacement_method, 'void', ['pointer'], fastOptions), translate: new NativeFunction(cm.translate_method, 'pointer', ['pointer'], fastOptions), findReplacementFromQuickCode: cm.find_replacement_method_from_quick_code @@ -2102,6 +2261,18 @@ on_leave_gc_concurrent_copying_copying_phase (GumInvocationContext * ic) Interpreter: { doCall: cm.on_interpreter_do_call }, + QuickTrampoline: { + resolution: { + onEnter: cm.on_enter_art_quick_resolution_trampoline, + onLeave: cm.on_leave_art_quick_resolution_trampoline + } + }, + Instrumentation: { + updateMethodsCode: cm.on_instrumentation_update_methods_code + }, + ClassLinker: { + synchronize: cm.on_synchronize_replacement_methods + }, ArtMethod: { getOatQuickMethodHeader: cm.on_art_method_get_oat_quick_method_header, prettyMethod: cm.on_art_method_pretty_method @@ -2124,10 +2295,43 @@ function ensureArtKnowsHowToHandleMethodInstrumentation (vm) { } taughtArtAboutMethodInstrumentation = true; + const { offset } = getArtMethodSpec(vm); + artController.methodOffsets.writeU32(offset.quickCode); + artController.methodOffsets.add(4).writeU32(offset.accessFlags); + instrumentArtQuickEntrypoints(vm); instrumentArtMethodInvocationFromInterpreter(); instrumentArtGarbageCollection(); - instrumentArtFixupStaticTrampolines(); + instrumentArtClassLifecycle(); +} + +function findArtQuickResolutionTrampolineImpl (api) { + const symbol = api.find('artQuickResolutionTrampoline'); + if (symbol !== null) { + return symbol; + } + + const stub = api.artQuickResolutionTrampoline; + const { base, size } = api.module; + const end = base.add(size); + const { arch } = Process; + const callMnemonic = (arch === 'arm64') ? 'bl' : (arch === 'arm') ? 'blx' : 'call'; + const isThumb = (arch === 'arm') && !stub.and(1).isNull(); + + return parseInstructionsAt(stub, insn => { + const { mnemonic, operands } = insn; + if ((mnemonic !== callMnemonic && !(arch === 'arm' && mnemonic === 'bl')) || + operands.length !== 1 || operands[0].type !== 'imm') { + return null; + } + + const target = ptr(operands[0].value); + if (target.equals(insn.next) || target.compare(base) < 0 || target.compare(end) >= 0) { + return null; + } + + return (arch === 'arm' && ((mnemonic === 'bl') ? isThumb : !isThumb)) ? target.or(1) : target; + }, { limit: 64 }); } function instrumentArtQuickEntrypoints (vm) { @@ -2136,10 +2340,16 @@ function instrumentArtQuickEntrypoints (vm) { // Entrypoints that dispatch method invocation from the quick ABI. const quickEntrypoints = [ api.artQuickGenericJniTrampoline, - api.artQuickToInterpreterBridge, - api.artQuickResolutionTrampoline + api.artQuickToInterpreterBridge ]; + const resolutionTrampoline = findArtQuickResolutionTrampolineImpl(api); + if (resolutionTrampoline !== null) { + Interceptor.attach(resolutionTrampoline, artController.hooks.QuickTrampoline.resolution); + } else { + quickEntrypoints.push(api.artQuickResolutionTrampoline); + } + quickEntrypoints.forEach(entrypoint => { Memory.protect(entrypoint, 32, 'rwx'); @@ -2188,13 +2398,75 @@ function instrumentArtGarbageCollection () { return; } - const { artNterpEntryPoint, artQuickToInterpreterBridge } = api; - const quickCodeOffset = getArtMethodSpec(api.vm).offset.quickCode; - Interceptor.attach(gc, { - onLeave () { - artController.replacedMethods.synchronize(quickCodeOffset, artNterpEntryPoint, artQuickToInterpreterBridge); + Interceptor.attach(gc, { onLeave: artController.hooks.ClassLinker.synchronize }); +} + +function instrumentArtClassLifecycle () { + const api = getApi(); + const { hooks } = artController; + const art = api.module; + const exports = art.enumerateExports(); + let symbols = null; + + const findFunctions = (prefixes, seen) => { + const isMatch = entry => !entry.address.isNull() && + (entry.type === 'function' || entry.type === 'unknown') && + !/\.(?:cold|part|isra|constprop)\b/.test(entry.name) && + prefixes.some(prefix => entry.name.startsWith(prefix)); + const addresses = []; + + const collect = entries => { + for (const entry of entries) { + if (!isMatch(entry)) { + continue; + } + const key = entry.address.toString(); + if (!seen.has(key)) { + seen.add(key); + addresses.push(entry.address); + } + } + }; + + collect(exports); + if (addresses.length === 0) { + if (symbols === null) { + symbols = art.enumerateSymbols(); + } + collect(symbols); } - }); + + return addresses; + }; + + const updateSeen = new Set(); + for (const prefixes of [ + [ + '_ZN3art15instrumentation15Instrumentation17UpdateMethodsCodeEPNS_9ArtMethodEPKv', + '_ZN3art15instrumentation15Instrumentation17UpdateMethodsCodeEPNS_6mirror9ArtMethodEPKv' + ], + [ + '_ZN3art15instrumentation15Instrumentation21UpdateMethodsCodeImplEPNS_9ArtMethodEPKv', + '_ZN3art15instrumentation15Instrumentation21UpdateMethodsCodeImplEPNS_6mirror9ArtMethodEPKv' + ] + ]) { + for (const address of findFunctions(prefixes, updateSeen)) { + Interceptor.attach(address, hooks.Instrumentation.updateMethodsCode); + } + } + + const syncSeen = new Set(); + for (const prefixes of [ + ['_ZN3art11ClassLinker11VerifyClassE'], + ['_ZN3art11ClassLinker15InitializeClassE'], + ['_ZN3art11ClassLinker22FixupStaticTrampolinesE'] + ]) { + for (const address of findFunctions(prefixes, syncSeen)) { + Interceptor.attach(address, { onLeave: hooks.ClassLinker.synchronize }); + } + } + + instrumentArtFixupStaticTrampolines(); } function instrumentArtFixupStaticTrampolines () { @@ -2215,11 +2487,7 @@ function instrumentArtFixupStaticTrampolines () { return; } - const { artNterpEntryPoint, artQuickToInterpreterBridge } = api; - const quickCodeOffset = getArtMethodSpec(api.vm).offset.quickCode; - Interceptor.attach(matches[0].address, function () { - artController.replacedMethods.synchronize(quickCodeOffset, artNterpEntryPoint, artQuickToInterpreterBridge); - }); + Interceptor.attach(matches[0].address, artController.hooks.ClassLinker.synchronize); return; } @@ -3749,7 +4017,7 @@ class ArtMethodMangler { } replace (impl, isInstanceMethod, argTypes, vm, api) { - const { kAccCompileDontBother, artNterpEntryPoint } = api; + const { kAccCompileDontBother, artNterpEntryPoint, artNterpWithClinitEntryPoint } = api; this.originalMethod = fetchArtMethod(this.methodId, vm); @@ -3790,29 +4058,64 @@ class ArtMethodMangler { // of ART's next-generation interpreter and use the quick stub instead. if (artNterpEntryPoint !== null && quickCode.equals(artNterpEntryPoint)) { patchArtMethod(hookedMethodId, { - quickCode: api.artQuickToInterpreterBridge + quickCode: api.artClassLinker.quickToInterpreterBridgeTrampoline + }, vm); + } else if (artNterpWithClinitEntryPoint !== null && quickCode.equals(artNterpWithClinitEntryPoint)) { + patchArtMethod(hookedMethodId, { + quickCode: api.artClassLinker.quickResolutionTrampoline }, vm); } + let interceptedQuickCode = NULL; if (!isArtQuickEntrypoint(quickCode)) { const interceptor = new ArtQuickCodeInterceptor(quickCode); interceptor.activate(vm); this.interceptor = interceptor; + interceptedQuickCode = quickCode; } - artController.replacedMethods.set(hookedMethodId, replacementMethodId); + artController.replacedMethods.set(hookedMethodId, replacementMethodId, interceptedQuickCode); notifyArtMethodHooked(hookedMethodId, vm); } revert (vm) { - const { hookedMethodId, interceptor } = this; - - patchArtMethod(hookedMethodId, this.originalMethod, vm); + const { hookedMethodId, interceptor, originalMethod } = this; artController.replacedMethods.delete(hookedMethodId); + const api = getApi(); + const { quickResolutionTrampoline } = api.artClassLinker; + const { artQuickResolutionTrampoline, artNterpEntryPoint, artNterpWithClinitEntryPoint } = api; + const originalQuickCode = originalMethod.quickCode; + const isPreInitTrampoline = address => address.equals(quickResolutionTrampoline) || + address.equals(artQuickResolutionTrampoline) || + (artNterpWithClinitEntryPoint !== null && address.equals(artNterpWithClinitEntryPoint)); + + let restored = originalMethod; + if (isPreInitTrampoline(originalQuickCode)) { + const currentMethod = fetchArtMethod(hookedMethodId, vm); + if (!isPreInitTrampoline(currentMethod.quickCode)) { + const quickCode = (artNterpWithClinitEntryPoint !== null && + originalQuickCode.equals(artNterpWithClinitEntryPoint) && + artNterpEntryPoint !== null) + ? artNterpEntryPoint + : currentMethod.quickCode; + const accessFlags = (artNterpEntryPoint !== null && !quickCode.equals(artNterpEntryPoint)) + ? (originalMethod.accessFlags & ~kAccNterpEntryPointFastPathFlag) >>> 0 + : originalMethod.accessFlags; + restored = { + ...originalMethod, + jniCode: currentMethod.jniCode, + accessFlags, + quickCode + }; + } + } + + patchArtMethod(hookedMethodId, restored, vm); + if (interceptor !== null) { interceptor.deactivate(); diff --git a/lib/class-factory.js b/lib/class-factory.js index 29c0dd0..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'; @@ -18,9 +22,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 +240,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() }, @@ -282,8 +295,6 @@ export default class ClassFactory { try { const classHandle = h.value; - ensureClassInitialized(env, classHandle); - proto.$l = ClassModel.build(classHandle, env); } finally { h.unref(env); @@ -914,6 +925,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 () { @@ -1279,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); @@ -1287,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; @@ -1334,45 +1389,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) { @@ -1641,12 +1689,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; @@ -1791,6 +1840,9 @@ methodPrototype = Object.create(Function.prototype, { } else { borrowedHandle = receiver.$borrowClassHandle(env); jniThis = borrowedHandle.value; + if (type === STATIC_METHOD) { + ensureClassInitialized(env, jniThis); + } } let methodId; @@ -2106,6 +2158,7 @@ Object.defineProperties(Field.prototype, { } else { borrowedHandle = holder.$borrowClassHandle(env); jniThis = borrowedHandle.value; + ensureClassInitialized(env, jniThis); } const jniRetval = getValue(env.handle, jniThis, id); @@ -2137,6 +2190,7 @@ Object.defineProperties(Field.prototype, { } else { borrowedHandle = holder.$borrowClassHandle(env); jniThis = borrowedHandle.value; + ensureClassInitialized(env, jniThis); } if (!rtype.isCompatible(value)) { diff --git a/lib/class-model.js b/lib/class-model.js index 28b68b0..358f794 100644 --- a/lib/class-model.js +++ b/lib/class-model.js @@ -53,6 +53,8 @@ typedef void (* ArtPrettyMethodFunc) (StdString * result, ArtMethod * method, jb struct _Model { + jmethodID class_initializer; + GArray * constructors; GHashTable * members; }; @@ -68,6 +70,7 @@ struct _EnumerateMethodsContext struct _JavaClassApi { + jmethodID get_declared_constructors; jmethodID get_declared_methods; jmethodID get_declared_fields; }; @@ -236,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]; @@ -254,8 +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) { @@ -280,9 +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); - model_add_method (model, name, method, modifiers); + 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); } @@ -325,11 +335,18 @@ 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; + if ((access_flags & kAccConstructor) != 0) + { + if (is_static) + model->class_initializer = id; + else + g_array_append_val (model->constructors, 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); @@ -383,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++) @@ -489,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); @@ -508,6 +542,41 @@ 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_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) { @@ -619,7 +688,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; @@ -630,6 +699,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); @@ -640,14 +710,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 @@ -662,14 +730,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; } @@ -839,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) - goto skip_method; - } + if (strcmp (method_name, "") == 0) + method_name = "$clinit"; + else if (strcmp (method_name, "") == 0) + method_name = "$init"; if (include_signature) { @@ -1303,6 +1362,20 @@ 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; + } + + 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 { @@ -1328,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; @@ -1339,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 ] @@ -1409,6 +1482,8 @@ 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), + 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), diff --git a/lib/env.js b/lib/env.js index b8a5a7d..3076dc2 100644 --- a/lib/env.js +++ b/lib/env.js @@ -214,6 +214,29 @@ Env.prototype.findClass = proxy(6, 'pointer', ['pointer', 'pointer'], function ( return result; }); +Env.prototype.findClassWithoutInitializing = function (name, loader) { + const Class = this.javaLangClass(); + const nameValue = this.newStringUtf(name.replace(/\//g, '.')); + try { + const handle = this.staticVaMethod('pointer', ['pointer', 'int', 'pointer'])( + this.handle, Class.handle, Class.forName, nameValue, 0, loader); + this.throwIfExceptionPending(); + + try { + const methods = this.vaMethod('pointer', [])(this.handle, handle, Class.getDeclaredMethods); + this.throwIfExceptionPending(); + this.deleteLocalRef(methods); + } catch (e) { + this.deleteLocalRef(handle); + throw e; + } + + return handle; + } finally { + this.deleteLocalRef(nameValue); + } +}; + Env.prototype.throwIfExceptionPending = function () { const throwable = this.exceptionOccurred(); if (throwable.isNull()) { @@ -659,6 +682,8 @@ Env.prototype.javaLangClass = function () { const get = this.getMethodId.bind(this, handle); javaLangClass = { handle: register(this.newGlobalRef(handle)), + forName: this.getStaticMethodId(handle, 'forName', + '(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;'), getName: get('getName', '()Ljava/lang/String;'), getSimpleName: get('getSimpleName', '()Ljava/lang/String;'), getGenericSuperclass: get('getGenericSuperclass', '()Ljava/lang/reflect/Type;'), @@ -677,6 +702,24 @@ Env.prototype.javaLangClass = function () { return javaLangClass; }; +let systemClassLoader = null; +Env.prototype.systemClassLoader = function () { + if (systemClassLoader === null) { + const handle = this.findClass('java/lang/ClassLoader'); + try { + const getSystemClassLoader = this.getStaticMethodId(handle, 'getSystemClassLoader', + '()Ljava/lang/ClassLoader;'); + const loader = this.staticVaMethod('pointer', [])(this.handle, handle, getSystemClassLoader); + this.throwIfExceptionPending(); + systemClassLoader = register(this.newGlobalRef(loader)); + this.deleteLocalRef(loader); + } finally { + this.deleteLocalRef(handle); + } + } + return systemClassLoader; +}; + let javaLangObject = null; Env.prototype.javaLangObject = function () { if (javaLangObject === null) { diff --git a/lib/jvm.js b/lib/jvm.js index 0319cdb..69a5679 100644 --- a/lib/jvm.js +++ b/lib/jvm.js @@ -10,6 +10,7 @@ import VM from './vm.js'; const jsizeSize = 4; const { pointerSize } = Process; +const jvmtiFrameInfoSize = 16; const JVM_ACC_NATIVE = 0x0100; const JVM_ACC_IS_OLD = 0x00010000; @@ -427,6 +428,42 @@ function parseX64ThreadOffset (insn) { } export function ensureClassInitialized (env, classRef) { + const method = env.getMethodId(classRef, 'hashCode', '()I'); + if (method.isNull()) { + env.exceptionClear(); + } +} + +export function findClassWithoutInitializing (env, name) { + const loader = getCallerClassLoader(env); + try { + return env.findClassWithoutInitializing(name, (loader !== null) ? loader : env.systemClassLoader()); + } finally { + if (loader !== null && !loader.isNull()) { + env.deleteLocalRef(loader); + } + } +} + +function getCallerClassLoader (env) { + const { jvmti } = getApi(); + + const frames = Memory.alloc(jvmtiFrameInfoSize); + const numFrames = Memory.alloc(jsizeSize); + jvmti.getStackTrace(NULL, 0, 1, frames, numFrames); + if (numFrames.readS32() === 0) { + return null; + } + + const result = Memory.alloc(pointerSize); + jvmti.getMethodDeclaringClass(frames.readPointer(), result); + const klass = result.readPointer(); + try { + jvmti.getClassLoader(klass, result); + return result.readPointer(); + } finally { + env.deleteLocalRef(klass); + } } class JvmMethodMangler { diff --git a/lib/jvmti.js b/lib/jvmti.js index bcae1a8..d96b7cc 100644 --- a/lib/jvmti.js +++ b/lib/jvmti.js @@ -24,11 +24,26 @@ EnvJvmti.prototype.deallocate = proxy(47, 'int32', ['pointer', 'pointer'], funct return impl(this.handle, mem); }); +EnvJvmti.prototype.getClassLoader = proxy(57, 'int32', ['pointer', 'pointer', 'pointer'], function (impl, klass, classLoaderPtr) { + const result = impl(this.handle, klass, classLoaderPtr); + checkJniResult('EnvJvmti::getClassLoader', result); +}); + +EnvJvmti.prototype.getMethodDeclaringClass = proxy(65, 'int32', ['pointer', 'pointer', 'pointer'], function (impl, method, declaringClassPtr) { + const result = impl(this.handle, method, declaringClassPtr); + checkJniResult('EnvJvmti::getMethodDeclaringClass', result); +}); + EnvJvmti.prototype.getLoadedClasses = proxy(78, 'int32', ['pointer', 'pointer', 'pointer'], function (impl, classCountPtr, classesPtr) { const result = impl(this.handle, classCountPtr, classesPtr); checkJniResult('EnvJvmti::getLoadedClasses', result); }); +EnvJvmti.prototype.getStackTrace = proxy(104, 'int32', ['pointer', 'pointer', 'int', 'int', 'pointer', 'pointer'], function (impl, thread, startDepth, maxFrameCount, frameBuffer, countPtr) { + const result = impl(this.handle, thread, startDepth, maxFrameCount, frameBuffer, countPtr); + checkJniResult('EnvJvmti::getStackTrace', result); +}); + EnvJvmti.prototype.iterateOverInstancesOfClass = proxy(112, 'int32', ['pointer', 'pointer', 'int', 'pointer', 'pointer'], function (impl, klass, objectFilter, heapObjectCallback, userData) { const result = impl(this.handle, klass, objectFilter, heapObjectCallback, userData); checkJniResult('EnvJvmti::iterateOverInstancesOfClass', result); 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" ); }