PackageDexOptimizer.java revision b94c1657eb0140f7b91f5372a9f76de5a3d87e36
1/*
2 * Copyright (C) 2015 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;
18
19import android.annotation.Nullable;
20import android.content.pm.ApplicationInfo;
21import android.content.pm.PackageParser;
22import android.os.UserHandle;
23import android.util.ArraySet;
24import android.util.Log;
25import android.util.Slog;
26
27import java.io.File;
28import java.io.FileNotFoundException;
29import java.io.IOException;
30import java.util.ArrayList;
31import java.util.List;
32
33import dalvik.system.DexFile;
34import dalvik.system.StaleDexCacheError;
35
36import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
37import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
38
39/**
40 * Helper class for running dexopt command on packages.
41 */
42final class PackageDexOptimizer {
43    private static final String TAG = "PackageManager.DexOptimizer";
44    static final String OAT_DIR_NAME = "oat";
45    // TODO b/19550105 Remove error codes and use exceptions
46    static final int DEX_OPT_SKIPPED = 0;
47    static final int DEX_OPT_PERFORMED = 1;
48    static final int DEX_OPT_DEFERRED = 2;
49    static final int DEX_OPT_FAILED = -1;
50
51    private final PackageManagerService mPackageManagerService;
52    private ArraySet<PackageParser.Package> mDeferredDexOpt;
53
54    PackageDexOptimizer(PackageManagerService packageManagerService) {
55        this.mPackageManagerService = packageManagerService;
56    }
57
58    /**
59     * Performs dexopt on all code paths and libraries of the specified package for specified
60     * instruction sets.
61     *
62     * <p>Calls to {@link com.android.server.pm.Installer#dexopt} are synchronized on
63     * {@link PackageManagerService#mInstallLock}.
64     */
65    int performDexOpt(PackageParser.Package pkg, String[] instructionSets,
66            boolean forceDex, boolean defer, boolean inclDependencies) {
67        ArraySet<String> done;
68        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
69            done = new ArraySet<String>();
70            done.add(pkg.packageName);
71        } else {
72            done = null;
73        }
74        synchronized (mPackageManagerService.mInstallLock) {
75            return performDexOptLI(pkg, instructionSets, forceDex, defer, done);
76        }
77    }
78
79    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
80            boolean forceDex, boolean defer, ArraySet<String> done) {
81        final String[] instructionSets = targetInstructionSets != null ?
82                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
83
84        if (done != null) {
85            done.add(pkg.packageName);
86            if (pkg.usesLibraries != null) {
87                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
88            }
89            if (pkg.usesOptionalLibraries != null) {
90                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer,
91                        done);
92            }
93        }
94
95        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
96            return DEX_OPT_SKIPPED;
97        }
98
99        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
100        final boolean debuggable = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
101
102        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
103        boolean performedDexOpt = false;
104        // There are three basic cases here:
105        // 1.) we need to dexopt, either because we are forced or it is needed
106        // 2.) we are deferring a needed dexopt
107        // 3.) we are skipping an unneeded dexopt
108        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
109        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
110            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
111                continue;
112            }
113
114            for (String path : paths) {
115                try {
116                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
117                    // package or the one we find does not match the image checksum (i.e. it was
118                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
119                    // odex file and it matches the checksum of the image but not its base address,
120                    // meaning we need to move it.
121                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
122                            pkg.packageName, dexCodeInstructionSet, defer);
123                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
124                        File oatDir = createOatDirIfSupported(pkg, dexCodeInstructionSet);
125                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
126                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
127                                + " vmSafeMode=" + vmSafeMode + " debuggable=" + debuggable
128                                + " oatDir = " + oatDir);
129                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
130
131                        if (oatDir != null) {
132                            int ret = mPackageManagerService.mInstaller.dexopt(
133                                    path, sharedGid, !pkg.isForwardLocked(), pkg.packageName,
134                                    dexCodeInstructionSet, vmSafeMode, debuggable,
135                                    oatDir.getAbsolutePath());
136                            if (ret < 0) {
137                                return DEX_OPT_FAILED;
138                            }
139                        } else {
140                            final int ret = mPackageManagerService.mInstaller
141                                    .dexopt(path, sharedGid,
142                                            !pkg.isForwardLocked(), pkg.packageName,
143                                            dexCodeInstructionSet,
144                                            vmSafeMode, debuggable, null);
145                            if (ret < 0) {
146                                return DEX_OPT_FAILED;
147                            }
148                        }
149
150                        performedDexOpt = true;
151                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
152                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
153                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
154                        final int ret = mPackageManagerService.mInstaller.patchoat(path, sharedGid,
155                                !pkg.isForwardLocked(), pkg.packageName, dexCodeInstructionSet);
156
157                        if (ret < 0) {
158                            // Don't bother running patchoat again if we failed, it will probably
159                            // just result in an error again. Also, don't bother dexopting for other
160                            // paths & ISAs.
161                            return DEX_OPT_FAILED;
162                        }
163
164                        performedDexOpt = true;
165                    }
166
167                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
168                    // paths and instruction sets. We'll deal with them all together when we process
169                    // our list of deferred dexopts.
170                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
171                        addPackageForDeferredDexopt(pkg);
172                        return DEX_OPT_DEFERRED;
173                    }
174                } catch (FileNotFoundException e) {
175                    Slog.w(TAG, "Apk not found for dexopt: " + path);
176                    return DEX_OPT_FAILED;
177                } catch (IOException e) {
178                    Slog.w(TAG, "IOException reading apk: " + path, e);
179                    return DEX_OPT_FAILED;
180                } catch (StaleDexCacheError e) {
181                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
182                    return DEX_OPT_FAILED;
183                } catch (Exception e) {
184                    Slog.w(TAG, "Exception when doing dexopt : ", e);
185                    return DEX_OPT_FAILED;
186                }
187            }
188
189            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
190            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
191            // it isn't required. We therefore mark that this package doesn't need dexopt unless
192            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
193            // it.
194            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
195        }
196
197        // If we've gotten here, we're sure that no error occurred and that we haven't
198        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
199        // we've skipped all of them because they are up to date. In both cases this
200        // package doesn't need dexopt any longer.
201        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
202    }
203
204    /**
205     * Creates oat dir for the specified package. In certain cases oat directory
206     * <strong>cannot</strong> be created:
207     * <ul>
208     *      <li>{@code pkg} is a system app, which is not updated.</li>
209     *      <li>Package location is not a directory, i.e. monolithic install.</li>
210     * </ul>
211     *
212     * @return oat directory or null, if oat directory cannot be created.
213     */
214    @Nullable
215    private File createOatDirIfSupported(PackageParser.Package pkg, String dexInstructionSet)
216            throws IOException {
217        if (pkg.isSystemApp() && !pkg.isUpdatedSystemApp()) {
218            return null;
219        }
220        File codePath = new File(pkg.codePath);
221        if (codePath.isDirectory()) {
222            File oatDir = getOatDir(codePath);
223            mPackageManagerService.mInstaller.createOatDir(oatDir.getAbsolutePath(),
224                    dexInstructionSet);
225            return oatDir;
226        }
227        return null;
228    }
229
230    static File getOatDir(File codePath) {
231        return new File(codePath, OAT_DIR_NAME);
232    }
233
234    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
235            boolean forceDex, boolean defer, ArraySet<String> done) {
236        for (String libName : libs) {
237            PackageParser.Package libPkg = mPackageManagerService.findSharedNonSystemLibrary(
238                    libName);
239            if (libPkg != null && !done.contains(libName)) {
240                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
241            }
242        }
243    }
244
245    /**
246     * Clears set of deferred dexopt packages.
247     * @return content of dexopt set if it was not empty
248     */
249    public ArraySet<PackageParser.Package> clearDeferredDexOptPackages() {
250        ArraySet<PackageParser.Package> result = mDeferredDexOpt;
251        mDeferredDexOpt = null;
252        return result;
253    }
254
255    public void addPackageForDeferredDexopt(PackageParser.Package pkg) {
256        if (mDeferredDexOpt == null) {
257            mDeferredDexOpt = new ArraySet<>();
258        }
259        mDeferredDexOpt.add(pkg);
260    }
261}
262