DexoptUtils.java revision 9aab3b513d7a224270a578c128f334ad7c0334ff
1/*
2 * Copyright (C) 2017 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
17package com.android.server.pm.dex;
18
19import android.content.pm.ApplicationInfo;
20import android.util.Slog;
21import android.util.SparseArray;
22
23import java.io.File;
24import java.util.ArrayList;
25import java.util.Arrays;
26import java.util.List;
27
28public final class DexoptUtils {
29    private static final String TAG = "DexoptUtils";
30
31    private DexoptUtils() {}
32
33    /**
34     * Creates the class loader context dependencies for each of the application code paths.
35     * The returned array contains the class loader contexts that needs to be passed to dexopt in
36     * order to ensure correct optimizations. "Code" paths with no actual code, as specified by
37     * {@param pathsWithCode}, are ignored and will have null as their context in the returned array
38     * (configuration splits are an example of paths without code).
39     *
40     * A class loader context describes how the class loader chain should be built by dex2oat
41     * in order to ensure that classes are resolved during compilation as they would be resolved
42     * at runtime. The context will be encoded in the compiled code. If at runtime the dex file is
43     * loaded in a different context (with a different set of class loaders or a different
44     * classpath), the compiled code will be rejected.
45     *
46     * Note that the class loader context only includes dependencies and not the code path itself.
47     * The contexts are created based on the application split dependency list and
48     * the provided shared libraries.
49     *
50     * All the code paths encoded in the context will be relative to the base directory. This
51     * enables stage compilation where compiler artifacts may be moved around.
52     *
53     * The result is indexed as follows:
54     *   - index 0 contains the context for the base apk
55     *   - index 1 to n contain the context for the splits in the order determined by
56     *     {@code info.getSplitCodePaths()}
57     *
58     * IMPORTANT: keep this logic in sync with the loading code in {@link android.app.LoadedApk}
59     * and pay attention to the way the classpath is created for the non isolated mode in:
60     * {@link android.app.LoadedApk#makePaths(
61     * android.app.ActivityThread, boolean, ApplicationInfo, List, List)}.
62     */
63    public static String[] getClassLoaderContexts(ApplicationInfo info,
64            String[] sharedLibraries, boolean[] pathsWithCode) {
65        // The base class loader context contains only the shared library.
66        String sharedLibrariesClassPath = encodeClasspath(sharedLibraries);
67        String baseApkContextClassLoader = encodeClassLoader(
68                sharedLibrariesClassPath, "dalvik.system.PathClassLoader");
69
70        if (info.getSplitCodePaths() == null) {
71            // The application has no splits.
72            return new String[] {baseApkContextClassLoader};
73        }
74
75        // The application has splits. Compute their class loader contexts.
76
77        // First, cache the relative paths of the splits and do some sanity checks
78        String[] splitRelativeCodePaths = getSplitRelativeCodePaths(info);
79
80        // The splits have an implicit dependency on the base apk.
81        // This means that we have to add the base apk file in addition to the shared libraries.
82        String baseApkName = new File(info.getBaseCodePath()).getName();
83        String sharedLibrariesAndBaseClassPath =
84                encodeClasspath(sharedLibrariesClassPath, baseApkName);
85
86        // The result is stored in classLoaderContexts.
87        // Index 0 is the class loaded context for the base apk.
88        // Index `i` is the class loader context encoding for split `i`.
89        String[] classLoaderContexts = new String[/*base apk*/ 1 + splitRelativeCodePaths.length];
90        classLoaderContexts[0] = pathsWithCode[0] ? baseApkContextClassLoader : null;
91
92        if (!info.requestsIsolatedSplitLoading() || info.splitDependencies == null) {
93            // If the app didn't request for the splits to be loaded in isolation or if it does not
94            // declare inter-split dependencies, then all the splits will be loaded in the base
95            // apk class loader (in the order of their definition).
96            String classpath = sharedLibrariesAndBaseClassPath;
97            for (int i = 1; i < classLoaderContexts.length; i++) {
98                classLoaderContexts[i] = pathsWithCode[i]
99                        ? encodeClassLoader(classpath, "dalvik.system.PathClassLoader") : null;
100                // Note that the splits with no code are not removed from the classpath computation.
101                // i.e. split_n might get the split_n-1 in its classpath dependency even
102                // if split_n-1 has no code.
103                // The splits with no code do not matter for the runtime which ignores
104                // apks without code when doing the classpath checks. As such we could actually
105                // filter them but we don't do it in order to keep consistency with how the apps
106                // are loaded.
107                classpath = encodeClasspath(classpath, splitRelativeCodePaths[i - 1]);
108            }
109        } else {
110            // In case of inter-split dependencies, we need to walk the dependency chain of each
111            // split. We do this recursively and store intermediate results in classLoaderContexts.
112
113            // First, look at the split class loaders and cache their individual contexts (i.e.
114            // the class loader + the name of the split). This is an optimization to avoid
115            // re-computing them during the recursive call.
116            // The cache is stored in splitClassLoaderEncodingCache. The difference between this and
117            // classLoaderContexts is that the later contains the full chain of class loaders for
118            // a given split while splitClassLoaderEncodingCache only contains a single class loader
119            // encoding.
120            String[] splitClassLoaderEncodingCache = new String[splitRelativeCodePaths.length];
121            for (int i = 0; i < splitRelativeCodePaths.length; i++) {
122                splitClassLoaderEncodingCache[i] = encodeClassLoader(splitRelativeCodePaths[i],
123                        "dalvik.system.PathClassLoader");
124            }
125            String splitDependencyOnBase = encodeClassLoader(
126                    sharedLibrariesAndBaseClassPath, "dalvik.system.PathClassLoader");
127            SparseArray<int[]> splitDependencies = info.splitDependencies;
128
129            // Note that not all splits have dependencies (e.g. configuration splits)
130            // The splits without dependencies will have classLoaderContexts[config_split_index]
131            // set to null after this step.
132            for (int i = 1; i < splitDependencies.size(); i++) {
133                int splitIndex = splitDependencies.keyAt(i);
134                if (pathsWithCode[splitIndex]) {
135                    // Compute the class loader context only for the splits with code.
136                    getParentDependencies(splitIndex, splitClassLoaderEncodingCache,
137                            splitDependencies, classLoaderContexts, splitDependencyOnBase);
138                }
139            }
140
141            // At this point classLoaderContexts contains only the parent dependencies.
142            // We also need to add the class loader of the current split which should
143            // come first in the context.
144            for (int i = 1; i < classLoaderContexts.length; i++) {
145                String splitClassLoader = encodeClassLoader("", "dalvik.system.PathClassLoader");
146                if (pathsWithCode[i]) {
147                    // If classLoaderContexts[i] is null it means that the split does not have
148                    // any dependency. In this case its context equals its declared class loader.
149                    classLoaderContexts[i] = classLoaderContexts[i] == null
150                            ? splitClassLoader
151                            : encodeClassLoaderChain(splitClassLoader, classLoaderContexts[i]);
152                } else {
153                    // This is a split without code, it has no dependency and it is not compiled.
154                    // Its context will be null.
155                    classLoaderContexts[i] = null;
156                }
157            }
158        }
159
160        return classLoaderContexts;
161    }
162
163    /**
164     * Recursive method to generate the class loader context dependencies for the split with the
165     * given index. {@param classLoaderContexts} acts as an accumulator. Upton return
166     * {@code classLoaderContexts[index]} will contain the split dependency.
167     * During computation, the method may resolve the dependencies of other splits as it traverses
168     * the entire parent chain. The result will also be stored in {@param classLoaderContexts}.
169     *
170     * Note that {@code index 0} denotes the base apk and it is special handled. When the
171     * recursive call hits {@code index 0} the method returns {@code splitDependencyOnBase}.
172     * {@code classLoaderContexts[0]} is not modified in this method.
173     *
174     * @param index the index of the split (Note that index 0 denotes the base apk)
175     * @param splitClassLoaderEncodingCache the class loader encoding for the individual splits.
176     *    It contains only the split class loader and not the the base. The split
177     *    with {@code index} has its context at {@code splitClassLoaderEncodingCache[index - 1]}.
178     * @param splitDependencies the dependencies for all splits. Note that in this array index 0
179     *    is the base and splits start from index 1.
180     * @param classLoaderContexts the result accumulator. index 0 is the base and never set. Splits
181     *    start at index 1.
182     * @param splitDependencyOnBase the encoding of the implicit split dependency on base.
183     */
184    private static String getParentDependencies(int index, String[] splitClassLoaderEncodingCache,
185            SparseArray<int[]> splitDependencies, String[] classLoaderContexts,
186            String splitDependencyOnBase) {
187        // If we hit the base apk return its custom dependency list which is
188        // sharedLibraries + base.apk
189        if (index == 0) {
190            return splitDependencyOnBase;
191        }
192        // Return the result if we've computed the splitDependencies for this index already.
193        if (classLoaderContexts[index] != null) {
194            return classLoaderContexts[index];
195        }
196        // Get the splitDependencies for the parent of this index and append its path to it.
197        int parent = splitDependencies.get(index)[0];
198        String parentDependencies = getParentDependencies(parent, splitClassLoaderEncodingCache,
199                splitDependencies, classLoaderContexts, splitDependencyOnBase);
200
201        // The split context is: `parent context + parent dependencies context`.
202        String splitContext = (parent == 0) ?
203                parentDependencies :
204                encodeClassLoaderChain(splitClassLoaderEncodingCache[parent - 1], parentDependencies);
205        classLoaderContexts[index] = splitContext;
206        return splitContext;
207    }
208
209    /**
210     * Encodes the shared libraries classpathElements in a format accepted by dexopt.
211     * NOTE: Keep this in sync with the dexopt expectations! Right now that is
212     * a list separated by ':'.
213     */
214    private static String encodeClasspath(String[] classpathElements) {
215        if (classpathElements == null || classpathElements.length == 0) {
216            return "";
217        }
218        StringBuilder sb = new StringBuilder();
219        for (String element : classpathElements) {
220            if (sb.length() != 0) {
221                sb.append(":");
222            }
223            sb.append(element);
224        }
225        return sb.toString();
226    }
227
228    /**
229     * Adds an element to the encoding of an existing classpath.
230     * {@see PackageDexOptimizer.encodeClasspath(String[])}
231     */
232    private static String encodeClasspath(String classpath, String newElement) {
233        return classpath.isEmpty() ? newElement : (classpath + ":" + newElement);
234    }
235
236    /**
237     * Encodes a single class loader dependency starting from {@param path} and
238     * {@param classLoaderName}.
239     * NOTE: Keep this in sync with the dexopt expectations! Right now that is either "PCL[path]"
240     * for a PathClassLoader or "DLC[path]" for a DelegateLastClassLoader.
241     */
242    private static String encodeClassLoader(String classpath, String classLoaderName) {
243        String classLoaderDexoptEncoding = classLoaderName;
244        if ("dalvik.system.PathClassLoader".equals(classLoaderName)) {
245            classLoaderDexoptEncoding = "PCL";
246        } else {
247            Slog.wtf(TAG, "Unsupported classLoaderName: " + classLoaderName);
248        }
249        return classLoaderDexoptEncoding + "[" + classpath + "]";
250    }
251
252    /**
253     * Links to dependencies together in a format accepted by dexopt.
254     * NOTE: Keep this in sync with the dexopt expectations! Right now that is a list of split
255     * dependencies {@see encodeClassLoader} separated by ';'.
256     */
257    private static String encodeClassLoaderChain(String cl1, String cl2) {
258        if (cl1.isEmpty()) return cl2;
259        if (cl2.isEmpty()) return cl1;
260        return cl1 + ";" + cl2;
261    }
262
263    /**
264     * Compute the class loader context for the dex files present in the classpath of the first
265     * class loader from the given list (referred in the code as the {@code loadingClassLoader}).
266     * Each dex files gets its own class loader context in the returned array.
267     *
268     * Example:
269     *    If classLoadersNames = {"dalvik.system.DelegateLastClassLoader",
270     *    "dalvik.system.PathClassLoader"} and classPaths = {"foo.dex:bar.dex", "other.dex"}
271     *    The output will be
272     *    {"DLC[];PCL[other.dex]", "DLC[foo.dex];PCL[other.dex]"}
273     *    with "DLC[];PCL[other.dex]" being the context for "foo.dex"
274     *    and "DLC[foo.dex];PCL[other.dex]" the context for "bar.dex".
275     *
276     * If any of the class loaders names is unsupported the method will return null.
277     *
278     * The argument lists must be non empty and of the same size.
279     *
280     * @param classLoadersNames the names of the class loaders present in the loading chain. The
281     *    list encodes the class loader chain in the natural order. The first class loader has
282     *    the second one as its parent and so on.
283     * @param classPaths the class paths for the elements of {@param classLoadersNames}. The
284     *     the first element corresponds to the first class loader and so on. A classpath is
285     *     represented as a list of dex files separated by {@code File.pathSeparator}.
286     *     The return context will be for the dex files found in the first class path.
287     */
288    /*package*/ static String[] processContextForDexLoad(List<String> classLoadersNames,
289            List<String> classPaths) {
290        if (classLoadersNames.size() != classPaths.size()) {
291            throw new IllegalArgumentException(
292                    "The size of the class loader names and the dex paths do not match.");
293        }
294        if (classLoadersNames.isEmpty()) {
295            throw new IllegalArgumentException("Empty classLoadersNames");
296        }
297
298        // Compute the context for the parent class loaders.
299        String parentContext = "";
300        // We know that these lists are actually ArrayLists so getting the elements by index
301        // is fine (they come over binder). Even if something changes we expect the sizes to be
302        // very small and it shouldn't matter much.
303        for (int i = 1; i < classLoadersNames.size(); i++) {
304            if (!isValidClassLoaderName(classLoadersNames.get(i))) {
305                return null;
306            }
307            String classpath = encodeClasspath(classPaths.get(i).split(File.pathSeparator));
308            parentContext = encodeClassLoaderChain(parentContext,
309                    encodeClassLoader(classpath, classLoadersNames.get(i)));
310        }
311
312        // Now compute the class loader context for each dex file from the first classpath.
313        String loadingClassLoader = classLoadersNames.get(0);
314        if (!isValidClassLoaderName(loadingClassLoader)) {
315            return null;
316        }
317        String[] loadedDexPaths = classPaths.get(0).split(File.pathSeparator);
318        String[] loadedDexPathsContext = new String[loadedDexPaths.length];
319        String currentLoadedDexPathClasspath = "";
320        for (int i = 0; i < loadedDexPaths.length; i++) {
321            String dexPath = loadedDexPaths[i];
322            String currentContext = encodeClassLoader(
323                    currentLoadedDexPathClasspath, loadingClassLoader);
324            loadedDexPathsContext[i] = encodeClassLoaderChain(currentContext, parentContext);
325            currentLoadedDexPathClasspath = encodeClasspath(currentLoadedDexPathClasspath, dexPath);
326        }
327        return loadedDexPathsContext;
328    }
329
330    // AOSP-only hack.
331    private static boolean isValidClassLoaderName(String name) {
332        return "dalvik.system.PathClassLoader".equals(name) || "dalvik.system.DexClassLoader".equals(name);
333    }
334
335    /**
336     * Returns the relative paths of the splits declared by the application {@code info}.
337     * Assumes that the application declares a non-null array of splits.
338     */
339    private static String[] getSplitRelativeCodePaths(ApplicationInfo info) {
340        String baseCodePath = new File(info.getBaseCodePath()).getParent();
341        String[] splitCodePaths = info.getSplitCodePaths();
342        String[] splitRelativeCodePaths = new String[splitCodePaths.length];
343        for (int i = 0; i < splitCodePaths.length; i++) {
344            File pathFile = new File(splitCodePaths[i]);
345            splitRelativeCodePaths[i] = pathFile.getName();
346            // Sanity check that the base paths of the splits are all the same.
347            String basePath = pathFile.getParent();
348            if (!basePath.equals(baseCodePath)) {
349                Slog.wtf(TAG, "Split paths have different base paths: " + basePath + " and " +
350                        baseCodePath);
351            }
352        }
353        return splitRelativeCodePaths;
354    }
355}
356