blob: 2c935f138599f81cb5c7586ae2a60e5602e54aa6 [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
Fyodor Kupolovb94c1652015-03-03 12:25:30 -080019import android.annotation.Nullable;
Fyodor Kupolova627c092015-05-05 18:44:39 -070020import android.content.Context;
Fyodor Kupolov74876572015-02-23 17:14:45 -080021import android.content.pm.ApplicationInfo;
22import android.content.pm.PackageParser;
Calin Juravleadbadd52017-03-28 18:19:15 -070023import android.os.FileUtils;
Fyodor Kupolova627c092015-05-05 18:44:39 -070024import android.os.PowerManager;
Fyodor Kupolov28f28552017-05-02 12:11:02 -070025import android.os.SystemClock;
Fyodor Kupolov74876572015-02-23 17:14:45 -080026import android.os.UserHandle;
Fyodor Kupolova627c092015-05-05 18:44:39 -070027import android.os.WorkSource;
Fyodor Kupolov74876572015-02-23 17:14:45 -080028import android.util.Log;
29import android.util.Slog;
Jeff Hao5def5e52017-04-19 14:42:16 -070030import android.util.SparseArray;
Fyodor Kupolov74876572015-02-23 17:14:45 -080031
Calin Juravle2d4b6ad72017-01-04 13:22:14 -080032import com.android.internal.annotations.GuardedBy;
Narayan Kamath88eea9e2016-05-02 14:44:31 +010033import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey740f5232016-12-09 14:31:26 -070034import com.android.server.pm.Installer.InstallerException;
Calin Juravle1d0e83d2017-07-17 15:12:01 -070035import com.android.server.pm.dex.DexoptOptions;
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -070036
Fyodor Kupolovb94c1652015-03-03 12:25:30 -080037import java.io.File;
Fyodor Kupolov74876572015-02-23 17:14:45 -080038import java.io.IOException;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -080039import java.util.ArrayList;
Fyodor Kupolov74876572015-02-23 17:14:45 -080040import java.util.List;
Calin Juravlec22c30e2017-01-16 19:18:48 -080041import java.util.Set;
Fyodor Kupolov74876572015-02-23 17:14:45 -080042
43import dalvik.system.DexFile;
Fyodor Kupolov74876572015-02-23 17:14:45 -080044
Todd Kennedyfa54ab72015-09-25 07:46:12 -070045import static com.android.server.pm.Installer.DEXOPT_BOOTCOMPLETE;
46import static com.android.server.pm.Installer.DEXOPT_DEBUGGABLE;
Andreas Gampebdd30d82016-03-20 11:32:11 -070047import static com.android.server.pm.Installer.DEXOPT_PROFILE_GUIDED;
Todd Kennedyfa54ab72015-09-25 07:46:12 -070048import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
Calin Juravlec22c30e2017-01-16 19:18:48 -080049import static com.android.server.pm.Installer.DEXOPT_SECONDARY_DEX;
50import static com.android.server.pm.Installer.DEXOPT_FORCE;
51import static com.android.server.pm.Installer.DEXOPT_STORAGE_CE;
52import static com.android.server.pm.Installer.DEXOPT_STORAGE_DE;
Fyodor Kupolov74876572015-02-23 17:14:45 -080053import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
54import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -080055
Fyodor Kupolov28f28552017-05-02 12:11:02 -070056import static com.android.server.pm.PackageManagerService.WATCHDOG_TIMEOUT;
Nicolas Geoffrayb0818e82017-05-05 10:23:19 +010057
Nicolas Geoffrayd093b202017-05-03 13:11:58 +010058import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
59import static dalvik.system.DexFile.getSafeModeCompilerFilter;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -080060import static dalvik.system.DexFile.isProfileGuidedCompilerFilter;
Fyodor Kupolov74876572015-02-23 17:14:45 -080061
62/**
63 * Helper class for running dexopt command on packages.
64 */
Calin Juravlec22c30e2017-01-16 19:18:48 -080065public class PackageDexOptimizer {
Fyodor Kupolovb94c1652015-03-03 12:25:30 -080066 private static final String TAG = "PackageManager.DexOptimizer";
67 static final String OAT_DIR_NAME = "oat";
68 // TODO b/19550105 Remove error codes and use exceptions
Calin Juravlec22c30e2017-01-16 19:18:48 -080069 public static final int DEX_OPT_SKIPPED = 0;
70 public static final int DEX_OPT_PERFORMED = 1;
71 public static final int DEX_OPT_FAILED = -1;
Fyodor Kupolov28f28552017-05-02 12:11:02 -070072 // One minute over PM WATCHDOG_TIMEOUT
73 private static final long WAKELOCK_TIMEOUT_MS = WATCHDOG_TIMEOUT + 1000 * 60;
Fyodor Kupolov74876572015-02-23 17:14:45 -080074
Calin Juravleaae35762017-02-14 17:53:13 -080075 /** Special library name that skips shared libraries check during compilation. */
76 public static final String SKIP_SHARED_LIBRARY_CHECK = "&";
77
Fyodor Kupolov28f28552017-05-02 12:11:02 -070078 @GuardedBy("mInstallLock")
Andreas Gampea8908752015-11-10 08:58:14 -080079 private final Installer mInstaller;
80 private final Object mInstallLock;
Fyodor Kupolov74876572015-02-23 17:14:45 -080081
Fyodor Kupolov28f28552017-05-02 12:11:02 -070082 @GuardedBy("mInstallLock")
Fyodor Kupolova627c092015-05-05 18:44:39 -070083 private final PowerManager.WakeLock mDexoptWakeLock;
84 private volatile boolean mSystemReady;
85
Andreas Gampea8908752015-11-10 08:58:14 -080086 PackageDexOptimizer(Installer installer, Object installLock, Context context,
87 String wakeLockTag) {
88 this.mInstaller = installer;
89 this.mInstallLock = installLock;
90
91 PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
92 mDexoptWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakeLockTag);
93 }
94
95 protected PackageDexOptimizer(PackageDexOptimizer from) {
96 this.mInstaller = from.mInstaller;
97 this.mInstallLock = from.mInstallLock;
98 this.mDexoptWakeLock = from.mDexoptWakeLock;
99 this.mSystemReady = from.mSystemReady;
Fyodor Kupolov74876572015-02-23 17:14:45 -0800100 }
101
Calin Juravledb4a79a2015-12-23 18:55:08 +0200102 static boolean canOptimizePackage(PackageParser.Package pkg) {
Calin Juravle6dfd83d2016-01-29 18:23:57 +0000103 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
Calin Juravledb4a79a2015-12-23 18:55:08 +0200104 }
105
Fyodor Kupolov74876572015-02-23 17:14:45 -0800106 /**
107 * Performs dexopt on all code paths and libraries of the specified package for specified
108 * instruction sets.
109 *
Andreas Gampea8908752015-11-10 08:58:14 -0800110 * <p>Calls to {@link com.android.server.pm.Installer#dexopt} on {@link #mInstaller} are
111 * synchronized on {@link #mInstallLock}.
Fyodor Kupolov74876572015-02-23 17:14:45 -0800112 */
Jeff Haoc7b94822016-03-16 15:56:07 -0700113 int performDexOpt(PackageParser.Package pkg, String[] sharedLibraries,
Calin Juravle1d0e83d2017-07-17 15:12:01 -0700114 String[] instructionSets, CompilerStats.PackageStats packageStats,
115 boolean isUsedByOtherApps, DexoptOptions options) {
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800116 if (!canOptimizePackage(pkg)) {
117 return DEX_OPT_SKIPPED;
118 }
Andreas Gampea8908752015-11-10 08:58:14 -0800119 synchronized (mInstallLock) {
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700120 final long acquireTime = acquireWakeLockLI(pkg.applicationInfo.uid);
Fyodor Kupolova627c092015-05-05 18:44:39 -0700121 try {
Calin Juravle1d0e83d2017-07-17 15:12:01 -0700122 return performDexOptLI(pkg, sharedLibraries, instructionSets,
123 packageStats, isUsedByOtherApps, options);
Fyodor Kupolova627c092015-05-05 18:44:39 -0700124 } finally {
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700125 releaseWakeLockLI(acquireTime);
Fyodor Kupolova627c092015-05-05 18:44:39 -0700126 }
Fyodor Kupolov74876572015-02-23 17:14:45 -0800127 }
128 }
129
Andreas Gampea8908752015-11-10 08:58:14 -0800130 /**
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800131 * Performs dexopt on all code paths of the given package.
132 * It assumes the install lock is held.
133 */
134 @GuardedBy("mInstallLock")
135 private int performDexOptLI(PackageParser.Package pkg, String[] sharedLibraries,
Calin Juravle1d0e83d2017-07-17 15:12:01 -0700136 String[] targetInstructionSets, CompilerStats.PackageStats packageStats,
137 boolean isUsedByOtherApps, DexoptOptions options) {
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800138 final String[] instructionSets = targetInstructionSets != null ?
139 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
140 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
Jeff Hao5def5e52017-04-19 14:42:16 -0700141 final List<String> paths = pkg.getAllCodePaths();
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800142 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
143
Calin Juravlec22c30e2017-01-16 19:18:48 -0800144 final String compilerFilter = getRealCompilerFilter(pkg.applicationInfo,
Calin Juravle1d0e83d2017-07-17 15:12:01 -0700145 options.getCompilerFilter(), isUsedByOtherApps);
146 final boolean profileUpdated = options.isCheckForProfileUpdates() &&
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800147 isProfileUpdated(pkg, sharedGid, compilerFilter);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800148
Jeff Hao5def5e52017-04-19 14:42:16 -0700149 final String sharedLibrariesPath = getSharedLibrariesPath(sharedLibraries);
Calin Juravleefb1c942017-04-04 20:31:44 -0700150 // Get the dexopt flags after getRealCompilerFilter to make sure we get the correct flags.
Calin Juravle1d0e83d2017-07-17 15:12:01 -0700151 final int dexoptFlags = getDexFlags(pkg, compilerFilter, options.isBootComplete());
Jeff Hao5def5e52017-04-19 14:42:16 -0700152 // Get the dependencies of each split in the package. For each code path in the package,
153 // this array contains the relative paths of each split it depends on, separated by colons.
154 String[] splitDependencies = getSplitDependencies(pkg);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800155
156 int result = DEX_OPT_SKIPPED;
Jeff Hao5def5e52017-04-19 14:42:16 -0700157 for (int i = 0; i < paths.size(); i++) {
158 // Skip paths that have no code.
159 if ((i == 0 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) ||
160 (i != 0 && (pkg.splitFlags[i - 1] & ApplicationInfo.FLAG_HAS_CODE) == 0)) {
161 continue;
162 }
163 // Append shared libraries with split dependencies for this split.
164 String path = paths.get(i);
Calin Juravleb6f844d2017-07-17 15:23:21 -0700165 if (options.getSplitName() != null) {
166 // We are asked to compile only a specific split. Check that the current path is
167 // what we are looking for.
168 if (!options.getSplitName().equals(new File(path).getName())) {
169 continue;
170 }
171 }
172
Jeff Hao5def5e52017-04-19 14:42:16 -0700173 String sharedLibrariesPathWithSplits;
174 if (sharedLibrariesPath != null && splitDependencies[i] != null) {
175 sharedLibrariesPathWithSplits = sharedLibrariesPath + ":" + splitDependencies[i];
176 } else {
177 sharedLibrariesPathWithSplits =
178 splitDependencies[i] != null ? splitDependencies[i] : sharedLibrariesPath;
179 }
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800180 for (String dexCodeIsa : dexCodeInstructionSets) {
181 int newResult = dexOptPath(pkg, path, dexCodeIsa, compilerFilter, profileUpdated,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700182 sharedLibrariesPathWithSplits, dexoptFlags, sharedGid, packageStats,
Calin Juravle1d0e83d2017-07-17 15:12:01 -0700183 options.isDowngrade());
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800184 // The end result is:
185 // - FAILED if any path failed,
186 // - PERFORMED if at least one path needed compilation,
187 // - SKIPPED when all paths are up to date
188 if ((result != DEX_OPT_FAILED) && (newResult != DEX_OPT_SKIPPED)) {
189 result = newResult;
190 }
191 }
192 }
193 return result;
194 }
195
196 /**
197 * Performs dexopt on the {@code path} belonging to the package {@code pkg}.
198 *
199 * @return
200 * DEX_OPT_FAILED if there was any exception during dexopt
201 * DEX_OPT_PERFORMED if dexopt was performed successfully on the given path.
202 * DEX_OPT_SKIPPED if the path does not need to be deopt-ed.
203 */
204 @GuardedBy("mInstallLock")
205 private int dexOptPath(PackageParser.Package pkg, String path, String isa,
206 String compilerFilter, boolean profileUpdated, String sharedLibrariesPath,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700207 int dexoptFlags, int uid, CompilerStats.PackageStats packageStats, boolean downgrade) {
208 int dexoptNeeded = getDexoptNeeded(path, isa, compilerFilter, profileUpdated, downgrade);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800209 if (Math.abs(dexoptNeeded) == DexFile.NO_DEXOPT_NEEDED) {
210 return DEX_OPT_SKIPPED;
211 }
212
213 // TODO(calin): there's no need to try to create the oat dir over and over again,
214 // especially since it involve an extra installd call. We should create
215 // if (if supported) on the fly during the dexopt call.
216 String oatDir = createOatDirIfSupported(pkg, isa);
217
218 Log.i(TAG, "Running dexopt (dexoptNeeded=" + dexoptNeeded + ") on: " + path
219 + " pkg=" + pkg.applicationInfo.packageName + " isa=" + isa
220 + " dexoptFlags=" + printDexoptFlags(dexoptFlags)
221 + " target-filter=" + compilerFilter + " oatDir=" + oatDir
222 + " sharedLibraries=" + sharedLibrariesPath);
223
224 try {
225 long startTime = System.currentTimeMillis();
226
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700227 // TODO: Consider adding 2 different APIs for primary and secondary dexopt.
228 // installd only uses downgrade flag for secondary dex files and ignores it for
229 // primary dex files.
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800230 mInstaller.dexopt(path, uid, pkg.packageName, isa, dexoptNeeded, oatDir, dexoptFlags,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700231 compilerFilter, pkg.volumeUuid, sharedLibrariesPath, pkg.applicationInfo.seInfo,
232 false /* downgrade*/);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800233
234 if (packageStats != null) {
235 long endTime = System.currentTimeMillis();
236 packageStats.setCompileTime(path, (int)(endTime - startTime));
237 }
238 return DEX_OPT_PERFORMED;
239 } catch (InstallerException e) {
240 Slog.w(TAG, "Failed to dexopt", e);
241 return DEX_OPT_FAILED;
242 }
243 }
244
245 /**
Calin Juravlec22c30e2017-01-16 19:18:48 -0800246 * Performs dexopt on the secondary dex {@code path} belonging to the app {@code info}.
247 *
248 * @return
249 * DEX_OPT_FAILED if there was any exception during dexopt
250 * DEX_OPT_PERFORMED if dexopt was performed successfully on the given path.
251 * NOTE that DEX_OPT_PERFORMED for secondary dex files includes the case when the dex file
252 * didn't need an update. That's because at the moment we don't get more than success/failure
253 * from installd.
254 *
255 * TODO(calin): Consider adding return codes to installd dexopt invocation (rather than
256 * throwing exceptions). Or maybe make a separate call to installd to get DexOptNeeded, though
257 * that seems wasteful.
258 */
259 public int dexOptSecondaryDexPath(ApplicationInfo info, String path, Set<String> isas,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700260 String compilerFilter, boolean isUsedByOtherApps, boolean downgrade) {
Calin Juravlec22c30e2017-01-16 19:18:48 -0800261 synchronized (mInstallLock) {
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700262 final long acquireTime = acquireWakeLockLI(info.uid);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800263 try {
264 return dexOptSecondaryDexPathLI(info, path, isas, compilerFilter,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700265 isUsedByOtherApps, downgrade);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800266 } finally {
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700267 releaseWakeLockLI(acquireTime);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800268 }
269 }
270 }
271
272 @GuardedBy("mInstallLock")
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700273 private long acquireWakeLockLI(final int uid) {
274 // During boot the system doesn't need to instantiate and obtain a wake lock.
275 // PowerManager might not be ready, but that doesn't mean that we can't proceed with
276 // dexopt.
277 if (!mSystemReady) {
278 return -1;
279 }
280 mDexoptWakeLock.setWorkSource(new WorkSource(uid));
281 mDexoptWakeLock.acquire(WAKELOCK_TIMEOUT_MS);
282 return SystemClock.elapsedRealtime();
283 }
284
285 @GuardedBy("mInstallLock")
286 private void releaseWakeLockLI(final long acquireTime) {
287 if (acquireTime < 0) {
288 return;
289 }
290 try {
291 if (mDexoptWakeLock.isHeld()) {
292 mDexoptWakeLock.release();
293 }
294 final long duration = SystemClock.elapsedRealtime() - acquireTime;
295 if (duration >= WAKELOCK_TIMEOUT_MS) {
296 Slog.wtf(TAG, "WakeLock " + mDexoptWakeLock.getTag()
297 + " time out. Operation took " + duration + " ms. Thread: "
298 + Thread.currentThread().getName());
299 }
300 } catch (Exception e) {
301 Slog.wtf(TAG, "Error while releasing " + mDexoptWakeLock.getTag() + " lock", e);
302 }
303 }
304
305 @GuardedBy("mInstallLock")
Calin Juravlec22c30e2017-01-16 19:18:48 -0800306 private int dexOptSecondaryDexPathLI(ApplicationInfo info, String path, Set<String> isas,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700307 String compilerFilter, boolean isUsedByOtherApps, boolean downgrade) {
Calin Juravleefb1c942017-04-04 20:31:44 -0700308 compilerFilter = getRealCompilerFilter(info, compilerFilter, isUsedByOtherApps);
309 // Get the dexopt flags after getRealCompilerFilter to make sure we get the correct flags.
Nicolas Geoffray3b4359a2017-05-25 13:53:22 +0100310 // Secondary dex files are currently not compiled at boot.
311 int dexoptFlags = getDexFlags(info, compilerFilter, /* bootComplete */ true)
312 | DEXOPT_SECONDARY_DEX;
Calin Juravlec22c30e2017-01-16 19:18:48 -0800313 // Check the app storage and add the appropriate flags.
Calin Juravleadbadd52017-03-28 18:19:15 -0700314 if (info.deviceProtectedDataDir != null &&
315 FileUtils.contains(info.deviceProtectedDataDir, path)) {
Calin Juravlec22c30e2017-01-16 19:18:48 -0800316 dexoptFlags |= DEXOPT_STORAGE_DE;
Calin Juravleadbadd52017-03-28 18:19:15 -0700317 } else if (info.credentialProtectedDataDir != null &&
318 FileUtils.contains(info.credentialProtectedDataDir, path)) {
Calin Juravlec22c30e2017-01-16 19:18:48 -0800319 dexoptFlags |= DEXOPT_STORAGE_CE;
320 } else {
321 Slog.e(TAG, "Could not infer CE/DE storage for package " + info.packageName);
322 return DEX_OPT_FAILED;
323 }
Calin Juravlec22c30e2017-01-16 19:18:48 -0800324 Log.d(TAG, "Running dexopt on: " + path
325 + " pkg=" + info.packageName + " isa=" + isas
326 + " dexoptFlags=" + printDexoptFlags(dexoptFlags)
327 + " target-filter=" + compilerFilter);
328
329 try {
330 for (String isa : isas) {
331 // Reuse the same dexopt path as for the primary apks. We don't need all the
332 // arguments as some (dexopNeeded and oatDir) will be computed by installd because
333 // system server cannot read untrusted app content.
334 // TODO(calin): maybe add a separate call.
335 mInstaller.dexopt(path, info.uid, info.packageName, isa, /*dexoptNeeded*/ 0,
336 /*oatDir*/ null, dexoptFlags,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700337 compilerFilter, info.volumeUuid, SKIP_SHARED_LIBRARY_CHECK, info.seInfoUser,
338 downgrade);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800339 }
340
341 return DEX_OPT_PERFORMED;
342 } catch (InstallerException e) {
343 Slog.w(TAG, "Failed to dexopt", e);
344 return DEX_OPT_FAILED;
345 }
346 }
347
348 /**
Andreas Gampea8908752015-11-10 08:58:14 -0800349 * Adjust the given dexopt-needed value. Can be overridden to influence the decision to
350 * optimize or not (and in what way).
351 */
352 protected int adjustDexoptNeeded(int dexoptNeeded) {
353 return dexoptNeeded;
354 }
355
356 /**
357 * Adjust the given dexopt flags that will be passed to the installer.
358 */
359 protected int adjustDexoptFlags(int dexoptFlags) {
360 return dexoptFlags;
361 }
362
Narayan Kamath88eea9e2016-05-02 14:44:31 +0100363 /**
364 * Dumps the dexopt state of the given package {@code pkg} to the given {@code PrintWriter}.
365 */
366 void dumpDexoptState(IndentingPrintWriter pw, PackageParser.Package pkg) {
367 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
368 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
369
370 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
371
372 for (String instructionSet : dexCodeInstructionSets) {
373 pw.println("Instruction Set: " + instructionSet);
374 pw.increaseIndent();
375 for (String path : paths) {
376 String status = null;
377 try {
378 status = DexFile.getDexFileStatus(path, instructionSet);
379 } catch (IOException ioe) {
380 status = "[Exception]: " + ioe.getMessage();
381 }
382 pw.println("path: " + path);
383 pw.println("status: " + status);
384 }
385 pw.decreaseIndent();
386 }
387 }
388
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800389 /**
390 * Returns the compiler filter that should be used to optimize the package code.
391 * The target filter will be updated if the package code is used by other apps
392 * or if it has the safe mode flag set.
393 */
Calin Juravlec22c30e2017-01-16 19:18:48 -0800394 private String getRealCompilerFilter(ApplicationInfo info, String targetCompilerFilter,
395 boolean isUsedByOtherApps) {
396 int flags = info.flags;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800397 boolean vmSafeMode = (flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
Mathieu Chartier41e4a372016-09-02 16:36:42 -0700398 if (vmSafeMode) {
Nicolas Geoffrayd093b202017-05-03 13:11:58 +0100399 return getSafeModeCompilerFilter(targetCompilerFilter);
Mathieu Chartier41e4a372016-09-02 16:36:42 -0700400 }
401
Calin Juravlec22c30e2017-01-16 19:18:48 -0800402 if (isProfileGuidedCompilerFilter(targetCompilerFilter) && isUsedByOtherApps) {
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800403 // If the dex files is used by other apps, we cannot use profile-guided compilation.
404 return getNonProfileGuidedCompilerFilter(targetCompilerFilter);
Andreas Gampebdd30d82016-03-20 11:32:11 -0700405 }
406
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800407 return targetCompilerFilter;
Fyodor Kupolov74876572015-02-23 17:14:45 -0800408 }
409
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800410 /**
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800411 * Computes the dex flags that needs to be pass to installd for the given package and compiler
412 * filter.
413 */
Nicolas Geoffray3b4359a2017-05-25 13:53:22 +0100414 private int getDexFlags(PackageParser.Package pkg, String compilerFilter,
415 boolean bootComplete) {
416 return getDexFlags(pkg.applicationInfo, compilerFilter, bootComplete);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800417 }
418
Nicolas Geoffray3b4359a2017-05-25 13:53:22 +0100419 private int getDexFlags(ApplicationInfo info, String compilerFilter, boolean bootComplete) {
Calin Juravlec22c30e2017-01-16 19:18:48 -0800420 int flags = info.flags;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800421 boolean debuggable = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
422 // Profile guide compiled oat files should not be public.
423 boolean isProfileGuidedFilter = isProfileGuidedCompilerFilter(compilerFilter);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800424 boolean isPublic = !info.isForwardLocked() && !isProfileGuidedFilter;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800425 int profileFlag = isProfileGuidedFilter ? DEXOPT_PROFILE_GUIDED : 0;
426 int dexFlags =
427 (isPublic ? DEXOPT_PUBLIC : 0)
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800428 | (debuggable ? DEXOPT_DEBUGGABLE : 0)
429 | profileFlag
Nicolas Geoffray3b4359a2017-05-25 13:53:22 +0100430 | (bootComplete ? DEXOPT_BOOTCOMPLETE : 0);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800431 return adjustDexoptFlags(dexFlags);
432 }
433
434 /**
435 * Assesses if there's a need to perform dexopt on {@code path} for the given
436 * configuration (isa, compiler filter, profile).
437 */
438 private int getDexoptNeeded(String path, String isa, String compilerFilter,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700439 boolean newProfile, boolean downgrade) {
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800440 int dexoptNeeded;
441 try {
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700442 dexoptNeeded = DexFile.getDexOptNeeded(path, isa, compilerFilter, newProfile,
443 downgrade);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800444 } catch (IOException ioe) {
445 Slog.w(TAG, "IOException reading apk: " + path, ioe);
446 return DEX_OPT_FAILED;
447 }
448 return adjustDexoptNeeded(dexoptNeeded);
449 }
450
451 /**
452 * Computes the shared libraries path that should be passed to dexopt.
453 */
454 private String getSharedLibrariesPath(String[] sharedLibraries) {
455 if (sharedLibraries == null || sharedLibraries.length == 0) {
456 return null;
457 }
458 StringBuilder sb = new StringBuilder();
459 for (String lib : sharedLibraries) {
460 if (sb.length() != 0) {
461 sb.append(":");
462 }
463 sb.append(lib);
464 }
465 return sb.toString();
466 }
467
468 /**
Jeff Hao5def5e52017-04-19 14:42:16 -0700469 * Walks dependency tree and gathers the dependencies for each split in a split apk.
470 * The split paths are stored as relative paths, separated by colons.
471 */
472 private String[] getSplitDependencies(PackageParser.Package pkg) {
473 // Convert all the code paths to relative paths.
474 String baseCodePath = new File(pkg.baseCodePath).getParent();
475 List<String> paths = pkg.getAllCodePaths();
476 String[] splitDependencies = new String[paths.size()];
477 for (int i = 0; i < paths.size(); i++) {
478 File pathFile = new File(paths.get(i));
479 String fileName = pathFile.getName();
480 paths.set(i, fileName);
481
482 // Sanity check that the base paths of the splits are all the same.
483 String basePath = pathFile.getParent();
484 if (!basePath.equals(baseCodePath)) {
485 Slog.wtf(TAG, "Split paths have different base paths: " + basePath + " and " +
486 baseCodePath);
487 }
488 }
489
490 // If there are no other dependencies, fill in the implicit dependency on the base apk.
491 SparseArray<int[]> dependencies = pkg.applicationInfo.splitDependencies;
492 if (dependencies == null) {
493 for (int i = 1; i < paths.size(); i++) {
494 splitDependencies[i] = paths.get(0);
495 }
496 return splitDependencies;
497 }
498
499 // Fill in the dependencies, skipping the base apk which has no dependencies.
500 for (int i = 1; i < dependencies.size(); i++) {
501 getParentDependencies(dependencies.keyAt(i), paths, dependencies, splitDependencies);
502 }
503
504 return splitDependencies;
505 }
506
507 /**
508 * Recursive method to generate dependencies for a particular split.
509 * The index is a key from the package's splitDependencies.
510 */
511 private String getParentDependencies(int index, List<String> paths,
512 SparseArray<int[]> dependencies, String[] splitDependencies) {
513 // The base apk is always first, and has no dependencies.
514 if (index == 0) {
515 return null;
516 }
517 // Return the result if we've computed the dependencies for this index already.
518 if (splitDependencies[index] != null) {
519 return splitDependencies[index];
520 }
521 // Get the dependencies for the parent of this index and append its path to it.
522 int parent = dependencies.get(index)[0];
523 String parentDependencies =
524 getParentDependencies(parent, paths, dependencies, splitDependencies);
525 String path = parentDependencies == null ? paths.get(parent) :
526 parentDependencies + ":" + paths.get(parent);
527 splitDependencies[index] = path;
528 return path;
529 }
530
531 /**
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800532 * Checks if there is an update on the profile information of the {@code pkg}.
533 * If the compiler filter is not profile guided the method returns false.
534 *
535 * Note that this is a "destructive" operation with side effects. Under the hood the
536 * current profile and the reference profile will be merged and subsequent calls
537 * may return a different result.
538 */
539 private boolean isProfileUpdated(PackageParser.Package pkg, int uid, String compilerFilter) {
540 // Check if we are allowed to merge and if the compiler filter is profile guided.
541 if (!isProfileGuidedCompilerFilter(compilerFilter)) {
542 return false;
543 }
544 // Merge profiles. It returns whether or not there was an updated in the profile info.
545 try {
546 return mInstaller.mergeProfiles(uid, pkg.packageName);
547 } catch (InstallerException e) {
548 Slog.w(TAG, "Failed to merge profiles", e);
549 }
550 return false;
551 }
552
553 /**
554 * Creates oat dir for the specified package if needed and supported.
555 * In certain cases oat directory
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800556 * <strong>cannot</strong> be created:
557 * <ul>
558 * <li>{@code pkg} is a system app, which is not updated.</li>
559 * <li>Package location is not a directory, i.e. monolithic install.</li>
560 * </ul>
561 *
Richard Uhler7b08b352015-03-25 16:25:57 -0700562 * @return Absolute path to the oat directory or null, if oat directory
563 * cannot be created.
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800564 */
565 @Nullable
Todd Kennedy27c24fb2015-09-17 16:49:25 -0700566 private String createOatDirIfSupported(PackageParser.Package pkg, String dexInstructionSet) {
Fyodor Kupolovebcac162015-09-09 15:56:45 -0700567 if (!pkg.canHaveOatDir()) {
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800568 return null;
569 }
570 File codePath = new File(pkg.codePath);
571 if (codePath.isDirectory()) {
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800572 // TODO(calin): why do we create this only if the codePath is a directory? (i.e for
573 // cluster packages). It seems that the logic for the folder creation is
574 // split between installd and here.
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800575 File oatDir = getOatDir(codePath);
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -0700576 try {
Andreas Gampea8908752015-11-10 08:58:14 -0800577 mInstaller.createOatDir(oatDir.getAbsolutePath(), dexInstructionSet);
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -0700578 } catch (InstallerException e) {
579 Slog.w(TAG, "Failed to create oat dir", e);
580 return null;
581 }
Richard Uhler7b08b352015-03-25 16:25:57 -0700582 return oatDir.getAbsolutePath();
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800583 }
584 return null;
585 }
586
587 static File getOatDir(File codePath) {
588 return new File(codePath, OAT_DIR_NAME);
589 }
590
Fyodor Kupolova627c092015-05-05 18:44:39 -0700591 void systemReady() {
592 mSystemReady = true;
593 }
Andreas Gampea8908752015-11-10 08:58:14 -0800594
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800595 private String printDexoptFlags(int flags) {
596 ArrayList<String> flagsList = new ArrayList<>();
597
598 if ((flags & DEXOPT_BOOTCOMPLETE) == DEXOPT_BOOTCOMPLETE) {
599 flagsList.add("boot_complete");
600 }
601 if ((flags & DEXOPT_DEBUGGABLE) == DEXOPT_DEBUGGABLE) {
602 flagsList.add("debuggable");
603 }
604 if ((flags & DEXOPT_PROFILE_GUIDED) == DEXOPT_PROFILE_GUIDED) {
605 flagsList.add("profile_guided");
606 }
607 if ((flags & DEXOPT_PUBLIC) == DEXOPT_PUBLIC) {
608 flagsList.add("public");
609 }
Calin Juravlec22c30e2017-01-16 19:18:48 -0800610 if ((flags & DEXOPT_SECONDARY_DEX) == DEXOPT_SECONDARY_DEX) {
611 flagsList.add("secondary");
612 }
613 if ((flags & DEXOPT_FORCE) == DEXOPT_FORCE) {
614 flagsList.add("force");
615 }
616 if ((flags & DEXOPT_STORAGE_CE) == DEXOPT_STORAGE_CE) {
617 flagsList.add("storage_ce");
618 }
619 if ((flags & DEXOPT_STORAGE_DE) == DEXOPT_STORAGE_DE) {
620 flagsList.add("storage_de");
621 }
622
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800623 return String.join(",", flagsList);
624 }
625
Andreas Gampea8908752015-11-10 08:58:14 -0800626 /**
627 * A specialized PackageDexOptimizer that overrides already-installed checks, forcing a
628 * dexopt path.
629 */
630 public static class ForcedUpdatePackageDexOptimizer extends PackageDexOptimizer {
631
632 public ForcedUpdatePackageDexOptimizer(Installer installer, Object installLock,
633 Context context, String wakeLockTag) {
634 super(installer, installLock, context, wakeLockTag);
635 }
636
637 public ForcedUpdatePackageDexOptimizer(PackageDexOptimizer from) {
638 super(from);
639 }
640
641 @Override
Andreas Gampea8908752015-11-10 08:58:14 -0800642 protected int adjustDexoptNeeded(int dexoptNeeded) {
Nicolas Geoffray96d12a92017-05-03 11:51:53 +0100643 if (dexoptNeeded == DexFile.NO_DEXOPT_NEEDED) {
644 // Ensure compilation by pretending a compiler filter change on the
645 // apk/odex location (the reason for the '-'. A positive value means
646 // the 'oat' location).
647 return -DexFile.DEX2OAT_FOR_FILTER;
648 }
649 return dexoptNeeded;
Andreas Gampea8908752015-11-10 08:58:14 -0800650 }
Calin Juravlec22c30e2017-01-16 19:18:48 -0800651
652 @Override
653 protected int adjustDexoptFlags(int flags) {
654 // Add DEXOPT_FORCE flag to signal installd that it should force compilation
655 // and discard dexoptanalyzer result.
656 return flags | DEXOPT_FORCE;
657 }
Andreas Gampea8908752015-11-10 08:58:14 -0800658 }
Fyodor Kupolov74876572015-02-23 17:14:45 -0800659}