forked from rovo89/Xposed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xposed.cpp
557 lines (460 loc) · 20.2 KB
/
xposed.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
/*
* Xposed enables "god mode" for developers
*/
#define LOG_TAG "Xposed"
#include "xposed.h"
#include <utils/Log.h>
#include <android_runtime/AndroidRuntime.h>
#define private public
#if PLATFORM_SDK_VERSION == 15
#include <utils/ResourceTypes.h>
#else
#include <androidfw/ResourceTypes.h>
#endif
#undef private
#include <stdio.h>
#include <sys/mman.h>
#include <cutils/properties.h>
#include <dlfcn.h>
#include "xposed_offsets.h"
namespace android {
////////////////////////////////////////////////////////////
// variables
////////////////////////////////////////////////////////////
bool keepLoadingXposed = false;
jclass xposedClass = NULL;
jmethodID xposedHandleHookedMethod = NULL;
jclass xresourcesClass = NULL;
jmethodID xresourcesTranslateResId = NULL;
jmethodID xresourcesTranslateAttrId = NULL;
std::list<MethodXposedExt> xposedOriginalMethods;
const char* startClassName = NULL;
void* PTR_gDvmJit = NULL;
////////////////////////////////////////////////////////////
// called directoy by app_process
////////////////////////////////////////////////////////////
void xposedInfo() {
char release[PROPERTY_VALUE_MAX];
char sdk[PROPERTY_VALUE_MAX];
char manufacturer[PROPERTY_VALUE_MAX];
char model[PROPERTY_VALUE_MAX];
char rom[PROPERTY_VALUE_MAX];
property_get("ro.build.version.release", release, "n/a");
property_get("ro.build.version.sdk", sdk, "n/a");
property_get("ro.product.manufacturer", manufacturer, "n/a");
property_get("ro.product.model", model, "n/a");
property_get("ro.build.display.id", rom, "n/a");
ALOGD("Starting Xposed binary version %s, compiled for SDK %d\n", XPOSED_VERSION, PLATFORM_SDK_VERSION);
ALOGD("Phone: %s (%s), Android version %s (SDK %s)\n", model, manufacturer, release, sdk);
ALOGD("ROM: %s\n", rom);
}
bool isXposedDisabled() {
// is the blocker file present?
if (access(XPOSED_LOAD_BLOCKER, F_OK) == 0) {
ALOGE("found %s, not loading Xposed\n", XPOSED_LOAD_BLOCKER);
return true;
}
return false;
}
// ignore the broadcasts by various Superuser implementations to avoid spamming the Xposed log
bool xposedShouldIgnoreCommand(const char* className, int argc, const char* const argv[]) {
if (className == NULL || argc < 4 || strcmp(className, "com.android.commands.am.Am") != 0)
return false;
if (strcmp(argv[2], "broadcast") != 0 && strcmp(argv[2], "start") != 0)
return false;
bool mightBeSuperuser = false;
for (int i = 3; i < argc; i++) {
if (strcmp(argv[i], "com.noshufou.android.su.RESULT") == 0
|| strcmp(argv[i], "eu.chainfire.supersu.NativeAccess") == 0)
return true;
if (mightBeSuperuser && strcmp(argv[i], "--user") == 0)
return true;
char* lastComponent = strrchr(argv[i], '.');
if (!lastComponent)
continue;
if (strcmp(lastComponent, ".RequestActivity") == 0
|| strcmp(lastComponent, ".NotifyActivity") == 0
|| strcmp(lastComponent, ".SuReceiver") == 0)
mightBeSuperuser = true;
}
return false;
}
bool addXposedToClasspath(bool zygote) {
ALOGI("-----------------\n");
// do we have a new version and are (re)starting zygote? Then load it!
if (zygote && access(XPOSED_JAR_NEWVERSION, R_OK) == 0) {
ALOGI("Found new Xposed jar version, activating it\n");
if (rename(XPOSED_JAR_NEWVERSION, XPOSED_JAR) != 0) {
ALOGE("could not move %s to %s\n", XPOSED_JAR_NEWVERSION, XPOSED_JAR);
return false;
}
}
if (access(XPOSED_JAR, R_OK) == 0) {
char* oldClassPath = getenv("CLASSPATH");
if (oldClassPath == NULL) {
setenv("CLASSPATH", XPOSED_JAR, 1);
} else {
char classPath[4096];
sprintf(classPath, "%s:%s", XPOSED_JAR, oldClassPath);
setenv("CLASSPATH", classPath, 1);
}
ALOGI("Added Xposed (%s) to CLASSPATH.\n", XPOSED_JAR);
return true;
} else {
ALOGE("ERROR: could not access Xposed jar '%s'\n", XPOSED_JAR);
return false;
}
}
bool xposedOnVmCreated(JNIEnv* env, const char* className) {
if (!keepLoadingXposed)
return false;
startClassName = className;
xposedInitMemberOffsets();
// disable some access checks
patchReturnTrue((void*) &dvmCheckClassAccess);
patchReturnTrue((void*) &dvmCheckFieldAccess);
patchReturnTrue((void*) &dvmInSamePackage);
if (access(XPOSED_DIR "do_not_hook_dvmCheckMethodAccess", F_OK) != 0)
patchReturnTrue((void*) &dvmCheckMethodAccess);
xposedClass = env->FindClass(XPOSED_CLASS);
xposedClass = reinterpret_cast<jclass>(env->NewGlobalRef(xposedClass));
if (xposedClass == NULL) {
ALOGE("Error while loading Xposed class '%s':\n", XPOSED_CLASS);
dvmLogExceptionStackTrace();
env->ExceptionClear();
return false;
}
ALOGI("Found Xposed class '%s', now initializing\n", XPOSED_CLASS);
register_de_robv_android_xposed_XposedBridge(env);
register_android_content_res_XResources(env);
return true;
}
static void xposedInitMemberOffsets() {
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(Thread, jniLocalRefTable);
MEMBER_OFFSET_COPY(Thread, status);
MEMBER_OFFSET_COPY(Thread, jniEnv);
MEMBER_OFFSET_COPY(DvmJitGlobals, codeCacheFull);
}
////////////////////////////////////////////////////////////
// handling hooked methods / helpers
////////////////////////////////////////////////////////////
static void xposedCallHandler(const u4* args, JValue* pResult, const Method* method, ::Thread* self) {
XposedOriginalMethodsIt original = findXposedOriginalMethod(method);
if (original == xposedOriginalMethods.end()) {
dvmThrowNoSuchMethodError("could not find Xposed original method - how did you even get here?");
return;
}
ThreadStatus oldThreadStatus = MEMBER_VAL(self, Thread, status);
JNIEnv* env = MEMBER_VAL(self, Thread, jniEnv);
// get java.lang.reflect.Method object for original method
jobject originalReflected = env->ToReflectedMethod(
(jclass)xposedAddLocalReference(self, original->clazz),
(jmethodID)method,
true);
// 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*) xposedAddLocalReference(self, (Object*)args[0]);
srcIndex++;
}
jclass objectClass = env->FindClass("java/lang/Object");
jobjectArray argsArray = env->NewObjectArray(strlen(method->shorty) - 1, objectClass, NULL);
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, NULL);
break;
case 'D':
case 'J':
value.j = dvmGetArgLong(args, srcIndex);
srcIndex += 2;
obj = (Object*) dvmBoxPrimitive(value, dvmFindPrimitiveClass(descChar));
dvmReleaseTrackedAlloc(obj, NULL);
break;
case '[':
case 'L':
obj = (Object*) args[srcIndex++];
break;
default:
ALOGE("Unknown method signature description character: %c\n", descChar);
obj = NULL;
srcIndex++;
}
env->SetObjectArrayElement(argsArray, dstIndex++, xposedAddLocalReference(self, obj));
}
// call the Java handler function
jobject resultRef = env->CallStaticObjectMethod(
xposedClass, xposedHandleHookedMethod, originalReflected, thisObject, argsArray);
// exceptions are thrown to the caller
if (env->ExceptionCheck()) {
dvmChangeStatus(self, oldThreadStatus);
return;
}
// return result with proper type
Object* result = dvmDecodeIndirectRef(self, resultRef);
ClassObject* returnType = dvmGetBoxedReturnType(method);
if (returnType->primitiveType == PRIM_VOID) {
// ignored
} else if (result == NULL) {
if (dvmIsPrimitiveClass(returnType)) {
dvmThrowNullPointerException("null result when primitive expected");
}
pResult->l = NULL;
} else {
if (!dvmUnboxPrimitive(result, returnType, pResult)) {
dvmThrowClassCastException(result->clazz, returnType);
}
}
// set the thread status back to running. must be done after the last env->...()
dvmChangeStatus(self, oldThreadStatus);
}
static XposedOriginalMethodsIt findXposedOriginalMethod(const Method* method) {
if (method == NULL)
return xposedOriginalMethods.end();
XposedOriginalMethodsIt it;
for (XposedOriginalMethodsIt it = xposedOriginalMethods.begin() ; it != xposedOriginalMethods.end(); it++ ) {
if (strcmp(it->name, method->name) == 0
&& strcmp(it->clazz->descriptor, method->clazz->descriptor) == 0
&& dexProtoCompare(&it->prototype, &method->prototype) == 0) {
return it;
}
}
return xposedOriginalMethods.end();
}
// work-around to get a reference wrapper to an object so that it can be used
// for certain calls to the JNI environment. almost verbatim copy from Jni.cpp
static jobject xposedAddLocalReference(::Thread* self, Object* obj) {
if (obj == NULL) {
return NULL;
}
IndirectRefTable* pRefTable = MEMBER_PTR(self, Thread, jniLocalRefTable);
void* curFrame = self->interpSave.curFrame;
u4 cookie = SAVEAREA_FROM_FP(curFrame)->xtra.localRefCookie;
jobject jobj = (jobject) pRefTable->add(cookie, obj);
if (UNLIKELY(jobj == NULL)) {
pRefTable->dump("JNI local");
ALOGE("Failed adding to JNI local ref table (has %zd entries)", pRefTable->capacity());
dvmDumpThread(self, false);
dvmAbort(); // spec says call FatalError; this is equivalent
}
if (UNLIKELY(gDvmJni.workAroundAppJniBugs)) {
// Hand out direct pointers to support broken old apps.
return reinterpret_cast<jobject>(obj);
}
return jobj;
}
static void replaceAsm(void* function, char* newCode, int len) {
#ifdef __arm__
function = (void*)((int)function & ~1);
#endif
void* pageStart = (void*)((int)function & ~(PAGESIZE-1));
mprotect(pageStart, PAGESIZE, PROT_READ | PROT_WRITE | PROT_EXEC);
memcpy(function, newCode, len);
mprotect(pageStart, PAGESIZE, PROT_READ | PROT_EXEC);
__clear_cache(function, (char*)function+len);
}
static void patchReturnTrue(void* function) {
#ifdef __arm__
char asmReturnTrueThumb[] = { 0x01, 0x20, 0x70, 0x47 };
char asmReturnTrueArm[] = { 0x01, 0x00, 0xA0, 0xE3, 0x1E, 0xFF, 0x2F, 0xE1 };
if ((int)function & 1)
replaceAsm(function, asmReturnTrueThumb, sizeof(asmReturnTrueThumb));
else
replaceAsm(function, asmReturnTrueArm, sizeof(asmReturnTrueArm));
#else
char asmReturnTrueX86[] = { 0x31, 0xC0, 0x40, 0xC3 };
replaceAsm(function, asmReturnTrueX86, sizeof(asmReturnTrueX86));
#endif
}
////////////////////////////////////////////////////////////
// JNI methods
////////////////////////////////////////////////////////////
static jboolean de_robv_android_xposed_XposedBridge_initNative(JNIEnv* env, jclass clazz) {
if (!keepLoadingXposed) {
ALOGE("Not initializing Xposed because of previous errors\n");
return false;
}
xposedHandleHookedMethod = env->GetStaticMethodID(xposedClass, "handleHookedMethod",
"(Ljava/lang/reflect/Member;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;");
if (xposedHandleHookedMethod == NULL) {
ALOGE("ERROR: could not find method %s.handleHookedMethod(Method, Object, Object[])\n", XPOSED_CLASS);
dvmLogExceptionStackTrace();
env->ExceptionClear();
keepLoadingXposed = false;
return false;
}
xresourcesClass = env->FindClass(XRESOURCES_CLASS);
xresourcesClass = reinterpret_cast<jclass>(env->NewGlobalRef(xresourcesClass));
if (xresourcesClass == NULL) {
ALOGE("Error while loading XResources class '%s':\n", XRESOURCES_CLASS);
dvmLogExceptionStackTrace();
env->ExceptionClear();
keepLoadingXposed = false;
return false;
}
xresourcesTranslateResId = env->GetStaticMethodID(xresourcesClass, "translateResId",
"(ILandroid/content/res/XResources;Landroid/content/res/Resources;)I");
if (xresourcesTranslateResId == NULL) {
ALOGE("ERROR: could not find method %s.translateResId(int, Resources, Resources)\n", XRESOURCES_CLASS);
dvmLogExceptionStackTrace();
env->ExceptionClear();
keepLoadingXposed = false;
return false;
}
xresourcesTranslateAttrId = env->GetStaticMethodID(xresourcesClass, "translateAttrId",
"(Ljava/lang/String;Landroid/content/res/XResources;)I");
if (xresourcesTranslateAttrId == NULL) {
ALOGE("ERROR: could not find method %s.findAttrId(String, Resources, Resources)\n", XRESOURCES_CLASS);
dvmLogExceptionStackTrace();
env->ExceptionClear();
keepLoadingXposed = false;
return false;
}
return true;
}
static void de_robv_android_xposed_XposedBridge_hookMethodNative(JNIEnv* env, jclass clazz, jobject declaredClassIndirect, jint slot) {
// Usage errors?
if (declaredClassIndirect == NULL) {
dvmThrowIllegalArgumentException("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 (findXposedOriginalMethod(method) != xposedOriginalMethods.end()) {
// already hooked
return;
}
// Save a copy of the original method
xposedOriginalMethods.push_front(*((MethodXposedExt*)method));
// Replace method with our own code
SET_METHOD_FLAG(method, ACC_NATIVE);
method->nativeFunc = &xposedCallHandler;
method->registersSize = method->insSize;
method->outsSize = 0;
if (PTR_gDvmJit != NULL) {
// reset JIT cache
MEMBER_VAL(PTR_gDvmJit, DvmJitGlobals, codeCacheFull) = true;
}
}
// simplified copy of Method.invokeNative, but calls the original (non-hooked) method and has no access checks
// used when a method has been hooked
static jobject de_robv_android_xposed_XposedBridge_invokeOriginalMethodNative(JNIEnv* env, jclass clazz, jobject reflectedMethod,
jobjectArray params1, jclass returnType1, jobject thisObject1, jobjectArray args1) {
// try to find the original method
Method* method = (Method*)env->FromReflectedMethod(reflectedMethod);
XposedOriginalMethodsIt original = findXposedOriginalMethod(method);
if (original != xposedOriginalMethods.end()) {
method = &(*original);
}
// dereference parameters
::Thread* self = dvmThreadSelf();
Object* thisObject = dvmDecodeIndirectRef(self, thisObject1);
ArrayObject* args = (ArrayObject*)dvmDecodeIndirectRef(self, args1);
ArrayObject* params = (ArrayObject*)dvmDecodeIndirectRef(self, params1);
ClassObject* returnType = (ClassObject*)dvmDecodeIndirectRef(self, returnType1);
// invoke the method
dvmChangeStatus(self, THREAD_RUNNING);
Object* result = dvmInvokeMethod(thisObject, method, args, params, returnType, true);
dvmChangeStatus(self, THREAD_NATIVE);
return xposedAddLocalReference(self, result);
}
static void android_content_res_XResources_rewriteXmlReferencesNative(JNIEnv* env, jclass clazz,
jint parserPtr, jobject origRes, jobject repRes) {
ResXMLParser* parser = (ResXMLParser*)parserPtr;
const ResXMLTree& mTree = parser->mTree;
uint32_t* mResIds = (uint32_t*)mTree.mResIds;
ResXMLTree_attrExt* tag;
int attrCount;
if (parser == NULL)
return;
do {
switch (parser->next()) {
case ResXMLParser::START_TAG:
tag = (ResXMLTree_attrExt*)parser->mCurExt;
attrCount = dtohs(tag->attributeCount);
for (int idx = 0; idx < attrCount; idx++) {
ResXMLTree_attribute* attr = (ResXMLTree_attribute*)
(((const uint8_t*)tag)
+ dtohs(tag->attributeStart)
+ (dtohs(tag->attributeSize)*idx));
// find resource IDs for attribute names
int32_t attrNameID = parser->getAttributeNameID(idx);
// only replace attribute name IDs for app packages
if (attrNameID >= 0 && (size_t)attrNameID < mTree.mNumResIds && dtohl(mResIds[attrNameID]) >= 0x7f000000) {
size_t attNameLen;
const char16_t* attrName = mTree.mStrings.stringAt(attrNameID, &attNameLen);
jint attrResID = env->CallStaticIntMethod(xresourcesClass, xresourcesTranslateAttrId,
env->NewString((const jchar*)attrName, attNameLen), origRes);
if (env->ExceptionCheck())
goto leave;
mResIds[attrNameID] = htodl(attrResID);
}
// find original resource IDs for reference values (app packages only)
if (attr->typedValue.dataType != Res_value::TYPE_REFERENCE)
continue;
jint oldValue = dtohl(attr->typedValue.data);
if (oldValue < 0x7f000000)
continue;
jint newValue = env->CallStaticIntMethod(xresourcesClass, xresourcesTranslateResId,
oldValue, origRes, repRes);
if (env->ExceptionCheck())
goto leave;
if (newValue != oldValue)
attr->typedValue.data = htodl(newValue);
}
continue;
case ResXMLParser::END_DOCUMENT:
case ResXMLParser::BAD_DOCUMENT:
goto leave;
default:
continue;
}
} while (true);
leave:
parser->restart();
}
static jobject de_robv_android_xposed_XposedBridge_getStartClassName(JNIEnv* env, jclass clazz) {
return env->NewStringUTF(startClassName);
}
static const JNINativeMethod xposedMethods[] = {
{"initNative", "()Z", (void*)de_robv_android_xposed_XposedBridge_initNative},
{"hookMethodNative", "(Ljava/lang/Class;I)V", (void*)de_robv_android_xposed_XposedBridge_hookMethodNative},
{"invokeOriginalMethodNative", "(Ljava/lang/reflect/Member;[Ljava/lang/Class;Ljava/lang/Class;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", (void*)de_robv_android_xposed_XposedBridge_invokeOriginalMethodNative},
{"getStartClassName", "()Ljava/lang/String;", (void*)de_robv_android_xposed_XposedBridge_getStartClassName},
};
static const JNINativeMethod xresourcesMethods[] = {
{"rewriteXmlReferencesNative", "(ILandroid/content/res/XResources;Landroid/content/res/Resources;)V", (void*)android_content_res_XResources_rewriteXmlReferencesNative},
};
static int register_de_robv_android_xposed_XposedBridge(JNIEnv* env) {
return AndroidRuntime::registerNativeMethods(env, XPOSED_CLASS, xposedMethods, NELEM(xposedMethods));
}
static int register_android_content_res_XResources(JNIEnv* env) {
return AndroidRuntime::registerNativeMethods(env, XRESOURCES_CLASS, xresourcesMethods, NELEM(xresourcesMethods));
}
}