动态加载

2020-04-22  本文已影响0人  雪国落叶

动态加载的前提要知道为什么当前的classloader不能加载其他路径的apk?
dex动态加载之后能否和之前加载的类发生交互,是否能够获取到他们的实例?
普通类的加载受到的限制较少,系统相关的组件会受到权限等很多因素的影响,如何解决?
class文件是如何加载到虚拟机的,对应双亲代理机制如何生效。
classLoader真正是从哪里查找class文件的,classLoader可以指定加载路径,维护很多文件,免不了有遍历等操作,

尝试反射控制startActivity

ActivityThread中有静态变量:

static volatile IPackageManager sPackageManager;

public static IPackageManager getPackageManager() {
        if (sPackageManager != null) {
            return sPackageManager;
        } else {
            IBinder b = ServiceManager.getService("package");
            sPackageManager = Stub.asInterface(b);
            return sPackageManager;
        }
    }

private static volatile ActivityThread sCurrentActivityThread;
static volatile Handler sMainThreadHandler;

sCurrentActivityThread在attach的时候最先被赋值
sPackageManager获取的是IPackageManager的接口示例。

由于版本不一致,反射的过程中需要注意,可以通过getDeclaredFields方式打印所有的方法,找出对应的方法和域。

合并宿主和插件的ClassLoader

dalvik.system.BaseDexClassLoader内部定义了DexPathList,用于记录去哪里加载指定的类,而DexPathList内部定义了dexElements,专门记录已加载的dex。

对于宿主工程来说,在加载插件工程后,将插件dex插入到宿主工程的dexElements集合后面即可,在之后的运行中就可以按需加载插件中的class。

需要注意的是,插件中的类不可以和宿主重复 。

注意:PathClassLoader extends BaseDexClassLoader
ActivityThread中使用的classLoader为:

Java ClassLoader

一个类的唯一性要由它的类加载器和它本身来确定,也就是说一个Class文件如果使用不同的类加载器来加载,那么加载出来的类也是不相等的,而在Java中为了保证一个类的唯一性使用了双亲委派模型,也就是说如果要加载一个类首先会委托给自己的父加载器去完成,父加载器会再向上委托,直到最顶层的类加载器;如果所有向上父加载器没有找到这个要加载的类,子类才会尝试自己去加载,这样就保证了加载的类都是一个类,例如Object都是一个类。java中的类加载器主要有:BootstrapClassLoader、ExtensionClassLoader 及 ApplicationClassLoader

android ClassLoader

笔记源于:https://www.jianshu.com/p/c3e904dd3a70
关键词:BaseDexCLassLoader,PathClassLoader,DexClassLoader,BootClassLoader, DexPathList

package java.lang;

public abstract class ClassLoader {
 protected ClassLoader() {
        this(checkCreateClassLoader(), getSystemClassLoader());
    }
  @CallerSensitive
    public static ClassLoader getSystemClassLoader() {
        return SystemClassLoader.loader;
    }
 static private class SystemClassLoader {
        public static ClassLoader loader = ClassLoader.createSystemClassLoader();
    } 

 private static ClassLoader createSystemClassLoader() {
        String classPath = System.getProperty("java.class.path", ".");
        String librarySearchPath = System.getProperty("java.library.path", "");

        // String[] paths = classPath.split(":");
        // URL[] urls = new URL[paths.length];
        // for (int i = 0; i < paths.length; i++) {
        // try {
        // urls[i] = new URL("file://" + paths[i]);
        // }
        // catch (Exception ex) {
        // ex.printStackTrace();
        // }
        // }
        //
        // return new java.net.URLClassLoader(urls, null);

        // TODO Make this a java.net.URLClassLoader once we have those?
        return new PathClassLoader(classPath, librarySearchPath, BootClassLoader.getInstance());
    }
  class BootClassLoader extends ClassLoader {

    private static BootClassLoader instance;

    @FindBugsSuppressWarnings("DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED")
    public static synchronized BootClassLoader getInstance() {
        if (instance == null) {
            instance = new BootClassLoader();
        }

        return instance;
    }

    public BootClassLoader() {
        super(null, true);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        return Class.classForName(name, false, null);
    }

    @Override
    protected URL findResource(String name) {
        return VMClassLoader.getResource(name);
    }

    @SuppressWarnings("unused")
    @Override
    protected Enumeration<URL> findResources(String resName) throws IOException {
        return Collections.enumeration(VMClassLoader.getResources(resName));
    }

    /**
     * Returns package information for the given package. Unfortunately, the
     * Android BootClassLoader doesn't really have this information, and as a
     * non-secure ClassLoader, it isn't even required to, according to the spec.
     * Yet, we want to provide it, in order to make all those hopeful callers of
     * {@code myClass.getPackage().getName()} happy. Thus we construct a Package
     * object the first time it is being requested and fill most of the fields
     * with dummy values. The Package object is then put into the ClassLoader's
     * Package cache, so we see the same one next time. We don't create Package
     * objects for null arguments or for the default package.
     * <p>
     * There a limited chance that we end up with multiple Package objects
     * representing the same package: It can happen when when a package is
     * scattered across different JAR files being loaded by different
     * ClassLoaders. Rather unlikely, and given that this whole thing is more or
     * less a workaround, probably not worth the effort.
     */
    @Override
    protected Package getPackage(String name) {
        if (name != null && !name.isEmpty()) {
            synchronized (this) {
                Package pack = super.getPackage(name);

                if (pack == null) {
                    pack = definePackage(name, "Unknown", "0.0", "Unknown", "Unknown", "0.0",
                            "Unknown", null);
                }

                return pack;
            }
        }

        return null;
    }

    @Override
    public URL getResource(String resName) {
        return findResource(resName);
    }

    @Override
    protected Class<?> loadClass(String className, boolean resolve)
           throws ClassNotFoundException {
        Class<?> clazz = findLoadedClass(className);

        if (clazz == null) {
            clazz = findClass(className);
        }

        return clazz;
    }

    @Override
    public Enumeration<URL> getResources(String resName) throws IOException {
        return findResources(resName);
    }
}
}

通过ClassLoader baseParent = ClassLoader.getSystemClassLoader().getParent(); 获取到的是BootClassLoader

public ClassLoader getClassLoader() {
    synchronized (this) {

        //如果mClassLoader不为空,直接返回了
        if (mClassLoader != null) {
            return mClassLoader;
        }

        if (mIncludeCode && !mPackageName.equals("android")) {
            //不是系统应用
           。。。。
            //获取ClassLoader对象,这里传入的mBaseClassLoader还是null,因为LoadedApk创建的时候传入的就是null
            mClassLoader = ApplicationLoaders.getDefault().getClassLoader(zip, lib,
                    mBaseClassLoader);

            StrictMode.setThreadPolicy(oldPolicy);
        } else {
            //是系统应用
            if (mBaseClassLoader == null) {
                mClassLoader = ClassLoader.getSystemClassLoader();
            } else {
                mClassLoader = mBaseClassLoader;
            }
        }
        return mClassLoader;
    }
}

最终在ApplicationLoaders类中生成pathClassLoader:
//创建PathClassLoader,终于出现了
PathClassLoader pathClassloader = ApplicationLoaders.getDefault().getClassLoader(zip, lib,
mBaseClassLoader);

四大组件动态加载

Activity

Activity

采用宿主manifest中占坑的方式来绕过系统校验,然后再加载真正的activity;

图8描述了VirtualAPK根据launchMode定义了2(standard) + 8(singleTop) + 8(singleTask) + 8(singleInstance) = 26个SubActivity坑.

加载资源

参考:https://blog.csdn.net/luoshengyang/java/article/details/8806798
AssetManager类的成员函数getResources的实现看起来比较复杂,但是它要做的事情就是解析当前应用程序所使用的资源包里面的resources.arsc文件。从前面Android应用程序资源管理器(Asset Manager)的创建过程分析一文可以知道,当前应用程序所使用的资源包有两个,其中一个是系统资源包,即/system/framework/framework-res.apk,另外一个就是自己的APK文件。这些APK文件的路径都分别使用一个asset_path对象来描述,并且保存在AssetManager类的成员变量mAssetPaths中。
在动态加载过程中由于AssetManager通过自己的mAssetPaths解析加载resources.arsc文件。

  1. 通过自定义的CLassLoader可以加载apk或者dex文件。
    new DexClassLoader(resourcePath, mDexDir, null,mContext.getClassLoader()
    2.查找idmap,通过组拼资源文件生成类名,从类中反射获取到资源id。packageName通过PackageManager构建packageInfo.packageName获取包名
PackageInfo packageInfo = mContext.getPackageManager().getPackageArchiveInfo(resourcePath, PackageManager.GET_ACTIVITIES);



String rClassName = packageName + ".R$" + type;
        try {
            Class cls = mResourceLoadBean.getClassLoader().loadClass(rClassName);
            resID = (Integer) cls.getField(fieldName).get(null);
        } catch (Exception e) {
            e.printStackTrace();
        }

3.通过新建的AssetMananger和Resource根据id加载资源

其他

插件化也依赖于网络检查是否有插件需要下发,并被安装上,用插件实现功能时下发完整的插件,做bugfix或者其他的时候通常会作差分,用差分包的形式去下发。网络下发到本地存储,保存或者下次启动时加载。
插件要有版本,当插件版本高于或者等于apk版本则加载。

上一篇下一篇

猜你喜欢

热点阅读