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