android类加载

源码版本8.1

DexClassLoader、PathClassLoader、BaseDexClassLoader构造函数

public class DexClassLoader extends BaseDexClassLoader {
    public DexClassLoader(String dexPath, String optimizedDirectory,
            String librarySearchPath, ClassLoader parent) {
        super(dexPath, null, librarySearchPath, parent);
    }
}

DexClassLoader的构造函数有四个参数,根据注释,dexPath是包含类和资源的jar/apk文件的路径清单;optimizedDirectory参数已经过时,该参数没有任何作用,可以看到在调用父加载器时,传进去了一个null参数,这个参数在过去的版本中是optimizedDirectory,代表优化之后的odex存放路径。librarySearchPath是包含本地库的目录清单,可以为null。parent是父加载器。

public class PathClassLoader extends BaseDexClassLoader {
    public PathClassLoader(String dexPath, ClassLoader parent) {
        super(dexPath, null, null, parent);
    }

    public PathClassLoader(String dexPath, String librarySearchPath, ClassLoader parent) {
        super(dexPath, null, librarySearchPath, parent);
    }
}

PathClassLoader和DexClassLoader的构造函数完全没有区别。它们都把参数交给父类BaseDexClassLoader的构造函数。

public BaseDexClassLoader(String dexPath, File optimizedDirectory,
        String librarySearchPath, ClassLoader parent) {
    super(parent);
    this.pathList = new DexPathList(this, dexPath, librarySearchPath, null);

    if (reporter != null) {
        reportClassLoaderChain();
    }
}

调用了父类ClassLoader的构造函数,接下来new了一个DexPathList给pathList。ClassLoader的构造函数很简单,如下

///libcore/ojluni/src/main/java/java/lang/ClassLoader.java
protected ClassLoader(ClassLoader parent) {
	this(checkCreateClassLoader(), parent);
}
private ClassLoader(Void unused, ClassLoader parent) {
	this.parent = parent;
}

就是把父构造器保存在parent成员中。接着看DexPathList是什么。

DexPathList

先看该类的注释

/**
 * A pair of lists of entries, associated with a {@code ClassLoader}.
 * One of the lists is a dex/resource path — typically referred
 * to as a "class path" — list, and the other names directories
 * containing native code libraries. Class path entries may be any of:
 * a {@code .jar} or {@code .zip} file containing an optional
 * top-level {@code classes.dex} file as well as arbitrary resources,
 * or a plain {@code .dex} file (with no possibility of associated
 * resources).
 *
 * <p>This class also contains methods to use these lists to look up
 * classes and resources.</p>
 */

根据注释,该类包含了一对和类加载器相关的清单。一张是dex/resource路径清单,往往是类路径。另外一张是本地代码库的清单。类路径必须是含有.dex和任意资源(也可以没有资源)的jar或zip文件。DexPathList类同时包含了一些使用这些清单来查找类和资源的方法。

也就是说,DexPathList是用来检索由类加载器加载的类和资源的。继续看它的构造函数。

//new DexPathList(this, dexPath, librarySearchPath, null)
public DexPathList(ClassLoader definingContext, String dexPath,
        String librarySearchPath, File optimizedDirectory) {
	//definingContext为ClassLoader
    if (definingContext == null) {
        throw new NullPointerException("definingContext == null");
    }

    if (dexPath == null) {
        throw new NullPointerException("dexPath == null");
    }
	//optimizedDirectory肯定为null,不会进入该if
    if (optimizedDirectory != null) {
        if (!optimizedDirectory.exists())  {
            throw new IllegalArgumentException(
                    "optimizedDirectory doesn't exist: "
                    + optimizedDirectory);
        }

        if (!(optimizedDirectory.canRead()
                        && optimizedDirectory.canWrite())) {
            throw new IllegalArgumentException(
                    "optimizedDirectory not readable/writable: "
                    + optimizedDirectory);
        }
    }
	//在类成员中记录ClassLoader
    this.definingContext = definingContext;

    ArrayList<IOException> suppressedExceptions = new ArrayList<IOException>();
    // save dexPath for BaseDexClassLoader
    this.dexElements = makeDexElements(splitDexPath(dexPath), optimizedDirectory,
                                       suppressedExceptions, definingContext);                                 
//...

DexPathList构造函数的前半部分负责检查参数,类加载器和dex路径不能为null,然后把dexPath拆分成文件后交给了makeDexElements,用dexElements存储返回结果。

    // Native libraries may exist in both the system and
    // application library paths, and we use this search order:
    //
    //   1. This class loader's library path for application libraries (librarySearchPath):
    //   1.1. Native library directories
    //   1.2. Path to libraries in apk-files
    //   2. The VM's library path from the system property for system libraries
    //      also known as java.library.path
    //
    // This order was reversed prior to Gingerbread; see http://b/2933456.
    
    //传进来的本地库路径赋给nativeLibraryDirectories
    this.nativeLibraryDirectories = splitPaths(librarySearchPath, false);
    //从"java.library.path"获取路径赋给systemNativeLibraryDirectories
    this.systemNativeLibraryDirectories =
            splitPaths(System.getProperty("java.library.path"), true);
    //把上面两类路径都存到allNativeLibraryDirectories中。其中传进来的本地库
    //路径放在前面
    List<File> allNativeLibraryDirectories = new ArrayList<>(nativeLibraryDirectories);
    allNativeLibraryDirectories.addAll(systemNativeLibraryDirectories);
	//把本地库路径又交给makePathElements处理
    this.nativeLibraryPathElements = makePathElements(allNativeLibraryDirectories);

    if (suppressedExceptions.size() > 0) {
        this.dexElementsSuppressedExceptions =
            suppressedExceptions.toArray(new IOException[suppressedExceptions.size()]);
    } else {
        dexElementsSuppressedExceptions = null;
    }
}

后半部分把库路径传给了makePathElements,把返回结果存在nativeLibraryPathElements成员中。

所以DexPathList构造函数就是把dex路径交给makeDexElements。把库路径交给makePathElements。结合前面注释中说的,DexPathList包含一张是dex/resource路径清单和一张是本地代码库的清单,可以推测,两个make*Elements就是构造清单的函数,而dexElements和nativeLibraryPathElements就是那两张清单。

makeDexElements

//makeDexElements(splitDexPath(dexPath), optimizedDirectory,
//suppressedExceptions, definingContext); 
private static Element[] makeDexElements(List<File> files, File optimizedDirectory,
        List<IOException> suppressedExceptions, ClassLoader loader) {
  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();
			//文件名以.dex结尾(非zip和jar)的话进入该if
          if (name.endsWith(DEX_SUFFIX)) {
              // Raw dex file (not inside a zip/jar).
              try {
				//把dex文件交给loadDexFile
                  DexFile dex = loadDexFile(file, optimizedDirectory, loader, elements);
                  if (dex != null) {
                  //用dex创建了Element,并插入到elements表中。
                      elements[elementsPos++] = new Element(dex, null);
                  }
              } catch (IOException suppressed) {
                  System.logE("Unable to load dex file: " + file, suppressed);
                  suppressedExceptions.add(suppressed);
              }
          } else {//文件名不以.dex结尾或是null的话进入该分支
              DexFile dex = null;
              try {
              	//同样是调用了loadDexFile
                  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);
              }
			//这里把file也用来创建Element。
			//对其它后缀结尾的文件和以dex结尾的文件的处理区别可能就体现在这里。
              if (dex == null) {
                  elements[elementsPos++] = new Element(file);
              } else {
                  elements[elementsPos++] = new Element(dex, file);
              }
          }
      } else {
          System.logW("ClassLoader referenced unknown path: " + file);
      }
  }
  if (elementsPos != elements.length) {
      elements = Arrays.copyOf(elements, elementsPos);
  }
  return elements;
}

makeDexElements用传进来的文件交给loadDexFile来构造了DexFile,然后用该DexFile和文件来构造Element并插入到elements数组中。这个elements数组就是DexPathList中的dexElements清单。

我们看一下Element的构造函数。

Element构造函数

public Element(DexFile dexFile, File dexZipPath) {
    this.dexFile = dexFile;
    this.path = dexZipPath;
}

public Element(DexFile dexFile) {
    this.dexFile = dexFile;
    this.path = null;
}

public Element(File path) {
  this.path = path;
  this.dexFile = null;
}

其实就是把传进来的参数存储到成员变量中。根据makeDexElement中的传递的参数,可以知道.dex文件的Element只有dexFile成员。其它后缀文件的Element还包含了文件的路径。

接着看loadDexFile是怎么构造DexFile的。

loadDexFile、DexFile构造函数、openDexFile

    private static DexFile loadDexFile(File file, File optimizedDirectory, ClassLoader loader,
                                       Element[] elements)
            throws IOException {
        //optimizedDirectory必为null,进入该if
        if (optimizedDirectory == null) {
            return new DexFile(file, loader, elements);
        } else {
            String optimizedPath = optimizedPathFor(file, optimizedDirectory);
            return DexFile.loadDex(file.getPath(), optimizedPath, 0, loader, elements);
        }
    }

非常直接,把file交给了DexFile构造函数。接着看该构造函数。

DexFile(File file, ClassLoader loader, DexPathList.Element[] elements)
        throws IOException {
    this(file.getPath(), loader, elements);
}
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);
}

构造函数初始化了一些成员,其中mCookie和mInternalCookie都是object类型,存储了openDexFile的结果。

//mCookie = openDexFile(fileName, null, 0, loader, elements);
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);
}

而openDexFile调用了本地函数openDexFileNative。

DexFile_openDexFileNative

//\art\runtime\native\dalvik_system_DexFile.cc
static jobject DexFile_openDexFileNative(JNIEnv* env,
                                         jclass,
                                         jstring javaSourceName,
                                         jstring javaOutputName ATTRIBUTE_UNUSED,
                                         jint flags ATTRIBUTE_UNUSED,
                                         jobject class_loader,
                                         jobjectArray dex_elements) {
  ScopedUtfChars sourceName(env, javaSourceName);
  if (sourceName.c_str() == nullptr) {
    return 0;
  }

  Runtime* const runtime = Runtime::Current();
  ClassLinker* linker = runtime->GetClassLinker();
  std::vector<std::unique_ptr<const DexFile>> dex_files;
  std::vector<std::string> error_msgs;
  const OatFile* oat_file = nullptr;

  dex_files = runtime->GetOatFileManager().OpenDexFilesFromOat(sourceName.c_str(),
                                                               class_loader,
                                                               dex_elements,
                                                               /*out*/ &oat_file,
                                                               /*out*/ &error_msgs);

  if (!dex_files.empty()) {
    jlongArray array = ConvertDexFilesToJavaArray(env, oat_file, dex_files);
    if (array == nullptr) {
      ScopedObjectAccess soa(env);
      for (auto& dex_file : dex_files) {
        if (linker->IsDexFileRegistered(soa.Self(), *dex_file)) {
          dex_file.release();
        }
      }
    }
    return array;
  } else {
    ScopedObjectAccess soa(env);
    CHECK(!error_msgs.empty());
    // The most important message is at the end. So set up nesting by going forward, which will
    // wrap the existing exception as a cause for the following one.
    auto it = error_msgs.begin();
    auto itEnd = error_msgs.end();
    for ( ; it != itEnd; ++it) {
      ThrowWrappedIOException("%s", it->c_str());
    }

    return nullptr;
  }
}

OatFileManager::OpenDexFilesFromOat分段1

//\art\runtime\oat_file_manager.cc
std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
    const char* dex_location,
    jobject class_loader,
    jobjectArray dex_elements,
    const OatFile** out_oat_file,
    std::vector<std::string>* error_msgs) {
  ScopedTrace trace(__FUNCTION__);
  CHECK(dex_location != nullptr);
  CHECK(error_msgs != nullptr);

  // Verify we aren't holding the mutator lock, which could starve GC if we
  // have to generate or relocate an oat file.
  //保证自己没有持有mutator lock,该锁会在产生或重定位oat的时候导致GC饥饿
  Thread* const self = Thread::Current();
  Locks::mutator_lock_->AssertNotHeld(self);
  Runtime* const runtime = Runtime::Current();

  std::unique_ptr<ClassLoaderContext> context;
  // If the class_loader is null there's not much we can do. This happens if a dex files is loaded
  // directly with DexFile APIs instead of using class loaders.
  //保证class_loader不为null
  if (class_loader == nullptr) {
    LOG(WARNING) << "Opening an oat file without a class loader. "
                 << "Are you using the deprecated DexFile APIs?";
    context = nullptr;
  } else {
  //\art\runtime\scoped_thread_state_change.h
    context = ClassLoaderContext::CreateContextForClassLoader(class_loader, dex_elements);
  }

  OatFileAssistant oat_file_assistant(dex_location,
                                      kRuntimeISA,
                                      !runtime->IsAotCompiler());
	//...

这里构造了一个OatFileAssistant对象,先看该类的构造函数。

OatFileAssistant构造函数

//如果是AOT,则load_executable为false
OatFileAssistant::OatFileAssistant(const char* dex_location,
                                   const InstructionSet isa,
                                   bool load_executable)
    : isa_(isa),
      load_executable_(load_executable),
      odex_(this, /*is_oat_location*/ false),
      oat_(this, /*is_oat_location*/ true) {
  CHECK(dex_location != nullptr) << "OatFileAssistant: null dex location";
//一些注释
//取得真实路径
  UniqueCPtr<const char[]> dex_location_real(realpath(dex_location, nullptr));
  if (dex_location_real != nullptr) {
    dex_location_.assign(dex_location_real.get());
  } else {
    // If we can't get the realpath of the location there's not much point in trying to move on.
    PLOG(ERROR) << "Could not get the realpath of dex_location " << dex_location;
    return;
  }
	//如果加载的文件是可执行的,但指令集和当前环境指令集不同,则不会加载
  if (load_executable_ && isa != kRuntimeISA) {
    LOG(WARNING) << "OatFileAssistant: Load executable specified, "
      << "but isa is not kRuntimeISA. Will not attempt to load executable.";
    load_executable_ = false;
  }

  // Get the odex filename.
  std::string error_msg;
  std::string odex_file_name;
  //在dex路径的目录下创建oat和isa目录,然后把dex路径中文件后缀.dex换成.odex赋给
  //odex_file_name
  if (DexLocationToOdexFilename(dex_location_, isa_, &odex_file_name, &error_msg)) {
  //odex_成员属于OatFileInfo类型,该类记录.odex文件的信息。
    odex_.Reset(odex_file_name);
  } else {
    LOG(WARNING) << "Failed to determine odex file name: " << error_msg;
  }

  // Get the oat filename.
  std::string oat_file_name;
  //里面调用了GetDalvikCache等函数,最终结果为 
  // /data/dalvik-cache/<isa>/{把dex_location_路径中/换成@作为文件名}
  if (DexLocationToOatFilename(dex_location_, isa_, &oat_file_name, &error_msg)) {
  //oat_成员是OatFileInfo类型,该类记录oat文件的信息。
    oat_.Reset(oat_file_name);
  } else {
    LOG(WARNING) << "Failed to determine oat file name for dex location "
        << dex_location_ << ": " << error_msg;
  }

  // Check if the dex directory is writable.
  // This will be needed in most uses of OatFileAssistant and so it's OK to
  // compute it eagerly. (the only use which will not make use of it is
  // OatFileAssistant::GetStatusDump())
  //dex路径必须可写
  size_t pos = dex_location_.rfind('/');
  if (pos == std::string::npos) {
    LOG(WARNING) << "Failed to determine dex file parent directory: " << dex_location_;
  } else {
    std::string parent = dex_location_.substr(0, pos);
    if (access(parent.c_str(), W_OK) == 0) {
      dex_parent_writable_ = true;
    } else {
      VLOG(oat) << "Dex parent of " << dex_location_ << " is not writable: " << strerror(errno);
    }
  }
}

OatFileAssistant的构造函数主要是初始化odex_和oat_成员,这两个成员都是OatFileInfo类型。一个记录路径下的odex文件信息,一个记录 /data/dalvik-cache/{isa}/{把dex_location_路径中/换成@作为文件名}的文件信息。但是,这里的info也仅仅是存储了文件的名字,并没有去创建相关文件或者获取文件handle。这些工作是在OpenDexFilesFromOat后面的代码中完成,继续往下看。

OatFileManager::OpenDexFilesFromOat分段2

	//...
  // Lock the target oat location to avoid races generating and loading the
  // oat file.
  std::string error_msg;
  if (!oat_file_assistant.Lock(/*out*/&error_msg)) {
    // Don't worry too much if this fails. If it does fail, it's unlikely we
    // can generate an oat file anyway.
    VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg;
  }

  const OatFile* source_oat_file = nullptr;

  if (!oat_file_assistant.IsUpToDate()) {
    // Update the oat file on disk if we can, based on the --compiler-filter
    // option derived from the current runtime options.
    // This may fail, but that's okay. Best effort is all that matters here.
    // TODO(calin): b/64530081 b/66984396. Pass a null context to verify and compile
    // secondary dex files in isolation (and avoid to extract/verify the main apk
    // if it's in the class path). Note this trades correctness for performance
    // since the resulting slow down is unacceptable in some cases until b/64530081
    // is fixed.
    switch (oat_file_assistant.MakeUpToDate(/*profile_changed*/ false,
                                            /*class_loader_context*/ nullptr,
                                            /*out*/ &error_msg)) {
      case OatFileAssistant::kUpdateFailed:
        LOG(WARNING) << error_msg;
        break;

      case OatFileAssistant::kUpdateNotAttempted:
        // Avoid spamming the logs if we decided not to attempt making the oat
        // file up to date.
        VLOG(oat) << error_msg;
        break;

      case OatFileAssistant::kUpdateSucceeded:
        // Nothing to do.
        break;
    }
  }
	//...

调用了OatFileAssistant的MakeUpToDate。调用完后,如果一切正常的话会进入kUpdateSucceeded分支,也就是什么都不做。继续看MakeUpToDate做了什么。

OatFileAssistant::MakeUpToData和GetBestInfo

//oat_file_assistant.MakeUpToDate(false,nullptr,&error_msg)
OatFileAssistant::ResultOfAttemptToUpdate
OatFileAssistant::MakeUpToDate(bool profile_changed,
                               ClassLoaderContext* class_loader_context,
                               std::string* error_msg) {
  CompilerFilter::Filter target;
  //获取运行时编译器的信息
  if (!GetRuntimeCompilerFilterOption(&target, error_msg)) {
    return kUpdateNotAttempted;
  }

  OatFileInfo& info = GetBestInfo();
//一些注释...
//GetDexOptNeeded检查oat是否需要更新
  switch (info.GetDexOptNeeded(
        target, profile_changed, /*downgrade*/ false, class_loader_context)) {
    case kNoDexOptNeeded:
      return kUpdateSucceeded;
    case kDex2OatFromScratch:
    case kDex2OatForBootImage:
    case kDex2OatForRelocation:
    case kDex2OatForFilter:
      return GenerateOatFileNoChecks(info, target, class_loader_context, error_msg);
  }
  UNREACHABLE();
}

取得了OatFileInfo,如果info的信息需要更新,则交给GenerateOatFileNoChecks,从名字来看,这个函数的功能是产生oat文件。而从下面的GetBestInfo函数可以知道,info是OatFileAssistant构造函数中的两个文件的OatFileInfo之一。前面我们说OatFileAssistant的构造函数仅仅是用info来记录oat的文件名,并没有负责创建oat文件。这里看来,创建oat文件的工作由GenerateOatFileNoChecks完成。

OatFileAssistant::OatFileInfo& OatFileAssistant::GetBestInfo() {
  // TODO(calin): Document the side effects of class loading when
  // running dalvikvm command line.
  if (dex_parent_writable_) {
    //根据注释:
    //如果dex所在目录可写,则返回odex_。普通app在安装或者加载它们私有的从属
    //dex文件的时候会进入该分支。系统分区的app不会进入该分支
    return odex_;
  }
	//如果没有进入上面的分支,则可能是一个系统app。
  // 当oat无法打开,dex过时,bootimage过时的时候IsUseable返回false
  if (oat_.IsUseable()) {
    return oat_;
  }

  //根据注释:
  //当oat文件不可用,但odex文件是最新的情况下,进入该分支。
  //该app可能是一个不需要重定位的预装app。
  if (odex_.Status() == kOatUpToDate) {
    return odex_;
  }

  //根据注释:
  //当oat不可用,odex非最新,但可以访问到原始dex文件的情况下进入该分支。
  //能访问到原始dex则能更新oat。
  if (HasOriginalDexFiles()) {
    return oat_;
  }

  //根据注释:
  //当oat位置不可用,odex位置未更新,没有原始dex文件的情况下进入该分支。
  //当odex存在的时候返回odex,否则返回oat
  return (odex_.Status() == kOatCannotOpen) ? oat_ : odex_;
}

OatFileAssistant::GenerateOatFileNoChecks

继续看oat文件是怎么被创建的。

OatFileAssistant::ResultOfAttemptToUpdate OatFileAssistant::GenerateOatFileNoChecks(
      OatFileAssistant::OatFileInfo& info,
      CompilerFilter::Filter filter,
      const ClassLoaderContext* class_loader_context,
      std::string* error_msg) {
	//...
  const std::string& oat_file_name = *info.Filename();
  const std::string& vdex_file_name = GetVdexFilename(oat_file_name);

  // dex2oat ignores missing dex files and doesn't report an error. 这里的dex2oat是指系统应用程序dex2oat
  // Check explicitly here so we can detect the error properly.dex2oat不会因为缺乏dex文件报错,所以在这里提前检查
  // TODO: Why does dex2oat behave that way?
  struct stat dex_path_stat;
  if (TEMP_FAILURE_RETRY(stat(dex_location_.c_str(), &dex_path_stat)) != 0) {
    *error_msg = "Could not access dex location " + dex_location_ + ":" + strerror(errno);
    return kUpdateNotAttempted;
  }

  // If this is the odex location, we need to create the odex file layout (../oat/isa/..)
  //info可能是odex或者oat的info,如果是odex的info,则提前创建好路径。和OatFileManager构造函数中创建的路径一致
  if (!info.IsOatLocation()) {
    if (!PrepareOdexDirectories(dex_location_, oat_file_name, isa_, error_msg)) {
      return kUpdateNotAttempted;
    }
  }

 //向操作系统请求创建文件并设置文件权限,这里略过这一部分代码,最终得到oat_file和vdex_file。
 //...
 
 //设置运行dex2oat程序的运行环境,把创建的文件,文件名等通过环境传递给dex2oat程序。
  std::vector<std::string> args;
  args.push_back("--dex-file=" + dex_location_);//dex文件的路径
  args.push_back("--output-vdex-fd=" + std::to_string(vdex_file->Fd()));
  args.push_back("--oat-fd=" + std::to_string(oat_file->Fd()));
  args.push_back("--oat-location=" + oat_file_name);
  args.push_back("--compiler-filter=" + CompilerFilter::NameOfFilter(filter));
  const std::string dex2oat_context = class_loader_context == nullptr
        ? OatFile::kSpecialSharedLibrary
        : class_loader_context->EncodeContextForDex2oat(/*base_dir*/ "");
  args.push_back("--class-loader-context=" + dex2oat_context);
//Dex2Oat创建dex2oat程序,完成dex到oat的转换。
  if (!Dex2Oat(args, error_msg)) {
    return kUpdateFailed;
  }
  
//最后是更新file和info的状态
//...

  return kUpdateSucceeded;
}

GenerateOatFileNoChecks主要是向操作系统请求创建两个空文件,分别是vdex文件和oat文件。然后设置dex2oat应用的运行环境,接着把工作交给Dex2Oat。

OatFileAssistant::Dex2Oat


bool OatFileAssistant::Dex2Oat(const std::vector<std::string>& args,
                               std::string* error_msg) {
  Runtime* runtime = Runtime::Current();
  std::string image_location = ImageLocation();
  if (image_location.empty()) {
    *error_msg = "No image location found for Dex2Oat.";
    return false;
  }

  std::vector<std::string> argv;
  //注意这个push_back,会把"/bin/dex2oat"放进去。
  argv.push_back(runtime->GetCompilerExecutable());
  
  //往argv中插入其它环境变量
  //...

  std::string command_line(android::base::Join(argv, ' '));
  //fork一个进程来启动dex2oat程序
  return Exec(argv, error_msg);
}

继续设置好环境变量后,通过Exec来fork进程,启动dex2oat程序,完成dex到oat的转换。到这里就不继续往下钻了,Exec里面也没有什么值得注意的。当Dex2Oat执行完后,OpenDexFilesFromOat分段2部分就结束了,总结一下分段2的主要工作其实就是根据dex文件生成了oat文件。接着看分段3。

OatFileManager::OpenDexFilesFromOat分段3

  // Get the oat file on disk.
  std::unique_ptr<const OatFile> oat_file(oat_file_assistant.GetBestOatFile().release());

  // Prevent oat files from being loaded if no class_loader or dex_elements are provided.
  // This can happen when the deprecated DexFile.<init>(String) is called directly, and it
  // could load oat files without checking the classpath, which would be incorrect.
  if ((class_loader != nullptr || dex_elements != nullptr) && oat_file != nullptr) {
    // Take the file only if it has no collisions, or we must take it because of preopting.
    bool accept_oat_file =
        !HasCollisions(oat_file.get(), context.get(), /*out*/ &error_msg);
    if (!accept_oat_file) {
      // Failed the collision check. Print warning.
      if (Runtime::Current()->IsDexFileFallbackEnabled()) {
        if (!oat_file_assistant.HasOriginalDexFiles()) {
          // We need to fallback but don't have original dex files. We have to
          // fallback to opening the existing oat file. This is potentially
          // unsafe so we warn about it.
          accept_oat_file = true;

          LOG(WARNING) << "Dex location " << dex_location << " does not seem to include dex file. "
                       << "Allow oat file use. This is potentially dangerous.";
        } else {
          // We have to fallback and found original dex files - extract them from an APK.
          // Also warn about this operation because it's potentially wasteful.
          LOG(WARNING) << "Found duplicate classes, falling back to extracting from APK : "
                       << dex_location;
          LOG(WARNING) << "NOTE: This wastes RAM and hurts startup performance.";
        }
      } else {
        // TODO: We should remove this. The fact that we're here implies -Xno-dex-file-fallback
        // was set, which means that we should never fallback. If we don't have original dex
        // files, we should just fail resolution as the flag intended.
        if (!oat_file_assistant.HasOriginalDexFiles()) {
          accept_oat_file = true;
        }

        LOG(WARNING) << "Found duplicate classes, dex-file-fallback disabled, will be failing to "
                        " load classes for " << dex_location;
      }

      LOG(WARNING) << error_msg;
    }

  }
  //...

首先进入了HasCollisions函数对oat文件进行检查判断。该函数决定了是否接受oat文件。

OatFileManager::HasCollisions

bool OatFileManager::HasCollisions(const OatFile* oat_file,
                                   const ClassLoaderContext* context,
                                   std::string* error_msg /*out*/) const {
  DCHECK(oat_file != nullptr);
  DCHECK(error_msg != nullptr);

  // The context might be null if there are unrecognized class loaders in the chain or they
  // don't meet sensible sanity conditions. In this case we assume that the app knows what it's
  // doing and accept the oat file.
  // Note that this has correctness implications as we cannot guarantee that the class resolution
  // used during compilation is OK (b/37777332).
  if (context == nullptr) {
      LOG(WARNING) << "Skipping duplicate class check due to unsupported classloader";
      return false;
  }

  // If the pat file loading context matches the context used during compilation then we accept
  // the oat file without addition checks
  //检查的项目包括类加载器的数目和类型,类加载器的类路径
  if (context->VerifyClassLoaderContextMatch(oat_file->GetClassLoaderContext())) {
    return false;
  }

  // The class loader context does not match. Perform a full duplicate classes check.

  std::vector<const DexFile*> dex_files_loaded = context->FlattenOpenedDexFiles();

  // Vector that holds the newly opened dex files live, this is done to prevent leaks.
  std::vector<std::unique_ptr<const DexFile>> opened_dex_files;

  ScopedTrace st("Collision check");
  // Add dex files from the oat file to check.
  std::vector<const DexFile*> dex_files_unloaded;
  //从oat文件中获取要加载的dex文件
  AddDexFilesFromOat(oat_file, &dex_files_unloaded, &opened_dex_files);
  return CollisionCheck(dex_files_loaded, dex_files_unloaded, error_msg);
}

从环境中获取已经加载的dex文件的列表,和正在加载的oat文件中的dex文件比较,检查是否重复(CollisionCheck函数完成该检查)。若重复则返回真代表存在冲突。

而根据分段3后面的代码来看,当发生冲突的时候,会去找原dex文件。为什么这样能解决冲突???

OatFileManager::OpenDexFilesFromOat分段4

//只有当接受oat文件的时候,source_oat_file才不为空
    if (accept_oat_file) {
      VLOG(class_linker) << "Registering " << oat_file->GetLocation();
      source_oat_file = RegisterOatFile(std::move(oat_file));
      *out_oat_file = source_oat_file;
    }
  std::vector<std::unique_ptr<const DexFile>> dex_files;

  // Load the dex files from the oat file.
  if (source_oat_file != nullptr) {
    bool added_image_space = false;
    //executable表示要加载的OAT是不是应用程序的主执行文件。如果是的话进入该分支
    if (source_oat_file->IsExecutable()) {
    //打开app的imageSpace
      std::unique_ptr<gc::space::ImageSpace> image_space =
          kEnableAppImage ? oat_file_assistant.OpenImageSpace(source_oat_file) : nullptr;
      if (image_space != nullptr) {
        ScopedObjectAccess soa(self);
        StackHandleScope<1> hs(self);
        Handle<mirror::ClassLoader> h_loader(
            hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader)));
        // Can not load app image without class loader.
        if (h_loader != nullptr) {
          std::string temp_error_msg;
          // Add image space has a race condition since other threads could be reading from the
          // spaces array.
          {
            ScopedThreadSuspension sts(self, kSuspended);
            gc::ScopedGCCriticalSection gcs(self,
                                            gc::kGcCauseAddRemoveAppImageSpace,
                                            gc::kCollectorTypeAddRemoveAppImageSpace);
            ScopedSuspendAll ssa("Add image space");
            runtime->GetHeap()->AddSpace(image_space.get());//把space加到heap中
          }
          {
            ScopedTrace trace2(StringPrintf("Adding image space for location %s", dex_location));
            //加到ClassLinker中。这里传入了dex_files,推测该函数会提取dex文件信息到该vector中。
            added_image_space = runtime->GetClassLinker()->AddImageSpace(image_space.get(),
                                                                         h_loader,
                                                                         dex_elements,
                                                                         dex_location,
                                                                         /*out*/&dex_files,
                                                                         /*out*/&temp_error_msg);
          }
          if (added_image_space) {
            // Successfully added image space to heap, release the map so that it does not get
            // freed.
            image_space.release();//imagespace已经放到heap和classLinker中,这里将其释放

            // Register for tracking.
            //注册oat中的dex文件
            for (const auto& dex_file : dex_files) {
              dex::tracking::RegisterDexFile(dex_file.get());
            }
          } else {
            LOG(INFO) << "Failed to add image file " << temp_error_msg;
            dex_files.clear();
            {
              ScopedThreadSuspension sts(self, kSuspended);
              gc::ScopedGCCriticalSection gcs(self,
                                              gc::kGcCauseAddRemoveAppImageSpace,
                                              gc::kCollectorTypeAddRemoveAppImageSpace);
              ScopedSuspendAll ssa("Remove image space");
              runtime->GetHeap()->RemoveSpace(image_space.get());
            }
            // Non-fatal, don't update error_msg.
          }
        }
      }
    }
    //当要加载的oat不是主执行文件的时候,进入下面这个分支
    if (!added_image_space) {
      DCHECK(dex_files.empty());
      //调用另外一个函数来load dex文件。
      dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);

      // Register for tracking.
      //同样是注册dex 文件
      for (const auto& dex_file : dex_files) {
        dex::tracking::RegisterDexFile(dex_file.get());
      }
    }
    if (dex_files.empty()) {
      error_msgs->push_back("Failed to open dex files from " + source_oat_file->GetLocation());
    } else {
      // Opened dex files from an oat file, madvise them to their loaded state.
       for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
         OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
       }
    }
  }

  // Fall back to running out of the original dex file if we couldn't load any
  // dex_files from the oat file.
  if (dex_files.empty()) {
    if (oat_file_assistant.HasOriginalDexFiles()) {
      if (Runtime::Current()->IsDexFileFallbackEnabled()) {
        static constexpr bool kVerifyChecksum = true;
        if (!DexFile::Open(
            dex_location, dex_location, kVerifyChecksum, /*out*/ &error_msg, &dex_files)) {
          LOG(WARNING) << error_msg;
          error_msgs->push_back("Failed to open dex files from " + std::string(dex_location)
                                + " because: " + error_msg);
        }
      } else {
        error_msgs->push_back("Fallback mode disabled, skipping dex files.");
      }
    } else {
      error_msgs->push_back("No original dex files found for dex location "
          + std::string(dex_location));
    }
  }
	//把加载的dex文件返回
  return dex_files;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值