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