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