blob: 3eaeb6df64dd9db7d537c003a736745d8e2548cf [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;
Calin Juravlec22c30e2017-01-16 19:18:48 -080022import android.content.pm.PackageInfo;
Fyodor Kupolov74876572015-02-23 17:14:45 -080023import android.content.pm.PackageParser;
Calin Juravled479b522016-02-24 16:22:03 +000024import android.os.Environment;
Calin Juravleadbadd52017-03-28 18:19:15 -070025import android.os.FileUtils;
Fyodor Kupolova627c092015-05-05 18:44:39 -070026import android.os.PowerManager;
Fyodor Kupolov28f28552017-05-02 12:11:02 -070027import android.os.SystemClock;
Fyodor Kupolov74876572015-02-23 17:14:45 -080028import android.os.UserHandle;
Fyodor Kupolova627c092015-05-05 18:44:39 -070029import android.os.WorkSource;
Fyodor Kupolov74876572015-02-23 17:14:45 -080030import android.util.Log;
31import android.util.Slog;
Jeff Hao5def5e52017-04-19 14:42:16 -070032import android.util.SparseArray;
Fyodor Kupolov74876572015-02-23 17:14:45 -080033
Calin Juravle2d4b6ad72017-01-04 13:22:14 -080034import com.android.internal.annotations.GuardedBy;
Narayan Kamath88eea9e2016-05-02 14:44:31 +010035import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey740f5232016-12-09 14:31:26 -070036import com.android.server.pm.Installer.InstallerException;
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -070037
Fyodor Kupolovb94c1652015-03-03 12:25:30 -080038import java.io.File;
Fyodor Kupolov74876572015-02-23 17:14:45 -080039import java.io.IOException;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -080040import java.util.ArrayList;
Fyodor Kupolov74876572015-02-23 17:14:45 -080041import java.util.List;
Calin Juravlec22c30e2017-01-16 19:18:48 -080042import java.util.Set;
Fyodor Kupolov74876572015-02-23 17:14:45 -080043
44import dalvik.system.DexFile;
Fyodor Kupolov74876572015-02-23 17:14:45 -080045
Todd Kennedyfa54ab72015-09-25 07:46:12 -070046import static com.android.server.pm.Installer.DEXOPT_BOOTCOMPLETE;
47import static com.android.server.pm.Installer.DEXOPT_DEBUGGABLE;
Andreas Gampebdd30d82016-03-20 11:32:11 -070048import static com.android.server.pm.Installer.DEXOPT_PROFILE_GUIDED;
Todd Kennedyfa54ab72015-09-25 07:46:12 -070049import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
Calin Juravlec22c30e2017-01-16 19:18:48 -080050import 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;
Fyodor Kupolov74876572015-02-23 17:14:45 -080054import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
55import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -080056
Fyodor Kupolov28f28552017-05-02 12:11:02 -070057import static com.android.server.pm.PackageManagerService.WATCHDOG_TIMEOUT;
Nicolas Geoffrayb0818e82017-05-05 10:23:19 +010058
Nicolas Geoffrayd093b202017-05-03 13:11:58 +010059import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
60import static dalvik.system.DexFile.getSafeModeCompilerFilter;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -080061import static dalvik.system.DexFile.isProfileGuidedCompilerFilter;
Fyodor Kupolov74876572015-02-23 17:14:45 -080062
63/**
64 * Helper class for running dexopt command on packages.
65 */
Calin Juravlec22c30e2017-01-16 19:18:48 -080066public class PackageDexOptimizer {
Fyodor Kupolovb94c1652015-03-03 12:25:30 -080067 private static final String TAG = "PackageManager.DexOptimizer";
68 static final String OAT_DIR_NAME = "oat";
69 // TODO b/19550105 Remove error codes and use exceptions
Calin Juravlec22c30e2017-01-16 19:18:48 -080070 public static final int DEX_OPT_SKIPPED = 0;
71 public static final int DEX_OPT_PERFORMED = 1;
72 public static final int DEX_OPT_FAILED = -1;
Fyodor Kupolov28f28552017-05-02 12:11:02 -070073 // One minute over PM WATCHDOG_TIMEOUT
74 private static final long WAKELOCK_TIMEOUT_MS = WATCHDOG_TIMEOUT + 1000 * 60;
Fyodor Kupolov74876572015-02-23 17:14:45 -080075
Calin Juravleaae35762017-02-14 17:53:13 -080076 /** Special library name that skips shared libraries check during compilation. */
77 public static final String SKIP_SHARED_LIBRARY_CHECK = "&";
78
Fyodor Kupolov28f28552017-05-02 12:11:02 -070079 @GuardedBy("mInstallLock")
Andreas Gampea8908752015-11-10 08:58:14 -080080 private final Installer mInstaller;
81 private final Object mInstallLock;
Fyodor Kupolov74876572015-02-23 17:14:45 -080082
Fyodor Kupolov28f28552017-05-02 12:11:02 -070083 @GuardedBy("mInstallLock")
Fyodor Kupolova627c092015-05-05 18:44:39 -070084 private final PowerManager.WakeLock mDexoptWakeLock;
85 private volatile boolean mSystemReady;
86
Andreas Gampea8908752015-11-10 08:58:14 -080087 PackageDexOptimizer(Installer installer, Object installLock, Context context,
88 String wakeLockTag) {
89 this.mInstaller = installer;
90 this.mInstallLock = installLock;
91
92 PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
93 mDexoptWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakeLockTag);
94 }
95
96 protected PackageDexOptimizer(PackageDexOptimizer from) {
97 this.mInstaller = from.mInstaller;
98 this.mInstallLock = from.mInstallLock;
99 this.mDexoptWakeLock = from.mDexoptWakeLock;
100 this.mSystemReady = from.mSystemReady;
Fyodor Kupolov74876572015-02-23 17:14:45 -0800101 }
102
Calin Juravledb4a79a2015-12-23 18:55:08 +0200103 static boolean canOptimizePackage(PackageParser.Package pkg) {
Calin Juravle6dfd83d2016-01-29 18:23:57 +0000104 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
Calin Juravledb4a79a2015-12-23 18:55:08 +0200105 }
106
Fyodor Kupolov74876572015-02-23 17:14:45 -0800107 /**
108 * Performs dexopt on all code paths and libraries of the specified package for specified
109 * instruction sets.
110 *
Andreas Gampea8908752015-11-10 08:58:14 -0800111 * <p>Calls to {@link com.android.server.pm.Installer#dexopt} on {@link #mInstaller} are
112 * synchronized on {@link #mInstallLock}.
Fyodor Kupolov74876572015-02-23 17:14:45 -0800113 */
Jeff Haoc7b94822016-03-16 15:56:07 -0700114 int performDexOpt(PackageParser.Package pkg, String[] sharedLibraries,
Andreas Gampe7e619a92016-07-12 22:42:41 -0700115 String[] instructionSets, boolean checkProfiles, String targetCompilationFilter,
Nicolas Geoffray3b4359a2017-05-25 13:53:22 +0100116 CompilerStats.PackageStats packageStats, boolean isUsedByOtherApps,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700117 boolean bootComplete, boolean downgrade) {
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800118 if (!canOptimizePackage(pkg)) {
119 return DEX_OPT_SKIPPED;
120 }
Andreas Gampea8908752015-11-10 08:58:14 -0800121 synchronized (mInstallLock) {
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700122 final long acquireTime = acquireWakeLockLI(pkg.applicationInfo.uid);
Fyodor Kupolova627c092015-05-05 18:44:39 -0700123 try {
Jeff Haoc7b94822016-03-16 15:56:07 -0700124 return performDexOptLI(pkg, sharedLibraries, instructionSets, checkProfiles,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700125 targetCompilationFilter, packageStats, isUsedByOtherApps, bootComplete,
126 downgrade);
Fyodor Kupolova627c092015-05-05 18:44:39 -0700127 } finally {
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700128 releaseWakeLockLI(acquireTime);
Fyodor Kupolova627c092015-05-05 18:44:39 -0700129 }
Fyodor Kupolov74876572015-02-23 17:14:45 -0800130 }
131 }
132
Andreas Gampea8908752015-11-10 08:58:14 -0800133 /**
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800134 * 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,
Calin Juravle07b6eab2017-03-01 19:55:35 -0800140 String targetCompilerFilter, CompilerStats.PackageStats packageStats,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700141 boolean isUsedByOtherApps, boolean bootComplete, boolean downgrade) {
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800142 final String[] instructionSets = targetInstructionSets != null ?
143 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
144 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
Jeff Hao5def5e52017-04-19 14:42:16 -0700145 final List<String> paths = pkg.getAllCodePaths();
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800146 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
147
Calin Juravlec22c30e2017-01-16 19:18:48 -0800148 final String compilerFilter = getRealCompilerFilter(pkg.applicationInfo,
Calin Juravle07b6eab2017-03-01 19:55:35 -0800149 targetCompilerFilter, isUsedByOtherApps);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800150 final boolean profileUpdated = checkForProfileUpdates &&
151 isProfileUpdated(pkg, sharedGid, compilerFilter);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800152
Jeff Hao5def5e52017-04-19 14:42:16 -0700153 final String sharedLibrariesPath = getSharedLibrariesPath(sharedLibraries);
Calin Juravleefb1c942017-04-04 20:31:44 -0700154 // Get the dexopt flags after getRealCompilerFilter to make sure we get the correct flags.
Nicolas Geoffray3b4359a2017-05-25 13:53:22 +0100155 final int dexoptFlags = getDexFlags(pkg, compilerFilter, bootComplete);
Jeff Hao5def5e52017-04-19 14:42:16 -0700156 // 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);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800159
160 int result = DEX_OPT_SKIPPED;
Jeff Hao5def5e52017-04-19 14:42:16 -0700161 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 }
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800176 for (String dexCodeIsa : dexCodeInstructionSets) {
177 int newResult = dexOptPath(pkg, path, dexCodeIsa, compilerFilter, profileUpdated,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700178 sharedLibrariesPathWithSplits, dexoptFlags, sharedGid, packageStats,
179 downgrade);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800180 // The end result is:
181 // - FAILED if any path failed,
182 // - PERFORMED if at least one path needed compilation,
183 // - SKIPPED when all paths are up to date
184 if ((result != DEX_OPT_FAILED) && (newResult != DEX_OPT_SKIPPED)) {
185 result = newResult;
186 }
187 }
188 }
189 return result;
190 }
191
192 /**
193 * Performs dexopt on the {@code path} belonging to the package {@code pkg}.
194 *
195 * @return
196 * DEX_OPT_FAILED if there was any exception during dexopt
197 * DEX_OPT_PERFORMED if dexopt was performed successfully on the given path.
198 * DEX_OPT_SKIPPED if the path does not need to be deopt-ed.
199 */
200 @GuardedBy("mInstallLock")
201 private int dexOptPath(PackageParser.Package pkg, String path, String isa,
202 String compilerFilter, boolean profileUpdated, String sharedLibrariesPath,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700203 int dexoptFlags, int uid, CompilerStats.PackageStats packageStats, boolean downgrade) {
204 int dexoptNeeded = getDexoptNeeded(path, isa, compilerFilter, profileUpdated, downgrade);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800205 if (Math.abs(dexoptNeeded) == DexFile.NO_DEXOPT_NEEDED) {
206 return DEX_OPT_SKIPPED;
207 }
208
209 // TODO(calin): there's no need to try to create the oat dir over and over again,
210 // especially since it involve an extra installd call. We should create
211 // if (if supported) on the fly during the dexopt call.
212 String oatDir = createOatDirIfSupported(pkg, isa);
213
214 Log.i(TAG, "Running dexopt (dexoptNeeded=" + dexoptNeeded + ") on: " + path
215 + " pkg=" + pkg.applicationInfo.packageName + " isa=" + isa
216 + " dexoptFlags=" + printDexoptFlags(dexoptFlags)
217 + " target-filter=" + compilerFilter + " oatDir=" + oatDir
218 + " sharedLibraries=" + sharedLibrariesPath);
219
220 try {
221 long startTime = System.currentTimeMillis();
222
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700223 // TODO: Consider adding 2 different APIs for primary and secondary dexopt.
224 // installd only uses downgrade flag for secondary dex files and ignores it for
225 // primary dex files.
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800226 mInstaller.dexopt(path, uid, pkg.packageName, isa, dexoptNeeded, oatDir, dexoptFlags,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700227 compilerFilter, pkg.volumeUuid, sharedLibrariesPath, pkg.applicationInfo.seInfo,
228 false /* downgrade*/);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800229
230 if (packageStats != null) {
231 long endTime = System.currentTimeMillis();
232 packageStats.setCompileTime(path, (int)(endTime - startTime));
233 }
234 return DEX_OPT_PERFORMED;
235 } catch (InstallerException e) {
236 Slog.w(TAG, "Failed to dexopt", e);
237 return DEX_OPT_FAILED;
238 }
239 }
240
241 /**
Calin Juravlec22c30e2017-01-16 19:18:48 -0800242 * Performs dexopt on the secondary dex {@code path} belonging to the app {@code info}.
243 *
244 * @return
245 * DEX_OPT_FAILED if there was any exception during dexopt
246 * DEX_OPT_PERFORMED if dexopt was performed successfully on the given path.
247 * NOTE that DEX_OPT_PERFORMED for secondary dex files includes the case when the dex file
248 * didn't need an update. That's because at the moment we don't get more than success/failure
249 * from installd.
250 *
251 * TODO(calin): Consider adding return codes to installd dexopt invocation (rather than
252 * throwing exceptions). Or maybe make a separate call to installd to get DexOptNeeded, though
253 * that seems wasteful.
254 */
255 public int dexOptSecondaryDexPath(ApplicationInfo info, String path, Set<String> isas,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700256 String compilerFilter, boolean isUsedByOtherApps, boolean downgrade) {
Calin Juravlec22c30e2017-01-16 19:18:48 -0800257 synchronized (mInstallLock) {
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700258 final long acquireTime = acquireWakeLockLI(info.uid);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800259 try {
260 return dexOptSecondaryDexPathLI(info, path, isas, compilerFilter,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700261 isUsedByOtherApps, downgrade);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800262 } finally {
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700263 releaseWakeLockLI(acquireTime);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800264 }
265 }
266 }
267
268 @GuardedBy("mInstallLock")
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700269 private long acquireWakeLockLI(final int uid) {
270 // During boot the system doesn't need to instantiate and obtain a wake lock.
271 // PowerManager might not be ready, but that doesn't mean that we can't proceed with
272 // dexopt.
273 if (!mSystemReady) {
274 return -1;
275 }
276 mDexoptWakeLock.setWorkSource(new WorkSource(uid));
277 mDexoptWakeLock.acquire(WAKELOCK_TIMEOUT_MS);
278 return SystemClock.elapsedRealtime();
279 }
280
281 @GuardedBy("mInstallLock")
282 private void releaseWakeLockLI(final long acquireTime) {
283 if (acquireTime < 0) {
284 return;
285 }
286 try {
287 if (mDexoptWakeLock.isHeld()) {
288 mDexoptWakeLock.release();
289 }
290 final long duration = SystemClock.elapsedRealtime() - acquireTime;
291 if (duration >= WAKELOCK_TIMEOUT_MS) {
292 Slog.wtf(TAG, "WakeLock " + mDexoptWakeLock.getTag()
293 + " time out. Operation took " + duration + " ms. Thread: "
294 + Thread.currentThread().getName());
295 }
296 } catch (Exception e) {
297 Slog.wtf(TAG, "Error while releasing " + mDexoptWakeLock.getTag() + " lock", e);
298 }
299 }
300
301 @GuardedBy("mInstallLock")
Calin Juravlec22c30e2017-01-16 19:18:48 -0800302 private int dexOptSecondaryDexPathLI(ApplicationInfo info, String path, Set<String> isas,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700303 String compilerFilter, boolean isUsedByOtherApps, boolean downgrade) {
Calin Juravleefb1c942017-04-04 20:31:44 -0700304 compilerFilter = getRealCompilerFilter(info, compilerFilter, isUsedByOtherApps);
305 // Get the dexopt flags after getRealCompilerFilter to make sure we get the correct flags.
Nicolas Geoffray3b4359a2017-05-25 13:53:22 +0100306 // Secondary dex files are currently not compiled at boot.
307 int dexoptFlags = getDexFlags(info, compilerFilter, /* bootComplete */ true)
308 | DEXOPT_SECONDARY_DEX;
Calin Juravlec22c30e2017-01-16 19:18:48 -0800309 // Check the app storage and add the appropriate flags.
Calin Juravleadbadd52017-03-28 18:19:15 -0700310 if (info.deviceProtectedDataDir != null &&
311 FileUtils.contains(info.deviceProtectedDataDir, path)) {
Calin Juravlec22c30e2017-01-16 19:18:48 -0800312 dexoptFlags |= DEXOPT_STORAGE_DE;
Calin Juravleadbadd52017-03-28 18:19:15 -0700313 } else if (info.credentialProtectedDataDir != null &&
314 FileUtils.contains(info.credentialProtectedDataDir, path)) {
Calin Juravlec22c30e2017-01-16 19:18:48 -0800315 dexoptFlags |= DEXOPT_STORAGE_CE;
316 } else {
317 Slog.e(TAG, "Could not infer CE/DE storage for package " + info.packageName);
318 return DEX_OPT_FAILED;
319 }
Calin Juravlec22c30e2017-01-16 19:18:48 -0800320 Log.d(TAG, "Running dexopt on: " + path
321 + " pkg=" + info.packageName + " isa=" + isas
322 + " dexoptFlags=" + printDexoptFlags(dexoptFlags)
323 + " target-filter=" + compilerFilter);
324
325 try {
326 for (String isa : isas) {
327 // Reuse the same dexopt path as for the primary apks. We don't need all the
328 // arguments as some (dexopNeeded and oatDir) will be computed by installd because
329 // system server cannot read untrusted app content.
330 // TODO(calin): maybe add a separate call.
331 mInstaller.dexopt(path, info.uid, info.packageName, isa, /*dexoptNeeded*/ 0,
332 /*oatDir*/ null, dexoptFlags,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700333 compilerFilter, info.volumeUuid, SKIP_SHARED_LIBRARY_CHECK, info.seInfoUser,
334 downgrade);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800335 }
336
337 return DEX_OPT_PERFORMED;
338 } catch (InstallerException e) {
339 Slog.w(TAG, "Failed to dexopt", e);
340 return DEX_OPT_FAILED;
341 }
342 }
343
344 /**
Andreas Gampea8908752015-11-10 08:58:14 -0800345 * Adjust the given dexopt-needed value. Can be overridden to influence the decision to
346 * optimize or not (and in what way).
347 */
348 protected int adjustDexoptNeeded(int dexoptNeeded) {
349 return dexoptNeeded;
350 }
351
352 /**
353 * Adjust the given dexopt flags that will be passed to the installer.
354 */
355 protected int adjustDexoptFlags(int dexoptFlags) {
356 return dexoptFlags;
357 }
358
Narayan Kamath88eea9e2016-05-02 14:44:31 +0100359 /**
360 * Dumps the dexopt state of the given package {@code pkg} to the given {@code PrintWriter}.
361 */
362 void dumpDexoptState(IndentingPrintWriter pw, PackageParser.Package pkg) {
363 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
364 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
365
366 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
367
368 for (String instructionSet : dexCodeInstructionSets) {
369 pw.println("Instruction Set: " + instructionSet);
370 pw.increaseIndent();
371 for (String path : paths) {
372 String status = null;
373 try {
374 status = DexFile.getDexFileStatus(path, instructionSet);
375 } catch (IOException ioe) {
376 status = "[Exception]: " + ioe.getMessage();
377 }
378 pw.println("path: " + path);
379 pw.println("status: " + status);
380 }
381 pw.decreaseIndent();
382 }
383 }
384
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800385 /**
386 * Returns the compiler filter that should be used to optimize the package code.
387 * The target filter will be updated if the package code is used by other apps
388 * or if it has the safe mode flag set.
389 */
Calin Juravlec22c30e2017-01-16 19:18:48 -0800390 private String getRealCompilerFilter(ApplicationInfo info, String targetCompilerFilter,
391 boolean isUsedByOtherApps) {
392 int flags = info.flags;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800393 boolean vmSafeMode = (flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
Mathieu Chartier41e4a372016-09-02 16:36:42 -0700394 if (vmSafeMode) {
Nicolas Geoffrayd093b202017-05-03 13:11:58 +0100395 return getSafeModeCompilerFilter(targetCompilerFilter);
Mathieu Chartier41e4a372016-09-02 16:36:42 -0700396 }
397
Calin Juravlec22c30e2017-01-16 19:18:48 -0800398 if (isProfileGuidedCompilerFilter(targetCompilerFilter) && isUsedByOtherApps) {
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800399 // If the dex files is used by other apps, we cannot use profile-guided compilation.
400 return getNonProfileGuidedCompilerFilter(targetCompilerFilter);
Andreas Gampebdd30d82016-03-20 11:32:11 -0700401 }
402
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800403 return targetCompilerFilter;
Fyodor Kupolov74876572015-02-23 17:14:45 -0800404 }
405
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800406 /**
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800407 * Computes the dex flags that needs to be pass to installd for the given package and compiler
408 * filter.
409 */
Nicolas Geoffray3b4359a2017-05-25 13:53:22 +0100410 private int getDexFlags(PackageParser.Package pkg, String compilerFilter,
411 boolean bootComplete) {
412 return getDexFlags(pkg.applicationInfo, compilerFilter, bootComplete);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800413 }
414
Nicolas Geoffray3b4359a2017-05-25 13:53:22 +0100415 private int getDexFlags(ApplicationInfo info, String compilerFilter, boolean bootComplete) {
Calin Juravlec22c30e2017-01-16 19:18:48 -0800416 int flags = info.flags;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800417 boolean debuggable = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
418 // Profile guide compiled oat files should not be public.
419 boolean isProfileGuidedFilter = isProfileGuidedCompilerFilter(compilerFilter);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800420 boolean isPublic = !info.isForwardLocked() && !isProfileGuidedFilter;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800421 int profileFlag = isProfileGuidedFilter ? DEXOPT_PROFILE_GUIDED : 0;
422 int dexFlags =
423 (isPublic ? DEXOPT_PUBLIC : 0)
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800424 | (debuggable ? DEXOPT_DEBUGGABLE : 0)
425 | profileFlag
Nicolas Geoffray3b4359a2017-05-25 13:53:22 +0100426 | (bootComplete ? DEXOPT_BOOTCOMPLETE : 0);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800427 return adjustDexoptFlags(dexFlags);
428 }
429
430 /**
431 * Assesses if there's a need to perform dexopt on {@code path} for the given
432 * configuration (isa, compiler filter, profile).
433 */
434 private int getDexoptNeeded(String path, String isa, String compilerFilter,
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700435 boolean newProfile, boolean downgrade) {
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800436 int dexoptNeeded;
437 try {
Shubham Ajmera246dccf2017-05-24 17:46:36 -0700438 dexoptNeeded = DexFile.getDexOptNeeded(path, isa, compilerFilter, newProfile,
439 downgrade);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800440 } catch (IOException ioe) {
441 Slog.w(TAG, "IOException reading apk: " + path, ioe);
442 return DEX_OPT_FAILED;
443 }
444 return adjustDexoptNeeded(dexoptNeeded);
445 }
446
447 /**
448 * Computes the shared libraries path that should be passed to dexopt.
449 */
450 private String getSharedLibrariesPath(String[] sharedLibraries) {
451 if (sharedLibraries == null || sharedLibraries.length == 0) {
452 return null;
453 }
454 StringBuilder sb = new StringBuilder();
455 for (String lib : sharedLibraries) {
456 if (sb.length() != 0) {
457 sb.append(":");
458 }
459 sb.append(lib);
460 }
461 return sb.toString();
462 }
463
464 /**
Jeff Hao5def5e52017-04-19 14:42:16 -0700465 * Walks dependency tree and gathers the dependencies for each split in a split apk.
466 * The split paths are stored as relative paths, separated by colons.
467 */
468 private String[] getSplitDependencies(PackageParser.Package pkg) {
469 // Convert all the code paths to relative paths.
470 String baseCodePath = new File(pkg.baseCodePath).getParent();
471 List<String> paths = pkg.getAllCodePaths();
472 String[] splitDependencies = new String[paths.size()];
473 for (int i = 0; i < paths.size(); i++) {
474 File pathFile = new File(paths.get(i));
475 String fileName = pathFile.getName();
476 paths.set(i, fileName);
477
478 // Sanity check that the base paths of the splits are all the same.
479 String basePath = pathFile.getParent();
480 if (!basePath.equals(baseCodePath)) {
481 Slog.wtf(TAG, "Split paths have different base paths: " + basePath + " and " +
482 baseCodePath);
483 }
484 }
485
486 // If there are no other dependencies, fill in the implicit dependency on the base apk.
487 SparseArray<int[]> dependencies = pkg.applicationInfo.splitDependencies;
488 if (dependencies == null) {
489 for (int i = 1; i < paths.size(); i++) {
490 splitDependencies[i] = paths.get(0);
491 }
492 return splitDependencies;
493 }
494
495 // Fill in the dependencies, skipping the base apk which has no dependencies.
496 for (int i = 1; i < dependencies.size(); i++) {
497 getParentDependencies(dependencies.keyAt(i), paths, dependencies, splitDependencies);
498 }
499
500 return splitDependencies;
501 }
502
503 /**
504 * Recursive method to generate dependencies for a particular split.
505 * The index is a key from the package's splitDependencies.
506 */
507 private String getParentDependencies(int index, List<String> paths,
508 SparseArray<int[]> dependencies, String[] splitDependencies) {
509 // The base apk is always first, and has no dependencies.
510 if (index == 0) {
511 return null;
512 }
513 // Return the result if we've computed the dependencies for this index already.
514 if (splitDependencies[index] != null) {
515 return splitDependencies[index];
516 }
517 // Get the dependencies for the parent of this index and append its path to it.
518 int parent = dependencies.get(index)[0];
519 String parentDependencies =
520 getParentDependencies(parent, paths, dependencies, splitDependencies);
521 String path = parentDependencies == null ? paths.get(parent) :
522 parentDependencies + ":" + paths.get(parent);
523 splitDependencies[index] = path;
524 return path;
525 }
526
527 /**
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800528 * Checks if there is an update on the profile information of the {@code pkg}.
529 * If the compiler filter is not profile guided the method returns false.
530 *
531 * Note that this is a "destructive" operation with side effects. Under the hood the
532 * current profile and the reference profile will be merged and subsequent calls
533 * may return a different result.
534 */
535 private boolean isProfileUpdated(PackageParser.Package pkg, int uid, String compilerFilter) {
536 // Check if we are allowed to merge and if the compiler filter is profile guided.
537 if (!isProfileGuidedCompilerFilter(compilerFilter)) {
538 return false;
539 }
540 // Merge profiles. It returns whether or not there was an updated in the profile info.
541 try {
542 return mInstaller.mergeProfiles(uid, pkg.packageName);
543 } catch (InstallerException e) {
544 Slog.w(TAG, "Failed to merge profiles", e);
545 }
546 return false;
547 }
548
549 /**
550 * Creates oat dir for the specified package if needed and supported.
551 * In certain cases oat directory
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800552 * <strong>cannot</strong> be created:
553 * <ul>
554 * <li>{@code pkg} is a system app, which is not updated.</li>
555 * <li>Package location is not a directory, i.e. monolithic install.</li>
556 * </ul>
557 *
Richard Uhler7b08b352015-03-25 16:25:57 -0700558 * @return Absolute path to the oat directory or null, if oat directory
559 * cannot be created.
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800560 */
561 @Nullable
Todd Kennedy27c24fb2015-09-17 16:49:25 -0700562 private String createOatDirIfSupported(PackageParser.Package pkg, String dexInstructionSet) {
Fyodor Kupolovebcac162015-09-09 15:56:45 -0700563 if (!pkg.canHaveOatDir()) {
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800564 return null;
565 }
566 File codePath = new File(pkg.codePath);
567 if (codePath.isDirectory()) {
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800568 // TODO(calin): why do we create this only if the codePath is a directory? (i.e for
569 // cluster packages). It seems that the logic for the folder creation is
570 // split between installd and here.
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800571 File oatDir = getOatDir(codePath);
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -0700572 try {
Andreas Gampea8908752015-11-10 08:58:14 -0800573 mInstaller.createOatDir(oatDir.getAbsolutePath(), dexInstructionSet);
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -0700574 } catch (InstallerException e) {
575 Slog.w(TAG, "Failed to create oat dir", e);
576 return null;
577 }
Richard Uhler7b08b352015-03-25 16:25:57 -0700578 return oatDir.getAbsolutePath();
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800579 }
580 return null;
581 }
582
583 static File getOatDir(File codePath) {
584 return new File(codePath, OAT_DIR_NAME);
585 }
586
Fyodor Kupolova627c092015-05-05 18:44:39 -0700587 void systemReady() {
588 mSystemReady = true;
589 }
Andreas Gampea8908752015-11-10 08:58:14 -0800590
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800591 private String printDexoptFlags(int flags) {
592 ArrayList<String> flagsList = new ArrayList<>();
593
594 if ((flags & DEXOPT_BOOTCOMPLETE) == DEXOPT_BOOTCOMPLETE) {
595 flagsList.add("boot_complete");
596 }
597 if ((flags & DEXOPT_DEBUGGABLE) == DEXOPT_DEBUGGABLE) {
598 flagsList.add("debuggable");
599 }
600 if ((flags & DEXOPT_PROFILE_GUIDED) == DEXOPT_PROFILE_GUIDED) {
601 flagsList.add("profile_guided");
602 }
603 if ((flags & DEXOPT_PUBLIC) == DEXOPT_PUBLIC) {
604 flagsList.add("public");
605 }
Calin Juravlec22c30e2017-01-16 19:18:48 -0800606 if ((flags & DEXOPT_SECONDARY_DEX) == DEXOPT_SECONDARY_DEX) {
607 flagsList.add("secondary");
608 }
609 if ((flags & DEXOPT_FORCE) == DEXOPT_FORCE) {
610 flagsList.add("force");
611 }
612 if ((flags & DEXOPT_STORAGE_CE) == DEXOPT_STORAGE_CE) {
613 flagsList.add("storage_ce");
614 }
615 if ((flags & DEXOPT_STORAGE_DE) == DEXOPT_STORAGE_DE) {
616 flagsList.add("storage_de");
617 }
618
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800619 return String.join(",", flagsList);
620 }
621
Andreas Gampea8908752015-11-10 08:58:14 -0800622 /**
623 * A specialized PackageDexOptimizer that overrides already-installed checks, forcing a
624 * dexopt path.
625 */
626 public static class ForcedUpdatePackageDexOptimizer extends PackageDexOptimizer {
627
628 public ForcedUpdatePackageDexOptimizer(Installer installer, Object installLock,
629 Context context, String wakeLockTag) {
630 super(installer, installLock, context, wakeLockTag);
631 }
632
633 public ForcedUpdatePackageDexOptimizer(PackageDexOptimizer from) {
634 super(from);
635 }
636
637 @Override
Andreas Gampea8908752015-11-10 08:58:14 -0800638 protected int adjustDexoptNeeded(int dexoptNeeded) {
Nicolas Geoffray96d12a92017-05-03 11:51:53 +0100639 if (dexoptNeeded == DexFile.NO_DEXOPT_NEEDED) {
640 // Ensure compilation by pretending a compiler filter change on the
641 // apk/odex location (the reason for the '-'. A positive value means
642 // the 'oat' location).
643 return -DexFile.DEX2OAT_FOR_FILTER;
644 }
645 return dexoptNeeded;
Andreas Gampea8908752015-11-10 08:58:14 -0800646 }
Calin Juravlec22c30e2017-01-16 19:18:48 -0800647
648 @Override
649 protected int adjustDexoptFlags(int flags) {
650 // Add DEXOPT_FORCE flag to signal installd that it should force compilation
651 // and discard dexoptanalyzer result.
652 return flags | DEXOPT_FORCE;
653 }
Andreas Gampea8908752015-11-10 08:58:14 -0800654 }
Fyodor Kupolov74876572015-02-23 17:14:45 -0800655}