Android6.0 dex优化

一、代码

Android6.0 PackageManagerService dex优化是在scanPackageDirtyLI函数中,代码如下:

  1. if ((scanFlags & SCAN_NO_DEX) == 0) {  
  2.     int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,  
  3.             forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,  
  4.             (scanFlags & SCAN_BOOTING) == 0);  
  5.     if (result == PackageDexOptimizer.DEX_OPT_FAILED) {  
  6.         throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");  
  7.     }  
  8. }  

主要是调用了PackageDexOptimizer.performDexOpt函数,这个函数又继续调用了performDexOptLI函数

  1. private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,  
  2.         boolean forceDex, boolean defer, boolean bootComplete, ArraySet<String> done) {  
  3.     final String[] instructionSets = targetInstructionSets != null ?  
  4.             targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);  
  5.   
  6.     if (done != null) {  
  7.         done.add(pkg.packageName);  
  8.         if (pkg.usesLibraries != null) {//是否有一些共享库的apk也要dex优化  
  9.             performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer,  
  10.                     bootComplete, done);  
  11.         }  
  12.         if (pkg.usesOptionalLibraries != null) {  
  13.             performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer,  
  14.                     bootComplete, done);  
  15.         }  
  16.     }  
  17.   
  18.     if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {//没有代码的pkg直接跳过  
  19.         return DEX_OPT_SKIPPED;  
  20.     }  
  21.   
  22.     final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;  
  23.     final boolean debuggable = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;  
  24.   
  25.     final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();  
  26.     boolean performedDexOpt = false;  
  27.     // There are three basic cases here:  
  28.     // 1.) we need to dexopt, either because we are forced or it is needed  
  29.     // 2.) we are deferring a needed dexopt  
  30.     // 3.) we are skipping an unneeded dexopt  
  31.     final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);  
  32.     for (String dexCodeInstructionSet : dexCodeInstructionSets) {  
  33.         if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {//没有强制或者已经dex优化过直接continue  
  34.             continue;  
  35.         }  
  36.   
  37.         for (String path : paths) {//遍历所有代码路径  
  38.             final int dexoptNeeded;  
  39.             if (forceDex) {  
  40.                 dexoptNeeded = DexFile.DEX2OAT_NEEDED;  
  41.             } else {  
  42.                 try {  
  43.                     dexoptNeeded = DexFile.getDexOptNeeded(path, pkg.packageName,  
  44.                             dexCodeInstructionSet, defer);  
  45.                 } catch (IOException ioe) {  
  46.                     Slog.w(TAG, "IOException reading apk: " + path, ioe);  
  47.                     return DEX_OPT_FAILED;  
  48.                 }  
  49.             }  
  50.   
  51.             if (!forceDex && defer && dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {  
  52.                 // We're deciding to defer a needed dexopt. Don't bother dexopting for other  
  53.                 // paths and instruction sets. We'll deal with them all together when we process  
  54.                 // our list of deferred dexopts.  
  55.                 addPackageForDeferredDexopt(pkg);  
  56.                 return DEX_OPT_DEFERRED;  
  57.             }  
  58.   
  59.             if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {  
  60.                 final String dexoptType;  
  61.                 String oatDir = null;  
  62.                 if (dexoptNeeded == DexFile.DEX2OAT_NEEDED) {  
  63.                     dexoptType = "dex2oat";//dex-opt类型  
  64.                     try {  
  65.                         oatDir = createOatDirIfSupported(pkg, dexCodeInstructionSet);//获取otaDir  
  66.                     } catch (IOException ioe) {  
  67.                         Slog.w(TAG, "Unable to create oatDir for package: " + pkg.packageName);  
  68.                         return DEX_OPT_FAILED;  
  69.                     }  
  70.                 } else if (dexoptNeeded == DexFile.PATCHOAT_NEEDED) {  
  71.                     dexoptType = "patchoat";  
  72.                 } else if (dexoptNeeded == DexFile.SELF_PATCHOAT_NEEDED) {  
  73.                     dexoptType = "self patchoat";  
  74.                 } else {  
  75.                     throw new IllegalStateException("Invalid dexopt needed: " + dexoptNeeded);  
  76.                 }  
  77.   
  78.                 Log.i(TAG, "Running dexopt (" + dexoptType + ") on: " + path + " pkg="//关键信息打印  
  79.                         + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet  
  80.                         + " vmSafeMode=" + vmSafeMode + " debuggable=" + debuggable  
  81.                         + " oatDir = " + oatDir + " bootComplete=" + bootComplete);  
  82.                 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);  
  83.                 final int ret = mPackageManagerService.mInstaller.dexopt(path, sharedGid,//调用installd的dexopt  
  84.                         !pkg.isForwardLocked(), pkg.packageName, dexCodeInstructionSet,  
  85.                         dexoptNeeded, vmSafeMode, debuggable, oatDir, bootComplete);  
  86.   
  87.                 // Dex2oat might fail due to compiler / verifier errors. We soldier on  
  88.                 // regardless, and attempt to interpret the app as a safety net.  
  89.                 if (ret == 0) {//Installd dexopt成功了  
  90.                     performedDexOpt = true;  
  91.                 }  
  92.             }  
  93.         }  
  94.   
  95.         // At this point we haven't failed dexopt and we haven't deferred dexopt. We must  
  96.         // either have either succeeded dexopt, or have had getDexOptNeeded tell us  
  97.         // it isn't required. We therefore mark that this package doesn't need dexopt unless  
  98.         // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped  
  99.         // it.  
  100.         pkg.mDexOptPerformed.add(dexCodeInstructionSet);//这代表已经处理过了  
  101.     }  
  102.   
  103.     // If we've gotten here, we're sure that no error occurred and that we haven't  
  104.     // deferred dex-opt. We've either dex-opted one more paths or instruction sets or  
  105.     // we've skipped all of them because they are up to date. In both cases this  
  106.     // package doesn't need dexopt any longer.  
  107.     return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;  
  108. }  

上面这个函数遍历apk所有的代码路径,根据解析得到dexoptType,最后用installd来完成dexopt工作。

其中还有一个当dexoptType为dex2oat时,会调用createOatDirIfSupported来得到oatdir,其他情况oatdir为空了。

createOatDirIfSupported函数也是codePath如果是目录,就用Installd在该目录下创建一个目录,如果是apk文件直接返回空。

  1. private String createOatDirIfSupported(PackageParser.Package pkg, String dexInstructionSet)  
  2.         throws IOException {  
  3.     if (!pkg.canHaveOatDir()) {  
  4.         return null;  
  5.     }  
  6.     File codePath = new File(pkg.codePath);  
  7.     if (codePath.isDirectory()) {  
  8.         File oatDir = getOatDir(codePath);  
  9.         mPackageManagerService.mInstaller.createOatDir(oatDir.getAbsolutePath(),  
  10.                 dexInstructionSet);  
  11.         return oatDir.getAbsolutePath();  
  12.     }  
  13.     return null;  
  14. }  


最后我们再来看下Installd的dexopt函数,先会根据oat_dir是否为空,如果不为空判断是否有效,然后也会根据这个oat_dir计算这个out_path,没有oat_dir就会调用create_cache_path函数来计算out_path。

  1. int dexopt(const char *apk_path, uid_t uid, bool is_public,  
  2.            const char *pkgname, const char *instruction_set, int dexopt_needed,  
  3.            bool vm_safe_mode, bool debuggable, const char* oat_dir, bool boot_complete)  
  4. {  
  5.     ......  
  6.     // Early best-effort check whether we can fit the the path into our buffers.  
  7.     // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run  
  8.     // without a swap file, if necessary.  
  9.     if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {  
  10.         ALOGE("apk_path too long '%s'\n", apk_path);  
  11.         return -1;  
  12.     }  
  13.   
  14.     if (oat_dir != NULL && oat_dir[0] != '!') {  
  15.         if (validate_apk_path(oat_dir)) {  
  16.             ALOGE("invalid oat_dir '%s'\n", oat_dir);  
  17.             return -1;  
  18.         }  
  19.         if (calculate_oat_file_path(out_path, oat_dir, apk_path, instruction_set)) {  
  20.             return -1;  
  21.         }  
  22.     } else {  
  23.         if (create_cache_path(out_path, apk_path, instruction_set)) {  
  24.             return -1;  
  25.         }  
  26.     }  

calculate_oat_file_path函数就会根据oat_dir等来生成out_path.

  1. int calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir, const char *apk_path,  
  2.         const char *instruction_set) {  
  3.     char *file_name_start;  
  4.     char *file_name_end;  
  5.   
  6.     file_name_start = strrchr(apk_path, '/');  
  7.     if (file_name_start == NULL) {  
  8.          ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);  
  9.         return -1;  
  10.     }  
  11.     file_name_end = strrchr(apk_path, '.');  
  12.     if (file_name_end < file_name_start) {  
  13.         ALOGE("apk_path '%s' has no extension\n", apk_path);  
  14.         return -1;  
  15.     }  
  16.   
  17.     // Calculate file_name  
  18.     int file_name_len = file_name_end - file_name_start - 1;  
  19.     char file_name[file_name_len + 1];  
  20.     memcpy(file_name, file_name_start + 1, file_name_len);  
  21.     file_name[file_name_len] = '\0';  
  22.   
  23.     // <apk_parent_dir>/oat/<isa>/<file_name>.odex  
  24.     snprintf(path, PKG_PATH_MAX, "%s/%s/%s.odex", oat_dir, instruction_set, file_name);  
  25.     return 0;  
  26. }  

没有oat_dir就会调用create_cache_path函数来计算out_path,最后会在DALVIK_CACHE_PREFIX目录下创建,而这个目录就是/data/dalvik-cache/,也就是最终会在这个目录下生成dex文件。

  1. int create_cache_path(char path[PKG_PATH_MAX], const char *src, const char *instruction_set)  
  2. {  
  3.     char *tmp;  
  4.     int srclen;  
  5.     int dstlen;  
  6.   
  7.     srclen = strlen(src);  
  8.   
  9.         /* demand that we are an absolute path */  
  10.     if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {  
  11.         return -1;  
  12.     }  
  13.   
  14.     if (srclen > PKG_PATH_MAX) {        // XXX: PKG_NAME_MAX?  
  15.         return -1;  
  16.     }  
  17.   
  18.     dstlen = srclen + strlen(DALVIK_CACHE_PREFIX) +  
  19.         strlen(instruction_set) +  
  20.         strlen(DALVIK_CACHE_POSTFIX) + 2;  
  21.   
  22.     if (dstlen > PKG_PATH_MAX) {  
  23.         return -1;  
  24.     }  
  25.   
  26.     sprintf(path,"%s%s/%s%s",  
  27.             DALVIK_CACHE_PREFIX,  
  28.             instruction_set,  
  29.             src + 1, /* skip the leading / */  
  30.             DALVIK_CACHE_POSTFIX);  
  31.   
  32.     for(tmp = path + strlen(DALVIK_CACHE_PREFIX) + strlen(instruction_set) + 1; *tmp; tmp++) {  
  33.         if (*tmp == '/') {  
  34.             *tmp = '@';  
  35.         }  
  36.     }  
  37.   
  38.     return 0;  
  39. }  

继续分析dexopt函数,根据dexopt类型来看源文件,一般是apk文件

  1. switch (dexopt_needed) {  
  2.     case DEXOPT_DEX2OAT_NEEDED:  
  3.         input_file = apk_path;  
  4.         break;  
  5.   
  6.     case DEXOPT_PATCHOAT_NEEDED:  
  7.         if (!calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {  
  8.             return -1;  
  9.         }  
  10.         input_file = in_odex_path;  
  11.         break;  
  12.   
  13.     case DEXOPT_SELF_PATCHOAT_NEEDED:  
  14.         input_file = out_path;  
  15.         break;  
  16.   
  17.     default:  
  18.         ALOGE("Invalid dexopt needed: %d\n", dexopt_needed);  
  19.         exit(72);  
  20. }  

后面就是打开文件,然后fork进程,调用run_dex2oat函数来执行。我们就不分析了


二、实例

2.1 没有目录

最终如果你的apk没有目录,会在如下目录有classes.dex后缀的文件。

  1. root@lc1861evb_arm64:/data/dalvik-cache/arm # ls  
  2. data@app@IflytekInput.apk@classes.dex  
  3. data@app@NotePadPlus.apk@classes.dex  


2.2 有目录

而有目录的,比如我们自己安装的墨迹天气,会有一个oat目录,最后有一个base.odex文件

  1. root@lc1861evb_arm64:/data/app/com.moji.mjweather-1/oat/arm # ls  
  2. base.odex 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值