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