资讯专栏INFORMATION COLUMN

Android Classloader

chemzqm / 805人阅读

摘要:和关于他们两个恩怨情仇,动态加载基础工作机制已经有说明。这边的传入参数可以看到,会先把做切割继续丢下去在中主要是构造对象,具体的依据就是传入的,即。观察这个函数的入参,对应的是路径,则是对应的释放文件地址。

前言

关于ClassLoader的介绍,可以参考之前提到的:
Android动态加载基础 ClassLoader工作机制
另外文章会提到,android中classloader都是采用了“双亲委派机制”,关于这一点可以参考:
Parents Delegation Model

</>复制代码

  1. 简单总结一下:
    对于android中的classloader是按照以下的flow:

  2. </>复制代码

    1. loadClass方法在加载一个类的实例的时候:
      会先查询当前ClassLoader实例是否加载过此类,有就返回;
      如果没有。查询Parent是否已经加载过此类,如果已经加载过,就直接返回Parent加载的类;
      如果继承路线上的ClassLoader都没有加载,才由Child执行类的加载工作;

  3. 这样做的好处:

  4. </>复制代码

    1. 首先是共享功能,一些Framework层级的类一旦被顶层的ClassLoader加载过就缓存在内存里面,以后任何地方用到都不需要重新加载。
      除此之外还有隔离功能,不同继承路线上的ClassLoader加载的类肯定不是同一个类,这样的限制避免了用户自己的代码冒充核心类库的类访问核心类库包可见成员的情况。这也好理解,一些系统层级的类会在系统初始化的时候被加载,比如java.lang.String,如果在一个应用里面能够简单地用自定义的String类把这个系统的String类给替换掉,那将会有严重的安全问题。

DexClassLoader和PathClassLoader

关于他们两个恩怨情仇,Android动态加载基础 ClassLoader工作机制 已经有说明。

</>复制代码

  1. 直接说结论:

  2. </>复制代码

    1. DexClassLoader可以加载jar/apk/dex,可以从SD卡中加载未安装的apk;
      PathClassLoader只能加载系统中已经安装过的apk;

通过源代码可以知道,DexClassLoader和PathClassLoader都是继承自BaseDexClassLoader

</>复制代码

  1. // DexClassLoader.java
  2. public class DexClassLoader extends BaseDexClassLoader {
  3. public DexClassLoader(String dexPath, String optimizedDirectory,
  4. String libraryPath, ClassLoader parent) {
  5. super(dexPath, new File(optimizedDirectory), libraryPath, parent);
  6. }
  7. }
  8. // PathClassLoader.java
  9. public class PathClassLoader extends BaseDexClassLoader {
  10. public PathClassLoader(String dexPath, ClassLoader parent) {
  11. super(dexPath, null, null, parent);
  12. }
  13. public PathClassLoader(String dexPath, String libraryPath,
  14. ClassLoader parent) {
  15. super(dexPath, null, libraryPath, parent);
  16. }
  17. }

这边以DexClassLoader为例,trace一下整个ClassLoader的初始化过程。
其中有两个问题比较重要:

dex文件如何被load进来,产生了class文件

dex文件与oat文件的转化

DexClassLoader

</>复制代码

  1. super(dexPath, new File(optimizedDirectory), libraryPath, parent);

这里的四个参数作用如下:

dexPath:dex文件的路径

new File(optimizedDirectory):解析出来的dex文件存放的路径

libraryPath:native library的存放路径

parent:父classloader

BaseDexClassLoader

继续看super类BaseDexClassLoader:

</>复制代码

  1. public BaseDexClassLoader(String dexPath, File optimizedDirectory,
  2. String libraryPath, ClassLoader parent) {
  3. super(parent);
  4. this.pathList = new DexPathList(this, dexPath, libraryPath, optimizedDirectory);
  5. }

其中super(parnent)会call到ClassLoader的构造函数:

</>复制代码

  1. protected ClassLoader(ClassLoader parentLoader) {
  2. this(parentLoader, false);
  3. }
  4. ClassLoader(ClassLoader parentLoader, boolean nullAllowed) {
  5. if (parentLoader == null && !nullAllowed) {
  6. throw new NullPointerException("parentLoader == null && !nullAllowed");
  7. }
  8. parent = parentLoader;
  9. }

这边只是简单赋了一下parent成员变量。

DexPathList

</>复制代码

  1. public DexPathList(ClassLoader definingContext, String dexPath,
  2. String libraryPath, File optimizedDirectory) {
  3. ......
  4. this.dexElements = makePathElements(splitDexPath(dexPath), optimizedDirectory,
  5. suppressedExceptions);
  6. ......
  7. }

这边的传入参数可以看到,会先把dexPath做切割继续丢下去

DexPathList.makePathElements

在makePathElements中主要是构造dexElements对象,具体的依据就是传入的files list,即dexPath。

</>复制代码

  1. private static Element[] makePathElements(List files, File optimizedDirectory,
  2. List suppressedExceptions) {
  3. List elements = new ArrayList<>();
  4. for (File file : files) {
  5. ......
  6. dex = loadDexFile(file, optimizedDirectory);
  7. ......
  8. elements.add(new Element(dir, false, zip, dex));
  9. ......
  10. }
  11. return elements.toArray(new Element[elements.size()]);
  12. }
DexPathList.loadDexFile

观察这个函数的入参,file对应的是dex路径,optimizedDirectory则是对应的释放dex文件地址。
简单来说,src:file,dst:optimizedDirectory

</>复制代码

  1. private static DexFile loadDexFile(File file, File optimizedDirectory)
  2. throws IOException {
  3. if (optimizedDirectory == null) {
  4. return new DexFile(file);
  5. } else {
  6. String optimizedPath = optimizedPathFor(file, optimizedDirectory);
  7. return DexFile.loadDex(file.getPath(), optimizedPath, 0);
  8. }
  9. }

这边遇到了一个optimizedPath,看看他是怎么来的(其实就是一个路径转换罢了):

</>复制代码

  1. private static String optimizedPathFor(File path,
  2. File optimizedDirectory) {
  3. ......
  4. File result = new File(optimizedDirectory, fileName);
  5. return result.getPath();
  6. }
DexFile.loadDex

静态方法,并没有什么特别的东西,其中会new DexFile:

</>复制代码

  1. static public DexFile loadDex(String sourcePathName, String outputPathName,
  2. int flags) throws IOException {
  3. return new DexFile(sourcePathName, outputPathName, flags);
  4. }
DexFile Construct

这里在刚开始的时候回做一个权限检测,如果当前的文件目录所有者跟当前进程的不一致,那就GG。
当然了,这一句不是重点,重点仍旧在后面:openDexFile

</>复制代码

  1. private DexFile(String sourceName, String outputName, int flags) throws IOException {
  2. if (outputName != null) {
  3. try {
  4. String parent = new File(outputName).getParent();
  5. if (Libcore.os.getuid() != Libcore.os.stat(parent).st_uid) {
  6. ...
  7. }
  8. } catch (ErrnoException ignored) {
  9. // assume we"ll fail with a more contextual error later
  10. }
  11. }
  12. mCookie = openDexFile(sourceName, outputName, flags);
  13. mFileName = sourceName;
  14. guard.open("close")
  15. }
DexFile.openDexFile

</>复制代码

  1. private static Object openDexFile(String sourceName, String outputName, int flags) throws IOException {
  2. // Use absolute paths to enable the use of relative paths when testing on host.
  3. return openDexFileNative(new File(sourceName).getAbsolutePath(),
  4. (outputName == null) ? null : new File(outputName).getAbsolutePath(),
  5. flags);
  6. }

code trace到这边,基本上java层就已经到底了。因为openDexFileNative会直接call到jni层了:

</>复制代码

  1. private static native Object openDexFileNative(String sourceName, String outputName, int flags);

再次来回顾一下这边的三个参数:

String sourceName:dex文件的所在地址

String outputName:释放dex文件的目标地址

int flags:0

JNI Native Register JNI Method

DexFile对应的jni函数在:art/runtime/native/dalvik_system_DexFile.cc

</>复制代码

  1. grep大法好!

</>复制代码

  1. static JNINativeMethod gMethods[] = {
  2. ......
  3. NATIVE_METHOD(DexFile, openDexFileNative,
  4. "(Ljava/lang/String;Ljava/lang/String;I)Ljava/lang/Object;"),
  5. };
  6. void register_dalvik_system_DexFile(JNIEnv* env) {
  7. REGISTER_NATIVE_METHODS("dalvik/system/DexFile");
  8. }
Macro的定义

可以看到,在这里有两个Macro,他们究竟是什么呢?

</>复制代码

  1. 庐山真面目在:art/runtime/jni_internal.h

</>复制代码

  1. #ifndef NATIVE_METHOD
  2. #define NATIVE_METHOD(className, functionName, signature)
  3. { #functionName, signature, reinterpret_cast(className ## _ ## functionName) }
  4. #endif
  5. #define REGISTER_NATIVE_METHODS(jni_class_name)
  6. RegisterNativeMethods(env, jni_class_name, gMethods, arraysize(gMethods))
JNINativeMethod

</>复制代码

  1. typedef struct {
  2. const char* name;
  3. const char* signature;
  4. void* fnPtr;
  5. } JNINativeMethod;
Macro合体

</>复制代码

  1. NATIVE_METHOD(DexFile, openDexFileNative,
  2. "(Ljava/lang/String;Ljava/lang/String;I)Ljava/lang/Object;"),

展开后

</>复制代码

  1. "openDexFileNative",
  2. "(Ljava/lang/String;Ljava/lang/String;I)Ljava/lang/Object;",
  3. reinterpret_cast DexFile_openDexFileNative,

很自然,就是对应了JNINativeMethod中的name,signature以及fnPtr。
因此对应native层的function : DexFile_openDexFileNative

DexFile_openDexFileNative

native层的代码用到了很多C++ STL库的相关知识,另外还有不少namespace的相关概念。
STL:C++:STL标准入门汇总,三十分钟掌握STL
namespace:详解C++中命名空间的意义和用法

</>复制代码

  1. static jobject DexFile_openDexFileNative(
  2. JNIEnv* env, jclass, jstring javaSourceName, jstring javaOutputName, jint) {
  3. ......
  4. ClassLinker* linker = Runtime::Current()->GetClassLinker();
  5. ......
  6. dex_files = linker->OpenDexFilesFromOat(sourceName.c_str(), outputName.c_str(), &error_msgs);
  7. ......
  8. }

ClassLinker是一个很重要的东西,它与art息息相关。简单来说它的创建是伴随着runtime init的时候起来的,可以认为是每个art & 进程会维护一个对象(具体代码还没有分析,只是从网上看了一篇文章)
这里我们暂时放下ClassLinker的创建初始化职责权限,先看看OpenDexFilesFromOat

ClassLinker::OpenDexFilesFromOat

这个函数非常大,其主要的几个动作如下:

构造OatFileAssistant对象:这个对象的主要作用是协助dex文件解析成oat文件

遍历ClassLinker的成员变量:oat_files_,目的是查看当前的dex文件是否已经被解析成oat了

如果当前dex已经被解析成了oat文件,那么就跳过dex的解析,直接进入3)

反之,如果当前dex文件并没有被解析过,那么就会走:oat_file_assistant.MakeUpToDate

填充dex_files对象并返回,这里也有两种情况(区分oat or dex):

oat_file_assistant.LoadDexFiles

DexFile::Open

其中我们需要关注的点其实只有两点(上文划出的重点)共两个函数:

oat_file_assistant.MakeUpToDate

oat_file_assistant.LoadDexFiles

</>复制代码

  1. std::vector> ClassLinker::OpenDexFilesFromOat(
  2. const char* dex_location, const char* oat_location,
  3. std::vector* error_msgs) {
  4. ......
  5. OatFileAssistant oat_file_assistant(dex_location, oat_location, kRuntimeISA,
  6. !Runtime::Current()->IsAotCompiler());
  7. ......
  8. const OatFile* source_oat_file = nullptr;
  9. ......
  10. for (const OatFile* oat_file : oat_files_) {
  11. CHECK(oat_file != nullptr);
  12. if (oat_file_assistant.GivenOatFileIsUpToDate(*oat_file)) {
  13. source_oat_file = oat_file;
  14. break;
  15. }
  16. }
  17. ......
  18. if (source_oat_file == nullptr) {
  19. if (!oat_file_assistant.MakeUpToDate(&error_msg)) {
  20. ......
  21. }
  22. // Get the oat file on disk.
  23. std::unique_ptr oat_file = oat_file_assistant.GetBestOatFile();
  24. if (oat_file.get() != nullptr) {
  25. ......
  26. if (!DexFile::MaybeDex(dex_location)) {
  27. accept_oat_file = true;
  28. ......
  29. }
  30. }
  31. if (accept_oat_file) {
  32. source_oat_file = oat_file.release();
  33. RegisterOatFile(source_oat_file);
  34. }
  35. }
  36. }
  37. std::vector> dex_files;
  38. ......
  39. if (source_oat_file != nullptr) {
  40. dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
  41. ......
  42. }
  43. // Fall back to running out of the original dex file if we couldn"t load any
  44. // dex_files from the oat file.
  45. if (dex_files.empty()) {
  46. ......
  47. if (!DexFile::Open(dex_location, dex_location, &error_msg, &dex_files)) {
  48. ......
  49. }
  50. return dex_files;
  51. }

下面的内容会牵扯到很多oat file的解析,这一块的内容有点庞大,我也理解的不是很透彻。
如果有兴趣的话可以先阅读一下《罗升阳:Android运行时ART加载OAT文件的过程分析》,其中对于oat file format会有进一步的了解

这一部分的知识对于理顺classloader的flow来说障碍不大,但是对于了解整个art的flow来说至关重要。

OatFileAssistant::MakeUpToDate

一出4岔口的switch分支,对于这边我们关注的是kDex2OatNeeded(可以认为是第一次加载,这样就省略掉很多细节)
另外千万不要小看GetDexOptNeeded(),在它内部会去读取dex文件,检查checksum

</>复制代码

  1. bool OatFileAssistant::MakeUpToDate(std::string* error_msg) {
  2. switch (GetDexOptNeeded()) {
  3. case kNoDexOptNeeded: return true;
  4. case kDex2OatNeeded: return GenerateOatFile(error_msg);
  5. case kPatchOatNeeded: return RelocateOatFile(OdexFileName(), error_msg);
  6. case kSelfPatchOatNeeded: return RelocateOatFile(OatFileName(), error_msg);
  7. }
  8. UNREACHABLE();
  9. }

由于我们这里是第一次load,所以就会进入到GenerateOatFile

OatFileAssistant::GenerateOatFile

可以看到这支函数的主要最用是call Dex2Oat,在最终call之前会去检查一下文件是否存在。

</>复制代码

  1. bool OatFileAssistant::GenerateOatFile(std::string* error_msg) {
  2. ......
  3. std::vector args;
  4. args.push_back("--dex-file=" + std::string(dex_location_));
  5. args.push_back("--oat-file=" + oat_file_name);
  6. ......
  7. if (!OS::FileExists(dex_location_)) {
  8. ......
  9. return false;
  10. }
  11. if (!Dex2Oat(args, error_msg)) {
  12. ......
  13. }
  14. ......
  15. return true;
  16. }
OatFileAssistant::Dex2Oat

argv是此处的关键,不光会传入dst,src等基本信息,还会有诸如debugger,classpath等信息

</>复制代码

  1. bool OatFileAssistant::Dex2Oat(const std::vector& args,
  2. std::string* error_msg) {
  3. ......
  4. std::vector argv;
  5. argv.push_back(runtime->GetCompilerExecutable());
  6. argv.push_back("--runtime-arg");
  7. ......
  8. return Exec(argv, error_msg);
  9. }

至于文末的Exec,则会来到art/runtime/utils.cc
bool Exec(std::vector& arg_vector, std::string* error_msg)

Exec

这个函数的重点是在fork,而fork之后会在子进程执行arg带入的第一个参数指定的那个可执行文件。
而在fork的父进程,则会继续监听子进程的运行状态并一直wait,所以对于上层来说..这边就是一个同步调用了。

</>复制代码

  1. bool Exec(std::vector& arg_vector, std::string* error_msg) {
  2. ......
  3. const char* program = arg_vector[0].c_str();
  4. ......
  5. pid_t pid = fork();
  6. if (pid == 0) {
  7. ......
  8. execv(program, &args[0]);
  9. ......
  10. } else {
  11. ......
  12. pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
  13. ......
  14. return true;
  15. }

再回头看一下argv的第一个参数:argv.push_back(runtime->GetCompilerExecutable());
所以..如果非debug状态下,我们用到可执行文件就是:/bin/dex2oat

</>复制代码

  1. std::string Runtime::GetCompilerExecutable() const {
  2. if (!compiler_executable_.empty()) {
  3. return compiler_executable_;
  4. }
  5. std::string compiler_executable(GetAndroidRoot());
  6. compiler_executable += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
  7. return compiler_executable;
  8. }

所以到这边,我们大致就了解了dex文件是如何转换到oat文件的,所以也就是回答了最早提出的问题2。
从Exec返回之后,我们还会继续去检查一下oat文件是否真的弄好了,如果一切正常,最后就会通过

</>复制代码

  1. RegisterOatFile(source_oat_file);

把对应的oat file加入到ClassLinker的成员变量:oat_files_,下次就不用继续执行dex2oat了。

OatFileAssistant::LoadDexFiles

对于这一段的flow我之前一直很不解,为什么之前要把dex转换成oat,这边看起来又要通过oat去获取dex?
其实简单来想这里应该是两种情况:

首先是通过dex拿到oat文件

构造dex structure给上层
所以光从字面意义来解释这个函数,就会让人进入一种误区,我们来看code:

</>复制代码

  1. std::vector> OatFileAssistant::LoadDexFiles(
  2. const OatFile& oat_file, const char* dex_location) {
  3. std::vector> dex_files;
  4. // Load the primary dex file.
  5. ......
  6. const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(
  7. dex_location, nullptr, false);
  8. ......
  9. std::unique_ptr dex_file = oat_dex_file->OpenDexFile(&error_msg);
  10. ......
  11. dex_files.push_back(std::move(dex_file));
  12. // Load secondary multidex files
  13. for (size_t i = 1; ; i++) {
  14. std::string secondary_dex_location = DexFile::GetMultiDexLocation(i, dex_location);
  15. oat_dex_file = oat_file.GetOatDexFile(secondary_dex_location.c_str(), nullptr, false);
  16. ......
  17. dex_file = oat_dex_file->OpenDexFile(&error_msg);
  18. ......
  19. }
  20. return dex_files;
  21. }

这里的实现看起来比较复杂,但其实就是:

分别load primary dex和secondary multidex

再通过OpenDexFile方法获得DexFile对象。

</>复制代码

  1. 因为对于oat文件来说,它可以是由多个dex产生的,详细的情况可以参考老罗的文章,比如boot.oat

所以,我们需要看看这边OpenDexFile到底做了什么:

</>复制代码

  1. std::unique_ptr OatFile::OatDexFile::OpenDexFile(std::string* error_msg) const {
  2. return DexFile::Open(dex_file_pointer_, FileSize(), dex_file_location_,
  3. dex_file_location_checksum_, this, error_msg);
  4. }

其中dex_file_pointer_是oat文件中dex数据的起始地址(DexFile Meta段)

DexFile::Open

上文提到的Open原型是:

</>复制代码

  1. static std::unique_ptr Open(const uint8_t* base, size_t size,
  2. const std::string& location,
  3. uint32_t location_checksum,
  4. const OatDexFile* oat_dex_file,
  5. std::string* error_msg) {
  6. return OpenMemory(base, size, location, location_checksum, nullptr, oat_dex_file, error_msg);
  7. }

继续trace一下:

</>复制代码

  1. std::unique_ptr DexFile::OpenMemory(const uint8_t* base,
  2. size_t size,
  3. const std::string& location,
  4. uint32_t location_checksum,
  5. MemMap* mem_map,
  6. const OatDexFile* oat_dex_file,
  7. std::string* error_msg) {
  8. CHECK_ALIGNED(base, 4); // various dex file structures must be word aligned
  9. std::unique_ptr dex_file(
  10. new DexFile(base, size, location, location_checksum, mem_map, oat_dex_file));
  11. if (!dex_file->Init(error_msg)) {
  12. dex_file.reset();
  13. }
  14. return std::unique_ptr(dex_file.release());
  15. }

最后看一下构造函数:

</>复制代码

  1. DexFile::DexFile(const uint8_t* base, size_t size,
  2. const std::string& location,
  3. uint32_t location_checksum,
  4. MemMap* mem_map,
  5. const OatDexFile* oat_dex_file)
  6. : begin_(base),
  7. size_(size),
  8. location_(location),
  9. location_checksum_(location_checksum),
  10. mem_map_(mem_map),
  11. header_(reinterpret_cast(base)),
  12. string_ids_(reinterpret_cast(base + header_->string_ids_off_)),
  13. type_ids_(reinterpret_cast(base + header_->type_ids_off_)),
  14. field_ids_(reinterpret_cast(base + header_->field_ids_off_)),
  15. method_ids_(reinterpret_cast(base + header_->method_ids_off_)),
  16. proto_ids_(reinterpret_cast(base + header_->proto_ids_off_)),
  17. class_defs_(reinterpret_cast(base + header_->class_defs_off_)),
  18. find_class_def_misses_(0),
  19. class_def_index_(nullptr),
  20. oat_dex_file_(oat_dex_file) {
  21. CHECK(begin_ != nullptr) << GetLocation();
  22. CHECK_GT(size_, 0U) << GetLocation();
  23. }

其实就是一些数据的填充,然后再打包传回到上层(java端),丢该DexFile的mCookie对象。
:)

写在最后

整个classloader的部分到这里就算走完了,但是对于android art 来说还是冰山一角。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65035.html

相关文章

  • Android逆向之路---脱壳360加固

    摘要:前言众所周知,现在软件在防止逆向采取了混淆,加壳等措施。这两天在逆向一款的时候找到了一个不错的插件推荐给大家,下载地址点我下载前提环境过的手机文件下载地址在上方自动脱壳安装完成之后,在里面软重启,激活。 前言 众所周知,现在软件在防止逆向采取了混淆,加壳等措施。比如360加固,腾讯加固,梆梆加固等等。这两天在逆向一款app的时候找到了一个不错的xposed插件推荐给大家, 下载地址:点...

    pkhope 评论0 收藏0

发表评论

0条评论

chemzqm

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<