[实践] Android5.1.1源码 - 让某个APP以解释执行模式运行
@(Android研究)[Android5.1.1|APP解释执行]
前言
本文的实践修改了Android5.1.1的源码。
本文只简单的讲了一下原理。在“实践”一节讲了具体做法。
本文的内容涉及Art模式下dex加载的知识,想要详细了解这部分知识可以去看老罗的文章: Android运行时ART简要介绍和学习计划 Android运行时ART加载OAT文件的过程分析 Android运行时ART加载类和方法的过程分析Android运行时ART执行类方法的过程分析
本文的内容涉及zygote,如果不知道zygote是什么,或者好奇zygote如何启动,可以去看老罗的文章: Android系统进程Zygote启动过程的源代码分析
老罗的文章分析的是Android2.3的源码,所以下面提到的与zygote有关的函数在老罗的文章里面可能没有,如果想要对下面提到的与zygote有关的函数有一个简单的了解可以看我的文章:Android5.1.1源码 - zygote fork出的子进程如何权限降级
原理简介
怎么才能让方法解释执行
在函数ClassLinker::LinkCode中会链接dex中的方法代码,这个函数的定义在文件"art/runtime/class_linker.cc"中,下面是它的源码(这里只列出了与本文有关的部分):
void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method, const OatFile::OatClass* oat_class,
const DexFile& dex_file, uint32_t dex_method_index,
uint32_t method_index) {
......
bool enter_interpreter = NeedsInterpreter(...);
......
if (method->IsStatic() && !method->IsConstructor()) {
......
} else if (enter_interpreter) {
if (!method->IsNative()) {
// Set entry point from compiled code if there's no code or in interpreter only mode.
method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
......
} else {
......
}
} else {
......
}
......
}
在这个函数中调用了NeedsInterpreter函数判断当前方法是否要解释执行,如果返回值为true,即局部变量enter_interpreter被赋值为true,那么调用ArtMethod类中的SetEntryPointFromQuickCompiledCode函数并将GetQuickToInterpreterBridge()的返回值传入,GetQuickToInterpreterBridge()函数返回用于解释执行的函数的入口地址,这个入口函数解释执行dex中的方法。
那么现在来看看NeedsInterpreter函数,这个函数的定义在文件"art/runtime/class_linker.cc"中,下面是它的源码:
// Returns true if the method must run with interpreter, false otherwise.
static bool NeedsInterpreter(
......
// If interpreter mode is enabled, every method (except native and proxy) must
// be run with interpreter.
return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
!method->IsNative() && !method->IsProxyMethod();
}
当"Runtime::Current()->GetInstrumentation()->InterpretOnly()"返回true且不是本地方法和代理方法,那么这个函数就会返回true,否则返回false。
InterpretOnly函数是Instrumentation类的成员函数,它的函数定义在文件"art/runtime/instrumentation.h"中,下面是它的源码:
// Called by ArtMethod::Invoke to determine dispatch mechanism.
bool InterpretOnly() const {
return interpret_only_;
}
interpret_only_是类Instrumentation的成员变量,是布尔类型。可以发现InterpretOnly函数仅仅是将"interpret_only_"返回,如果将interpret_only_设置为true,那么根据上文分析,所有“非本地且非代理”方法都将被解释执行。
那么如何将interpret_only_设置为true哪,在Instrumentation类中有一个ForceInterpretOnly函数,下面是这个函数的源码:
void ForceInterpretOnly() {
interpret_only_ = true;
forced_interpret_only_ = true;
}
这个函数是Instrumentation类的公有成员函数,所以直接调用这个函数即可将interpret_only_设置为true。
这里有一个问题,将interpret_only_设置为true,那么“非本地且非代理”方法在链接代码时都将被设置成解释执行,那么会不会影响到其他的APP进程?不会,因为ClassLinker::LinkCode函数对方法的链接是在APP进程的内存中进行的,所以这个操作并不会影响到其他进程。
这里进行一个小节,当执行"Runtime::Current()->GetInstrumentation()->ForceInterpretOnly()"语句时,会把Instrumentation对象的interpret_only_成员变量设置为true。那么当方法是“非本地且非代理”方法时,NeedsInterpreter函数将返回true,那么在ClassLinker::LinkCode函数中会将这个方法设置为解释执行。
如果要将APP中所有方法都设置为解释执行,那么就需要在链接APP的dex中的方法代码之前执行"Runtime::Current()->GetInstrumentation()->ForceInterpretOnly()"语句。
调用ForceInterpretOnly函数的时机
我的办法是在EnableDebugFeatures函数中调用ForceInterpretOnly函数,在这一节中会先说明Android如何执行到EnableDebugFeatures函数,然后会说明在EnableDebugFeatures函数中调用ForceInterpretOnly函数的好处。
所有的Android应用进程都是zygote fork出来的,fork APP进程时的函数调用路径:
|- forkAndSpecialize - java方法
|- com_android_internal_os_Zygote_nativeForkAndSpecialize - native函数
|- ForkAndSpecializeCommon - native函数
调用完ForkAndSpecializeCommon函数后APP进程就被fork出来了。
ForkAndSpecializeCommon函数定义在文件"frameworks/base/core/jni/com_android_internal_os_Zygote.cpp"中,下面它的源码:
static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids, jint debug_flags, jobjectArray javaRlimits, jlong permittedCapabilities, jlong effectiveCapabilities, jint mount_external, jstring java_se_info, jstring java_se_name, bool is_system_server, jintArray fdsToClose, jstring instructionSet, jstring dataDir) {
......
pid_t pid = fork();
if (pid == 0) {
......
env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
is_system_server ? NULL : instructionSet);
......
} else if (pid > 0) {
// the parent process
}
return pid;
}
gCallPostForkChildHooks是一个全局变量,它在com_android_internal_os_Zygote.cpp文件的register_com_android_internal_os_Zygote函数中被初始化。
env->CallStaticVoidMethod(...)语句调用了Java方法"Zygote.callPostForkChildHooks"。
下面是Zygote.callPostForkChildHooks方法的源码,这个方法在文件"frameworks/base/core/java/com/android/internal/os/Zygote.java"中:
private static void callPostForkChildHooks(int debugFlags, String instructionSet) {
long startTime = SystemClock.elapsedRealtime();
VM_HOOKS.postForkChild(debugFlags, instructionSet);
checkTime(startTime, "Zygote.callPostForkChildHooks");
}
VM_HOOKS是Zygote类的成员变量,下面是它的定义:
private static final ZygoteHooks VM_HOOKS = new ZygoteHooks();
VM_HOOKS.postForkChild调用的就是ZygoteHooks类中的成员方法postForkChild,这个方法在文件"libcore/dalvik/src/main/java/dalvik/system/ZygoteHooks.java"中,下面是它的源码:
/** * Called by the zygote in the child process after every fork. The debug * flags from {@code debugFlags} are applied to the child process. The string * {@code instructionSet} determines whether to use a native bridge. */
public void postForkChild(int debugFlags, String instructionSet) {
nativePostForkChild(token, debugFlags, instructionSet);
}
这个方法中调用了native函数nativePostForkChild,nativePostForkChild函数的C层代码在文件"/home/sowuy/android/system/art/runtime/native/dalvik_system_ZygoteHooks.cc"中,下面是它的源码:
static void ZygoteHooks_nativePostForkChild(JNIEnv* env, jclass, jlong token, jint debug_flags,
jstring instruction_set) {
......
EnableDebugFeatures(debug_flags);
......
}
我将在EnableDebugFeatures函数中调用ForceInterpretOnly函数,原因有三点:
- EnableDebugFeatures函数参数接收的是一个标志,我可以设置一个新的标志位用来表示是否需要调用ForceInterpretOnly函数。
- 每次APP启动的时候都会执行EnableDebugFeatures函数。
- EnableDebugFeatures函数被调用的时机好,它运行在fork出的APP进程中,并且在链接APP的dex中的方法前被调用。
实践
修改Zygote.java中的代码
Zygote.java文件的位置是:frameworks/base/core/java/com/android/internal/os/Zygote.java,在Zygote类中添加一个成员变量:
public static final int DEBUG_ENABLE_INTERPRET = 1 << 31;
在Zygote类forkAndSpecialize方法的开始部分添加下面的代码:
if (<APP包名>.equals(niceName)) {
debugFlags |= DEBUG_ENABLE_INTERPRET;
}
修改dalvik_system_ZygoteHooks.cc中的代码
dalvik_system_ZygoteHooks.cc文件的位置是:art/runtime/native/dalvik_system_ZygoteHooks.cc,修改这个文件中的EnableDebugFeatures函数的代码。
向这个函数中添加下面的代码:
DEBUG_ENABLE_INTERPRET = 1 << 31,
if ((debug_flags & DEBUG_ENABLE_INTERPRET) != 0) {
Runtime::Current()->GetInstrumentation()->ForceInterpretOnly();
debug_flags &= ~DEBUG_ENABLE_INTERPRET;
}
下面是对这个函数修改后的完整代码:
static void EnableDebugFeatures(uint32_t debug_flags) {
// Must match values in dalvik.system.Zygote.
enum {
DEBUG_ENABLE_DEBUGGER = 1,
DEBUG_ENABLE_CHECKJNI = 1 << 1,
DEBUG_ENABLE_ASSERT = 1 << 2,
DEBUG_ENABLE_SAFEMODE = 1 << 3,
DEBUG_ENABLE_JNI_LOGGING = 1 << 4,
DEBUG_ENABLE_INTERPRET = 1 << 31,
};
if ((debug_flags & DEBUG_ENABLE_CHECKJNI) != 0) {
Runtime* runtime = Runtime::Current();
JavaVMExt* vm = runtime->GetJavaVM();
if (!vm->check_jni) {
LOG(INFO) << "Late-enabling -Xcheck:jni";
vm->SetCheckJniEnabled(true);
// There's only one thread running at this point, so only one JNIEnv to fix up.
Thread::Current()->GetJniEnv()->SetCheckJniEnabled(true);
} else {
LOG(INFO) << "Not late-enabling -Xcheck:jni (already on)";
}
debug_flags &= ~DEBUG_ENABLE_CHECKJNI;
}
if ((debug_flags & DEBUG_ENABLE_JNI_LOGGING) != 0) {
gLogVerbosity.third_party_jni = true;
debug_flags &= ~DEBUG_ENABLE_JNI_LOGGING;
}
Dbg::SetJdwpAllowed((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0);
if ((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0) {
EnableDebugger();
}
debug_flags &= ~DEBUG_ENABLE_DEBUGGER;
if ((debug_flags & DEBUG_ENABLE_SAFEMODE) != 0) {
// Ensure that any (secondary) oat files will be interpreted.
Runtime* runtime = Runtime::Current();
runtime->AddCompilerOption("--compiler-filter=interpret-only");
debug_flags &= ~DEBUG_ENABLE_SAFEMODE;
}
// This is for backwards compatibility with Dalvik.
debug_flags &= ~DEBUG_ENABLE_ASSERT;
if ((debug_flags & DEBUG_ENABLE_INTERPRET) != 0) {
Runtime::Current()->GetInstrumentation()->ForceInterpretOnly();
debug_flags &= ~DEBUG_ENABLE_INTERPRET;
}
if (debug_flags != 0) {
LOG(ERROR) << StringPrintf("Unknown bits set in debug_flags: %#x", debug_flags);
}
}