系统ClassLoader相关及Application初始化简单分析及总结

概述

1:ClassLoader相关知识
Class文件由类装载器装载后,在JVM中将形成一份描述Class结构的元信息对象,通过该元信息对象可以获知Class的结构信息:如构造函数,属性和方法等,Java允许用户借由这个Class相关的元信息对象间接调用Class对象的功能。ClassLoader即用于把类的数据从class文件加载到内存,并对数据进行校验,转换解析和初始化,最终形成可以被虚拟机直接使用的Java类型。

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


系统ClassLoader相关及Application初始化简单分析及总结_第1张图片
172124489257909.png

2:Android中的ClassLoader:

系统ClassLoader相关及Application初始化简单分析及总结_第2张图片
1437930-bb9d359f4c7e9935.png

Androroid 中所有类加载器均为java.lang.ClassLoader的子类,主要有2种构造方法,一种为支持传入父加载器,一种为无参构造方法,而无参构造方法,传入的默认父加载器为 getSystemClassLoader代码如下

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 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.
     * 

* 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 getResources(String resName) throws IOException { return findResources(resName); } } }

由以上可知
2.1BootClassLoader 为所有android加载器中最顶层加载器,与jvm的最顶层加载器BootstrapClassLoader由C++实现不同,其为java实现,为ClassLoader的内部类。可通过以上
ClassLoader.getSystemClassLoader().getParent()获取

2.2 PathClassLoader 继承自BaseDexClassLoader ,它是我们apk的默认加载器,它是用来加载系统类和主dex文件中的类的,但是系统类是由BootClassLoader加载的,如果apk中有多个dex文件,只会加载主dex

2.3 DexClassLoader继承自BaseDexClassLoader ,可以用来加载外置的dex文件或者apk等
Android中主要使用的ClassLoader有PathClassLoader和DexClassLoader,它们都继承自BaseDexClassLoader,BaseDexClassLoader中维护了一个DexPathList,PathClassLoader和DexClassLoader查找类的操作直接调用BaseClassLoader的findClass方法,而BaseClassLoader的findClass中又通过内部维护的DexPathList来查找,DexPathList中又维护这一个Element数组,这个数组中Element元素其实就是Dex文件。

PathClassLoader和DexClassLoader最大的区别就是DexClassLoader可以加载外置dex文件,这是因为PathClassLoader构造方法中像上传递时第二个参数传了null,这个参数代表的是dex优化后的路径,DexPathList在生成Element数组时会判断这个参数是否为null,如果为null就使用系统默认路径/data/dalvik-cache,这也是导致如果要加载外置dex文件只能使用DexClassLoader的原因。

PathClassLoader只会加载apk中的主dex文件,其他的dex文件是使用DexClassloader动态加载进来,然后通过反射获取到PathClassLoader中的DexPathList,然后再拿到DexPathList中的Element数组,最后将后加载进来的dex和反射拿到的数组进行合并后并重新设置回去,这也是Google的MultiDex的做法。
``
总结完class loader,接下来分析Application创建过程(分析的源码基于21).

Andoriod应用zygote进程中fork后,首先会创建一个属于自己的进程,在进程创建后会调用ActivityThread中的main方法,在main方法中会开启消息循环并和AMS绑定,然后AMS会调用ActivityThread中的bindApplication方法,这个方法发送了一个消息到Handler中并调用handleBindApplication方法开始创建Application,也代表了一个应用程序真正的启动了,就从这个方法开始,所以顶端加载主dex的方法入口也在这。
frameworks/base/core/java/android/app/ActivityThread.java

 static final class AppBindData {
        LoadedApk info;
       。。。
    }
//-------------------**********************我是入口***************----------------------
private void handleBindApplication(AppBindData data) {

    。。。。
    //创建LoaderApk
    data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);

    。。。。

    try {
        //调用了LoadedApk中的makeApplication方法创建Application,也就是我们应用中的Application 
        Application app = data.info.makeApplication(data.restrictedBackupMode, null);

        。。。。
    } finally {
        StrictMode.setThreadPolicy(savedPolicy);
    }
//--------------------我是b----------------------->
   public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
            CompatibilityInfo compatInfo) {
        return getPackageInfo(ai, compatInfo, null, false, true, false);
    }
//--------------------我是c----------------------->

//上面b中传入的第3个参数是null,也就是说这里的ClassLoader是null

private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
        ClassLoader baseLoader, boolean securityViolation, boolean includeCode,
        boolean registerPackage) {
    synchronized (mResourcesManager) {
        //尝试从缓存中获取
        WeakReference ref;
        if (includeCode) {
            ref = mPackages.get(aInfo.packageName);
        } else {
            ref = mResourcePackages.get(aInfo.packageName);
        }           
        LoadedApk packageInfo = ref != null ? ref.get() : null;

        //未命中缓存 或者 有资源且资源管理器AssetManage未过期
        if (packageInfo == null || (packageInfo.mResources != null
                && !packageInfo.mResources.getAssets().isUpToDate())) {
            //直接创建一个LoadedApk,传入了ClassLoader,但是上面传入的是null
            packageInfo =
                new LoadedApk(this, aInfo, compatInfo, baseLoader,
                        securityViolation, includeCode &&
                        (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != , registerPackage);

            //如果是系统进程
            if (mSystemThread && "android".equals(aInfo.packageName)) {
                packageInfo.installSystemApplicationInfo(aInfo,
                        getSystemContext().mPackageInfo.getClassLoader());
            }
            //存入缓存
            if (includeCode) {
                mPackages.put(aInfo.packageName,
                        new WeakReference(packageInfo));
            } else {
                mResourcePackages.put(aInfo.packageName,
                        new WeakReference(packageInfo));
            }
        }
        return packageInfo;
    }
}
}

入口为handleBindApplication方法,先调用了getPackageInfoNoCheck该方法即调用getPackageInfo,从缓存中获取名为packageInfoLoadedApk,没有则创建一个新的。
frameworks/base/core/java/android/app/LoadedApk.java

public final class LoadedApk {
   public LoadedApk(ActivityThread activityThread, ApplicationInfo aInfo,
        CompatibilityInfo compatInfo, ClassLoader baseLoader,
        boolean securityViolation, boolean includeCode, boolean registerPackage) {

    mActivityThread = activityThread;
    setApplicationInfo(aInfo);
    mPackageName = aInfo.packageName;
    //将传入的ClassLoader赋值给了mBaseClassLoader,上面传入的为null
    mBaseClassLoader = baseLoader;
    mSecurityViolation = securityViolation;
    mIncludeCode = includeCode;
    mRegisterPackage = registerPackage;
    mDisplayAdjustments.setCompatibilityInfo(compatInfo);
}
//---------------------------------------------------------------------->
 public Application makeApplication(boolean forceDefaultAppClass,
        Instrumentation instrumentation) {

    //保证只创建一次Application    
    if (mApplication != null) {
        return mApplication;
    }
  
        String appClass = mApplicationInfo.className;
        if (forceDefaultAppClass || (appClass == null)) {
            appClass = "android.app.Application";
        }

    Application app = null;
   。。。。

    try {
        //获取ClassLoader
        java.lang.ClassLoader cl = getClassLoader();
        //不是系统包名
        if (!mPackageName.equals("android")) {
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
                    "initializeJavaContextClassLoader");
            //不是系统应用执行了initializeJavaContextClassLoader     
            initializeJavaContextClassLoader();
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        }
        //创建Context,这个由于系统版本不同可能是ContextImpl或者ApplicationContext
        ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);

        //创建Application
        app = mActivityThread.mInstrumentation.newApplication(
                cl, appClass, appContext);
        appContext.setOuterContext(app);
    } catch (Exception e) {
        if (!mActivityThread.mInstrumentation.onException(app, e)) {
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            throw new RuntimeException(
                "Unable to instantiate application " + appClass
                + ": " + e.toString(), e);
        }
    }
   mActivityThread.mAllApplications.add(app);
   mApplication = app;
    。。。。

    return app;
}   
}

LoadedApk的构造方法仅是将传进来的baseLoader赋值给成员变量mBaseClassLoader,由上可知,此时传进来的baseLoader为null,到此构造方法结束主要进行些赋值操作。

回到入口的第2个方法即LoadedApkmakeApplication.LoadedApk的成员变量
mApplication就是该方法返回的应用Application.先进行非空判断,有则直接返回没有则新建一个在赋值给成员变量再返回,保证只创建一次。创建context,从而创建Application。但到此时成员变量baseLoader仍为null,故getClassLoader获取ClassLoader cl,该方法对ClassLoader应该有些操作。

frameworks/base/core/java/android/app/LoadedApk.java

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.getDefault().getClassLoader(zip, lib, mBaseClassLoader);mBaseClassLoader为null。

frameworks/base/core/java/android/app/ApplicationLoaders.java

public ClassLoader getClassLoader(String zip, String libPath, ClassLoader parent)
{
    //这里获取的是BootClassLoader  在 2 中代码可见
    ClassLoader baseParent = ClassLoader.getSystemClassLoader().getParent();

    synchronized (mLoaders) {

        //parent是LoadedApk刚传入的mBaseClassLoader,还是null
        if (parent == null) {
            //设置parent=BootClassLoader
            parent = baseParent;
        }

        //这里肯定相等
        if (parent == baseParent) {
            //尝试获取缓存
            ClassLoader loader = mLoaders.get(zip);
            if (loader != null) {
                return loader;
            }

            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, zip);

            //创建PathClassLoader,终于出现了
          PathClassLoader pathClassloader  = ApplicationLoaders.getDefault().getClassLoader(zip, lib,
                        mBaseClassLoader);
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
          //存入缓存
            mLoaders.put(zip, pathClassloader);
            return pathClassloader;
        }

        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, zip);
        PathClassLoader pathClassloader = new PathClassLoader(zip, parent);
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        return pathClassloader;
    }
}

判断是否非空,空则创建。判断传入的classloader 是否为null,null则取系统BootClassLoader作为parent,创建PathClassLoader并赋值mClassLoader。到此PathClassLoader创建完成回到LoadApk.makeApplication方法创建Applicaiton前,非系统应用调用了initializeJavaContextClassLoader.

frameworks/base/core/java/android/app/LoadedApk.java

 private void initializeJavaContextClassLoader() {
    IPackageManager pm = ActivityThread.getPackageManager();
    android.content.pm.PackageInfo pi;
    try {
        pi = pm.getPackageInfo(mPackageName, , UserHandle.myUserId());
    } catch (RemoteException e) {
        throw new IllegalStateException("Unable to get package info for "
                + mPackageName + "; is system dying?", e);
    }
    if (pi == null) {
        throw new IllegalStateException("Unable to get package info for "
                + mPackageName + "; is package not installed?");
    }

    boolean sharedUserIdSet = (pi.sharedUserId != null);
    boolean processNameNotDefault =
        (pi.applicationInfo != null &&
         !mPackageName.equals(pi.applicationInfo.processName));
    boolean sharable = (sharedUserIdSet || processNameNotDefault);
    ClassLoader contextClassLoader =
        (sharable)
        ? new WarningContextClassLoader()
        : mClassLoader;

    //设置当前线程的ClassLoader    
    Thread.currentThread().setContextClassLoader(contextClassLoader);
}

该方法只是将主进程进程的classloader设置为创建的PathClassLoader.接下来回到
LoadedApk.makeApplication中Context的创建,系统版本不同,该创建的context可能为ContextImplApplicationContext,21的源码为ContextImpl,调用方法为ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo)

frameworks/base/core/java/android/app/ContextImpl.java

  static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) {
    if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
    //直接new了一个ContextImpl
    return new ContextImpl(null, mainThread,
            packageInfo, null, null, false, null, null);
}

//-----------------------------------
 private ContextImpl(ContextImpl container, ActivityThread mainThread,
        LoadedApk packageInfo, IBinder activityToken, UserHandle user, boolean restricted,
        Display display, Configuration overrideConfiguration) {
   。。。。

    //mPackageInfo,将传入的LoadedApk赋值给了mPackageInfo
    mPackageInfo = packageInfo;

调用ContextImpl构造方法创建对象,将传入的LoadedApk赋值给了mPackageInfo,接下来回到LoadedApk.makeApplication中最后Applicaiton的创建。

frameworks/base/core/java/android/app/Instrumentation.java

  public Application newApplication(ClassLoader cl, String className, Context context)
        throws InstantiationException, IllegalAccessException, 
        ClassNotFoundException {
/**cl为上面创建的 PathClassLoader
 context  为上面创建的ContextImpl 
  className 为 String appClass = mApplicationInfo.className;
        if (forceDefaultAppClass || (appClass == null)) {
            appClass = "android.app.Application";
        }
即我们Androidmenifest指定的Application类名,没指定则为系统Application

**/


    //使用了ClassLoader.loadClass来加载Application类,这个ClassLoader就是上面创建的PathClassLoader,这里传入的context就是上面创建的ContextImpl    
    return newApplication(cl.loadClass(className), context);
}

ClassLoader.loadClass来加载Application类,后直接调用另外一个重载方法
frameworks/base/core/java/android/app/Instrumentation.java

static public Application newApplication(Class clazz, Context context)
        throws InstantiationException, IllegalAccessException, 
        ClassNotFoundException {
    //创建Application并回调  attach方法
    Application app = (Application)clazz.newInstance();
    //调用Application的attach方法,传入的context还是上面创建的ContextImpl   
    app.attach(context);
    return app;
    }

类加载进来后直接反射创建实例,调用attach方法
frameworks/base/core/java/android/app/Application.java

final void attach(Context context) {
     attachBaseContext(context);
    mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
}

该方法做了2件事
a:调用了ContextWrapper的方法,该方法即将传入的context(此处为上面创建的ContextImpl)赋值给mBase成员变量,此处即为Application的mBase
b:将AtivityThead中的packageInfo,即刚创建 ContextImpl赋值给自身成员变量的mPackageInfo,再赋值给Application的成员变量mLoadedApk。故此3个类的LoadApk为同一对象。

另外由以上的分析可知系统产生出来的PathClassLoader 仅在
1:packageInfo握有其成员变量引用,
2:当前线程的classLoader
故要替换系统的类加载器只需要从这2个方面入手即可

总结

到此统ClassLoader相关及Application初始化相关跟踪及总结结束,该文章为接下来跟踪replugin-host-library的hook点的准备知识

你可能感兴趣的:(系统ClassLoader相关及Application初始化简单分析及总结)