• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.content.pm.dex;
18 
19 import static android.content.pm.PackageManager.INSTALL_FAILED_BAD_DEX_METADATA;
20 import static android.content.pm.PackageParser.APK_FILE_EXTENSION;
21 
22 import android.content.pm.PackageParser;
23 import android.content.pm.PackageParser.PackageLite;
24 import android.content.pm.PackageParser.PackageParserException;
25 import android.util.ArrayMap;
26 import android.util.jar.StrictJarFile;
27 
28 import java.io.File;
29 import java.io.IOException;
30 import java.nio.file.Files;
31 import java.nio.file.Paths;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.List;
35 import java.util.Map;
36 
37 /**
38  * Helper class used to compute and validate the location of dex metadata files.
39  *
40  * @hide
41  */
42 public class DexMetadataHelper {
43     private static final String DEX_METADATA_FILE_EXTENSION = ".dm";
44 
DexMetadataHelper()45     private DexMetadataHelper() {}
46 
47     /** Return true if the given file is a dex metadata file. */
isDexMetadataFile(File file)48     public static boolean isDexMetadataFile(File file) {
49         return isDexMetadataPath(file.getName());
50     }
51 
52     /** Return true if the given path is a dex metadata path. */
isDexMetadataPath(String path)53     private static boolean isDexMetadataPath(String path) {
54         return path.endsWith(DEX_METADATA_FILE_EXTENSION);
55     }
56 
57     /**
58      * Return the size (in bytes) of all dex metadata files associated with the given package.
59      */
getPackageDexMetadataSize(PackageLite pkg)60     public static long getPackageDexMetadataSize(PackageLite pkg) {
61         long sizeBytes = 0;
62         Collection<String> dexMetadataList = DexMetadataHelper.getPackageDexMetadata(pkg).values();
63         for (String dexMetadata : dexMetadataList) {
64             sizeBytes += new File(dexMetadata).length();
65         }
66         return sizeBytes;
67     }
68 
69     /**
70      * Search for the dex metadata file associated with the given target file.
71      * If it exists, the method returns the dex metadata file; otherwise it returns null.
72      *
73      * Note that this performs a loose matching suitable to be used in the InstallerSession logic.
74      * i.e. the method will attempt to match the {@code dmFile} regardless of {@code targetFile}
75      * extension (e.g. 'foo.dm' will match 'foo' or 'foo.apk').
76      */
findDexMetadataForFile(File targetFile)77     public static File findDexMetadataForFile(File targetFile) {
78         String dexMetadataPath = buildDexMetadataPathForFile(targetFile);
79         File dexMetadataFile = new File(dexMetadataPath);
80         return dexMetadataFile.exists() ? dexMetadataFile : null;
81     }
82 
83     /**
84      * Return the dex metadata files for the given package as a map
85      * [code path -> dex metadata path].
86      *
87      * NOTE: involves I/O checks.
88      */
getPackageDexMetadata(PackageLite pkg)89     private static Map<String, String> getPackageDexMetadata(PackageLite pkg) {
90         return buildPackageApkToDexMetadataMap(pkg.getAllCodePaths());
91     }
92 
93     /**
94      * Look up the dex metadata files for the given code paths building the map
95      * [code path -> dex metadata].
96      *
97      * For each code path (.apk) the method checks if a matching dex metadata file (.dm) exists.
98      * If it does it adds the pair to the returned map.
99      *
100      * Note that this method will do a loose
101      * matching based on the extension ('foo.dm' will match 'foo.apk' or 'foo').
102      *
103      * This should only be used for code paths extracted from a package structure after the naming
104      * was enforced in the installer.
105      */
buildPackageApkToDexMetadataMap( List<String> codePaths)106     public static Map<String, String> buildPackageApkToDexMetadataMap(
107             List<String> codePaths) {
108         ArrayMap<String, String> result = new ArrayMap<>();
109         for (int i = codePaths.size() - 1; i >= 0; i--) {
110             String codePath = codePaths.get(i);
111             String dexMetadataPath = buildDexMetadataPathForFile(new File(codePath));
112 
113             if (Files.exists(Paths.get(dexMetadataPath))) {
114                 result.put(codePath, dexMetadataPath);
115             }
116         }
117 
118         return result;
119     }
120 
121     /**
122      * Return the dex metadata path associated with the given code path.
123      * (replaces '.apk' extension with '.dm')
124      *
125      * @throws IllegalArgumentException if the code path is not an .apk.
126      */
buildDexMetadataPathForApk(String codePath)127     public static String buildDexMetadataPathForApk(String codePath) {
128         if (!PackageParser.isApkPath(codePath)) {
129             throw new IllegalStateException(
130                     "Corrupted package. Code path is not an apk " + codePath);
131         }
132         return codePath.substring(0, codePath.length() - APK_FILE_EXTENSION.length())
133                 + DEX_METADATA_FILE_EXTENSION;
134     }
135 
136     /**
137      * Return the dex metadata path corresponding to the given {@code targetFile} using a loose
138      * matching.
139      * i.e. the method will attempt to match the {@code dmFile} regardless of {@code targetFile}
140      * extension (e.g. 'foo.dm' will match 'foo' or 'foo.apk').
141      */
buildDexMetadataPathForFile(File targetFile)142     private static String buildDexMetadataPathForFile(File targetFile) {
143         return PackageParser.isApkFile(targetFile)
144                 ? buildDexMetadataPathForApk(targetFile.getPath())
145                 : targetFile.getPath() + DEX_METADATA_FILE_EXTENSION;
146     }
147 
148     /**
149      * Validate that the given file is a dex metadata archive.
150      * This is just a sanity validation that the file is a zip archive.
151      *
152      * @throws PackageParserException if the file is not a .dm file.
153      */
validateDexMetadataFile(String dmaPath)154     public static void validateDexMetadataFile(String dmaPath) throws PackageParserException {
155         StrictJarFile jarFile = null;
156         try {
157             jarFile = new StrictJarFile(dmaPath, false, false);
158         } catch (IOException e) {
159             throw new PackageParserException(INSTALL_FAILED_BAD_DEX_METADATA,
160                     "Error opening " + dmaPath, e);
161         } finally {
162             if (jarFile != null) {
163                 try {
164                     jarFile.close();
165                 } catch (IOException ignored) {
166                 }
167             }
168         }
169     }
170 
171     /**
172      * Validates that all dex metadata paths in the given list have a matching apk.
173      * (for any foo.dm there should be either a 'foo' of a 'foo.apk' file).
174      * If that's not the case it throws {@code IllegalStateException}.
175      *
176      * This is used to perform a basic sanity check during adb install commands.
177      * (The installer does not support stand alone .dm files)
178      */
validateDexPaths(String[] paths)179     public static void validateDexPaths(String[] paths) {
180         ArrayList<String> apks = new ArrayList<>();
181         for (int i = 0; i < paths.length; i++) {
182             if (PackageParser.isApkPath(paths[i])) {
183                 apks.add(paths[i]);
184             }
185         }
186         ArrayList<String> unmatchedDmFiles = new ArrayList<>();
187         for (int i = 0; i < paths.length; i++) {
188             String dmPath = paths[i];
189             if (isDexMetadataPath(dmPath)) {
190                 boolean valid = false;
191                 for (int j = apks.size() - 1; j >= 0; j--) {
192                     if (dmPath.equals(buildDexMetadataPathForFile(new File(apks.get(j))))) {
193                         valid = true;
194                         break;
195                     }
196                 }
197                 if (!valid) {
198                     unmatchedDmFiles.add(dmPath);
199                 }
200             }
201         }
202         if (!unmatchedDmFiles.isEmpty()) {
203             throw new IllegalStateException("Unmatched .dm files: " + unmatchedDmFiles);
204         }
205     }
206 
207 }
208