forked from rovo89/Xposed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
libxposed_dalvik.cpp
396 lines (327 loc) · 14 KB
/
libxposed_dalvik.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/**
* This file includes functions specific to the Dalvik runtime.
*/
#define LOG_TAG "Xposed"
#include "libxposed_dalvik.h"
#include "xposed_offsets.h"
#include <dlfcn.h>
namespace xposed {
////////////////////////////////////////////////////////////
// Forward declarations
////////////////////////////////////////////////////////////
bool initMemberOffsets(JNIEnv* env);
void prepareSubclassReplacement(jclass clazz);
void hookedMethodCallback(const u4* args, JValue* pResult, const Method* method, ::Thread* self);
void XposedBridge_invokeOriginalMethodNative(const u4* args, JValue* pResult, const Method* method, ::Thread* self);
////////////////////////////////////////////////////////////
// Variables
////////////////////////////////////////////////////////////
static Method* xposedHandleHookedMethod = NULL;
static ClassObject* objectArrayClass = NULL;
static size_t arrayContentsOffset = 0;
static void* PTR_gDvmJit = NULL;
////////////////////////////////////////////////////////////
// Library initialization
////////////////////////////////////////////////////////////
/** Called by Xposed's app_process replacement. */
bool xposedInitLib(xposed::XposedShared* shared) {
xposed = shared;
xposed->onVmCreated = &onVmCreated;
return true;
}
/** Called very early during VM startup. */
void onVmCreated(JNIEnv* env) {
if (!initMemberOffsets(env))
return;
jclass classMiuiResources = env->FindClass(CLASS_MIUI_RESOURCES);
if (classMiuiResources != NULL) {
ClassObject* clazz = (ClassObject*)dvmDecodeIndirectRef(dvmThreadSelf(), classMiuiResources);
if (dvmIsFinalClass(clazz)) {
ALOGD("Removing final flag for class '%s'", CLASS_MIUI_RESOURCES);
clazz->accessFlags &= ~ACC_FINAL;
}
}
env->ExceptionClear();
jclass classXTypedArray = env->FindClass(CLASS_XTYPED_ARRAY);
if (classXTypedArray == NULL) {
ALOGE("Error while loading XTypedArray class '%s':", CLASS_XTYPED_ARRAY);
dvmLogExceptionStackTrace();
env->ExceptionClear();
return;
}
prepareSubclassReplacement(classXTypedArray);
classXposedBridge = env->FindClass(CLASS_XPOSED_BRIDGE);
classXposedBridge = reinterpret_cast<jclass>(env->NewGlobalRef(classXposedBridge));
if (classXposedBridge == NULL) {
ALOGE("Error while loading Xposed class '%s':", CLASS_XPOSED_BRIDGE);
dvmLogExceptionStackTrace();
env->ExceptionClear();
return;
}
ALOGI("Found Xposed class '%s', now initializing", CLASS_XPOSED_BRIDGE);
if (register_natives_XposedBridge(env, classXposedBridge) != JNI_OK) {
ALOGE("Could not register natives for '%s'", CLASS_XPOSED_BRIDGE);
dvmLogExceptionStackTrace();
env->ExceptionClear();
return;
}
xposedLoadedSuccessfully = true;
}
bool initMemberOffsets(JNIEnv* env) {
PTR_gDvmJit = dlsym(RTLD_DEFAULT, "gDvmJit");
if (PTR_gDvmJit == NULL) {
offsetMode = MEMBER_OFFSET_MODE_NO_JIT;
} else {
offsetMode = MEMBER_OFFSET_MODE_WITH_JIT;
}
ALOGD("Using structure member offsets for mode %s", xposedOffsetModesDesc[offsetMode]);
MEMBER_OFFSET_COPY(DvmJitGlobals, codeCacheFull);
int overrideCodeCacheFull = readIntConfig(XPOSED_OVERRIDE_JIT_RESET_OFFSET, -1);
if (overrideCodeCacheFull > 0 && overrideCodeCacheFull < 0x400) {
ALOGI("Offset for DvmJitGlobals.codeCacheFull is overridden, new value is 0x%x", overrideCodeCacheFull);
MEMBER_OFFSET_VAR(DvmJitGlobals, codeCacheFull) = overrideCodeCacheFull;
}
// detect offset of ArrayObject->contents
jintArray dummyArray = env->NewIntArray(1);
if (dummyArray == NULL) {
ALOGE("Could allocate int array for testing");
dvmLogExceptionStackTrace();
env->ExceptionClear();
return false;
}
jint* dummyArrayElements = env->GetIntArrayElements(dummyArray, NULL);
arrayContentsOffset = (size_t)dummyArrayElements - (size_t)dvmDecodeIndirectRef(dvmThreadSelf(), dummyArray);
env->ReleaseIntArrayElements(dummyArray,dummyArrayElements, 0);
env->DeleteLocalRef(dummyArray);
if (arrayContentsOffset < 12 || arrayContentsOffset > 128) {
ALOGE("Detected strange offset %d of ArrayObject->contents", arrayContentsOffset);
return false;
}
return true;
}
////////////////////////////////////////////////////////////
// Utility methods
////////////////////////////////////////////////////////////
/** Portable clone of dvmSetObjectArrayElement() */
inline void setObjectArrayElement(const ArrayObject* obj, int index, Object* val) {
uintptr_t arrayContents = (uintptr_t)obj + arrayContentsOffset;
((Object **)arrayContents)[index] = val;
dvmWriteBarrierArray(obj, index, index + 1);
}
/** Lay the foundations for XposedBridge.setObjectClassNative() */
void prepareSubclassReplacement(jclass clazz) {
// clazz is supposed to replace its superclass, so make sure enough memory is allocated
ClassObject* sub = (ClassObject*) dvmDecodeIndirectRef(dvmThreadSelf(), clazz);
ClassObject* super = sub->super;
super->objectSize = sub->objectSize;
}
/** Wrapper used by the common part of the library. */
void logExceptionStackTrace() {
dvmLogExceptionStackTrace();
}
/** Check whether a method is already hooked. */
inline bool isMethodHooked(const Method* method) {
return (method->nativeFunc == &hookedMethodCallback);
}
////////////////////////////////////////////////////////////
// JNI methods
////////////////////////////////////////////////////////////
jboolean callback_XposedBridge_initNative(JNIEnv* env) {
xposedHandleHookedMethod = (Method*) env->GetStaticMethodID(classXposedBridge, "handleHookedMethod",
"(Ljava/lang/reflect/Member;ILjava/lang/Object;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;");
if (xposedHandleHookedMethod == NULL) {
ALOGE("ERROR: could not find method %s.handleHookedMethod(Member, int, Object, Object, Object[])", CLASS_XPOSED_BRIDGE);
dvmLogExceptionStackTrace();
env->ExceptionClear();
return false;
}
Method* xposedInvokeOriginalMethodNative = (Method*) env->GetStaticMethodID(classXposedBridge, "invokeOriginalMethodNative",
"(Ljava/lang/reflect/Member;I[Ljava/lang/Class;Ljava/lang/Class;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;");
if (xposedInvokeOriginalMethodNative == NULL) {
ALOGE("ERROR: could not find method %s.invokeOriginalMethodNative(Member, int, Class[], Class, Object, Object[])", CLASS_XPOSED_BRIDGE);
dvmLogExceptionStackTrace();
env->ExceptionClear();
return false;
}
dvmSetNativeFunc(xposedInvokeOriginalMethodNative, XposedBridge_invokeOriginalMethodNative, NULL);
objectArrayClass = dvmFindArrayClass("[Ljava/lang/Object;", NULL);
if (objectArrayClass == NULL) {
ALOGE("Error while loading Object[] class");
dvmLogExceptionStackTrace();
env->ExceptionClear();
return false;
}
return true;
}
/** This is called when a hooked method is executed. */
void hookedMethodCallback(const u4* args, JValue* pResult, const Method* method, ::Thread* self) {
if (!isMethodHooked(method)) {
dvmThrowNoSuchMethodError("Could not find Xposed original method - how did you even get here?");
return;
}
XposedHookInfo* hookInfo = (XposedHookInfo*) method->insns;
Method* original = (Method*) hookInfo;
Object* originalReflected = hookInfo->reflectedMethod;
Object* additionalInfo = hookInfo->additionalInfo;
// convert/box arguments
const char* desc = &method->shorty[1]; // [0] is the return type.
Object* thisObject = NULL;
size_t srcIndex = 0;
size_t dstIndex = 0;
// for non-static methods determine the "this" pointer
if (!dvmIsStaticMethod(original)) {
thisObject = (Object*) args[0];
srcIndex++;
}
ArrayObject* argsArray = dvmAllocArrayByClass(objectArrayClass, strlen(method->shorty) - 1, ALLOC_DEFAULT);
if (argsArray == NULL) {
return;
}
while (*desc != '\0') {
char descChar = *(desc++);
JValue value;
Object* obj;
switch (descChar) {
case 'Z':
case 'C':
case 'F':
case 'B':
case 'S':
case 'I':
value.i = args[srcIndex++];
obj = (Object*) dvmBoxPrimitive(value, dvmFindPrimitiveClass(descChar));
dvmReleaseTrackedAlloc(obj, self);
break;
case 'D':
case 'J':
value.j = dvmGetArgLong(args, srcIndex);
srcIndex += 2;
obj = (Object*) dvmBoxPrimitive(value, dvmFindPrimitiveClass(descChar));
dvmReleaseTrackedAlloc(obj, self);
break;
case '[':
case 'L':
obj = (Object*) args[srcIndex++];
break;
default:
ALOGE("Unknown method signature description character: %c", descChar);
obj = NULL;
srcIndex++;
}
setObjectArrayElement(argsArray, dstIndex++, obj);
}
// call the Java handler function
JValue result;
dvmCallMethod(self, xposedHandleHookedMethod, NULL, &result,
originalReflected, (int) original, additionalInfo, thisObject, argsArray);
dvmReleaseTrackedAlloc(argsArray, self);
// exceptions are thrown to the caller
if (dvmCheckException(self)) {
return;
}
// return result with proper type
ClassObject* returnType = dvmGetBoxedReturnType(method);
if (returnType->primitiveType == PRIM_VOID) {
// ignored
} else if (result.l == NULL) {
if (dvmIsPrimitiveClass(returnType)) {
dvmThrowNullPointerException("null result when primitive expected");
}
pResult->l = NULL;
} else {
if (!dvmUnboxPrimitive(result.l, returnType, pResult)) {
dvmThrowClassCastException(result.l->clazz, returnType);
}
}
}
void XposedBridge_hookMethodNative(JNIEnv* env, jclass clazz, jobject reflectedMethodIndirect,
jobject declaredClassIndirect, jint slot, jobject additionalInfoIndirect) {
// Usage errors?
if (declaredClassIndirect == NULL || reflectedMethodIndirect == NULL) {
dvmThrowIllegalArgumentException("method and declaredClass must not be null");
return;
}
// Find the internal representation of the method
ClassObject* declaredClass = (ClassObject*) dvmDecodeIndirectRef(dvmThreadSelf(), declaredClassIndirect);
Method* method = dvmSlotToMethod(declaredClass, slot);
if (method == NULL) {
dvmThrowNoSuchMethodError("Could not get internal representation for method");
return;
}
if (isMethodHooked(method)) {
// already hooked
return;
}
// Save a copy of the original method and other hook info
XposedHookInfo* hookInfo = (XposedHookInfo*) calloc(1, sizeof(XposedHookInfo));
memcpy(hookInfo, method, sizeof(hookInfo->originalMethodStruct));
hookInfo->reflectedMethod = dvmDecodeIndirectRef(dvmThreadSelf(), env->NewGlobalRef(reflectedMethodIndirect));
hookInfo->additionalInfo = dvmDecodeIndirectRef(dvmThreadSelf(), env->NewGlobalRef(additionalInfoIndirect));
// Replace method with our own code
SET_METHOD_FLAG(method, ACC_NATIVE);
method->nativeFunc = &hookedMethodCallback;
method->insns = (const u2*) hookInfo;
method->registersSize = method->insSize;
method->outsSize = 0;
if (PTR_gDvmJit != NULL) {
// reset JIT cache
char currentValue = *((char*)PTR_gDvmJit + MEMBER_OFFSET_VAR(DvmJitGlobals,codeCacheFull));
if (currentValue == 0 || currentValue == 1) {
MEMBER_VAL(PTR_gDvmJit, DvmJitGlobals, codeCacheFull) = true;
} else {
ALOGE("Unexpected current value for codeCacheFull: %d", currentValue);
}
}
}
/**
* Simplified copy of Method.invokeNative(), but calls the original (non-hooked) method
* and has no access checks. Used to call the real implementation of hooked methods.
*/
void XposedBridge_invokeOriginalMethodNative(const u4* args, JValue* pResult,
const Method* method, ::Thread* self) {
Method* meth = (Method*) args[1];
if (meth == NULL) {
meth = dvmGetMethodFromReflectObj((Object*) args[0]);
if (isMethodHooked(meth)) {
meth = (Method*) meth->insns;
}
}
ArrayObject* params = (ArrayObject*) args[2];
ClassObject* returnType = (ClassObject*) args[3];
Object* thisObject = (Object*) args[4]; // null for static methods
ArrayObject* argList = (ArrayObject*) args[5];
// invoke the method
pResult->l = dvmInvokeMethod(thisObject, meth, argList, params, returnType, true);
return;
}
void XposedBridge_setObjectClassNative(JNIEnv* env, jclass clazz, jobject objIndirect, jclass clzIndirect) {
Object* obj = (Object*) dvmDecodeIndirectRef(dvmThreadSelf(), objIndirect);
ClassObject* clz = (ClassObject*) dvmDecodeIndirectRef(dvmThreadSelf(), clzIndirect);
if (clz->status < CLASS_INITIALIZED && !dvmInitClass(clz)) {
ALOGE("Could not initialize class %s", clz->descriptor);
return;
}
obj->clazz = clz;
}
void XposedBridge_dumpObjectNative(JNIEnv* env, jclass clazz, jobject objIndirect) {
Object* obj = (Object*) dvmDecodeIndirectRef(dvmThreadSelf(), objIndirect);
dvmDumpObject(obj);
}
jobject XposedBridge_cloneToSubclassNative(JNIEnv* env, jclass clazz, jobject objIndirect, jclass clzIndirect) {
Object* obj = (Object*) dvmDecodeIndirectRef(dvmThreadSelf(), objIndirect);
ClassObject* clz = (ClassObject*) dvmDecodeIndirectRef(dvmThreadSelf(), clzIndirect);
jobject copyIndirect = env->AllocObject(clzIndirect);
if (copyIndirect == NULL)
return NULL;
Object* copy = (Object*) dvmDecodeIndirectRef(dvmThreadSelf(), copyIndirect);
size_t size = obj->clazz->objectSize;
size_t offset = sizeof(Object);
memcpy((char*)copy + offset, (char*)obj + offset, size - offset);
if (IS_CLASS_FLAG_SET(clz, CLASS_ISFINALIZABLE))
dvmSetFinalizable(copy);
return copyIndirect;
}
jint XposedBridge_getRuntime(JNIEnv* env, jclass clazz) {
return 1; // RUNTIME_DALVIK
}
} // namespace android