PackageDexOptimizer.java revision 389bb7f509fc74de3656492a9c474c11bcc96e5b
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.FileNotFoundException;
32import java.io.IOException;
33import java.util.ArrayList;
34import java.util.List;
35
36import dalvik.system.DexFile;
37
38import static com.android.server.pm.Installer.DEXOPT_BOOTCOMPLETE;
39import static com.android.server.pm.Installer.DEXOPT_DEBUGGABLE;
40import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
41import static com.android.server.pm.Installer.DEXOPT_SAFEMODE;
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, boolean bootComplete) {
79        ArraySet<String> done;
80        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
81            done = new ArraySet<String>();
82            done.add(pkg.packageName);
83        } else {
84            done = null;
85        }
86        synchronized (mPackageManagerService.mInstallLock) {
87            final boolean useLock = mSystemReady;
88            if (useLock) {
89                mDexoptWakeLock.setWorkSource(new WorkSource(pkg.applicationInfo.uid));
90                mDexoptWakeLock.acquire();
91            }
92            try {
93                return performDexOptLI(pkg, instructionSets, forceDex, defer, bootComplete, done);
94            } finally {
95                if (useLock) {
96                    mDexoptWakeLock.release();
97                }
98            }
99        }
100    }
101
102    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
103            boolean forceDex, boolean defer, boolean bootComplete, ArraySet<String> done) {
104        final String[] instructionSets = targetInstructionSets != null ?
105                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
106
107        if (done != null) {
108            done.add(pkg.packageName);
109            if (pkg.usesLibraries != null) {
110                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer,
111                        bootComplete, done);
112            }
113            if (pkg.usesOptionalLibraries != null) {
114                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer,
115                        bootComplete, done);
116            }
117        }
118
119        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
120            return DEX_OPT_SKIPPED;
121        }
122
123        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
124        final boolean debuggable = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
125
126        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
127        boolean performedDexOpt = false;
128        // There are three basic cases here:
129        // 1.) we need to dexopt, either because we are forced or it is needed
130        // 2.) we are deferring a needed dexopt
131        // 3.) we are skipping an unneeded dexopt
132        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
133        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
134            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
135                continue;
136            }
137
138            for (String path : paths) {
139                final int dexoptNeeded;
140                if (forceDex) {
141                    dexoptNeeded = DexFile.DEX2OAT_NEEDED;
142                } else {
143                    try {
144                        dexoptNeeded = DexFile.getDexOptNeeded(path, pkg.packageName,
145                                dexCodeInstructionSet, defer);
146                    } catch (IOException ioe) {
147                        Slog.w(TAG, "IOException reading apk: " + path, ioe);
148                        return DEX_OPT_FAILED;
149                    }
150                }
151
152                if (!forceDex && defer && dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
153                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
154                    // paths and instruction sets. We'll deal with them all together when we process
155                    // our list of deferred dexopts.
156                    addPackageForDeferredDexopt(pkg);
157                    return DEX_OPT_DEFERRED;
158                }
159
160                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
161                    final String dexoptType;
162                    String oatDir = null;
163                    if (dexoptNeeded == DexFile.DEX2OAT_NEEDED) {
164                        dexoptType = "dex2oat";
165                        try {
166                            oatDir = createOatDirIfSupported(pkg, dexCodeInstructionSet);
167                        } catch (IOException ioe) {
168                            Slog.w(TAG, "Unable to create oatDir for package: " + pkg.packageName);
169                            return DEX_OPT_FAILED;
170                        }
171                    } else if (dexoptNeeded == DexFile.PATCHOAT_NEEDED) {
172                        dexoptType = "patchoat";
173                    } else if (dexoptNeeded == DexFile.SELF_PATCHOAT_NEEDED) {
174                        dexoptType = "self patchoat";
175                    } else {
176                        throw new IllegalStateException("Invalid dexopt needed: " + dexoptNeeded);
177                    }
178
179                    Log.i(TAG, "Running dexopt (" + dexoptType + ") on: " + path + " pkg="
180                            + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
181                            + " vmSafeMode=" + vmSafeMode + " debuggable=" + debuggable
182                            + " oatDir = " + oatDir + " bootComplete=" + bootComplete);
183                    final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
184                    final int dexFlags =
185                            (!pkg.isForwardLocked() ? DEXOPT_PUBLIC : 0)
186                            | (vmSafeMode ? DEXOPT_SAFEMODE : 0)
187                            | (debuggable ? DEXOPT_DEBUGGABLE : 0)
188                            | (bootComplete ? DEXOPT_BOOTCOMPLETE : 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            throws IOException {
229        if (!pkg.canHaveOatDir()) {
230            return null;
231        }
232        File codePath = new File(pkg.codePath);
233        if (codePath.isDirectory()) {
234            File oatDir = getOatDir(codePath);
235            mPackageManagerService.mInstaller.createOatDir(oatDir.getAbsolutePath(),
236                    dexInstructionSet);
237            return oatDir.getAbsolutePath();
238        }
239        return null;
240    }
241
242    static File getOatDir(File codePath) {
243        return new File(codePath, OAT_DIR_NAME);
244    }
245
246    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
247            boolean forceDex, boolean defer, boolean bootComplete, 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, 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