PackageDexOptimizer.java revision d670d5866754beca43a217ef5013b5acd1976e78
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.Environment;
24import android.os.PowerManager;
25import android.os.UserHandle;
26import android.os.WorkSource;
27import android.util.Log;
28import android.util.Slog;
29
30import com.android.internal.util.IndentingPrintWriter;
31import com.android.server.pm.Installer.InstallerException;
32
33import java.io.File;
34import java.io.IOException;
35import java.util.List;
36
37import dalvik.system.DexFile;
38
39import static com.android.server.pm.Installer.DEXOPT_BOOTCOMPLETE;
40import static com.android.server.pm.Installer.DEXOPT_DEBUGGABLE;
41import static com.android.server.pm.Installer.DEXOPT_PROFILE_GUIDED;
42import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
43import static com.android.server.pm.Installer.DEXOPT_SAFEMODE;
44import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
45import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
46import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
47
48/**
49 * Helper class for running dexopt command on packages.
50 */
51class 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_FAILED = -1;
58
59    private final Installer mInstaller;
60    private final Object mInstallLock;
61
62    private final PowerManager.WakeLock mDexoptWakeLock;
63    private volatile boolean mSystemReady;
64
65    PackageDexOptimizer(Installer installer, Object installLock, Context context,
66            String wakeLockTag) {
67        this.mInstaller = installer;
68        this.mInstallLock = installLock;
69
70        PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
71        mDexoptWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakeLockTag);
72    }
73
74    protected PackageDexOptimizer(PackageDexOptimizer from) {
75        this.mInstaller = from.mInstaller;
76        this.mInstallLock = from.mInstallLock;
77        this.mDexoptWakeLock = from.mDexoptWakeLock;
78        this.mSystemReady = from.mSystemReady;
79    }
80
81    static boolean canOptimizePackage(PackageParser.Package pkg) {
82        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
83    }
84
85    /**
86     * Performs dexopt on all code paths and libraries of the specified package for specified
87     * instruction sets.
88     *
89     * <p>Calls to {@link com.android.server.pm.Installer#dexopt} on {@link #mInstaller} are
90     * synchronized on {@link #mInstallLock}.
91     */
92    int performDexOpt(PackageParser.Package pkg, String[] sharedLibraries,
93            String[] instructionSets, boolean checkProfiles, String targetCompilationFilter,
94            CompilerStats.PackageStats packageStats) {
95        synchronized (mInstallLock) {
96            final boolean useLock = mSystemReady;
97            if (useLock) {
98                mDexoptWakeLock.setWorkSource(new WorkSource(pkg.applicationInfo.uid));
99                mDexoptWakeLock.acquire();
100            }
101            try {
102                return performDexOptLI(pkg, sharedLibraries, instructionSets, checkProfiles,
103                        targetCompilationFilter, packageStats);
104            } finally {
105                if (useLock) {
106                    mDexoptWakeLock.release();
107                }
108            }
109        }
110    }
111
112    /**
113     * Adjust the given dexopt-needed value. Can be overridden to influence the decision to
114     * optimize or not (and in what way).
115     */
116    protected int adjustDexoptNeeded(int dexoptNeeded) {
117        return dexoptNeeded;
118    }
119
120    /**
121     * Adjust the given dexopt flags that will be passed to the installer.
122     */
123    protected int adjustDexoptFlags(int dexoptFlags) {
124        return dexoptFlags;
125    }
126
127    /**
128     * Dumps the dexopt state of the given package {@code pkg} to the given {@code PrintWriter}.
129     */
130    void dumpDexoptState(IndentingPrintWriter pw, PackageParser.Package pkg) {
131        final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
132        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
133
134        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
135
136        for (String instructionSet : dexCodeInstructionSets) {
137             pw.println("Instruction Set: " + instructionSet);
138             pw.increaseIndent();
139             for (String path : paths) {
140                  String status = null;
141                  try {
142                      status = DexFile.getDexFileStatus(path, instructionSet);
143                  } catch (IOException ioe) {
144                      status = "[Exception]: " + ioe.getMessage();
145                  }
146                  pw.println("path: " + path);
147                  pw.println("status: " + status);
148             }
149             pw.decreaseIndent();
150        }
151    }
152
153    private int performDexOptLI(PackageParser.Package pkg, String[] sharedLibraries,
154            String[] targetInstructionSets, boolean checkProfiles, String targetCompilerFilter,
155            CompilerStats.PackageStats packageStats) {
156        final String[] instructionSets = targetInstructionSets != null ?
157                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
158
159        if (!canOptimizePackage(pkg)) {
160            return DEX_OPT_SKIPPED;
161        }
162
163        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
164        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
165
166        boolean isProfileGuidedFilter = DexFile.isProfileGuidedCompilerFilter(targetCompilerFilter);
167        // If any part of the app is used by other apps, we cannot use profile-guided
168        // compilation.
169        if (isProfileGuidedFilter && isUsedByOtherApps(pkg)) {
170            checkProfiles = false;
171
172            targetCompilerFilter = getNonProfileGuidedCompilerFilter(targetCompilerFilter);
173            if (DexFile.isProfileGuidedCompilerFilter(targetCompilerFilter)) {
174                throw new IllegalStateException(targetCompilerFilter);
175            }
176            isProfileGuidedFilter = false;
177        }
178
179        // Disable profile guided compilation for vmSafeMode.
180        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE)
181                != 0;
182        final boolean debuggable = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE)
183                != 0;
184        if (vmSafeMode) {
185            targetCompilerFilter = getNonProfileGuidedCompilerFilter(targetCompilerFilter);
186            isProfileGuidedFilter = false;
187        }
188
189        // If we're asked to take profile updates into account, check now.
190        boolean newProfile = false;
191        if (checkProfiles && isProfileGuidedFilter) {
192            // Merge profiles, see if we need to do anything.
193            try {
194                newProfile = mInstaller.mergeProfiles(sharedGid, pkg.packageName);
195            } catch (InstallerException e) {
196                Slog.w(TAG, "Failed to merge profiles", e);
197            }
198        }
199
200        boolean performedDexOpt = false;
201        boolean successfulDexOpt = true;
202
203        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
204        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
205            for (String path : paths) {
206                int dexoptNeeded;
207                try {
208                    dexoptNeeded = DexFile.getDexOptNeeded(path,
209                            dexCodeInstructionSet, targetCompilerFilter, newProfile);
210                } catch (IOException ioe) {
211                    Slog.w(TAG, "IOException reading apk: " + path, ioe);
212                    return DEX_OPT_FAILED;
213                }
214                dexoptNeeded = adjustDexoptNeeded(dexoptNeeded);
215                if (PackageManagerService.DEBUG_DEXOPT) {
216                    Log.i(TAG, "DexoptNeeded for " + path + "@" + targetCompilerFilter + " is " +
217                            dexoptNeeded);
218                }
219
220                if (dexoptNeeded == DexFile.NO_DEXOPT_NEEDED) {
221                    continue;
222                }
223
224                String oatDir = createOatDirIfSupported(pkg, dexCodeInstructionSet);
225                String sharedLibrariesPath = null;
226                if (sharedLibraries != null && sharedLibraries.length != 0) {
227                    StringBuilder sb = new StringBuilder();
228                    for (String lib : sharedLibraries) {
229                        if (sb.length() != 0) {
230                            sb.append(":");
231                        }
232                        sb.append(lib);
233                    }
234                    sharedLibrariesPath = sb.toString();
235                }
236                Log.i(TAG, "Running dexopt on: " + path + " pkg="
237                        + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
238                        + " vmSafeMode=" + vmSafeMode + " debuggable=" + debuggable
239                        + " target-filter=" + targetCompilerFilter + " oatDir = " + oatDir
240                        + " sharedLibraries=" + sharedLibrariesPath);
241                // Profile guide compiled oat files should not be public.
242                final boolean isPublic = !pkg.isForwardLocked() && !isProfileGuidedFilter;
243                final int profileFlag = isProfileGuidedFilter ? DEXOPT_PROFILE_GUIDED : 0;
244                final int dexFlags = adjustDexoptFlags(
245                        ( isPublic ? DEXOPT_PUBLIC : 0)
246                        | (vmSafeMode ? DEXOPT_SAFEMODE : 0)
247                        | (debuggable ? DEXOPT_DEBUGGABLE : 0)
248                        | profileFlag
249                        | DEXOPT_BOOTCOMPLETE);
250
251                try {
252                    long startTime = System.currentTimeMillis();
253
254                    mInstaller.dexopt(path, sharedGid, pkg.packageName, dexCodeInstructionSet,
255                            dexoptNeeded, oatDir, dexFlags, targetCompilerFilter, pkg.volumeUuid,
256                            sharedLibrariesPath);
257                    performedDexOpt = true;
258
259                    if (packageStats != null) {
260                        long endTime = System.currentTimeMillis();
261                        packageStats.setCompileTime(path, (int)(endTime - startTime));
262                    }
263                } catch (InstallerException e) {
264                    Slog.w(TAG, "Failed to dexopt", e);
265                    successfulDexOpt = false;
266                }
267            }
268        }
269
270        if (successfulDexOpt) {
271            // If we've gotten here, we're sure that no error occurred. We've either
272            // dex-opted one or more paths or instruction sets or we've skipped
273            // all of them because they are up to date. In both cases this package
274            // doesn't need dexopt any longer.
275            return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
276        } else {
277            return DEX_OPT_FAILED;
278        }
279    }
280
281    /**
282     * Creates oat dir for the specified package. In certain cases oat directory
283     * <strong>cannot</strong> be created:
284     * <ul>
285     *      <li>{@code pkg} is a system app, which is not updated.</li>
286     *      <li>Package location is not a directory, i.e. monolithic install.</li>
287     * </ul>
288     *
289     * @return Absolute path to the oat directory or null, if oat directory
290     * cannot be created.
291     */
292    @Nullable
293    private String createOatDirIfSupported(PackageParser.Package pkg, String dexInstructionSet) {
294        if (!pkg.canHaveOatDir()) {
295            return null;
296        }
297        File codePath = new File(pkg.codePath);
298        if (codePath.isDirectory()) {
299            File oatDir = getOatDir(codePath);
300            try {
301                mInstaller.createOatDir(oatDir.getAbsolutePath(), dexInstructionSet);
302            } catch (InstallerException e) {
303                Slog.w(TAG, "Failed to create oat dir", e);
304                return null;
305            }
306            return oatDir.getAbsolutePath();
307        }
308        return null;
309    }
310
311    static File getOatDir(File codePath) {
312        return new File(codePath, OAT_DIR_NAME);
313    }
314
315    void systemReady() {
316        mSystemReady = true;
317    }
318
319    /**
320     * Returns true if the profiling data collected for the given app indicate
321     * that the apps's APK has been loaded by another app.
322     * Note that this returns false for all forward-locked apps and apps without
323     * any collected profiling data.
324     */
325    public static boolean isUsedByOtherApps(PackageParser.Package pkg) {
326        if (pkg.isForwardLocked()) {
327            // Skip the check for forward locked packages since they don't share their code.
328            return false;
329        }
330
331        for (String apkPath : pkg.getAllCodePathsExcludingResourceOnly()) {
332            try {
333                apkPath = PackageManagerServiceUtils.realpath(new File(apkPath));
334            } catch (IOException e) {
335                // Log an error but continue without it.
336                Slog.w(TAG, "Failed to get canonical path", e);
337                continue;
338            }
339            String useMarker = apkPath.replace('/', '@');
340            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
341            for (int i = 0; i < currentUserIds.length; i++) {
342                File profileDir =
343                        Environment.getDataProfilesDeForeignDexDirectory(currentUserIds[i]);
344                File foreignUseMark = new File(profileDir, useMarker);
345                if (foreignUseMark.exists()) {
346                    return true;
347                }
348            }
349        }
350        return false;
351    }
352
353    /**
354     * A specialized PackageDexOptimizer that overrides already-installed checks, forcing a
355     * dexopt path.
356     */
357    public static class ForcedUpdatePackageDexOptimizer extends PackageDexOptimizer {
358
359        public ForcedUpdatePackageDexOptimizer(Installer installer, Object installLock,
360                Context context, String wakeLockTag) {
361            super(installer, installLock, context, wakeLockTag);
362        }
363
364        public ForcedUpdatePackageDexOptimizer(PackageDexOptimizer from) {
365            super(from);
366        }
367
368        @Override
369        protected int adjustDexoptNeeded(int dexoptNeeded) {
370            // Ensure compilation, no matter the current state.
371            // TODO: The return value is wrong when patchoat is needed.
372            return DexFile.DEX2OAT_FROM_SCRATCH;
373        }
374    }
375}
376