blob: acdcc72c7f71677aaf64e1a52ff6498e724fd205 [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 Juravled479b522016-02-24 16:22:03 +000023import android.os.Environment;
Fyodor Kupolova627c092015-05-05 18:44:39 -070024import android.os.PowerManager;
Fyodor Kupolov74876572015-02-23 17:14:45 -080025import android.os.UserHandle;
Fyodor Kupolova627c092015-05-05 18:44:39 -070026import android.os.WorkSource;
Fyodor Kupolov74876572015-02-23 17:14:45 -080027import android.util.Log;
28import android.util.Slog;
29
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -070030import com.android.internal.os.InstallerConnection.InstallerException;
Narayan Kamath88eea9e2016-05-02 14:44:31 +010031import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -070032
Fyodor Kupolovb94c1652015-03-03 12:25:30 -080033import java.io.File;
Fyodor Kupolov74876572015-02-23 17:14:45 -080034import java.io.IOException;
Fyodor Kupolov74876572015-02-23 17:14:45 -080035import java.util.List;
36
37import dalvik.system.DexFile;
Fyodor Kupolov74876572015-02-23 17:14:45 -080038
Todd Kennedyfa54ab72015-09-25 07:46:12 -070039import static com.android.server.pm.Installer.DEXOPT_BOOTCOMPLETE;
40import static com.android.server.pm.Installer.DEXOPT_DEBUGGABLE;
Andreas Gampebdd30d82016-03-20 11:32:11 -070041import static com.android.server.pm.Installer.DEXOPT_PROFILE_GUIDED;
Todd Kennedyfa54ab72015-09-25 07:46:12 -070042import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
43import static com.android.server.pm.Installer.DEXOPT_SAFEMODE;
Fyodor Kupolov74876572015-02-23 17:14:45 -080044import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
45import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
Andreas Gampe47c170a2016-03-30 17:21:19 -070046import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
Fyodor Kupolov74876572015-02-23 17:14:45 -080047
48/**
49 * Helper class for running dexopt command on packages.
50 */
Andreas Gampea8908752015-11-10 08:58:14 -080051class PackageDexOptimizer {
Fyodor Kupolovb94c1652015-03-03 12:25:30 -080052 private static final String TAG = "PackageManager.DexOptimizer";
53 static final String OAT_DIR_NAME = "oat";
54 // TODO b/19550105 Remove error codes and use exceptions
Fyodor Kupolov74876572015-02-23 17:14:45 -080055 static final int DEX_OPT_SKIPPED = 0;
56 static final int DEX_OPT_PERFORMED = 1;
Fyodor Kupolov74876572015-02-23 17:14:45 -080057 static final int DEX_OPT_FAILED = -1;
58
Andreas Gampea8908752015-11-10 08:58:14 -080059 private final Installer mInstaller;
60 private final Object mInstallLock;
Fyodor Kupolov74876572015-02-23 17:14:45 -080061
Fyodor Kupolova627c092015-05-05 18:44:39 -070062 private final PowerManager.WakeLock mDexoptWakeLock;
63 private volatile boolean mSystemReady;
64
Andreas Gampea8908752015-11-10 08:58:14 -080065 PackageDexOptimizer(Installer installer, Object installLock, Context context,
66 String wakeLockTag) {
67 this.mInstaller = installer;
68 this.mInstallLock = installLock;
69
70 PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
71 mDexoptWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakeLockTag);
72 }
73
74 protected PackageDexOptimizer(PackageDexOptimizer from) {
75 this.mInstaller = from.mInstaller;
76 this.mInstallLock = from.mInstallLock;
77 this.mDexoptWakeLock = from.mDexoptWakeLock;
78 this.mSystemReady = from.mSystemReady;
Fyodor Kupolov74876572015-02-23 17:14:45 -080079 }
80
Calin Juravledb4a79a2015-12-23 18:55:08 +020081 static boolean canOptimizePackage(PackageParser.Package pkg) {
Calin Juravle6dfd83d2016-01-29 18:23:57 +000082 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
Calin Juravledb4a79a2015-12-23 18:55:08 +020083 }
84
Fyodor Kupolov74876572015-02-23 17:14:45 -080085 /**
86 * Performs dexopt on all code paths and libraries of the specified package for specified
87 * instruction sets.
88 *
Andreas Gampea8908752015-11-10 08:58:14 -080089 * <p>Calls to {@link com.android.server.pm.Installer#dexopt} on {@link #mInstaller} are
90 * synchronized on {@link #mInstallLock}.
Fyodor Kupolov74876572015-02-23 17:14:45 -080091 */
Jeff Haoc7b94822016-03-16 15:56:07 -070092 int performDexOpt(PackageParser.Package pkg, String[] sharedLibraries,
Andreas Gampe7e619a92016-07-12 22:42:41 -070093 String[] instructionSets, boolean checkProfiles, String targetCompilationFilter,
94 CompilerStats.PackageStats packageStats) {
Andreas Gampea8908752015-11-10 08:58:14 -080095 synchronized (mInstallLock) {
Fyodor Kupolova627c092015-05-05 18:44:39 -070096 final boolean useLock = mSystemReady;
97 if (useLock) {
98 mDexoptWakeLock.setWorkSource(new WorkSource(pkg.applicationInfo.uid));
99 mDexoptWakeLock.acquire();
100 }
101 try {
Jeff Haoc7b94822016-03-16 15:56:07 -0700102 return performDexOptLI(pkg, sharedLibraries, instructionSets, checkProfiles,
Andreas Gampe7e619a92016-07-12 22:42:41 -0700103 targetCompilationFilter, packageStats);
Fyodor Kupolova627c092015-05-05 18:44:39 -0700104 } finally {
105 if (useLock) {
106 mDexoptWakeLock.release();
107 }
108 }
Fyodor Kupolov74876572015-02-23 17:14:45 -0800109 }
110 }
111
Andreas Gampea8908752015-11-10 08:58:14 -0800112 /**
Andreas Gampea8908752015-11-10 08:58:14 -0800113 * Adjust the given dexopt-needed value. Can be overridden to influence the decision to
114 * optimize or not (and in what way).
115 */
116 protected int adjustDexoptNeeded(int dexoptNeeded) {
117 return dexoptNeeded;
118 }
119
120 /**
121 * Adjust the given dexopt flags that will be passed to the installer.
122 */
123 protected int adjustDexoptFlags(int dexoptFlags) {
124 return dexoptFlags;
125 }
126
Narayan Kamath88eea9e2016-05-02 14:44:31 +0100127 /**
128 * Dumps the dexopt state of the given package {@code pkg} to the given {@code PrintWriter}.
129 */
130 void dumpDexoptState(IndentingPrintWriter pw, PackageParser.Package pkg) {
131 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
132 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
133
134 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
135
136 for (String instructionSet : dexCodeInstructionSets) {
137 pw.println("Instruction Set: " + instructionSet);
138 pw.increaseIndent();
139 for (String path : paths) {
140 String status = null;
141 try {
142 status = DexFile.getDexFileStatus(path, instructionSet);
143 } catch (IOException ioe) {
144 status = "[Exception]: " + ioe.getMessage();
145 }
146 pw.println("path: " + path);
147 pw.println("status: " + status);
148 }
149 pw.decreaseIndent();
150 }
151 }
152
Jeff Haoc7b94822016-03-16 15:56:07 -0700153 private int performDexOptLI(PackageParser.Package pkg, String[] sharedLibraries,
Andreas Gampe7e619a92016-07-12 22:42:41 -0700154 String[] targetInstructionSets, boolean checkProfiles, String targetCompilerFilter,
155 CompilerStats.PackageStats packageStats) {
Fyodor Kupolov74876572015-02-23 17:14:45 -0800156 final String[] instructionSets = targetInstructionSets != null ?
157 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
158
Calin Juravledb4a79a2015-12-23 18:55:08 +0200159 if (!canOptimizePackage(pkg)) {
Fyodor Kupolov74876572015-02-23 17:14:45 -0800160 return DEX_OPT_SKIPPED;
161 }
162
Andreas Gampebdd30d82016-03-20 11:32:11 -0700163 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
164 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
165
166 boolean isProfileGuidedFilter = DexFile.isProfileGuidedCompilerFilter(targetCompilerFilter);
167 // If any part of the app is used by other apps, we cannot use profile-guided
168 // compilation.
David Brazdil90e26992016-04-18 14:08:52 +0100169 if (isProfileGuidedFilter && isUsedByOtherApps(pkg)) {
170 checkProfiles = false;
Andreas Gampebdd30d82016-03-20 11:32:11 -0700171
David Brazdil90e26992016-04-18 14:08:52 +0100172 targetCompilerFilter = getNonProfileGuidedCompilerFilter(targetCompilerFilter);
173 if (DexFile.isProfileGuidedCompilerFilter(targetCompilerFilter)) {
174 throw new IllegalStateException(targetCompilerFilter);
Andreas Gampebdd30d82016-03-20 11:32:11 -0700175 }
David Brazdil90e26992016-04-18 14:08:52 +0100176 isProfileGuidedFilter = false;
Andreas Gampebdd30d82016-03-20 11:32:11 -0700177 }
178
Mathieu Chartier41e4a372016-09-02 16:36:42 -0700179 // Disable profile guided compilation for vmSafeMode.
180 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE)
181 != 0;
182 final boolean debuggable = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE)
183 != 0;
184 if (vmSafeMode) {
185 targetCompilerFilter = getNonProfileGuidedCompilerFilter(targetCompilerFilter);
186 isProfileGuidedFilter = false;
187 }
188
Andreas Gampebdd30d82016-03-20 11:32:11 -0700189 // If we're asked to take profile updates into account, check now.
190 boolean newProfile = false;
191 if (checkProfiles && isProfileGuidedFilter) {
192 // Merge profiles, see if we need to do anything.
193 try {
194 newProfile = mInstaller.mergeProfiles(sharedGid, pkg.packageName);
195 } catch (InstallerException e) {
196 Slog.w(TAG, "Failed to merge profiles", e);
197 }
198 }
199
Fyodor Kupolov74876572015-02-23 17:14:45 -0800200 boolean performedDexOpt = false;
David Brazdil6a3b2d22016-04-08 16:09:06 +0100201 boolean successfulDexOpt = true;
202
Fyodor Kupolov74876572015-02-23 17:14:45 -0800203 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
204 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
Fyodor Kupolov74876572015-02-23 17:14:45 -0800205 for (String path : paths) {
Calin Juravledb4a79a2015-12-23 18:55:08 +0200206 int dexoptNeeded;
Andreas Gampea8908752015-11-10 08:58:14 -0800207 try {
Calin Juravle693f9972016-02-25 15:26:20 +0000208 dexoptNeeded = DexFile.getDexOptNeeded(path,
Andreas Gampebdd30d82016-03-20 11:32:11 -0700209 dexCodeInstructionSet, targetCompilerFilter, newProfile);
Andreas Gampea8908752015-11-10 08:58:14 -0800210 } catch (IOException ioe) {
211 Slog.w(TAG, "IOException reading apk: " + path, ioe);
212 return DEX_OPT_FAILED;
Narayan Kamath01dcb762015-05-07 17:48:42 +0100213 }
Andreas Gampea8908752015-11-10 08:58:14 -0800214 dexoptNeeded = adjustDexoptNeeded(dexoptNeeded);
Andreas Gampe47c170a2016-03-30 17:21:19 -0700215 if (PackageManagerService.DEBUG_DEXOPT) {
216 Log.i(TAG, "DexoptNeeded for " + path + "@" + targetCompilerFilter + " is " +
217 dexoptNeeded);
218 }
Richard Uhler7b08b352015-03-25 16:25:57 -0700219
Calin Juravledb4a79a2015-12-23 18:55:08 +0200220 final String dexoptType;
221 String oatDir = null;
Nicolas Geoffray79c9e062016-11-25 09:50:29 +0000222 boolean isOdexLocation = (dexoptNeeded < 0);
223 switch (Math.abs(dexoptNeeded)) {
Calin Juravle693f9972016-02-25 15:26:20 +0000224 case DexFile.NO_DEXOPT_NEEDED:
225 continue;
Nicolas Geoffray79c9e062016-11-25 09:50:29 +0000226 case DexFile.DEX2OAT_FROM_SCRATCH:
227 case DexFile.DEX2OAT_FOR_BOOT_IMAGE:
228 case DexFile.DEX2OAT_FOR_FILTER:
229 case DexFile.DEX2OAT_FOR_RELOCATION:
Calin Juravle693f9972016-02-25 15:26:20 +0000230 dexoptType = "dex2oat";
231 oatDir = createOatDirIfSupported(pkg, dexCodeInstructionSet);
232 break;
Nicolas Geoffray79c9e062016-11-25 09:50:29 +0000233 case DexFile.PATCHOAT_FOR_RELOCATION:
Calin Juravle693f9972016-02-25 15:26:20 +0000234 dexoptType = "patchoat";
235 break;
Calin Juravle693f9972016-02-25 15:26:20 +0000236 default:
237 throw new IllegalStateException("Invalid dexopt:" + dexoptNeeded);
Calin Juravledb4a79a2015-12-23 18:55:08 +0200238 }
Narayan Kamath01dcb762015-05-07 17:48:42 +0100239
Jeff Haoc7b94822016-03-16 15:56:07 -0700240 String sharedLibrariesPath = null;
241 if (sharedLibraries != null && sharedLibraries.length != 0) {
242 StringBuilder sb = new StringBuilder();
243 for (String lib : sharedLibraries) {
244 if (sb.length() != 0) {
245 sb.append(":");
246 }
247 sb.append(lib);
248 }
249 sharedLibrariesPath = sb.toString();
250 }
Calin Juravledb4a79a2015-12-23 18:55:08 +0200251 Log.i(TAG, "Running dexopt (" + dexoptType + ") on: " + path + " pkg="
252 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
253 + " vmSafeMode=" + vmSafeMode + " debuggable=" + debuggable
Jeff Haoc7b94822016-03-16 15:56:07 -0700254 + " target-filter=" + targetCompilerFilter + " oatDir = " + oatDir
255 + " sharedLibraries=" + sharedLibrariesPath);
Calin Juravled479b522016-02-24 16:22:03 +0000256 // Profile guide compiled oat files should not be public.
Andreas Gampebdd30d82016-03-20 11:32:11 -0700257 final boolean isPublic = !pkg.isForwardLocked() && !isProfileGuidedFilter;
258 final int profileFlag = isProfileGuidedFilter ? DEXOPT_PROFILE_GUIDED : 0;
Andreas Gampea8908752015-11-10 08:58:14 -0800259 final int dexFlags = adjustDexoptFlags(
Calin Juravled479b522016-02-24 16:22:03 +0000260 ( isPublic ? DEXOPT_PUBLIC : 0)
Calin Juravledb4a79a2015-12-23 18:55:08 +0200261 | (vmSafeMode ? DEXOPT_SAFEMODE : 0)
262 | (debuggable ? DEXOPT_DEBUGGABLE : 0)
Andreas Gampebdd30d82016-03-20 11:32:11 -0700263 | profileFlag
Andreas Gampea8908752015-11-10 08:58:14 -0800264 | DEXOPT_BOOTCOMPLETE);
265
Calin Juravledb4a79a2015-12-23 18:55:08 +0200266 try {
Andreas Gampe7e619a92016-07-12 22:42:41 -0700267 long startTime = System.currentTimeMillis();
268
Andreas Gampea8908752015-11-10 08:58:14 -0800269 mInstaller.dexopt(path, sharedGid, pkg.packageName, dexCodeInstructionSet,
Jeff Haoc7b94822016-03-16 15:56:07 -0700270 dexoptNeeded, oatDir, dexFlags, targetCompilerFilter, pkg.volumeUuid,
271 sharedLibrariesPath);
Calin Juravledb4a79a2015-12-23 18:55:08 +0200272 performedDexOpt = true;
Andreas Gampe7e619a92016-07-12 22:42:41 -0700273
274 if (packageStats != null) {
275 long endTime = System.currentTimeMillis();
276 packageStats.setCompileTime(path, (int)(endTime - startTime));
277 }
Calin Juravledb4a79a2015-12-23 18:55:08 +0200278 } catch (InstallerException e) {
279 Slog.w(TAG, "Failed to dexopt", e);
David Brazdil6a3b2d22016-04-08 16:09:06 +0100280 successfulDexOpt = false;
Fyodor Kupolov74876572015-02-23 17:14:45 -0800281 }
282 }
Fyodor Kupolov74876572015-02-23 17:14:45 -0800283 }
284
David Brazdil6a3b2d22016-04-08 16:09:06 +0100285 if (successfulDexOpt) {
286 // If we've gotten here, we're sure that no error occurred. We've either
287 // dex-opted one or more paths or instruction sets or we've skipped
288 // all of them because they are up to date. In both cases this package
289 // doesn't need dexopt any longer.
290 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
291 } else {
292 return DEX_OPT_FAILED;
293 }
Fyodor Kupolov74876572015-02-23 17:14:45 -0800294 }
295
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800296 /**
297 * Creates oat dir for the specified package. In certain cases oat directory
298 * <strong>cannot</strong> be created:
299 * <ul>
300 * <li>{@code pkg} is a system app, which is not updated.</li>
301 * <li>Package location is not a directory, i.e. monolithic install.</li>
302 * </ul>
303 *
Richard Uhler7b08b352015-03-25 16:25:57 -0700304 * @return Absolute path to the oat directory or null, if oat directory
305 * cannot be created.
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800306 */
307 @Nullable
Todd Kennedy27c24fb2015-09-17 16:49:25 -0700308 private String createOatDirIfSupported(PackageParser.Package pkg, String dexInstructionSet) {
Fyodor Kupolovebcac162015-09-09 15:56:45 -0700309 if (!pkg.canHaveOatDir()) {
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800310 return null;
311 }
312 File codePath = new File(pkg.codePath);
313 if (codePath.isDirectory()) {
314 File oatDir = getOatDir(codePath);
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -0700315 try {
Andreas Gampea8908752015-11-10 08:58:14 -0800316 mInstaller.createOatDir(oatDir.getAbsolutePath(), dexInstructionSet);
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -0700317 } catch (InstallerException e) {
318 Slog.w(TAG, "Failed to create oat dir", e);
319 return null;
320 }
Richard Uhler7b08b352015-03-25 16:25:57 -0700321 return oatDir.getAbsolutePath();
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800322 }
323 return null;
324 }
325
326 static File getOatDir(File codePath) {
327 return new File(codePath, OAT_DIR_NAME);
328 }
329
Fyodor Kupolova627c092015-05-05 18:44:39 -0700330 void systemReady() {
331 mSystemReady = true;
332 }
Andreas Gampea8908752015-11-10 08:58:14 -0800333
David Brazdil90e26992016-04-18 14:08:52 +0100334 /**
335 * Returns true if the profiling data collected for the given app indicate
336 * that the apps's APK has been loaded by another app.
337 * Note that this returns false for all forward-locked apps and apps without
338 * any collected profiling data.
339 */
340 public static boolean isUsedByOtherApps(PackageParser.Package pkg) {
341 if (pkg.isForwardLocked()) {
342 // Skip the check for forward locked packages since they don't share their code.
343 return false;
Calin Juravled479b522016-02-24 16:22:03 +0000344 }
David Brazdil90e26992016-04-18 14:08:52 +0100345
346 for (String apkPath : pkg.getAllCodePathsExcludingResourceOnly()) {
347 try {
Narayan Kamath6d99f792016-05-16 17:34:48 +0100348 apkPath = PackageManagerServiceUtils.realpath(new File(apkPath));
David Brazdil90e26992016-04-18 14:08:52 +0100349 } catch (IOException e) {
350 // Log an error but continue without it.
351 Slog.w(TAG, "Failed to get canonical path", e);
Narayan Kamath6d99f792016-05-16 17:34:48 +0100352 continue;
David Brazdil90e26992016-04-18 14:08:52 +0100353 }
354 String useMarker = apkPath.replace('/', '@');
355 final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
356 for (int i = 0; i < currentUserIds.length; i++) {
357 File profileDir =
358 Environment.getDataProfilesDeForeignDexDirectory(currentUserIds[i]);
359 File foreignUseMark = new File(profileDir, useMarker);
360 if (foreignUseMark.exists()) {
361 return true;
362 }
Calin Juravled479b522016-02-24 16:22:03 +0000363 }
364 }
365 return false;
366 }
367
Andreas Gampea8908752015-11-10 08:58:14 -0800368 /**
369 * A specialized PackageDexOptimizer that overrides already-installed checks, forcing a
370 * dexopt path.
371 */
372 public static class ForcedUpdatePackageDexOptimizer extends PackageDexOptimizer {
373
374 public ForcedUpdatePackageDexOptimizer(Installer installer, Object installLock,
375 Context context, String wakeLockTag) {
376 super(installer, installLock, context, wakeLockTag);
377 }
378
379 public ForcedUpdatePackageDexOptimizer(PackageDexOptimizer from) {
380 super(from);
381 }
382
383 @Override
Andreas Gampea8908752015-11-10 08:58:14 -0800384 protected int adjustDexoptNeeded(int dexoptNeeded) {
385 // Ensure compilation, no matter the current state.
386 // TODO: The return value is wrong when patchoat is needed.
Nicolas Geoffray79c9e062016-11-25 09:50:29 +0000387 return DexFile.DEX2OAT_FROM_SCRATCH;
Andreas Gampea8908752015-11-10 08:58:14 -0800388 }
389 }
Fyodor Kupolov74876572015-02-23 17:14:45 -0800390}