PackageDexOptimizer.java revision 731a7f38a9949bb9d15f9dd16514e7908c84ed9e
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.SystemClock;
28import android.os.UserHandle;
29import android.os.WorkSource;
30import android.util.Log;
31import android.util.Slog;
32import android.util.SparseArray;
33
34import com.android.internal.annotations.GuardedBy;
35import com.android.internal.util.IndentingPrintWriter;
36import com.android.server.pm.Installer.InstallerException;
37
38import java.io.File;
39import java.io.IOException;
40import java.util.ArrayList;
41import java.util.List;
42import java.util.Set;
43
44import dalvik.system.DexFile;
45
46import static com.android.server.pm.Installer.DEXOPT_BOOTCOMPLETE;
47import static com.android.server.pm.Installer.DEXOPT_DEBUGGABLE;
48import static com.android.server.pm.Installer.DEXOPT_PROFILE_GUIDED;
49import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
50import static com.android.server.pm.Installer.DEXOPT_SAFEMODE;
51import static com.android.server.pm.Installer.DEXOPT_SECONDARY_DEX;
52import static com.android.server.pm.Installer.DEXOPT_FORCE;
53import static com.android.server.pm.Installer.DEXOPT_STORAGE_CE;
54import static com.android.server.pm.Installer.DEXOPT_STORAGE_DE;
55import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
56import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
57
58import static com.android.server.pm.PackageManagerService.WATCHDOG_TIMEOUT;
59
60import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
61import static dalvik.system.DexFile.getSafeModeCompilerFilter;
62import static dalvik.system.DexFile.isProfileGuidedCompilerFilter;
63
64/**
65 * Helper class for running dexopt command on packages.
66 */
67public class PackageDexOptimizer {
68    private static final String TAG = "PackageManager.DexOptimizer";
69    static final String OAT_DIR_NAME = "oat";
70    // TODO b/19550105 Remove error codes and use exceptions
71    public static final int DEX_OPT_SKIPPED = 0;
72    public static final int DEX_OPT_PERFORMED = 1;
73    public static final int DEX_OPT_FAILED = -1;
74    // One minute over PM WATCHDOG_TIMEOUT
75    private static final long WAKELOCK_TIMEOUT_MS = WATCHDOG_TIMEOUT + 1000 * 60;
76
77    /** Special library name that skips shared libraries check during compilation. */
78    public static final String SKIP_SHARED_LIBRARY_CHECK = "&";
79
80    @GuardedBy("mInstallLock")
81    private final Installer mInstaller;
82    private final Object mInstallLock;
83
84    @GuardedBy("mInstallLock")
85    private final PowerManager.WakeLock mDexoptWakeLock;
86    private volatile boolean mSystemReady;
87
88    PackageDexOptimizer(Installer installer, Object installLock, Context context,
89            String wakeLockTag) {
90        this.mInstaller = installer;
91        this.mInstallLock = installLock;
92
93        PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
94        mDexoptWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakeLockTag);
95    }
96
97    protected PackageDexOptimizer(PackageDexOptimizer from) {
98        this.mInstaller = from.mInstaller;
99        this.mInstallLock = from.mInstallLock;
100        this.mDexoptWakeLock = from.mDexoptWakeLock;
101        this.mSystemReady = from.mSystemReady;
102    }
103
104    static boolean canOptimizePackage(PackageParser.Package pkg) {
105        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
106    }
107
108    /**
109     * Performs dexopt on all code paths and libraries of the specified package for specified
110     * instruction sets.
111     *
112     * <p>Calls to {@link com.android.server.pm.Installer#dexopt} on {@link #mInstaller} are
113     * synchronized on {@link #mInstallLock}.
114     */
115    int performDexOpt(PackageParser.Package pkg, String[] sharedLibraries,
116            String[] instructionSets, boolean checkProfiles, String targetCompilationFilter,
117            CompilerStats.PackageStats packageStats, boolean isUsedByOtherApps) {
118        if (!canOptimizePackage(pkg)) {
119            return DEX_OPT_SKIPPED;
120        }
121        synchronized (mInstallLock) {
122            final long acquireTime = acquireWakeLockLI(pkg.applicationInfo.uid);
123            try {
124                return performDexOptLI(pkg, sharedLibraries, instructionSets, checkProfiles,
125                        targetCompilationFilter, packageStats, isUsedByOtherApps);
126            } finally {
127                releaseWakeLockLI(acquireTime);
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.getAllCodePaths();
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        final String sharedLibrariesPath = getSharedLibrariesPath(sharedLibraries);
153        // Get the dexopt flags after getRealCompilerFilter to make sure we get the correct flags.
154        final int dexoptFlags = getDexFlags(pkg, compilerFilter);
155        // Get the dependencies of each split in the package. For each code path in the package,
156        // this array contains the relative paths of each split it depends on, separated by colons.
157        String[] splitDependencies = getSplitDependencies(pkg);
158
159        int result = DEX_OPT_SKIPPED;
160        for (int i = 0; i < paths.size(); i++) {
161            // Skip paths that have no code.
162            if ((i == 0 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) ||
163                    (i != 0 && (pkg.splitFlags[i - 1] & ApplicationInfo.FLAG_HAS_CODE) == 0)) {
164                continue;
165            }
166            // Append shared libraries with split dependencies for this split.
167            String path = paths.get(i);
168            String sharedLibrariesPathWithSplits;
169            if (sharedLibrariesPath != null && splitDependencies[i] != null) {
170                sharedLibrariesPathWithSplits = sharedLibrariesPath + ":" + splitDependencies[i];
171            } else {
172                sharedLibrariesPathWithSplits =
173                        splitDependencies[i] != null ? splitDependencies[i] : sharedLibrariesPath;
174            }
175            for (String dexCodeIsa : dexCodeInstructionSets) {
176                int newResult = dexOptPath(pkg, path, dexCodeIsa, compilerFilter, profileUpdated,
177                        sharedLibrariesPathWithSplits, dexoptFlags, sharedGid, packageStats);
178                // The end result is:
179                //  - FAILED if any path failed,
180                //  - PERFORMED if at least one path needed compilation,
181                //  - SKIPPED when all paths are up to date
182                if ((result != DEX_OPT_FAILED) && (newResult != DEX_OPT_SKIPPED)) {
183                    result = newResult;
184                }
185            }
186        }
187        return result;
188    }
189
190    /**
191     * Performs dexopt on the {@code path} belonging to the package {@code pkg}.
192     *
193     * @return
194     *      DEX_OPT_FAILED if there was any exception during dexopt
195     *      DEX_OPT_PERFORMED if dexopt was performed successfully on the given path.
196     *      DEX_OPT_SKIPPED if the path does not need to be deopt-ed.
197     */
198    @GuardedBy("mInstallLock")
199    private int dexOptPath(PackageParser.Package pkg, String path, String isa,
200            String compilerFilter, boolean profileUpdated, String sharedLibrariesPath,
201            int dexoptFlags, int uid, CompilerStats.PackageStats packageStats) {
202        int dexoptNeeded = getDexoptNeeded(path, isa, compilerFilter, profileUpdated);
203        if (Math.abs(dexoptNeeded) == DexFile.NO_DEXOPT_NEEDED) {
204            return DEX_OPT_SKIPPED;
205        }
206
207        // TODO(calin): there's no need to try to create the oat dir over and over again,
208        //              especially since it involve an extra installd call. We should create
209        //              if (if supported) on the fly during the dexopt call.
210        String oatDir = createOatDirIfSupported(pkg, isa);
211
212        Log.i(TAG, "Running dexopt (dexoptNeeded=" + dexoptNeeded + ") on: " + path
213                + " pkg=" + pkg.applicationInfo.packageName + " isa=" + isa
214                + " dexoptFlags=" + printDexoptFlags(dexoptFlags)
215                + " target-filter=" + compilerFilter + " oatDir=" + oatDir
216                + " sharedLibraries=" + sharedLibrariesPath);
217
218        try {
219            long startTime = System.currentTimeMillis();
220
221            mInstaller.dexopt(path, uid, pkg.packageName, isa, dexoptNeeded, oatDir, dexoptFlags,
222                    compilerFilter, pkg.volumeUuid, sharedLibrariesPath, pkg.applicationInfo.seInfo);
223
224            if (packageStats != null) {
225                long endTime = System.currentTimeMillis();
226                packageStats.setCompileTime(path, (int)(endTime - startTime));
227            }
228            return DEX_OPT_PERFORMED;
229        } catch (InstallerException e) {
230            Slog.w(TAG, "Failed to dexopt", e);
231            return DEX_OPT_FAILED;
232        }
233    }
234
235    /**
236     * Performs dexopt on the secondary dex {@code path} belonging to the app {@code info}.
237     *
238     * @return
239     *      DEX_OPT_FAILED if there was any exception during dexopt
240     *      DEX_OPT_PERFORMED if dexopt was performed successfully on the given path.
241     * NOTE that DEX_OPT_PERFORMED for secondary dex files includes the case when the dex file
242     * didn't need an update. That's because at the moment we don't get more than success/failure
243     * from installd.
244     *
245     * TODO(calin): Consider adding return codes to installd dexopt invocation (rather than
246     * throwing exceptions). Or maybe make a separate call to installd to get DexOptNeeded, though
247     * that seems wasteful.
248     */
249    public int dexOptSecondaryDexPath(ApplicationInfo info, String path, Set<String> isas,
250            String compilerFilter, boolean isUsedByOtherApps) {
251        synchronized (mInstallLock) {
252            final long acquireTime = acquireWakeLockLI(info.uid);
253            try {
254                return dexOptSecondaryDexPathLI(info, path, isas, compilerFilter,
255                        isUsedByOtherApps);
256            } finally {
257                releaseWakeLockLI(acquireTime);
258            }
259        }
260    }
261
262    @GuardedBy("mInstallLock")
263    private long acquireWakeLockLI(final int uid) {
264        // During boot the system doesn't need to instantiate and obtain a wake lock.
265        // PowerManager might not be ready, but that doesn't mean that we can't proceed with
266        // dexopt.
267        if (!mSystemReady) {
268            return -1;
269        }
270        mDexoptWakeLock.setWorkSource(new WorkSource(uid));
271        mDexoptWakeLock.acquire(WAKELOCK_TIMEOUT_MS);
272        return SystemClock.elapsedRealtime();
273    }
274
275    @GuardedBy("mInstallLock")
276    private void releaseWakeLockLI(final long acquireTime) {
277        if (acquireTime < 0) {
278            return;
279        }
280        try {
281            if (mDexoptWakeLock.isHeld()) {
282                mDexoptWakeLock.release();
283            }
284            final long duration = SystemClock.elapsedRealtime() - acquireTime;
285            if (duration >= WAKELOCK_TIMEOUT_MS) {
286                Slog.wtf(TAG, "WakeLock " + mDexoptWakeLock.getTag()
287                        + " time out. Operation took " + duration + " ms. Thread: "
288                        + Thread.currentThread().getName());
289            }
290        } catch (Exception e) {
291            Slog.wtf(TAG, "Error while releasing " + mDexoptWakeLock.getTag() + " lock", e);
292        }
293    }
294
295    @GuardedBy("mInstallLock")
296    private int dexOptSecondaryDexPathLI(ApplicationInfo info, String path, Set<String> isas,
297            String compilerFilter, boolean isUsedByOtherApps) {
298        compilerFilter = getRealCompilerFilter(info, compilerFilter, isUsedByOtherApps);
299        // Get the dexopt flags after getRealCompilerFilter to make sure we get the correct flags.
300        int dexoptFlags = getDexFlags(info, compilerFilter) | DEXOPT_SECONDARY_DEX;
301        // Check the app storage and add the appropriate flags.
302        if (info.deviceProtectedDataDir != null &&
303                FileUtils.contains(info.deviceProtectedDataDir, path)) {
304            dexoptFlags |= DEXOPT_STORAGE_DE;
305        } else if (info.credentialProtectedDataDir != null &&
306                FileUtils.contains(info.credentialProtectedDataDir, path)) {
307            dexoptFlags |= DEXOPT_STORAGE_CE;
308        } else {
309            Slog.e(TAG, "Could not infer CE/DE storage for package " + info.packageName);
310            return DEX_OPT_FAILED;
311        }
312        Log.d(TAG, "Running dexopt on: " + path
313                + " pkg=" + info.packageName + " isa=" + isas
314                + " dexoptFlags=" + printDexoptFlags(dexoptFlags)
315                + " target-filter=" + compilerFilter);
316
317        try {
318            for (String isa : isas) {
319                // Reuse the same dexopt path as for the primary apks. We don't need all the
320                // arguments as some (dexopNeeded and oatDir) will be computed by installd because
321                // system server cannot read untrusted app content.
322                // TODO(calin): maybe add a separate call.
323                mInstaller.dexopt(path, info.uid, info.packageName, isa, /*dexoptNeeded*/ 0,
324                        /*oatDir*/ null, dexoptFlags,
325                        compilerFilter, info.volumeUuid, SKIP_SHARED_LIBRARY_CHECK, info.seInfoUser);
326            }
327
328            return DEX_OPT_PERFORMED;
329        } catch (InstallerException e) {
330            Slog.w(TAG, "Failed to dexopt", e);
331            return DEX_OPT_FAILED;
332        }
333    }
334
335    /**
336     * Adjust the given dexopt-needed value. Can be overridden to influence the decision to
337     * optimize or not (and in what way).
338     */
339    protected int adjustDexoptNeeded(int dexoptNeeded) {
340        return dexoptNeeded;
341    }
342
343    /**
344     * Adjust the given dexopt flags that will be passed to the installer.
345     */
346    protected int adjustDexoptFlags(int dexoptFlags) {
347        return dexoptFlags;
348    }
349
350    /**
351     * Dumps the dexopt state of the given package {@code pkg} to the given {@code PrintWriter}.
352     */
353    void dumpDexoptState(IndentingPrintWriter pw, PackageParser.Package pkg) {
354        final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
355        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
356
357        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
358
359        for (String instructionSet : dexCodeInstructionSets) {
360             pw.println("Instruction Set: " + instructionSet);
361             pw.increaseIndent();
362             for (String path : paths) {
363                  String status = null;
364                  try {
365                      status = DexFile.getDexFileStatus(path, instructionSet);
366                  } catch (IOException ioe) {
367                      status = "[Exception]: " + ioe.getMessage();
368                  }
369                  pw.println("path: " + path);
370                  pw.println("status: " + status);
371             }
372             pw.decreaseIndent();
373        }
374    }
375
376    /**
377     * Returns the compiler filter that should be used to optimize the package code.
378     * The target filter will be updated if the package code is used by other apps
379     * or if it has the safe mode flag set.
380     */
381    private String getRealCompilerFilter(ApplicationInfo info, String targetCompilerFilter,
382            boolean isUsedByOtherApps) {
383        int flags = info.flags;
384        boolean vmSafeMode = (flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
385        if (vmSafeMode) {
386            return getSafeModeCompilerFilter(targetCompilerFilter);
387        }
388
389        if (isProfileGuidedCompilerFilter(targetCompilerFilter) && isUsedByOtherApps) {
390            // If the dex files is used by other apps, we cannot use profile-guided compilation.
391            return getNonProfileGuidedCompilerFilter(targetCompilerFilter);
392        }
393
394        return targetCompilerFilter;
395    }
396
397    /**
398     * Computes the dex flags that needs to be pass to installd for the given package and compiler
399     * filter.
400     */
401    private int getDexFlags(PackageParser.Package pkg, String compilerFilter) {
402        return getDexFlags(pkg.applicationInfo, compilerFilter);
403    }
404
405    private int getDexFlags(ApplicationInfo info, String compilerFilter) {
406        int flags = info.flags;
407        boolean vmSafeMode = (flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
408        boolean debuggable = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
409        // Profile guide compiled oat files should not be public.
410        boolean isProfileGuidedFilter = isProfileGuidedCompilerFilter(compilerFilter);
411        boolean isPublic = !info.isForwardLocked() && !isProfileGuidedFilter;
412        int profileFlag = isProfileGuidedFilter ? DEXOPT_PROFILE_GUIDED : 0;
413        int dexFlags =
414                (isPublic ? DEXOPT_PUBLIC : 0)
415                | (vmSafeMode ? DEXOPT_SAFEMODE : 0)
416                | (debuggable ? DEXOPT_DEBUGGABLE : 0)
417                | profileFlag
418                | DEXOPT_BOOTCOMPLETE;
419        return adjustDexoptFlags(dexFlags);
420    }
421
422    /**
423     * Assesses if there's a need to perform dexopt on {@code path} for the given
424     * configuration (isa, compiler filter, profile).
425     */
426    private int getDexoptNeeded(String path, String isa, String compilerFilter,
427            boolean newProfile) {
428        int dexoptNeeded;
429        try {
430            dexoptNeeded = DexFile.getDexOptNeeded(path, isa, compilerFilter, newProfile);
431        } catch (IOException ioe) {
432            Slog.w(TAG, "IOException reading apk: " + path, ioe);
433            return DEX_OPT_FAILED;
434        }
435        return adjustDexoptNeeded(dexoptNeeded);
436    }
437
438    /**
439     * Computes the shared libraries path that should be passed to dexopt.
440     */
441    private String getSharedLibrariesPath(String[] sharedLibraries) {
442        if (sharedLibraries == null || sharedLibraries.length == 0) {
443            return null;
444        }
445        StringBuilder sb = new StringBuilder();
446        for (String lib : sharedLibraries) {
447            if (sb.length() != 0) {
448                sb.append(":");
449            }
450            sb.append(lib);
451        }
452        return sb.toString();
453    }
454
455    /**
456     * Walks dependency tree and gathers the dependencies for each split in a split apk.
457     * The split paths are stored as relative paths, separated by colons.
458     */
459    private String[] getSplitDependencies(PackageParser.Package pkg) {
460        // Convert all the code paths to relative paths.
461        String baseCodePath = new File(pkg.baseCodePath).getParent();
462        List<String> paths = pkg.getAllCodePaths();
463        String[] splitDependencies = new String[paths.size()];
464        for (int i = 0; i < paths.size(); i++) {
465            File pathFile = new File(paths.get(i));
466            String fileName = pathFile.getName();
467            paths.set(i, fileName);
468
469            // Sanity check that the base paths of the splits are all the same.
470            String basePath = pathFile.getParent();
471            if (!basePath.equals(baseCodePath)) {
472                Slog.wtf(TAG, "Split paths have different base paths: " + basePath + " and " +
473                        baseCodePath);
474            }
475        }
476
477        // If there are no other dependencies, fill in the implicit dependency on the base apk.
478        SparseArray<int[]> dependencies = pkg.applicationInfo.splitDependencies;
479        if (dependencies == null) {
480            for (int i = 1; i < paths.size(); i++) {
481                splitDependencies[i] = paths.get(0);
482            }
483            return splitDependencies;
484        }
485
486        // Fill in the dependencies, skipping the base apk which has no dependencies.
487        for (int i = 1; i < dependencies.size(); i++) {
488            getParentDependencies(dependencies.keyAt(i), paths, dependencies, splitDependencies);
489        }
490
491        return splitDependencies;
492    }
493
494    /**
495     * Recursive method to generate dependencies for a particular split.
496     * The index is a key from the package's splitDependencies.
497     */
498    private String getParentDependencies(int index, List<String> paths,
499            SparseArray<int[]> dependencies, String[] splitDependencies) {
500        // The base apk is always first, and has no dependencies.
501        if (index == 0) {
502            return null;
503        }
504        // Return the result if we've computed the dependencies for this index already.
505        if (splitDependencies[index] != null) {
506            return splitDependencies[index];
507        }
508        // Get the dependencies for the parent of this index and append its path to it.
509        int parent = dependencies.get(index)[0];
510        String parentDependencies =
511                getParentDependencies(parent, paths, dependencies, splitDependencies);
512        String path = parentDependencies == null ? paths.get(parent) :
513                parentDependencies + ":" + paths.get(parent);
514        splitDependencies[index] = path;
515        return path;
516    }
517
518    /**
519     * Checks if there is an update on the profile information of the {@code pkg}.
520     * If the compiler filter is not profile guided the method returns false.
521     *
522     * Note that this is a "destructive" operation with side effects. Under the hood the
523     * current profile and the reference profile will be merged and subsequent calls
524     * may return a different result.
525     */
526    private boolean isProfileUpdated(PackageParser.Package pkg, int uid, String compilerFilter) {
527        // Check if we are allowed to merge and if the compiler filter is profile guided.
528        if (!isProfileGuidedCompilerFilter(compilerFilter)) {
529            return false;
530        }
531        // Merge profiles. It returns whether or not there was an updated in the profile info.
532        try {
533            return mInstaller.mergeProfiles(uid, pkg.packageName);
534        } catch (InstallerException e) {
535            Slog.w(TAG, "Failed to merge profiles", e);
536        }
537        return false;
538    }
539
540    /**
541     * Creates oat dir for the specified package if needed and supported.
542     * In certain cases oat directory
543     * <strong>cannot</strong> be created:
544     * <ul>
545     *      <li>{@code pkg} is a system app, which is not updated.</li>
546     *      <li>Package location is not a directory, i.e. monolithic install.</li>
547     * </ul>
548     *
549     * @return Absolute path to the oat directory or null, if oat directory
550     * cannot be created.
551     */
552    @Nullable
553    private String createOatDirIfSupported(PackageParser.Package pkg, String dexInstructionSet) {
554        if (!pkg.canHaveOatDir()) {
555            return null;
556        }
557        File codePath = new File(pkg.codePath);
558        if (codePath.isDirectory()) {
559            // TODO(calin): why do we create this only if the codePath is a directory? (i.e for
560            //              cluster packages). It seems that the logic for the folder creation is
561            //              split between installd and here.
562            File oatDir = getOatDir(codePath);
563            try {
564                mInstaller.createOatDir(oatDir.getAbsolutePath(), dexInstructionSet);
565            } catch (InstallerException e) {
566                Slog.w(TAG, "Failed to create oat dir", e);
567                return null;
568            }
569            return oatDir.getAbsolutePath();
570        }
571        return null;
572    }
573
574    static File getOatDir(File codePath) {
575        return new File(codePath, OAT_DIR_NAME);
576    }
577
578    void systemReady() {
579        mSystemReady = true;
580    }
581
582    private String printDexoptFlags(int flags) {
583        ArrayList<String> flagsList = new ArrayList<>();
584
585        if ((flags & DEXOPT_BOOTCOMPLETE) == DEXOPT_BOOTCOMPLETE) {
586            flagsList.add("boot_complete");
587        }
588        if ((flags & DEXOPT_DEBUGGABLE) == DEXOPT_DEBUGGABLE) {
589            flagsList.add("debuggable");
590        }
591        if ((flags & DEXOPT_PROFILE_GUIDED) == DEXOPT_PROFILE_GUIDED) {
592            flagsList.add("profile_guided");
593        }
594        if ((flags & DEXOPT_PUBLIC) == DEXOPT_PUBLIC) {
595            flagsList.add("public");
596        }
597        if ((flags & DEXOPT_SAFEMODE) == DEXOPT_SAFEMODE) {
598            flagsList.add("safemode");
599        }
600        if ((flags & DEXOPT_SECONDARY_DEX) == DEXOPT_SECONDARY_DEX) {
601            flagsList.add("secondary");
602        }
603        if ((flags & DEXOPT_FORCE) == DEXOPT_FORCE) {
604            flagsList.add("force");
605        }
606        if ((flags & DEXOPT_STORAGE_CE) == DEXOPT_STORAGE_CE) {
607            flagsList.add("storage_ce");
608        }
609        if ((flags & DEXOPT_STORAGE_DE) == DEXOPT_STORAGE_DE) {
610            flagsList.add("storage_de");
611        }
612
613        return String.join(",", flagsList);
614    }
615
616    /**
617     * A specialized PackageDexOptimizer that overrides already-installed checks, forcing a
618     * dexopt path.
619     */
620    public static class ForcedUpdatePackageDexOptimizer extends PackageDexOptimizer {
621
622        public ForcedUpdatePackageDexOptimizer(Installer installer, Object installLock,
623                Context context, String wakeLockTag) {
624            super(installer, installLock, context, wakeLockTag);
625        }
626
627        public ForcedUpdatePackageDexOptimizer(PackageDexOptimizer from) {
628            super(from);
629        }
630
631        @Override
632        protected int adjustDexoptNeeded(int dexoptNeeded) {
633            if (dexoptNeeded == DexFile.NO_DEXOPT_NEEDED) {
634                // Ensure compilation by pretending a compiler filter change on the
635                // apk/odex location (the reason for the '-'. A positive value means
636                // the 'oat' location).
637                return -DexFile.DEX2OAT_FOR_FILTER;
638            }
639            return dexoptNeeded;
640        }
641
642        @Override
643        protected int adjustDexoptFlags(int flags) {
644            // Add DEXOPT_FORCE flag to signal installd that it should force compilation
645            // and discard dexoptanalyzer result.
646            return flags | DEXOPT_FORCE;
647        }
648    }
649}
650