Android中的ClassLoader
在Android中我们常用的ClassLoader有两种,PathClassLoader 和DexClassLoader
我们来看下继承层级
可以看到, PathClassLoader和DexClassLoader继承自BaseDexClassLoader
PathClassLoader 只能加载我们安装过的 apk,DexClassLoader 可以加载 sd 卡上的 apk,根据DexClassLoader的这个特性,RePlugin的插件化方案就是通过 Hook DexClassLoader 破坏其原本的双亲委派机制,并交由自己的ClassLoader(RePluginClassLoader)加载方案来实现的。
我们先来看DexClassLoader是如何加载sd卡上的apk的
DexClassLoader
public class DexClassLoader extends BaseDexClassLoader {
/**
* Creates a {@code DexClassLoader} that finds interpreted and native
* code. Interpreted classes are found in a set of DEX files contained
* in Jar or APK files.
*
* The path lists are separated using the character specified by the
* {@code path.separator} system property, which defaults to {@code :}.
*
* @param dexPath the list of jar/apk files containing classes and
* resources, delimited by {@code File.pathSeparator}, which
* defaults to {@code ":"} on Android
* @param optimizedDirectory this parameter is deprecated and has no effect since API level 26.
* @param librarySearchPath the list of directories containing native
* libraries, delimited by {@code File.pathSeparator}; may be
* {@code null}
* @param parent the parent class loader
*/
public DexClassLoader(String dexPath, String optimizedDirectory,
String librarySearchPath, ClassLoader parent) {
super(dexPath, null, librarySearchPath, parent);
}
}
DexClassLoader里面仅仅只有一个构造方法,(其他代码一概没有), 父类BaseDexClassLoader已经实现了所有代码
这里说下这些参数都是
- dex文件的路径(多个,默认以:隔开)
- null 这个参数原本的作用是传一个用来缓存optimizedDirectory,重点说下这个参数吧, 我们先来看源码对该参数给到的注释
optimizedDirectory this parameter is deprecated and has no effect since API level 26.
可以知道, 该参数在26API被废弃了, 从源码开头的注释得知, 该参数原本是提供一个application-private
,writable
的目录, 用来缓存我们优化过后的class文件,这里第一个问题, API26废弃了这个参数, 那么我们class文件还会被缓存吗 - 本地库的路径(多个),
- 父加载器
针对2, 我们再来看看PathClassLoader的源码
public class PathClassLoader extends BaseDexClassLoader {
...
public PathClassLoader(String dexPath, String librarySearchPath, ClassLoader parent) {
super(dexPath, null, librarySearchPath, parent);
}
...
}
(省略了两个构造器代码,有兴趣可以翻翻源码)
和DexClassLoader没区别(单从这个构造函数来讲)
好了, 我们接下来看BaseDexClassLoader
BaseDexClassLoader
@UnsupportedAppUsage
public BaseDexClassLoader(String dexPath, File optimizedDirectory,
String librarySearchPath, ClassLoader parent, boolean isTrusted) {
this(dexPath, librarySearchPath, parent, null, isTrusted);
}
BaseDexClassLoader, 他的所有构造函数,都指向这个构造函数
public BaseDexClassLoader(String dexPath,
String librarySearchPath, ClassLoader parent, ClassLoader[] sharedLibraryLoaders,
boolean isTrusted) {
super(parent);
// Setup shared libraries before creating the path list. ART relies on the class loader
// hierarchy being finalized before loading dex files.
this.sharedLibraryLoaders = sharedLibraryLoaders == null
? null
: Arrays.copyOf(sharedLibraryLoaders, sharedLibraryLoaders.length);
this.pathList = new DexPathList(this, dexPath, librarySearchPath, null, isTrusted);
if (reporter != null) {
reportClassLoaderChain();
}
}
重点看DexPathList
DexPathList
先说DexPathList是干啥的, 源码注释说, 他关联了一个ClassLoader, 就是我们new的时候传进去的那个, 并且存放了很多''资源", 具体可以翻看源码注释
这里列下他的属性成员
/** class definition context */
@UnsupportedAppUsage
private final ClassLoader definingContext;
/**
* List of dex/resource (class path) elements.
* Should be called pathElements, but the Facebook app uses reflection
* to modify 'dexElements' (http://b/7726934).
*/
@UnsupportedAppUsage
private Element[] dexElements;
/** List of native library path elements. */
// Some applications rely on this field being an array or we'd use a final list here
@UnsupportedAppUsage
/* package visible for testing */
NativeLibraryElement[] nativeLibraryPathElements;
/** List of application native library directories. */
@UnsupportedAppUsage
private final List nativeLibraryDirectories;
/** List of system native library directories. */
@UnsupportedAppUsage
private final List systemNativeLibraryDirectories;
/**
* Exceptions thrown during creation of the dexElements list.
*/
@UnsupportedAppUsage
private IOException[] dexElementsSuppressedExceptions;
找到BaseDexClassLoader调用的DexPathList构造方法
DexPathList(ClassLoader definingContext, String dexPath,
String librarySearchPath, File optimizedDirectory, boolean isTrusted) {
//忽略部分判空代码,
...
this.definingContext = definingContext;
ArrayList suppressedExceptions = new ArrayList();
// save dexPath for BaseDexClassLoader
this.dexElements = makeDexElements(splitDexPath(dexPath), optimizedDirectory,
suppressedExceptions, definingContext, isTrusted);
//忽略部分与参数无关的代码
...
if (suppressedExceptions.size() > 0) {
this.dexElementsSuppressedExceptions =
suppressedExceptions.toArray(new IOException[suppressedExceptions.size()]);
} else {
dexElementsSuppressedExceptions = null;
}
}
这里我们只关注makeDexElements这个方法, 比较有意思的是传了个异常列表进去,将出现的异常保存到了dexElementsSuppressedExceptions里面
接下来我们去看下源码对dexElements的解释,并去看下makeDexElements()的源码
private static Element[] makeDexElements(List files, File optimizedDirectory,
List suppressedExceptions, ClassLoader loader, boolean isTrusted) {
Element[] elements = new Element[files.size()];
int elementsPos = 0;
/*
* Open all files and load the (direct or contained) dex files up front.
*/
for (File file : files) {
if (file.isDirectory()) {
// We support directories for looking up resources. Looking up resources in
// directories is useful for running libcore tests.
elements[elementsPos++] = new Element(file);
} else if (file.isFile()) {
String name = file.getName();
DexFile dex = null;
if (name.endsWith(DEX_SUFFIX)) {
// Raw dex file (not inside a zip/jar).
try {
dex = loadDexFile(file, optimizedDirectory, loader, elements);
if (dex != null) {
elements[elementsPos++] = new Element(dex, null);
}
} catch (IOException suppressed) {
System.logE("Unable to load dex file: " + file, suppressed);
suppressedExceptions.add(suppressed);
}
} else {
try {
dex = loadDexFile(file, optimizedDirectory, loader, elements);
} catch (IOException suppressed) {
/*
* IOException might get thrown "legitimately" by the DexFile constructor if
* the zip file turns out to be resource-only (that is, no classes.dex file
* in it).
* Let dex == null and hang on to the exception to add to the tea-leaves for
* when findClass returns null.
*/
suppressedExceptions.add(suppressed);
}
if (dex == null) {
elements[elementsPos++] = new Element(file);
} else {
elements[elementsPos++] = new Element(dex, file);
}
}
if (dex != null && isTrusted) {
dex.setTrusted();
}
} else {
System.logW("ClassLoader referenced unknown path: " + file);
}
}
if (elementsPos != elements.length) {
elements = Arrays.copyOf(elements, elementsPos);
}
return elements;
}
遍历所有dexPath, 生成DexFile loadDexFile()
存放到dexElmenet中,
我们去看下loadDexFile
/**
* Constructs a {@code DexFile} instance, as appropriate depending on whether
* {@code optimizedDirectory} is {@code null}. An application image file may be associated with
* the {@code loader} if it is not null.
*/
@UnsupportedAppUsage
private static DexFile loadDexFile(File file, File optimizedDirectory, ClassLoader loader,
Element[] elements)
throws IOException {
if (optimizedDirectory == null) {
return new DexFile(file, loader, elements);
} else {
String optimizedPath = optimizedPathFor(file, optimizedDirectory);
return DexFile.loadDex(file.getPath(), optimizedPath, 0, loader, elements);
}
}
optimziedDirectory一直都没有赋值 null成立, 我们直接看DexFile的这个构造函数
/*
* Private version with class loader argument.
*
* @param fileName
* the filename of the DEX file
* @param loader
* the class loader creating the DEX file object
* @param elements
* the temporary dex path list elements from DexPathList.makeElements
*/
DexFile(String fileName, ClassLoader loader, DexPathList.Element[] elements)
throws IOException {
mCookie = openDexFile(fileName, null, 0, loader, elements);
mInternalCookie = mCookie;
mFileName = fileName;
//System.out.println("DEX FILE cookie is " + mCookie + " fileName=" + fileName);
}
来看openDexFile
@UnsupportedAppUsage
private static Object openDexFile(String sourceName, String outputName, int flags,
ClassLoader loader, DexPathList.Element[] elements) throws IOException {
// Use absolute paths to enable the use of relative paths when testing on host.
return openDexFileNative(new File(sourceName).getAbsolutePath(),
(outputName == null)
? null
: new File(outputName).getAbsolutePath(),
flags,
loader,
elements);
}
输出目录依然是null,最后调用了本地方法, 缓存没缓存我是不知道了
但大体我们知道DexClassLoader里面通过pathList保存了所有的关于dex的文件, DexClassLoader分析完毕。