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