blob: 1951e7417b2c5323fba4b608661f133210c539b0 [file] [log] [blame]
Fyodor Kupolov74876572015-02-23 17:14:45 -08001/*
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
Patrick Baumannfc2851e2018-11-13 15:23:22 -080019import static android.content.pm.ApplicationInfo.HIDDEN_API_ENFORCEMENT_DISABLED;
20
21import static com.android.server.pm.Installer.DEXOPT_BOOTCOMPLETE;
22import static com.android.server.pm.Installer.DEXOPT_DEBUGGABLE;
23import static com.android.server.pm.Installer.DEXOPT_ENABLE_HIDDEN_API_CHECKS;
24import static com.android.server.pm.Installer.DEXOPT_FORCE;
25import static com.android.server.pm.Installer.DEXOPT_GENERATE_APP_IMAGE;
26import static com.android.server.pm.Installer.DEXOPT_GENERATE_COMPACT_DEX;
27import static com.android.server.pm.Installer.DEXOPT_IDLE_BACKGROUND_JOB;
28import static com.android.server.pm.Installer.DEXOPT_PROFILE_GUIDED;
29import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
30import static com.android.server.pm.Installer.DEXOPT_SECONDARY_DEX;
31import static com.android.server.pm.Installer.DEXOPT_STORAGE_CE;
32import static com.android.server.pm.Installer.DEXOPT_STORAGE_DE;
33import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
34import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
Calin Juravle5ebac362020-04-09 20:03:26 -070035import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
Patrick Baumannfc2851e2018-11-13 15:23:22 -080036import static com.android.server.pm.PackageManagerService.WATCHDOG_TIMEOUT;
37import static com.android.server.pm.PackageManagerServiceCompilerMapping.getReasonName;
38
39import static dalvik.system.DexFile.getSafeModeCompilerFilter;
40import static dalvik.system.DexFile.isProfileGuidedCompilerFilter;
41
Winsone0756292020-01-31 12:21:54 -080042import android.annotation.NonNull;
Fyodor Kupolovb94c1652015-03-03 12:25:30 -080043import android.annotation.Nullable;
Fyodor Kupolova627c092015-05-05 18:44:39 -070044import android.content.Context;
Fyodor Kupolov74876572015-02-23 17:14:45 -080045import android.content.pm.ApplicationInfo;
Nicolas Geoffray8d144eb2018-11-15 12:59:52 +000046import android.content.pm.SharedLibraryInfo;
Calin Juravle6ae39fc2018-01-19 20:32:47 -080047import android.content.pm.dex.ArtManager;
Calin Juravlecc651942018-02-01 17:20:51 +000048import android.content.pm.dex.DexMetadataHelper;
Calin Juravleadbadd52017-03-28 18:19:15 -070049import android.os.FileUtils;
Fyodor Kupolova627c092015-05-05 18:44:39 -070050import android.os.PowerManager;
Fyodor Kupolov28f28552017-05-02 12:11:02 -070051import android.os.SystemClock;
Nicolas Geoffray20a894e2017-09-08 13:01:40 +010052import android.os.SystemProperties;
Fyodor Kupolov74876572015-02-23 17:14:45 -080053import android.os.UserHandle;
Fyodor Kupolova627c092015-05-05 18:44:39 -070054import android.os.WorkSource;
Calin Juravle4fdf8272020-04-02 18:09:53 -070055import android.os.storage.StorageManager;
Fyodor Kupolov74876572015-02-23 17:14:45 -080056import android.util.Log;
57import android.util.Slog;
Winson14ff7172019-10-23 10:42:27 -070058import android.util.SparseArray;
Fyodor Kupolov74876572015-02-23 17:14:45 -080059
Calin Juravle2d4b6ad72017-01-04 13:22:14 -080060import com.android.internal.annotations.GuardedBy;
Narayan Kamath88eea9e2016-05-02 14:44:31 +010061import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey740f5232016-12-09 14:31:26 -070062import com.android.server.pm.Installer.InstallerException;
Calin Juravle0610dd12018-07-20 15:51:17 -070063import com.android.server.pm.dex.ArtManagerService;
Victor Hsieh785d6182018-04-19 14:26:28 -070064import com.android.server.pm.dex.DexManager;
Calin Juravle1d0e83d2017-07-17 15:12:01 -070065import com.android.server.pm.dex.DexoptOptions;
Calin Juravle19da1cf2017-07-12 18:52:49 -070066import com.android.server.pm.dex.DexoptUtils;
Calin Juravlef1ff36f2017-07-22 12:33:41 -070067import com.android.server.pm.dex.PackageDexUsage;
Winson5e0a1d52020-01-24 12:00:33 -080068import com.android.server.pm.parsing.pkg.AndroidPackage;
69import com.android.server.pm.parsing.pkg.AndroidPackageUtils;
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -070070
Patrick Baumannfc2851e2018-11-13 15:23:22 -080071import dalvik.system.DexFile;
72
Fyodor Kupolovb94c1652015-03-03 12:25:30 -080073import java.io.File;
Fyodor Kupolov74876572015-02-23 17:14:45 -080074import java.io.IOException;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -080075import java.util.ArrayList;
Calin Juravle4c2b9552017-08-10 17:23:00 -070076import java.util.Arrays;
Fyodor Kupolov74876572015-02-23 17:14:45 -080077import java.util.List;
Calin Juravle41a57a62017-08-06 19:20:19 -070078import java.util.Map;
Fyodor Kupolov74876572015-02-23 17:14:45 -080079
Fyodor Kupolov74876572015-02-23 17:14:45 -080080/**
81 * Helper class for running dexopt command on packages.
82 */
Calin Juravlec22c30e2017-01-16 19:18:48 -080083public class PackageDexOptimizer {
Calin Juravle4fdf8272020-04-02 18:09:53 -070084 private static final String TAG = "PackageDexOptimizer";
Fyodor Kupolovb94c1652015-03-03 12:25:30 -080085 static final String OAT_DIR_NAME = "oat";
86 // TODO b/19550105 Remove error codes and use exceptions
Calin Juravlec22c30e2017-01-16 19:18:48 -080087 public static final int DEX_OPT_SKIPPED = 0;
88 public static final int DEX_OPT_PERFORMED = 1;
89 public static final int DEX_OPT_FAILED = -1;
Fyodor Kupolov28f28552017-05-02 12:11:02 -070090 // One minute over PM WATCHDOG_TIMEOUT
91 private static final long WAKELOCK_TIMEOUT_MS = WATCHDOG_TIMEOUT + 1000 * 60;
Fyodor Kupolov74876572015-02-23 17:14:45 -080092
Fyodor Kupolov28f28552017-05-02 12:11:02 -070093 @GuardedBy("mInstallLock")
Andreas Gampea8908752015-11-10 08:58:14 -080094 private final Installer mInstaller;
95 private final Object mInstallLock;
Fyodor Kupolov74876572015-02-23 17:14:45 -080096
Fyodor Kupolov28f28552017-05-02 12:11:02 -070097 @GuardedBy("mInstallLock")
Fyodor Kupolova627c092015-05-05 18:44:39 -070098 private final PowerManager.WakeLock mDexoptWakeLock;
99 private volatile boolean mSystemReady;
100
Andreas Gampea8908752015-11-10 08:58:14 -0800101 PackageDexOptimizer(Installer installer, Object installLock, Context context,
102 String wakeLockTag) {
103 this.mInstaller = installer;
104 this.mInstallLock = installLock;
105
106 PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
107 mDexoptWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakeLockTag);
108 }
109
110 protected PackageDexOptimizer(PackageDexOptimizer from) {
111 this.mInstaller = from.mInstaller;
112 this.mInstallLock = from.mInstallLock;
113 this.mDexoptWakeLock = from.mDexoptWakeLock;
114 this.mSystemReady = from.mSystemReady;
Fyodor Kupolov74876572015-02-23 17:14:45 -0800115 }
116
Winson14ff7172019-10-23 10:42:27 -0700117 static boolean canOptimizePackage(AndroidPackage pkg) {
Nicolas Geoffray20a894e2017-09-08 13:01:40 +0100118 // We do not dexopt a package with no code.
Calin Juravle5ebac362020-04-09 20:03:26 -0700119 // Note that the system package is marked as having no code, however we can
120 // still optimize it via dexoptSystemServerPath.
121 if (!PLATFORM_PACKAGE_NAME.equals(pkg.getPackageName()) && !pkg.isHasCode()) {
Nicolas Geoffray20a894e2017-09-08 13:01:40 +0100122 return false;
123 }
124
Nicolas Geoffray20a894e2017-09-08 13:01:40 +0100125 return true;
Calin Juravledb4a79a2015-12-23 18:55:08 +0200126 }
127
Fyodor Kupolov74876572015-02-23 17:14:45 -0800128 /**
129 * Performs dexopt on all code paths and libraries of the specified package for specified
130 * instruction sets.
131 *
Andreas Gampea8908752015-11-10 08:58:14 -0800132 * <p>Calls to {@link com.android.server.pm.Installer#dexopt} on {@link #mInstaller} are
133 * synchronized on {@link #mInstallLock}.
Fyodor Kupolov74876572015-02-23 17:14:45 -0800134 */
Winsone0756292020-01-31 12:21:54 -0800135 int performDexOpt(AndroidPackage pkg, @NonNull PackageSetting pkgSetting,
Calin Juravle1d0e83d2017-07-17 15:12:01 -0700136 String[] instructionSets, CompilerStats.PackageStats packageStats,
Calin Juravle3b74c412017-08-03 19:48:37 -0700137 PackageDexUsage.PackageUseInfo packageUseInfo, DexoptOptions options) {
Calin Juravle5ebac362020-04-09 20:03:26 -0700138 if (PLATFORM_PACKAGE_NAME.equals(pkg.getPackageName())) {
139 throw new IllegalArgumentException("System server dexopting should be done via "
140 + " DexManager and PackageDexOptimizer#dexoptSystemServerPath");
141 }
Winson14ff7172019-10-23 10:42:27 -0700142 if (pkg.getUid() == -1) {
143 throw new IllegalArgumentException("Dexopt for " + pkg.getPackageName()
Calin Juravlec6540da2017-11-15 16:28:01 -0800144 + " has invalid uid.");
145 }
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800146 if (!canOptimizePackage(pkg)) {
147 return DEX_OPT_SKIPPED;
148 }
Andreas Gampea8908752015-11-10 08:58:14 -0800149 synchronized (mInstallLock) {
Winson14ff7172019-10-23 10:42:27 -0700150 final long acquireTime = acquireWakeLockLI(pkg.getUid());
Fyodor Kupolova627c092015-05-05 18:44:39 -0700151 try {
Winsone0756292020-01-31 12:21:54 -0800152 return performDexOptLI(pkg, pkgSetting, instructionSets,
Calin Juravle3b74c412017-08-03 19:48:37 -0700153 packageStats, packageUseInfo, options);
Fyodor Kupolova627c092015-05-05 18:44:39 -0700154 } finally {
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700155 releaseWakeLockLI(acquireTime);
Fyodor Kupolova627c092015-05-05 18:44:39 -0700156 }
Fyodor Kupolov74876572015-02-23 17:14:45 -0800157 }
158 }
159
Andreas Gampea8908752015-11-10 08:58:14 -0800160 /**
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800161 * Performs dexopt on all code paths of the given package.
162 * It assumes the install lock is held.
163 */
164 @GuardedBy("mInstallLock")
Winsone0756292020-01-31 12:21:54 -0800165 private int performDexOptLI(AndroidPackage pkg, @NonNull PackageSetting pkgSetting,
Calin Juravle1d0e83d2017-07-17 15:12:01 -0700166 String[] targetInstructionSets, CompilerStats.PackageStats packageStats,
Calin Juravle3b74c412017-08-03 19:48:37 -0700167 PackageDexUsage.PackageUseInfo packageUseInfo, DexoptOptions options) {
Winsone0756292020-01-31 12:21:54 -0800168 final List<SharedLibraryInfo> sharedLibraries = pkgSetting.getPkgState()
169 .getUsesLibraryInfos();
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800170 final String[] instructionSets = targetInstructionSets != null ?
Winsone0756292020-01-31 12:21:54 -0800171 targetInstructionSets : getAppDexInstructionSets(
172 AndroidPackageUtils.getPrimaryCpuAbi(pkg, pkgSetting),
173 AndroidPackageUtils.getSecondaryCpuAbi(pkg, pkgSetting));
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800174 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
Winson5e0a1d52020-01-24 12:00:33 -0800175 final List<String> paths = AndroidPackageUtils.getAllCodePaths(pkg);
Jeff Sharkeya73e1652017-11-15 19:07:14 -0700176
Winson14ff7172019-10-23 10:42:27 -0700177 int sharedGid = UserHandle.getSharedAppGid(pkg.getUid());
Jeff Sharkeya73e1652017-11-15 19:07:14 -0700178 if (sharedGid == -1) {
Winson5e0a1d52020-01-24 12:00:33 -0800179 Slog.wtf(TAG, "Well this is awkward; package " + pkg.getPackageName() + " had UID "
Winson14ff7172019-10-23 10:42:27 -0700180 + pkg.getUid(), new Throwable());
Jeff Sharkeya73e1652017-11-15 19:07:14 -0700181 sharedGid = android.os.Process.NOBODY_UID;
182 }
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800183
Calin Juravle19da1cf2017-07-12 18:52:49 -0700184 // Get the class loader context dependencies.
185 // For each code path in the package, this array contains the class loader context that
186 // needs to be passed to dexopt in order to ensure correct optimizations.
Calin Juravleda098152017-09-01 17:30:01 -0700187 boolean[] pathsWithCode = new boolean[paths.size()];
Winsonf00c7552020-01-28 12:52:01 -0800188 pathsWithCode[0] = pkg.isHasCode();
Calin Juravleda098152017-09-01 17:30:01 -0700189 for (int i = 1; i < paths.size(); i++) {
Winson14ff7172019-10-23 10:42:27 -0700190 pathsWithCode[i] = (pkg.getSplitFlags()[i - 1] & ApplicationInfo.FLAG_HAS_CODE) != 0;
Calin Juravleda098152017-09-01 17:30:01 -0700191 }
Calin Juravle19da1cf2017-07-12 18:52:49 -0700192 String[] classLoaderContexts = DexoptUtils.getClassLoaderContexts(
Winson14ff7172019-10-23 10:42:27 -0700193 pkg, sharedLibraries, pathsWithCode);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800194
Calin Juravle4c2b9552017-08-10 17:23:00 -0700195 // Sanity check that we do not call dexopt with inconsistent data.
196 if (paths.size() != classLoaderContexts.length) {
Winson14ff7172019-10-23 10:42:27 -0700197 String[] splitCodePaths = pkg.getSplitCodePaths();
Calin Juravle4c2b9552017-08-10 17:23:00 -0700198 throw new IllegalStateException("Inconsistent information "
199 + "between PackageParser.Package and its ApplicationInfo. "
200 + "pkg.getAllCodePaths=" + paths
Winson14ff7172019-10-23 10:42:27 -0700201 + " pkg.getBaseCodePath=" + pkg.getBaseCodePath()
202 + " pkg.getSplitCodePaths="
Calin Juravle4c2b9552017-08-10 17:23:00 -0700203 + (splitCodePaths == null ? "null" : Arrays.toString(splitCodePaths)));
204 }
205
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800206 int result = DEX_OPT_SKIPPED;
Jeff Hao5def5e52017-04-19 14:42:16 -0700207 for (int i = 0; i < paths.size(); i++) {
208 // Skip paths that have no code.
Calin Juravleda098152017-09-01 17:30:01 -0700209 if (!pathsWithCode[i]) {
Jeff Hao5def5e52017-04-19 14:42:16 -0700210 continue;
211 }
Calin Juravleda098152017-09-01 17:30:01 -0700212 if (classLoaderContexts[i] == null) {
213 throw new IllegalStateException("Inconsistent information in the "
214 + "package structure. A split is marked to contain code "
215 + "but has no dependency listed. Index=" + i + " path=" + paths.get(i));
216 }
217
Jeff Hao5def5e52017-04-19 14:42:16 -0700218 // Append shared libraries with split dependencies for this split.
219 String path = paths.get(i);
Calin Juravleb6f844d2017-07-17 15:23:21 -0700220 if (options.getSplitName() != null) {
221 // We are asked to compile only a specific split. Check that the current path is
222 // what we are looking for.
223 if (!options.getSplitName().equals(new File(path).getName())) {
224 continue;
225 }
226 }
227
Winson14ff7172019-10-23 10:42:27 -0700228 String profileName = ArtManager.getProfileName(
229 i == 0 ? null : pkg.getSplitNames()[i - 1]);
Calin Juravle6ae39fc2018-01-19 20:32:47 -0800230
Calin Juravlecc651942018-02-01 17:20:51 +0000231 String dexMetadataPath = null;
232 if (options.isDexoptInstallWithDexMetadata()) {
233 File dexMetadataFile = DexMetadataHelper.findDexMetadataForFile(new File(path));
234 dexMetadataPath = dexMetadataFile == null
235 ? null : dexMetadataFile.getAbsolutePath();
236 }
237
Calin Juravle3b74c412017-08-03 19:48:37 -0700238 final boolean isUsedByOtherApps = options.isDexoptAsSharedLibrary()
Calin Juravle52a452c2017-08-04 01:42:17 -0700239 || packageUseInfo.isUsedByOtherApps(path);
Winson14ff7172019-10-23 10:42:27 -0700240 final String compilerFilter = getRealCompilerFilter(pkg,
Calin Juravle3b74c412017-08-03 19:48:37 -0700241 options.getCompilerFilter(), isUsedByOtherApps);
242 final boolean profileUpdated = options.isCheckForProfileUpdates() &&
Calin Juravle6ae39fc2018-01-19 20:32:47 -0800243 isProfileUpdated(pkg, sharedGid, profileName, compilerFilter);
Calin Juravle3b74c412017-08-03 19:48:37 -0700244
245 // Get the dexopt flags after getRealCompilerFilter to make sure we get the correct
246 // flags.
Winsone0756292020-01-31 12:21:54 -0800247 final int dexoptFlags = getDexFlags(pkg, pkgSetting, compilerFilter, options);
Calin Juravle3b74c412017-08-03 19:48:37 -0700248
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800249 for (String dexCodeIsa : dexCodeInstructionSets) {
Winsone0756292020-01-31 12:21:54 -0800250 int newResult = dexOptPath(pkg, pkgSetting, path, dexCodeIsa, compilerFilter,
Calin Juravle19da1cf2017-07-12 18:52:49 -0700251 profileUpdated, classLoaderContexts[i], dexoptFlags, sharedGid,
Calin Juravle4bc8f4d2018-02-12 12:00:44 -0800252 packageStats, options.isDowngrade(), profileName, dexMetadataPath,
253 options.getCompilationReason());
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800254 // The end result is:
255 // - FAILED if any path failed,
256 // - PERFORMED if at least one path needed compilation,
257 // - SKIPPED when all paths are up to date
258 if ((result != DEX_OPT_FAILED) && (newResult != DEX_OPT_SKIPPED)) {
259 result = newResult;
260 }
261 }
262 }
263 return result;
264 }
265
266 /**
267 * Performs dexopt on the {@code path} belonging to the package {@code pkg}.
268 *
269 * @return
270 * DEX_OPT_FAILED if there was any exception during dexopt
271 * DEX_OPT_PERFORMED if dexopt was performed successfully on the given path.
272 * DEX_OPT_SKIPPED if the path does not need to be deopt-ed.
273 */
274 @GuardedBy("mInstallLock")
Winsone0756292020-01-31 12:21:54 -0800275 private int dexOptPath(AndroidPackage pkg, @NonNull PackageSetting pkgSetting, String path,
276 String isa, String compilerFilter, boolean profileUpdated, String classLoaderContext,
Calin Juravle6ae39fc2018-01-19 20:32:47 -0800277 int dexoptFlags, int uid, CompilerStats.PackageStats packageStats, boolean downgrade,
Calin Juravle4bc8f4d2018-02-12 12:00:44 -0800278 String profileName, String dexMetadataPath, int compilationReason) {
Calin Juravle576e6c02017-09-12 00:58:33 -0700279 int dexoptNeeded = getDexoptNeeded(path, isa, compilerFilter, classLoaderContext,
280 profileUpdated, downgrade);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800281 if (Math.abs(dexoptNeeded) == DexFile.NO_DEXOPT_NEEDED) {
282 return DEX_OPT_SKIPPED;
283 }
284
Winsone0756292020-01-31 12:21:54 -0800285 String oatDir = getPackageOatDirIfSupported(pkg,
286 pkgSetting.getPkgState().isUpdatedSystemApp());
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800287
288 Log.i(TAG, "Running dexopt (dexoptNeeded=" + dexoptNeeded + ") on: " + path
Winson5e0a1d52020-01-24 12:00:33 -0800289 + " pkg=" + pkg.getPackageName() + " isa=" + isa
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800290 + " dexoptFlags=" + printDexoptFlags(dexoptFlags)
Calin Juravle576e6c02017-09-12 00:58:33 -0700291 + " targetFilter=" + compilerFilter + " oatDir=" + oatDir
292 + " classLoaderContext=" + classLoaderContext);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800293
294 try {
295 long startTime = System.currentTimeMillis();
296
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700297 // TODO: Consider adding 2 different APIs for primary and secondary dexopt.
298 // installd only uses downgrade flag for secondary dex files and ignores it for
299 // primary dex files.
Winsone0756292020-01-31 12:21:54 -0800300 String seInfo = AndroidPackageUtils.getSeInfo(pkg, pkgSetting);
Winson14ff7172019-10-23 10:42:27 -0700301 mInstaller.dexopt(path, uid, pkg.getPackageName(), isa, dexoptNeeded, oatDir,
302 dexoptFlags, compilerFilter, pkg.getVolumeUuid(), classLoaderContext,
Winsone0756292020-01-31 12:21:54 -0800303 seInfo, false /* downgrade*/, pkg.getTargetSdkVersion(),
Calin Juravle0610dd12018-07-20 15:51:17 -0700304 profileName, dexMetadataPath,
305 getAugmentedReasonName(compilationReason, dexMetadataPath != null));
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800306
307 if (packageStats != null) {
308 long endTime = System.currentTimeMillis();
309 packageStats.setCompileTime(path, (int)(endTime - startTime));
310 }
311 return DEX_OPT_PERFORMED;
312 } catch (InstallerException e) {
313 Slog.w(TAG, "Failed to dexopt", e);
314 return DEX_OPT_FAILED;
315 }
316 }
317
Calin Juravle4fdf8272020-04-02 18:09:53 -0700318 /**
319 * Perform dexopt (if needed) on a system server code path).
320 */
321 public int dexoptSystemServerPath(
322 String dexPath, PackageDexUsage.DexUseInfo dexUseInfo, DexoptOptions options) {
323 int dexoptFlags = DEXOPT_PUBLIC
324 | (options.isBootComplete() ? DEXOPT_BOOTCOMPLETE : 0)
325 | (options.isDexoptIdleBackgroundJob() ? DEXOPT_IDLE_BACKGROUND_JOB : 0);
326
327 int result = DEX_OPT_SKIPPED;
328 for (String isa : dexUseInfo.getLoaderIsas()) {
329 int dexoptNeeded = getDexoptNeeded(
330 dexPath,
331 isa,
332 options.getCompilerFilter(),
333 dexUseInfo.getClassLoaderContext(),
334 /* newProfile= */false,
335 /* downgrade= */ false);
336
337 if (dexoptNeeded == DexFile.NO_DEXOPT_NEEDED) {
338 continue;
339 }
340 try {
341 mInstaller.dexopt(
342 dexPath,
343 android.os.Process.SYSTEM_UID,
344 /* packageName= */ "android",
345 isa,
346 dexoptNeeded,
347 /* oatDir= */ null,
348 dexoptFlags,
349 options.getCompilerFilter(),
350 StorageManager.UUID_PRIVATE_INTERNAL,
351 dexUseInfo.getClassLoaderContext(),
352 /* seInfo= */ null,
353 /* downgrade= */ false ,
354 /* targetSdk= */ 0,
355 /* profileName */ null,
356 /* dexMetadataPath */ null,
357 getReasonName(options.getCompilationReason()));
358 } catch (InstallerException e) {
359 Slog.w(TAG, "Failed to dexopt", e);
360 return DEX_OPT_FAILED;
361 }
362 result = DEX_OPT_PERFORMED;
363 }
364 return result;
365 }
366
Calin Juravle0610dd12018-07-20 15:51:17 -0700367 private String getAugmentedReasonName(int compilationReason, boolean useDexMetadata) {
368 String annotation = useDexMetadata
369 ? ArtManagerService.DEXOPT_REASON_WITH_DEX_METADATA_ANNOTATION : "";
370 return getReasonName(compilationReason) + annotation;
371 }
372
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800373 /**
Calin Juravlec22c30e2017-01-16 19:18:48 -0800374 * Performs dexopt on the secondary dex {@code path} belonging to the app {@code info}.
375 *
376 * @return
377 * DEX_OPT_FAILED if there was any exception during dexopt
378 * DEX_OPT_PERFORMED if dexopt was performed successfully on the given path.
379 * NOTE that DEX_OPT_PERFORMED for secondary dex files includes the case when the dex file
380 * didn't need an update. That's because at the moment we don't get more than success/failure
381 * from installd.
382 *
383 * TODO(calin): Consider adding return codes to installd dexopt invocation (rather than
384 * throwing exceptions). Or maybe make a separate call to installd to get DexOptNeeded, though
385 * that seems wasteful.
386 */
Calin Juravlef1ff36f2017-07-22 12:33:41 -0700387 public int dexOptSecondaryDexPath(ApplicationInfo info, String path,
388 PackageDexUsage.DexUseInfo dexUseInfo, DexoptOptions options) {
Calin Juravlec6540da2017-11-15 16:28:01 -0800389 if (info.uid == -1) {
390 throw new IllegalArgumentException("Dexopt for path " + path + " has invalid uid.");
391 }
Calin Juravlec22c30e2017-01-16 19:18:48 -0800392 synchronized (mInstallLock) {
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700393 final long acquireTime = acquireWakeLockLI(info.uid);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800394 try {
Calin Juravlef1ff36f2017-07-22 12:33:41 -0700395 return dexOptSecondaryDexPathLI(info, path, dexUseInfo, options);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800396 } finally {
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700397 releaseWakeLockLI(acquireTime);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800398 }
399 }
400 }
401
402 @GuardedBy("mInstallLock")
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700403 private long acquireWakeLockLI(final int uid) {
404 // During boot the system doesn't need to instantiate and obtain a wake lock.
405 // PowerManager might not be ready, but that doesn't mean that we can't proceed with
406 // dexopt.
407 if (!mSystemReady) {
408 return -1;
409 }
410 mDexoptWakeLock.setWorkSource(new WorkSource(uid));
411 mDexoptWakeLock.acquire(WAKELOCK_TIMEOUT_MS);
412 return SystemClock.elapsedRealtime();
413 }
414
415 @GuardedBy("mInstallLock")
416 private void releaseWakeLockLI(final long acquireTime) {
417 if (acquireTime < 0) {
418 return;
419 }
420 try {
421 if (mDexoptWakeLock.isHeld()) {
422 mDexoptWakeLock.release();
423 }
424 final long duration = SystemClock.elapsedRealtime() - acquireTime;
425 if (duration >= WAKELOCK_TIMEOUT_MS) {
426 Slog.wtf(TAG, "WakeLock " + mDexoptWakeLock.getTag()
427 + " time out. Operation took " + duration + " ms. Thread: "
428 + Thread.currentThread().getName());
429 }
430 } catch (Exception e) {
431 Slog.wtf(TAG, "Error while releasing " + mDexoptWakeLock.getTag() + " lock", e);
432 }
433 }
434
435 @GuardedBy("mInstallLock")
Calin Juravlef1ff36f2017-07-22 12:33:41 -0700436 private int dexOptSecondaryDexPathLI(ApplicationInfo info, String path,
437 PackageDexUsage.DexUseInfo dexUseInfo, DexoptOptions options) {
438 if (options.isDexoptOnlySharedDex() && !dexUseInfo.isUsedByOtherApps()) {
439 // We are asked to optimize only the dex files used by other apps and this is not
440 // on of them: skip it.
441 return DEX_OPT_SKIPPED;
442 }
443
444 String compilerFilter = getRealCompilerFilter(info, options.getCompilerFilter(),
445 dexUseInfo.isUsedByOtherApps());
Calin Juravleefb1c942017-04-04 20:31:44 -0700446 // Get the dexopt flags after getRealCompilerFilter to make sure we get the correct flags.
Nicolas Geoffray3b4359a2017-05-25 13:53:22 +0100447 // Secondary dex files are currently not compiled at boot.
Andreas Gampec041c332017-11-01 17:05:53 -0700448 int dexoptFlags = getDexFlags(info, compilerFilter, options) | DEXOPT_SECONDARY_DEX;
Calin Juravlec22c30e2017-01-16 19:18:48 -0800449 // Check the app storage and add the appropriate flags.
Calin Juravleadbadd52017-03-28 18:19:15 -0700450 if (info.deviceProtectedDataDir != null &&
451 FileUtils.contains(info.deviceProtectedDataDir, path)) {
Calin Juravlec22c30e2017-01-16 19:18:48 -0800452 dexoptFlags |= DEXOPT_STORAGE_DE;
Calin Juravleadbadd52017-03-28 18:19:15 -0700453 } else if (info.credentialProtectedDataDir != null &&
454 FileUtils.contains(info.credentialProtectedDataDir, path)) {
Calin Juravlec22c30e2017-01-16 19:18:48 -0800455 dexoptFlags |= DEXOPT_STORAGE_CE;
456 } else {
457 Slog.e(TAG, "Could not infer CE/DE storage for package " + info.packageName);
458 return DEX_OPT_FAILED;
459 }
Nicolas Geoffray03dba3b2018-12-20 09:47:00 +0000460 String classLoaderContext = null;
Calin Juravle33fc19c2020-03-29 16:53:21 -0700461 if (dexUseInfo.isUnsupportedClassLoaderContext()
462 || dexUseInfo.isVariableClassLoaderContext()) {
Nicolas Geoffray03dba3b2018-12-20 09:47:00 +0000463 // If we have an unknown (not yet set), or a variable class loader chain. Just extract
464 // the dex file.
465 compilerFilter = "extract";
David Brazdil22217f62018-12-18 13:43:55 +0000466 } else {
467 classLoaderContext = dexUseInfo.getClassLoaderContext();
468 }
469
Calin Juravle4bc8f4d2018-02-12 12:00:44 -0800470 int reason = options.getCompilationReason();
Nicolas Geoffray03dba3b2018-12-20 09:47:00 +0000471 Log.d(TAG, "Running dexopt on: " + path
472 + " pkg=" + info.packageName + " isa=" + dexUseInfo.getLoaderIsas()
473 + " reason=" + getReasonName(reason)
474 + " dexoptFlags=" + printDexoptFlags(dexoptFlags)
475 + " target-filter=" + compilerFilter
476 + " class-loader-context=" + classLoaderContext);
477
Calin Juravlec22c30e2017-01-16 19:18:48 -0800478 try {
Calin Juravlef1ff36f2017-07-22 12:33:41 -0700479 for (String isa : dexUseInfo.getLoaderIsas()) {
Calin Juravlec22c30e2017-01-16 19:18:48 -0800480 // Reuse the same dexopt path as for the primary apks. We don't need all the
481 // arguments as some (dexopNeeded and oatDir) will be computed by installd because
482 // system server cannot read untrusted app content.
483 // TODO(calin): maybe add a separate call.
484 mInstaller.dexopt(path, info.uid, info.packageName, isa, /*dexoptNeeded*/ 0,
485 /*oatDir*/ null, dexoptFlags,
Nick Kralevich005f9592018-08-14 11:11:02 -0700486 compilerFilter, info.volumeUuid, classLoaderContext, info.seInfo,
Calin Juravlecc651942018-02-01 17:20:51 +0000487 options.isDowngrade(), info.targetSdkVersion, /*profileName*/ null,
Calin Juravle4bc8f4d2018-02-12 12:00:44 -0800488 /*dexMetadataPath*/ null, getReasonName(reason));
Calin Juravlec22c30e2017-01-16 19:18:48 -0800489 }
490
491 return DEX_OPT_PERFORMED;
492 } catch (InstallerException e) {
493 Slog.w(TAG, "Failed to dexopt", e);
494 return DEX_OPT_FAILED;
495 }
496 }
497
498 /**
Andreas Gampea8908752015-11-10 08:58:14 -0800499 * Adjust the given dexopt-needed value. Can be overridden to influence the decision to
500 * optimize or not (and in what way).
501 */
502 protected int adjustDexoptNeeded(int dexoptNeeded) {
503 return dexoptNeeded;
504 }
505
506 /**
507 * Adjust the given dexopt flags that will be passed to the installer.
508 */
509 protected int adjustDexoptFlags(int dexoptFlags) {
510 return dexoptFlags;
511 }
512
Narayan Kamath88eea9e2016-05-02 14:44:31 +0100513 /**
514 * Dumps the dexopt state of the given package {@code pkg} to the given {@code PrintWriter}.
515 */
Winsone0756292020-01-31 12:21:54 -0800516 void dumpDexoptState(IndentingPrintWriter pw, AndroidPackage pkg, PackageSetting pkgSetting,
Calin Juravle41a57a62017-08-06 19:20:19 -0700517 PackageDexUsage.PackageUseInfo useInfo) {
Winsone0756292020-01-31 12:21:54 -0800518 final String[] instructionSets = getAppDexInstructionSets(
519 AndroidPackageUtils.getPrimaryCpuAbi(pkg, pkgSetting),
520 AndroidPackageUtils.getSecondaryCpuAbi(pkg, pkgSetting));
Narayan Kamath88eea9e2016-05-02 14:44:31 +0100521 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
522
Winson5e0a1d52020-01-24 12:00:33 -0800523 final List<String> paths = AndroidPackageUtils.getAllCodePathsExcludingResourceOnly(pkg);
Narayan Kamath88eea9e2016-05-02 14:44:31 +0100524
Calin Juravle41a57a62017-08-06 19:20:19 -0700525 for (String path : paths) {
526 pw.println("path: " + path);
527 pw.increaseIndent();
528
529 for (String isa : dexCodeInstructionSets) {
Calin Juravle41a57a62017-08-06 19:20:19 -0700530 try {
Calin Juravle7fc0f632018-03-30 12:38:59 -0700531 DexFile.OptimizationInfo info = DexFile.getDexFileOptimizationInfo(path, isa);
532 pw.println(isa + ": [status=" + info.getStatus()
533 +"] [reason=" + info.getReason() + "]");
Calin Juravle41a57a62017-08-06 19:20:19 -0700534 } catch (IOException ioe) {
Calin Juravleab49fc42018-03-28 19:00:18 -0700535 pw.println(isa + ": [Exception]: " + ioe.getMessage());
Calin Juravle41a57a62017-08-06 19:20:19 -0700536 }
Calin Juravle41a57a62017-08-06 19:20:19 -0700537 }
538
539 if (useInfo.isUsedByOtherApps(path)) {
Calin Juravle94837e32017-09-26 13:23:00 -0700540 pw.println("used by other apps: " + useInfo.getLoadingPackages(path));
Calin Juravle41a57a62017-08-06 19:20:19 -0700541 }
542
543 Map<String, PackageDexUsage.DexUseInfo> dexUseInfoMap = useInfo.getDexUseInfoMap();
544
545 if (!dexUseInfoMap.isEmpty()) {
546 pw.println("known secondary dex files:");
547 pw.increaseIndent();
548 for (Map.Entry<String, PackageDexUsage.DexUseInfo> e : dexUseInfoMap.entrySet()) {
549 String dex = e.getKey();
550 PackageDexUsage.DexUseInfo dexUseInfo = e.getValue();
551 pw.println(dex);
552 pw.increaseIndent();
Calin Juravlecf722222017-09-18 17:40:48 -0700553 // TODO(calin): get the status of the oat file (needs installd call)
Calin Juravle41a57a62017-08-06 19:20:19 -0700554 pw.println("class loader context: " + dexUseInfo.getClassLoaderContext());
555 if (dexUseInfo.isUsedByOtherApps()) {
Calin Juravle94837e32017-09-26 13:23:00 -0700556 pw.println("used by other apps: " + dexUseInfo.getLoadingPackages());
Calin Juravle41a57a62017-08-06 19:20:19 -0700557 }
558 pw.decreaseIndent();
559 }
560 pw.decreaseIndent();
561 }
562 pw.decreaseIndent();
Narayan Kamath88eea9e2016-05-02 14:44:31 +0100563 }
564 }
565
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800566 /**
567 * Returns the compiler filter that should be used to optimize the package code.
568 * The target filter will be updated if the package code is used by other apps
569 * or if it has the safe mode flag set.
570 */
Calin Juravlec22c30e2017-01-16 19:18:48 -0800571 private String getRealCompilerFilter(ApplicationInfo info, String targetCompilerFilter,
572 boolean isUsedByOtherApps) {
Victor Hsiehf12af2f2019-01-03 10:11:03 -0800573 // When an app or priv app is configured to run out of box, only verify it.
Victor Hsiehfa9df0b2019-01-29 12:48:36 -0800574 if (info.isEmbeddedDexUsed()
Victor Hsiehf12af2f2019-01-03 10:11:03 -0800575 || (info.isPrivilegedApp()
Winson14ff7172019-10-23 10:42:27 -0700576 && DexManager.isPackageSelectedToRunOob(info.packageName))) {
Victor Hsieh785d6182018-04-19 14:26:28 -0700577 return "verify";
Nicolas Geoffray11d21a292018-01-24 14:07:14 +0000578 }
Calin Juravle1aa15482019-05-08 15:00:07 -0700579
580 // We force vmSafeMode on debuggable apps as well:
581 // - the runtime ignores their compiled code
582 // - they generally have lots of methods that could make the compiler used run
583 // out of memory (b/130828957)
584 // Note that forcing the compiler filter here applies to all compilations (even if they
585 // are done via adb shell commands). That's ok because right now the runtime will ignore
586 // the compiled code anyway. The alternative would have been to update either
587 // PackageDexOptimizer#canOptimizePackage or PackageManagerService#getOptimizablePackages
588 // but that would have the downside of possibly producing a big odex files which would
589 // be ignored anyway.
590 boolean vmSafeModeOrDebuggable = ((info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0)
591 || ((info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
592
593 if (vmSafeModeOrDebuggable) {
Nicolas Geoffrayd093b202017-05-03 13:11:58 +0100594 return getSafeModeCompilerFilter(targetCompilerFilter);
Mathieu Chartier41e4a372016-09-02 16:36:42 -0700595 }
596
Calin Juravlec22c30e2017-01-16 19:18:48 -0800597 if (isProfileGuidedCompilerFilter(targetCompilerFilter) && isUsedByOtherApps) {
Calin Juravlef53201f2017-09-15 11:09:29 -0700598 // If the dex files is used by other apps, apply the shared filter.
599 return PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
600 PackageManagerService.REASON_SHARED);
Andreas Gampebdd30d82016-03-20 11:32:11 -0700601 }
602
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800603 return targetCompilerFilter;
Fyodor Kupolov74876572015-02-23 17:14:45 -0800604 }
605
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800606 /**
Winson14ff7172019-10-23 10:42:27 -0700607 * Returns the compiler filter that should be used to optimize the package code.
608 * The target filter will be updated if the package code is used by other apps
609 * or if it has the safe mode flag set.
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800610 */
Winson14ff7172019-10-23 10:42:27 -0700611 private String getRealCompilerFilter(AndroidPackage pkg, String targetCompilerFilter,
612 boolean isUsedByOtherApps) {
613 // When an app or priv app is configured to run out of box, only verify it.
Winson5e0a1d52020-01-24 12:00:33 -0800614 if (pkg.isUseEmbeddedDex()
Winson14ff7172019-10-23 10:42:27 -0700615 || (pkg.isPrivileged()
616 && DexManager.isPackageSelectedToRunOob(pkg.getPackageName()))) {
617 return "verify";
618 }
619
620 // We force vmSafeMode on debuggable apps as well:
621 // - the runtime ignores their compiled code
622 // - they generally have lots of methods that could make the compiler used run
623 // out of memory (b/130828957)
624 // Note that forcing the compiler filter here applies to all compilations (even if they
625 // are done via adb shell commands). That's ok because right now the runtime will ignore
626 // the compiled code anyway. The alternative would have been to update either
627 // PackageDexOptimizer#canOptimizePackage or PackageManagerService#getOptimizablePackages
628 // but that would have the downside of possibly producing a big odex files which would
629 // be ignored anyway.
Winsonf00c7552020-01-28 12:52:01 -0800630 boolean vmSafeModeOrDebuggable = pkg.isVmSafeMode() || pkg.isDebuggable();
Winson14ff7172019-10-23 10:42:27 -0700631
632 if (vmSafeModeOrDebuggable) {
633 return getSafeModeCompilerFilter(targetCompilerFilter);
634 }
635
636 if (isProfileGuidedCompilerFilter(targetCompilerFilter) && isUsedByOtherApps) {
637 // If the dex files is used by other apps, apply the shared filter.
638 return PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
639 PackageManagerService.REASON_SHARED);
640 }
641
642 return targetCompilerFilter;
Calin Juravlec22c30e2017-01-16 19:18:48 -0800643 }
644
Mathieu Chartiera9c34332018-03-12 17:11:07 -0700645 private boolean isAppImageEnabled() {
646 return SystemProperties.get("dalvik.vm.appimageformat", "").length() > 0;
647 }
648
Andreas Gampec041c332017-11-01 17:05:53 -0700649 private int getDexFlags(ApplicationInfo info, String compilerFilter, DexoptOptions options) {
Winsonf00c7552020-01-28 12:52:01 -0800650 return getDexFlags((info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0,
651 info.getHiddenApiEnforcementPolicy(), info.splitDependencies,
652 info.requestsIsolatedSplitLoading(), compilerFilter, options);
Winson14ff7172019-10-23 10:42:27 -0700653 }
Winsone0756292020-01-31 12:21:54 -0800654 private int getDexFlags(AndroidPackage pkg, @NonNull PackageSetting pkgSetting,
655 String compilerFilter, DexoptOptions options) {
Winsonf00c7552020-01-28 12:52:01 -0800656 return getDexFlags(pkg.isDebuggable(),
Winsone0756292020-01-31 12:21:54 -0800657 AndroidPackageUtils.getHiddenApiEnforcementPolicy(pkg, pkgSetting),
Winson5e0a1d52020-01-24 12:00:33 -0800658 pkg.getSplitDependencies(), pkg.isIsolatedSplitLoading(), compilerFilter,
Winson14ff7172019-10-23 10:42:27 -0700659 options);
660 }
661
662 /**
663 * Computes the dex flags that needs to be pass to installd for the given package and compiler
664 * filter.
665 */
Winsonf00c7552020-01-28 12:52:01 -0800666 private int getDexFlags(boolean debuggable, int hiddenApiEnforcementPolicy,
Winson14ff7172019-10-23 10:42:27 -0700667 SparseArray<int[]> splitDependencies, boolean requestsIsolatedSplitLoading,
668 String compilerFilter, DexoptOptions options) {
Calin Juravleff3e4a12018-02-01 17:23:13 +0000669 // Profile guide compiled oat files should not be public unles they are based
670 // on profiles from dex metadata archives.
671 // The flag isDexoptInstallWithDexMetadata applies only on installs when we know that
672 // the user does not have an existing profile.
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800673 boolean isProfileGuidedFilter = isProfileGuidedCompilerFilter(compilerFilter);
Patrick Baumannfc2851e2018-11-13 15:23:22 -0800674 boolean isPublic = !isProfileGuidedFilter || options.isDexoptInstallWithDexMetadata();
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800675 int profileFlag = isProfileGuidedFilter ? DEXOPT_PROFILE_GUIDED : 0;
David Brazdilf7e31c02018-02-13 17:04:26 +0000676 // Some apps are executed with restrictions on hidden API usage. If this app is one
677 // of them, pass a flag to dexopt to enable the same restrictions during compilation.
Mathew Inwoode3299532018-02-22 13:19:53 +0000678 // TODO we should pass the actual flag value to dexopt, rather than assuming blacklist
Winson14ff7172019-10-23 10:42:27 -0700679 // TODO(b/135203078): This flag is no longer set as part of AndroidPackage
680 // and may not be preserved
681 int hiddenApiFlag = hiddenApiEnforcementPolicy == HIDDEN_API_ENFORCEMENT_DISABLED
Mathew Inwoode3299532018-02-22 13:19:53 +0000682 ? 0
683 : DEXOPT_ENABLE_HIDDEN_API_CHECKS;
Mathieu Chartiera6d43e42018-03-08 13:11:40 -0800684 // Avoid generating CompactDex for modes that are latency critical.
Mathieu Chartierfa3e9762018-03-06 18:28:22 -0800685 final int compilationReason = options.getCompilationReason();
686 boolean generateCompactDex = true;
687 switch (compilationReason) {
688 case PackageManagerService.REASON_FIRST_BOOT:
689 case PackageManagerService.REASON_BOOT:
690 case PackageManagerService.REASON_INSTALL:
691 generateCompactDex = false;
692 }
Mathieu Chartiera9c34332018-03-12 17:11:07 -0700693 // Use app images only if it is enabled and we are compiling
694 // profile-guided (so the app image doesn't conservatively contain all classes).
695 // If the app didn't request for the splits to be loaded in isolation or if it does not
696 // declare inter-split dependencies, then all the splits will be loaded in the base
697 // apk class loader (in the order of their definition, otherwise disable app images
698 // because they are unsupported for multiple class loaders. b/7269679
Winson14ff7172019-10-23 10:42:27 -0700699 boolean generateAppImage = isProfileGuidedFilter && (splitDependencies == null ||
700 !requestsIsolatedSplitLoading) && isAppImageEnabled();
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800701 int dexFlags =
702 (isPublic ? DEXOPT_PUBLIC : 0)
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800703 | (debuggable ? DEXOPT_DEBUGGABLE : 0)
704 | profileFlag
Andreas Gampec041c332017-11-01 17:05:53 -0700705 | (options.isBootComplete() ? DEXOPT_BOOTCOMPLETE : 0)
David Brazdil464ed3d2018-01-18 15:25:18 +0000706 | (options.isDexoptIdleBackgroundJob() ? DEXOPT_IDLE_BACKGROUND_JOB : 0)
Mathieu Chartierfa3e9762018-03-06 18:28:22 -0800707 | (generateCompactDex ? DEXOPT_GENERATE_COMPACT_DEX : 0)
Mathieu Chartiera9c34332018-03-12 17:11:07 -0700708 | (generateAppImage ? DEXOPT_GENERATE_APP_IMAGE : 0)
David Brazdil464ed3d2018-01-18 15:25:18 +0000709 | hiddenApiFlag;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800710 return adjustDexoptFlags(dexFlags);
711 }
712
713 /**
714 * Assesses if there's a need to perform dexopt on {@code path} for the given
715 * configuration (isa, compiler filter, profile).
716 */
717 private int getDexoptNeeded(String path, String isa, String compilerFilter,
Calin Juravle576e6c02017-09-12 00:58:33 -0700718 String classLoaderContext, boolean newProfile, boolean downgrade) {
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800719 int dexoptNeeded;
720 try {
Calin Juravle576e6c02017-09-12 00:58:33 -0700721 dexoptNeeded = DexFile.getDexOptNeeded(path, isa, compilerFilter, classLoaderContext,
722 newProfile, downgrade);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800723 } catch (IOException ioe) {
724 Slog.w(TAG, "IOException reading apk: " + path, ioe);
725 return DEX_OPT_FAILED;
726 }
727 return adjustDexoptNeeded(dexoptNeeded);
728 }
729
730 /**
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800731 * Checks if there is an update on the profile information of the {@code pkg}.
732 * If the compiler filter is not profile guided the method returns false.
733 *
734 * Note that this is a "destructive" operation with side effects. Under the hood the
735 * current profile and the reference profile will be merged and subsequent calls
736 * may return a different result.
737 */
Winson14ff7172019-10-23 10:42:27 -0700738 private boolean isProfileUpdated(AndroidPackage pkg, int uid, String profileName,
Calin Juravle6ae39fc2018-01-19 20:32:47 -0800739 String compilerFilter) {
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800740 // Check if we are allowed to merge and if the compiler filter is profile guided.
741 if (!isProfileGuidedCompilerFilter(compilerFilter)) {
742 return false;
743 }
744 // Merge profiles. It returns whether or not there was an updated in the profile info.
745 try {
Winson14ff7172019-10-23 10:42:27 -0700746 return mInstaller.mergeProfiles(uid, pkg.getPackageName(), profileName);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800747 } catch (InstallerException e) {
748 Slog.w(TAG, "Failed to merge profiles", e);
749 }
750 return false;
751 }
752
753 /**
Alex Buynytskyy54bc47a2019-06-20 16:30:20 -0700754 * Gets oat dir for the specified package if needed and supported.
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800755 * In certain cases oat directory
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800756 * <strong>cannot</strong> be created:
757 * <ul>
758 * <li>{@code pkg} is a system app, which is not updated.</li>
759 * <li>Package location is not a directory, i.e. monolithic install.</li>
760 * </ul>
761 *
Alex Buynytskyy54bc47a2019-06-20 16:30:20 -0700762 * @return Absolute path to the oat directory or null, if oat directories
763 * not needed or unsupported for the package.
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800764 */
765 @Nullable
Winsone0756292020-01-31 12:21:54 -0800766 private String getPackageOatDirIfSupported(AndroidPackage pkg, boolean isUpdatedSystemApp) {
767 if (!AndroidPackageUtils.canHaveOatDir(pkg, isUpdatedSystemApp)) {
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800768 return null;
769 }
Winson14ff7172019-10-23 10:42:27 -0700770 File codePath = new File(pkg.getCodePath());
Alex Buynytskyy54bc47a2019-06-20 16:30:20 -0700771 if (!codePath.isDirectory()) {
772 return null;
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800773 }
Alex Buynytskyy54bc47a2019-06-20 16:30:20 -0700774 return getOatDir(codePath).getAbsolutePath();
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800775 }
776
777 static File getOatDir(File codePath) {
778 return new File(codePath, OAT_DIR_NAME);
779 }
780
Fyodor Kupolova627c092015-05-05 18:44:39 -0700781 void systemReady() {
782 mSystemReady = true;
783 }
Andreas Gampea8908752015-11-10 08:58:14 -0800784
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800785 private String printDexoptFlags(int flags) {
786 ArrayList<String> flagsList = new ArrayList<>();
787
788 if ((flags & DEXOPT_BOOTCOMPLETE) == DEXOPT_BOOTCOMPLETE) {
789 flagsList.add("boot_complete");
790 }
791 if ((flags & DEXOPT_DEBUGGABLE) == DEXOPT_DEBUGGABLE) {
792 flagsList.add("debuggable");
793 }
794 if ((flags & DEXOPT_PROFILE_GUIDED) == DEXOPT_PROFILE_GUIDED) {
795 flagsList.add("profile_guided");
796 }
797 if ((flags & DEXOPT_PUBLIC) == DEXOPT_PUBLIC) {
798 flagsList.add("public");
799 }
Calin Juravlec22c30e2017-01-16 19:18:48 -0800800 if ((flags & DEXOPT_SECONDARY_DEX) == DEXOPT_SECONDARY_DEX) {
801 flagsList.add("secondary");
802 }
803 if ((flags & DEXOPT_FORCE) == DEXOPT_FORCE) {
804 flagsList.add("force");
805 }
806 if ((flags & DEXOPT_STORAGE_CE) == DEXOPT_STORAGE_CE) {
807 flagsList.add("storage_ce");
808 }
809 if ((flags & DEXOPT_STORAGE_DE) == DEXOPT_STORAGE_DE) {
810 flagsList.add("storage_de");
811 }
David Sehr2118ec42017-10-25 14:28:29 -0700812 if ((flags & DEXOPT_IDLE_BACKGROUND_JOB) == DEXOPT_IDLE_BACKGROUND_JOB) {
813 flagsList.add("idle_background_job");
814 }
David Brazdilf7e31c02018-02-13 17:04:26 +0000815 if ((flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) == DEXOPT_ENABLE_HIDDEN_API_CHECKS) {
816 flagsList.add("enable_hidden_api_checks");
David Brazdil464ed3d2018-01-18 15:25:18 +0000817 }
Calin Juravlec22c30e2017-01-16 19:18:48 -0800818
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800819 return String.join(",", flagsList);
820 }
821
Andreas Gampea8908752015-11-10 08:58:14 -0800822 /**
823 * A specialized PackageDexOptimizer that overrides already-installed checks, forcing a
824 * dexopt path.
825 */
826 public static class ForcedUpdatePackageDexOptimizer extends PackageDexOptimizer {
827
828 public ForcedUpdatePackageDexOptimizer(Installer installer, Object installLock,
829 Context context, String wakeLockTag) {
830 super(installer, installLock, context, wakeLockTag);
831 }
832
833 public ForcedUpdatePackageDexOptimizer(PackageDexOptimizer from) {
834 super(from);
835 }
836
837 @Override
Andreas Gampea8908752015-11-10 08:58:14 -0800838 protected int adjustDexoptNeeded(int dexoptNeeded) {
Nicolas Geoffray96d12a92017-05-03 11:51:53 +0100839 if (dexoptNeeded == DexFile.NO_DEXOPT_NEEDED) {
840 // Ensure compilation by pretending a compiler filter change on the
841 // apk/odex location (the reason for the '-'. A positive value means
842 // the 'oat' location).
843 return -DexFile.DEX2OAT_FOR_FILTER;
844 }
845 return dexoptNeeded;
Andreas Gampea8908752015-11-10 08:58:14 -0800846 }
Calin Juravlec22c30e2017-01-16 19:18:48 -0800847
848 @Override
849 protected int adjustDexoptFlags(int flags) {
850 // Add DEXOPT_FORCE flag to signal installd that it should force compilation
851 // and discard dexoptanalyzer result.
852 return flags | DEXOPT_FORCE;
853 }
Andreas Gampea8908752015-11-10 08:58:14 -0800854 }
Fyodor Kupolov74876572015-02-23 17:14:45 -0800855}