PackageDexOptimizer.java revision 07b6eabe79261267ecd7114790e96e1f6828672a
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.PackageInfo;
23import android.content.pm.PackageParser;
24import android.os.Environment;
25import android.os.PowerManager;
26import android.os.UserHandle;
27import android.os.WorkSource;
28import android.util.Log;
29import android.util.Slog;
30
31import com.android.internal.annotations.GuardedBy;
32import com.android.internal.util.IndentingPrintWriter;
33import com.android.server.pm.Installer.InstallerException;
34
35import java.io.File;
36import java.io.IOException;
37import java.util.ArrayList;
38import java.util.List;
39import java.util.Set;
40
41import dalvik.system.DexFile;
42
43import static com.android.server.pm.Installer.DEXOPT_BOOTCOMPLETE;
44import static com.android.server.pm.Installer.DEXOPT_DEBUGGABLE;
45import static com.android.server.pm.Installer.DEXOPT_PROFILE_GUIDED;
46import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
47import static com.android.server.pm.Installer.DEXOPT_SAFEMODE;
48import static com.android.server.pm.Installer.DEXOPT_SECONDARY_DEX;
49import static com.android.server.pm.Installer.DEXOPT_FORCE;
50import static com.android.server.pm.Installer.DEXOPT_STORAGE_CE;
51import static com.android.server.pm.Installer.DEXOPT_STORAGE_DE;
52import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
53import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
54
55import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
56import static dalvik.system.DexFile.isProfileGuidedCompilerFilter;
57
58/**
59 * Helper class for running dexopt command on packages.
60 */
61public class PackageDexOptimizer {
62    private static final String TAG = "PackageManager.DexOptimizer";
63    static final String OAT_DIR_NAME = "oat";
64    // TODO b/19550105 Remove error codes and use exceptions
65    public static final int DEX_OPT_SKIPPED = 0;
66    public static final int DEX_OPT_PERFORMED = 1;
67    public static final int DEX_OPT_FAILED = -1;
68
69    /** Special library name that skips shared libraries check during compilation. */
70    public static final String SKIP_SHARED_LIBRARY_CHECK = "&";
71
72    private final Installer mInstaller;
73    private final Object mInstallLock;
74
75    private final PowerManager.WakeLock mDexoptWakeLock;
76    private volatile boolean mSystemReady;
77
78    PackageDexOptimizer(Installer installer, Object installLock, Context context,
79            String wakeLockTag) {
80        this.mInstaller = installer;
81        this.mInstallLock = installLock;
82
83        PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
84        mDexoptWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakeLockTag);
85    }
86
87    protected PackageDexOptimizer(PackageDexOptimizer from) {
88        this.mInstaller = from.mInstaller;
89        this.mInstallLock = from.mInstallLock;
90        this.mDexoptWakeLock = from.mDexoptWakeLock;
91        this.mSystemReady = from.mSystemReady;
92    }
93
94    static boolean canOptimizePackage(PackageParser.Package pkg) {
95        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
96    }
97
98    /**
99     * Performs dexopt on all code paths and libraries of the specified package for specified
100     * instruction sets.
101     *
102     * <p>Calls to {@link com.android.server.pm.Installer#dexopt} on {@link #mInstaller} are
103     * synchronized on {@link #mInstallLock}.
104     */
105    int performDexOpt(PackageParser.Package pkg, String[] sharedLibraries,
106            String[] instructionSets, boolean checkProfiles, String targetCompilationFilter,
107            CompilerStats.PackageStats packageStats, boolean isUsedByOtherApps) {
108        if (!canOptimizePackage(pkg)) {
109            return DEX_OPT_SKIPPED;
110        }
111        synchronized (mInstallLock) {
112            // During boot the system doesn't need to instantiate and obtain a wake lock.
113            // PowerManager might not be ready, but that doesn't mean that we can't proceed with
114            // dexopt.
115            final boolean useLock = mSystemReady;
116            if (useLock) {
117                mDexoptWakeLock.setWorkSource(new WorkSource(pkg.applicationInfo.uid));
118                mDexoptWakeLock.acquire();
119            }
120            try {
121                return performDexOptLI(pkg, sharedLibraries, instructionSets, checkProfiles,
122                        targetCompilationFilter, packageStats, isUsedByOtherApps);
123            } finally {
124                if (useLock) {
125                    mDexoptWakeLock.release();
126                }
127            }
128        }
129    }
130
131    /**
132     * Performs dexopt on all code paths of the given package.
133     * It assumes the install lock is held.
134     */
135    @GuardedBy("mInstallLock")
136    private int performDexOptLI(PackageParser.Package pkg, String[] sharedLibraries,
137            String[] targetInstructionSets, boolean checkForProfileUpdates,
138            String targetCompilerFilter, CompilerStats.PackageStats packageStats,
139            boolean isUsedByOtherApps) {
140        final String[] instructionSets = targetInstructionSets != null ?
141                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
142        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
143        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
144        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
145
146        final String compilerFilter = getRealCompilerFilter(pkg.applicationInfo,
147                targetCompilerFilter, isUsedByOtherApps);
148        final boolean profileUpdated = checkForProfileUpdates &&
149                isProfileUpdated(pkg, sharedGid, compilerFilter);
150
151        // TODO(calin,jeffhao): shared library paths should be adjusted to include previous code
152        // paths (b/34169257).
153        final String sharedLibrariesPath = getSharedLibrariesPath(sharedLibraries);
154        final int dexoptFlags = getDexFlags(pkg, compilerFilter);
155
156        int result = DEX_OPT_SKIPPED;
157        for (String path : paths) {
158            for (String dexCodeIsa : dexCodeInstructionSets) {
159                int newResult = dexOptPath(pkg, path, dexCodeIsa, compilerFilter, profileUpdated,
160                        sharedLibrariesPath, dexoptFlags, sharedGid, packageStats);
161                // The end result is:
162                //  - FAILED if any path failed,
163                //  - PERFORMED if at least one path needed compilation,
164                //  - SKIPPED when all paths are up to date
165                if ((result != DEX_OPT_FAILED) && (newResult != DEX_OPT_SKIPPED)) {
166                    result = newResult;
167                }
168            }
169        }
170        return result;
171    }
172
173    /**
174     * Performs dexopt on the {@code path} belonging to the package {@code pkg}.
175     *
176     * @return
177     *      DEX_OPT_FAILED if there was any exception during dexopt
178     *      DEX_OPT_PERFORMED if dexopt was performed successfully on the given path.
179     *      DEX_OPT_SKIPPED if the path does not need to be deopt-ed.
180     */
181    @GuardedBy("mInstallLock")
182    private int dexOptPath(PackageParser.Package pkg, String path, String isa,
183            String compilerFilter, boolean profileUpdated, String sharedLibrariesPath,
184            int dexoptFlags, int uid, CompilerStats.PackageStats packageStats) {
185        int dexoptNeeded = getDexoptNeeded(path, isa, compilerFilter, profileUpdated);
186        if (Math.abs(dexoptNeeded) == DexFile.NO_DEXOPT_NEEDED) {
187            return DEX_OPT_SKIPPED;
188        }
189
190        // TODO(calin): there's no need to try to create the oat dir over and over again,
191        //              especially since it involve an extra installd call. We should create
192        //              if (if supported) on the fly during the dexopt call.
193        String oatDir = createOatDirIfSupported(pkg, isa);
194
195        Log.i(TAG, "Running dexopt (dexoptNeeded=" + dexoptNeeded + ") on: " + path
196                + " pkg=" + pkg.applicationInfo.packageName + " isa=" + isa
197                + " dexoptFlags=" + printDexoptFlags(dexoptFlags)
198                + " target-filter=" + compilerFilter + " oatDir=" + oatDir
199                + " sharedLibraries=" + sharedLibrariesPath);
200
201        try {
202            long startTime = System.currentTimeMillis();
203
204            mInstaller.dexopt(path, uid, pkg.packageName, isa, dexoptNeeded, oatDir, dexoptFlags,
205                    compilerFilter, pkg.volumeUuid, sharedLibrariesPath);
206
207            if (packageStats != null) {
208                long endTime = System.currentTimeMillis();
209                packageStats.setCompileTime(path, (int)(endTime - startTime));
210            }
211            return DEX_OPT_PERFORMED;
212        } catch (InstallerException e) {
213            Slog.w(TAG, "Failed to dexopt", e);
214            return DEX_OPT_FAILED;
215        }
216    }
217
218    /**
219     * Performs dexopt on the secondary dex {@code path} belonging to the app {@code info}.
220     *
221     * @return
222     *      DEX_OPT_FAILED if there was any exception during dexopt
223     *      DEX_OPT_PERFORMED if dexopt was performed successfully on the given path.
224     * NOTE that DEX_OPT_PERFORMED for secondary dex files includes the case when the dex file
225     * didn't need an update. That's because at the moment we don't get more than success/failure
226     * from installd.
227     *
228     * TODO(calin): Consider adding return codes to installd dexopt invocation (rather than
229     * throwing exceptions). Or maybe make a separate call to installd to get DexOptNeeded, though
230     * that seems wasteful.
231     */
232    public int dexOptSecondaryDexPath(ApplicationInfo info, String path, Set<String> isas,
233            String compilerFilter, boolean isUsedByOtherApps) {
234        synchronized (mInstallLock) {
235            // During boot the system doesn't need to instantiate and obtain a wake lock.
236            // PowerManager might not be ready, but that doesn't mean that we can't proceed with
237            // dexopt.
238            final boolean useLock = mSystemReady;
239            if (useLock) {
240                mDexoptWakeLock.setWorkSource(new WorkSource(info.uid));
241                mDexoptWakeLock.acquire();
242            }
243            try {
244                return dexOptSecondaryDexPathLI(info, path, isas, compilerFilter,
245                        isUsedByOtherApps);
246            } finally {
247                if (useLock) {
248                    mDexoptWakeLock.release();
249                }
250            }
251        }
252    }
253
254    @GuardedBy("mInstallLock")
255    private int dexOptSecondaryDexPathLI(ApplicationInfo info, String path, Set<String> isas,
256            String compilerFilter, boolean isUsedByOtherApps) {
257        int dexoptFlags = getDexFlags(info, compilerFilter) | DEXOPT_SECONDARY_DEX;
258        // Check the app storage and add the appropriate flags.
259        if (info.dataDir.equals(info.deviceProtectedDataDir)) {
260            dexoptFlags |= DEXOPT_STORAGE_DE;
261        } else if (info.dataDir.equals(info.credentialProtectedDataDir)) {
262            dexoptFlags |= DEXOPT_STORAGE_CE;
263        } else {
264            Slog.e(TAG, "Could not infer CE/DE storage for package " + info.packageName);
265            return DEX_OPT_FAILED;
266        }
267        compilerFilter = getRealCompilerFilter(info, compilerFilter, isUsedByOtherApps);
268        Log.d(TAG, "Running dexopt on: " + path
269                + " pkg=" + info.packageName + " isa=" + isas
270                + " dexoptFlags=" + printDexoptFlags(dexoptFlags)
271                + " target-filter=" + compilerFilter);
272
273        try {
274            for (String isa : isas) {
275                // Reuse the same dexopt path as for the primary apks. We don't need all the
276                // arguments as some (dexopNeeded and oatDir) will be computed by installd because
277                // system server cannot read untrusted app content.
278                // TODO(calin): maybe add a separate call.
279                mInstaller.dexopt(path, info.uid, info.packageName, isa, /*dexoptNeeded*/ 0,
280                        /*oatDir*/ null, dexoptFlags,
281                        compilerFilter, info.volumeUuid, SKIP_SHARED_LIBRARY_CHECK);
282            }
283
284            return DEX_OPT_PERFORMED;
285        } catch (InstallerException e) {
286            Slog.w(TAG, "Failed to dexopt", e);
287            return DEX_OPT_FAILED;
288        }
289    }
290
291    /**
292     * Adjust the given dexopt-needed value. Can be overridden to influence the decision to
293     * optimize or not (and in what way).
294     */
295    protected int adjustDexoptNeeded(int dexoptNeeded) {
296        return dexoptNeeded;
297    }
298
299    /**
300     * Adjust the given dexopt flags that will be passed to the installer.
301     */
302    protected int adjustDexoptFlags(int dexoptFlags) {
303        return dexoptFlags;
304    }
305
306    /**
307     * Dumps the dexopt state of the given package {@code pkg} to the given {@code PrintWriter}.
308     */
309    void dumpDexoptState(IndentingPrintWriter pw, PackageParser.Package pkg) {
310        final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
311        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
312
313        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
314
315        for (String instructionSet : dexCodeInstructionSets) {
316             pw.println("Instruction Set: " + instructionSet);
317             pw.increaseIndent();
318             for (String path : paths) {
319                  String status = null;
320                  try {
321                      status = DexFile.getDexFileStatus(path, instructionSet);
322                  } catch (IOException ioe) {
323                      status = "[Exception]: " + ioe.getMessage();
324                  }
325                  pw.println("path: " + path);
326                  pw.println("status: " + status);
327             }
328             pw.decreaseIndent();
329        }
330    }
331
332    /**
333     * Returns the compiler filter that should be used to optimize the package code.
334     * The target filter will be updated if the package code is used by other apps
335     * or if it has the safe mode flag set.
336     */
337    private String getRealCompilerFilter(ApplicationInfo info, String targetCompilerFilter,
338            boolean isUsedByOtherApps) {
339        int flags = info.flags;
340        boolean vmSafeMode = (flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
341        if (vmSafeMode) {
342            // For the compilation, it doesn't really matter what we return here because installd
343            // will replace the filter with interpret-only anyway.
344            // However, we return a non profile guided filter so that we simplify the logic of
345            // merging profiles.
346            // TODO(calin): safe mode path could be simplified if we pass interpret-only from
347            //              here rather than letting installd decide on the filter.
348            return getNonProfileGuidedCompilerFilter(targetCompilerFilter);
349        }
350
351        if (isProfileGuidedCompilerFilter(targetCompilerFilter) && isUsedByOtherApps) {
352            // If the dex files is used by other apps, we cannot use profile-guided compilation.
353            return getNonProfileGuidedCompilerFilter(targetCompilerFilter);
354        }
355
356        return targetCompilerFilter;
357    }
358
359    /**
360     * Computes the dex flags that needs to be pass to installd for the given package and compiler
361     * filter.
362     */
363    private int getDexFlags(PackageParser.Package pkg, String compilerFilter) {
364        return getDexFlags(pkg.applicationInfo, compilerFilter);
365    }
366
367    private int getDexFlags(ApplicationInfo info, String compilerFilter) {
368        int flags = info.flags;
369        boolean vmSafeMode = (flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
370        boolean debuggable = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
371        // Profile guide compiled oat files should not be public.
372        boolean isProfileGuidedFilter = isProfileGuidedCompilerFilter(compilerFilter);
373        boolean isPublic = !info.isForwardLocked() && !isProfileGuidedFilter;
374        int profileFlag = isProfileGuidedFilter ? DEXOPT_PROFILE_GUIDED : 0;
375        int dexFlags =
376                (isPublic ? DEXOPT_PUBLIC : 0)
377                | (vmSafeMode ? DEXOPT_SAFEMODE : 0)
378                | (debuggable ? DEXOPT_DEBUGGABLE : 0)
379                | profileFlag
380                | DEXOPT_BOOTCOMPLETE;
381        return adjustDexoptFlags(dexFlags);
382    }
383
384    /**
385     * Assesses if there's a need to perform dexopt on {@code path} for the given
386     * configuration (isa, compiler filter, profile).
387     */
388    private int getDexoptNeeded(String path, String isa, String compilerFilter,
389            boolean newProfile) {
390        int dexoptNeeded;
391        try {
392            dexoptNeeded = DexFile.getDexOptNeeded(path, isa, compilerFilter, newProfile);
393        } catch (IOException ioe) {
394            Slog.w(TAG, "IOException reading apk: " + path, ioe);
395            return DEX_OPT_FAILED;
396        }
397        return adjustDexoptNeeded(dexoptNeeded);
398    }
399
400    /**
401     * Computes the shared libraries path that should be passed to dexopt.
402     */
403    private String getSharedLibrariesPath(String[] sharedLibraries) {
404        if (sharedLibraries == null || sharedLibraries.length == 0) {
405            return null;
406        }
407        StringBuilder sb = new StringBuilder();
408        for (String lib : sharedLibraries) {
409            if (sb.length() != 0) {
410                sb.append(":");
411            }
412            sb.append(lib);
413        }
414        return sb.toString();
415    }
416
417    /**
418     * Checks if there is an update on the profile information of the {@code pkg}.
419     * If the compiler filter is not profile guided the method returns false.
420     *
421     * Note that this is a "destructive" operation with side effects. Under the hood the
422     * current profile and the reference profile will be merged and subsequent calls
423     * may return a different result.
424     */
425    private boolean isProfileUpdated(PackageParser.Package pkg, int uid, String compilerFilter) {
426        // Check if we are allowed to merge and if the compiler filter is profile guided.
427        if (!isProfileGuidedCompilerFilter(compilerFilter)) {
428            return false;
429        }
430        // Merge profiles. It returns whether or not there was an updated in the profile info.
431        try {
432            return mInstaller.mergeProfiles(uid, pkg.packageName);
433        } catch (InstallerException e) {
434            Slog.w(TAG, "Failed to merge profiles", e);
435        }
436        return false;
437    }
438
439    /**
440     * Creates oat dir for the specified package if needed and supported.
441     * In certain cases oat directory
442     * <strong>cannot</strong> be created:
443     * <ul>
444     *      <li>{@code pkg} is a system app, which is not updated.</li>
445     *      <li>Package location is not a directory, i.e. monolithic install.</li>
446     * </ul>
447     *
448     * @return Absolute path to the oat directory or null, if oat directory
449     * cannot be created.
450     */
451    @Nullable
452    private String createOatDirIfSupported(PackageParser.Package pkg, String dexInstructionSet) {
453        if (!pkg.canHaveOatDir()) {
454            return null;
455        }
456        File codePath = new File(pkg.codePath);
457        if (codePath.isDirectory()) {
458            // TODO(calin): why do we create this only if the codePath is a directory? (i.e for
459            //              cluster packages). It seems that the logic for the folder creation is
460            //              split between installd and here.
461            File oatDir = getOatDir(codePath);
462            try {
463                mInstaller.createOatDir(oatDir.getAbsolutePath(), dexInstructionSet);
464            } catch (InstallerException e) {
465                Slog.w(TAG, "Failed to create oat dir", e);
466                return null;
467            }
468            return oatDir.getAbsolutePath();
469        }
470        return null;
471    }
472
473    static File getOatDir(File codePath) {
474        return new File(codePath, OAT_DIR_NAME);
475    }
476
477    void systemReady() {
478        mSystemReady = true;
479    }
480
481    private String printDexoptFlags(int flags) {
482        ArrayList<String> flagsList = new ArrayList<>();
483
484        if ((flags & DEXOPT_BOOTCOMPLETE) == DEXOPT_BOOTCOMPLETE) {
485            flagsList.add("boot_complete");
486        }
487        if ((flags & DEXOPT_DEBUGGABLE) == DEXOPT_DEBUGGABLE) {
488            flagsList.add("debuggable");
489        }
490        if ((flags & DEXOPT_PROFILE_GUIDED) == DEXOPT_PROFILE_GUIDED) {
491            flagsList.add("profile_guided");
492        }
493        if ((flags & DEXOPT_PUBLIC) == DEXOPT_PUBLIC) {
494            flagsList.add("public");
495        }
496        if ((flags & DEXOPT_SAFEMODE) == DEXOPT_SAFEMODE) {
497            flagsList.add("safemode");
498        }
499        if ((flags & DEXOPT_SECONDARY_DEX) == DEXOPT_SECONDARY_DEX) {
500            flagsList.add("secondary");
501        }
502        if ((flags & DEXOPT_FORCE) == DEXOPT_FORCE) {
503            flagsList.add("force");
504        }
505        if ((flags & DEXOPT_STORAGE_CE) == DEXOPT_STORAGE_CE) {
506            flagsList.add("storage_ce");
507        }
508        if ((flags & DEXOPT_STORAGE_DE) == DEXOPT_STORAGE_DE) {
509            flagsList.add("storage_de");
510        }
511
512        return String.join(",", flagsList);
513    }
514
515    /**
516     * A specialized PackageDexOptimizer that overrides already-installed checks, forcing a
517     * dexopt path.
518     */
519    public static class ForcedUpdatePackageDexOptimizer extends PackageDexOptimizer {
520
521        public ForcedUpdatePackageDexOptimizer(Installer installer, Object installLock,
522                Context context, String wakeLockTag) {
523            super(installer, installLock, context, wakeLockTag);
524        }
525
526        public ForcedUpdatePackageDexOptimizer(PackageDexOptimizer from) {
527            super(from);
528        }
529
530        @Override
531        protected int adjustDexoptNeeded(int dexoptNeeded) {
532            // Ensure compilation, no matter the current state.
533            // TODO: The return value is wrong when patchoat is needed.
534            return DexFile.DEX2OAT_FROM_SCRATCH;
535        }
536
537        @Override
538        protected int adjustDexoptFlags(int flags) {
539            // Add DEXOPT_FORCE flag to signal installd that it should force compilation
540            // and discard dexoptanalyzer result.
541            return flags | DEXOPT_FORCE;
542        }
543    }
544}
545