一、代码
Android6.0 PackageManagerService dex优化是在scanPackageDirtyLI函数中,代码如下:
- if ((scanFlags & SCAN_NO_DEX) == 0) {
- int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
- forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,
- (scanFlags & SCAN_BOOTING) == 0);
- if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
- throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
- }
- }
主要是调用了PackageDexOptimizer.performDexOpt函数,这个函数又继续调用了performDexOptLI函数
- private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
- boolean forceDex, boolean defer, boolean bootComplete, ArraySet<String> done) {
- final String[] instructionSets = targetInstructionSets != null ?
- targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
- if (done != null) {
- done.add(pkg.packageName);
- if (pkg.usesLibraries != null) {//是否有一些共享库的apk也要dex优化
- performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer,
- bootComplete, done);
- }
- if (pkg.usesOptionalLibraries != null) {
- performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer,
- bootComplete, done);
- }
- }
- if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {//没有代码的pkg直接跳过
- return DEX_OPT_SKIPPED;
- }
- final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
- final boolean debuggable = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
- final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
- boolean performedDexOpt = false;
- // There are three basic cases here:
- // 1.) we need to dexopt, either because we are forced or it is needed
- // 2.) we are deferring a needed dexopt
- // 3.) we are skipping an unneeded dexopt
- final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
- for (String dexCodeInstructionSet : dexCodeInstructionSets) {
- if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {//没有强制或者已经dex优化过直接continue
- continue;
- }
- for (String path : paths) {//遍历所有代码路径
- final int dexoptNeeded;
- if (forceDex) {
- dexoptNeeded = DexFile.DEX2OAT_NEEDED;
- } else {
- try {
- dexoptNeeded = DexFile.getDexOptNeeded(path, pkg.packageName,
- dexCodeInstructionSet, defer);
- } catch (IOException ioe) {
- Slog.w(TAG, "IOException reading apk: " + path, ioe);
- return DEX_OPT_FAILED;
- }
- }
- if (!forceDex && defer && dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
- // We're deciding to defer a needed dexopt. Don't bother dexopting for other
- // paths and instruction sets. We'll deal with them all together when we process
- // our list of deferred dexopts.
- addPackageForDeferredDexopt(pkg);
- return DEX_OPT_DEFERRED;
- }
- if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
- final String dexoptType;
- String oatDir = null;
- if (dexoptNeeded == DexFile.DEX2OAT_NEEDED) {
- dexoptType = "dex2oat";//dex-opt类型
- try {
- oatDir = createOatDirIfSupported(pkg, dexCodeInstructionSet);//获取otaDir
- } catch (IOException ioe) {
- Slog.w(TAG, "Unable to create oatDir for package: " + pkg.packageName);
- return DEX_OPT_FAILED;
- }
- } else if (dexoptNeeded == DexFile.PATCHOAT_NEEDED) {
- dexoptType = "patchoat";
- } else if (dexoptNeeded == DexFile.SELF_PATCHOAT_NEEDED) {
- dexoptType = "self patchoat";
- } else {
- throw new IllegalStateException("Invalid dexopt needed: " + dexoptNeeded);
- }
- Log.i(TAG, "Running dexopt (" + dexoptType + ") on: " + path + " pkg="//关键信息打印
- + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
- + " vmSafeMode=" + vmSafeMode + " debuggable=" + debuggable
- + " oatDir = " + oatDir + " bootComplete=" + bootComplete);
- final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
- final int ret = mPackageManagerService.mInstaller.dexopt(path, sharedGid,//调用installd的dexopt
- !pkg.isForwardLocked(), pkg.packageName, dexCodeInstructionSet,
- dexoptNeeded, vmSafeMode, debuggable, oatDir, bootComplete);
- // Dex2oat might fail due to compiler / verifier errors. We soldier on
- // regardless, and attempt to interpret the app as a safety net.
- if (ret == 0) {//Installd dexopt成功了
- performedDexOpt = true;
- }
- }
- }
- // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
- // either have either succeeded dexopt, or have had getDexOptNeeded tell us
- // it isn't required. We therefore mark that this package doesn't need dexopt unless
- // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
- // it.
- pkg.mDexOptPerformed.add(dexCodeInstructionSet);//这代表已经处理过了
- }
- // If we've gotten here, we're sure that no error occurred and that we haven't
- // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
- // we've skipped all of them because they are up to date. In both cases this
- // package doesn't need dexopt any longer.
- return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
- }
上面这个函数遍历apk所有的代码路径,根据解析得到dexoptType,最后用installd来完成dexopt工作。
其中还有一个当dexoptType为dex2oat时,会调用createOatDirIfSupported来得到oatdir,其他情况oatdir为空了。
createOatDirIfSupported函数也是codePath如果是目录,就用Installd在该目录下创建一个目录,如果是apk文件直接返回空。
- private String createOatDirIfSupported(PackageParser.Package pkg, String dexInstructionSet)
- throws IOException {
- if (!pkg.canHaveOatDir()) {
- return null;
- }
- File codePath = new File(pkg.codePath);
- if (codePath.isDirectory()) {
- File oatDir = getOatDir(codePath);
- mPackageManagerService.mInstaller.createOatDir(oatDir.getAbsolutePath(),
- dexInstructionSet);
- return oatDir.getAbsolutePath();
- }
- return null;
- }
最后我们再来看下Installd的dexopt函数,先会根据oat_dir是否为空,如果不为空判断是否有效,然后也会根据这个oat_dir计算这个out_path,没有oat_dir就会调用create_cache_path函数来计算out_path。
- int dexopt(const char *apk_path, uid_t uid, bool is_public,
- const char *pkgname, const char *instruction_set, int dexopt_needed,
- bool vm_safe_mode, bool debuggable, const char* oat_dir, bool boot_complete)
- {
- ......
- // Early best-effort check whether we can fit the the path into our buffers.
- // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
- // without a swap file, if necessary.
- if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
- ALOGE("apk_path too long '%s'\n", apk_path);
- return -1;
- }
- if (oat_dir != NULL && oat_dir[0] != '!') {
- if (validate_apk_path(oat_dir)) {
- ALOGE("invalid oat_dir '%s'\n", oat_dir);
- return -1;
- }
- if (calculate_oat_file_path(out_path, oat_dir, apk_path, instruction_set)) {
- return -1;
- }
- } else {
- if (create_cache_path(out_path, apk_path, instruction_set)) {
- return -1;
- }
- }
calculate_oat_file_path函数就会根据oat_dir等来生成out_path.
- int calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir, const char *apk_path,
- const char *instruction_set) {
- char *file_name_start;
- char *file_name_end;
- file_name_start = strrchr(apk_path, '/');
- if (file_name_start == NULL) {
- ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
- return -1;
- }
- file_name_end = strrchr(apk_path, '.');
- if (file_name_end < file_name_start) {
- ALOGE("apk_path '%s' has no extension\n", apk_path);
- return -1;
- }
- // Calculate file_name
- int file_name_len = file_name_end - file_name_start - 1;
- char file_name[file_name_len + 1];
- memcpy(file_name, file_name_start + 1, file_name_len);
- file_name[file_name_len] = '\0';
- // <apk_parent_dir>/oat/<isa>/<file_name>.odex
- snprintf(path, PKG_PATH_MAX, "%s/%s/%s.odex", oat_dir, instruction_set, file_name);
- return 0;
- }
没有oat_dir就会调用create_cache_path函数来计算out_path,最后会在DALVIK_CACHE_PREFIX目录下创建,而这个目录就是/data/dalvik-cache/,也就是最终会在这个目录下生成dex文件。
- int create_cache_path(char path[PKG_PATH_MAX], const char *src, const char *instruction_set)
- {
- char *tmp;
- int srclen;
- int dstlen;
- srclen = strlen(src);
- /* demand that we are an absolute path */
- if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
- return -1;
- }
- if (srclen > PKG_PATH_MAX) { // XXX: PKG_NAME_MAX?
- return -1;
- }
- dstlen = srclen + strlen(DALVIK_CACHE_PREFIX) +
- strlen(instruction_set) +
- strlen(DALVIK_CACHE_POSTFIX) + 2;
- if (dstlen > PKG_PATH_MAX) {
- return -1;
- }
- sprintf(path,"%s%s/%s%s",
- DALVIK_CACHE_PREFIX,
- instruction_set,
- src + 1, /* skip the leading / */
- DALVIK_CACHE_POSTFIX);
- for(tmp = path + strlen(DALVIK_CACHE_PREFIX) + strlen(instruction_set) + 1; *tmp; tmp++) {
- if (*tmp == '/') {
- *tmp = '@';
- }
- }
- return 0;
- }
继续分析dexopt函数,根据dexopt类型来看源文件,一般是apk文件
- switch (dexopt_needed) {
- case DEXOPT_DEX2OAT_NEEDED:
- input_file = apk_path;
- break;
- case DEXOPT_PATCHOAT_NEEDED:
- if (!calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
- return -1;
- }
- input_file = in_odex_path;
- break;
- case DEXOPT_SELF_PATCHOAT_NEEDED:
- input_file = out_path;
- break;
- default:
- ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);
- exit(72);
- }
后面就是打开文件,然后fork进程,调用run_dex2oat函数来执行。我们就不分析了
二、实例
2.1 没有目录
最终如果你的apk没有目录,会在如下目录有classes.dex后缀的文件。
- root@lc1861evb_arm64:/data/dalvik-cache/arm # ls
- data@app@IflytekInput.apk@classes.dex
- data@app@NotePadPlus.apk@classes.dex
2.2 有目录
而有目录的,比如我们自己安装的墨迹天气,会有一个oat目录,最后有一个base.odex文件
- root@lc1861evb_arm64:/data/app/com.moji.mjweather-1/oat/arm # ls
- base.odex