blob: 0d9b08d3c61701bc84819015d2f12c47ca24fd73 [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;
50import static com.android.server.pm.Installer.DEXOPT_SAFEMODE;
Calin Juravlec22c30e2017-01-16 19:18:48 -080051import static com.android.server.pm.Installer.DEXOPT_SECONDARY_DEX;
52import static com.android.server.pm.Installer.DEXOPT_FORCE;
53import static com.android.server.pm.Installer.DEXOPT_STORAGE_CE;
54import static com.android.server.pm.Installer.DEXOPT_STORAGE_DE;
Fyodor Kupolov74876572015-02-23 17:14:45 -080055import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
56import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -080057
Fyodor Kupolov28f28552017-05-02 12:11:02 -070058import static com.android.server.pm.PackageManagerService.WATCHDOG_TIMEOUT;
Andreas Gampe47c170a2016-03-30 17:21:19 -070059import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
Nicolas Geoffrayb0818e82017-05-05 10:23:19 +010060
Nicolas Geoffrayd093b202017-05-03 13:11:58 +010061import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
62import static dalvik.system.DexFile.getSafeModeCompilerFilter;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -080063import static dalvik.system.DexFile.isProfileGuidedCompilerFilter;
Fyodor Kupolov74876572015-02-23 17:14:45 -080064
65/**
66 * Helper class for running dexopt command on packages.
67 */
Calin Juravlec22c30e2017-01-16 19:18:48 -080068public class PackageDexOptimizer {
Fyodor Kupolovb94c1652015-03-03 12:25:30 -080069 private static final String TAG = "PackageManager.DexOptimizer";
70 static final String OAT_DIR_NAME = "oat";
71 // TODO b/19550105 Remove error codes and use exceptions
Calin Juravlec22c30e2017-01-16 19:18:48 -080072 public static final int DEX_OPT_SKIPPED = 0;
73 public static final int DEX_OPT_PERFORMED = 1;
74 public static final int DEX_OPT_FAILED = -1;
Fyodor Kupolov28f28552017-05-02 12:11:02 -070075 // One minute over PM WATCHDOG_TIMEOUT
76 private static final long WAKELOCK_TIMEOUT_MS = WATCHDOG_TIMEOUT + 1000 * 60;
Fyodor Kupolov74876572015-02-23 17:14:45 -080077
Calin Juravleaae35762017-02-14 17:53:13 -080078 /** Special library name that skips shared libraries check during compilation. */
79 public static final String SKIP_SHARED_LIBRARY_CHECK = "&";
80
Fyodor Kupolov28f28552017-05-02 12:11:02 -070081 @GuardedBy("mInstallLock")
Andreas Gampea8908752015-11-10 08:58:14 -080082 private final Installer mInstaller;
83 private final Object mInstallLock;
Fyodor Kupolov74876572015-02-23 17:14:45 -080084
Fyodor Kupolov28f28552017-05-02 12:11:02 -070085 @GuardedBy("mInstallLock")
Fyodor Kupolova627c092015-05-05 18:44:39 -070086 private final PowerManager.WakeLock mDexoptWakeLock;
87 private volatile boolean mSystemReady;
88
Andreas Gampea8908752015-11-10 08:58:14 -080089 PackageDexOptimizer(Installer installer, Object installLock, Context context,
90 String wakeLockTag) {
91 this.mInstaller = installer;
92 this.mInstallLock = installLock;
93
94 PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
95 mDexoptWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakeLockTag);
96 }
97
98 protected PackageDexOptimizer(PackageDexOptimizer from) {
99 this.mInstaller = from.mInstaller;
100 this.mInstallLock = from.mInstallLock;
101 this.mDexoptWakeLock = from.mDexoptWakeLock;
102 this.mSystemReady = from.mSystemReady;
Fyodor Kupolov74876572015-02-23 17:14:45 -0800103 }
104
Calin Juravledb4a79a2015-12-23 18:55:08 +0200105 static boolean canOptimizePackage(PackageParser.Package pkg) {
Calin Juravle6dfd83d2016-01-29 18:23:57 +0000106 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
Calin Juravledb4a79a2015-12-23 18:55:08 +0200107 }
108
Fyodor Kupolov74876572015-02-23 17:14:45 -0800109 /**
110 * Performs dexopt on all code paths and libraries of the specified package for specified
111 * instruction sets.
112 *
Andreas Gampea8908752015-11-10 08:58:14 -0800113 * <p>Calls to {@link com.android.server.pm.Installer#dexopt} on {@link #mInstaller} are
114 * synchronized on {@link #mInstallLock}.
Fyodor Kupolov74876572015-02-23 17:14:45 -0800115 */
Jeff Haoc7b94822016-03-16 15:56:07 -0700116 int performDexOpt(PackageParser.Package pkg, String[] sharedLibraries,
Andreas Gampe7e619a92016-07-12 22:42:41 -0700117 String[] instructionSets, boolean checkProfiles, String targetCompilationFilter,
Calin Juravle07b6eab2017-03-01 19:55:35 -0800118 CompilerStats.PackageStats packageStats, boolean isUsedByOtherApps) {
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800119 if (!canOptimizePackage(pkg)) {
120 return DEX_OPT_SKIPPED;
121 }
Andreas Gampea8908752015-11-10 08:58:14 -0800122 synchronized (mInstallLock) {
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700123 final long acquireTime = acquireWakeLockLI(pkg.applicationInfo.uid);
Fyodor Kupolova627c092015-05-05 18:44:39 -0700124 try {
Jeff Haoc7b94822016-03-16 15:56:07 -0700125 return performDexOptLI(pkg, sharedLibraries, instructionSets, checkProfiles,
Calin Juravle07b6eab2017-03-01 19:55:35 -0800126 targetCompilationFilter, packageStats, isUsedByOtherApps);
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,
141 boolean isUsedByOtherApps) {
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.
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800155 final int dexoptFlags = getDexFlags(pkg, compilerFilter);
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,
Jeff Hao5def5e52017-04-19 14:42:16 -0700178 sharedLibrariesPathWithSplits, dexoptFlags, sharedGid, packageStats);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800179 // The end result is:
180 // - FAILED if any path failed,
181 // - PERFORMED if at least one path needed compilation,
182 // - SKIPPED when all paths are up to date
183 if ((result != DEX_OPT_FAILED) && (newResult != DEX_OPT_SKIPPED)) {
184 result = newResult;
185 }
186 }
187 }
188 return result;
189 }
190
191 /**
192 * Performs dexopt on the {@code path} belonging to the package {@code pkg}.
193 *
194 * @return
195 * DEX_OPT_FAILED if there was any exception during dexopt
196 * DEX_OPT_PERFORMED if dexopt was performed successfully on the given path.
197 * DEX_OPT_SKIPPED if the path does not need to be deopt-ed.
198 */
199 @GuardedBy("mInstallLock")
200 private int dexOptPath(PackageParser.Package pkg, String path, String isa,
201 String compilerFilter, boolean profileUpdated, String sharedLibrariesPath,
202 int dexoptFlags, int uid, CompilerStats.PackageStats packageStats) {
203 int dexoptNeeded = getDexoptNeeded(path, isa, compilerFilter, profileUpdated);
204 if (Math.abs(dexoptNeeded) == DexFile.NO_DEXOPT_NEEDED) {
205 return DEX_OPT_SKIPPED;
206 }
207
208 // TODO(calin): there's no need to try to create the oat dir over and over again,
209 // especially since it involve an extra installd call. We should create
210 // if (if supported) on the fly during the dexopt call.
211 String oatDir = createOatDirIfSupported(pkg, isa);
212
213 Log.i(TAG, "Running dexopt (dexoptNeeded=" + dexoptNeeded + ") on: " + path
214 + " pkg=" + pkg.applicationInfo.packageName + " isa=" + isa
215 + " dexoptFlags=" + printDexoptFlags(dexoptFlags)
216 + " target-filter=" + compilerFilter + " oatDir=" + oatDir
217 + " sharedLibraries=" + sharedLibrariesPath);
218
219 try {
220 long startTime = System.currentTimeMillis();
221
222 mInstaller.dexopt(path, uid, pkg.packageName, isa, dexoptNeeded, oatDir, dexoptFlags,
Calin Juravle811a75a2017-04-05 22:49:38 -0700223 compilerFilter, pkg.volumeUuid, sharedLibrariesPath, pkg.applicationInfo.seInfo);
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800224
225 if (packageStats != null) {
226 long endTime = System.currentTimeMillis();
227 packageStats.setCompileTime(path, (int)(endTime - startTime));
228 }
229 return DEX_OPT_PERFORMED;
230 } catch (InstallerException e) {
231 Slog.w(TAG, "Failed to dexopt", e);
232 return DEX_OPT_FAILED;
233 }
234 }
235
236 /**
Calin Juravlec22c30e2017-01-16 19:18:48 -0800237 * Performs dexopt on the secondary dex {@code path} belonging to the app {@code info}.
238 *
239 * @return
240 * DEX_OPT_FAILED if there was any exception during dexopt
241 * DEX_OPT_PERFORMED if dexopt was performed successfully on the given path.
242 * NOTE that DEX_OPT_PERFORMED for secondary dex files includes the case when the dex file
243 * didn't need an update. That's because at the moment we don't get more than success/failure
244 * from installd.
245 *
246 * TODO(calin): Consider adding return codes to installd dexopt invocation (rather than
247 * throwing exceptions). Or maybe make a separate call to installd to get DexOptNeeded, though
248 * that seems wasteful.
249 */
250 public int dexOptSecondaryDexPath(ApplicationInfo info, String path, Set<String> isas,
251 String compilerFilter, boolean isUsedByOtherApps) {
252 synchronized (mInstallLock) {
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700253 final long acquireTime = acquireWakeLockLI(info.uid);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800254 try {
255 return dexOptSecondaryDexPathLI(info, path, isas, compilerFilter,
256 isUsedByOtherApps);
257 } finally {
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700258 releaseWakeLockLI(acquireTime);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800259 }
260 }
261 }
262
263 @GuardedBy("mInstallLock")
Fyodor Kupolov28f28552017-05-02 12:11:02 -0700264 private long acquireWakeLockLI(final int uid) {
265 // During boot the system doesn't need to instantiate and obtain a wake lock.
266 // PowerManager might not be ready, but that doesn't mean that we can't proceed with
267 // dexopt.
268 if (!mSystemReady) {
269 return -1;
270 }
271 mDexoptWakeLock.setWorkSource(new WorkSource(uid));
272 mDexoptWakeLock.acquire(WAKELOCK_TIMEOUT_MS);
273 return SystemClock.elapsedRealtime();
274 }
275
276 @GuardedBy("mInstallLock")
277 private void releaseWakeLockLI(final long acquireTime) {
278 if (acquireTime < 0) {
279 return;
280 }
281 try {
282 if (mDexoptWakeLock.isHeld()) {
283 mDexoptWakeLock.release();
284 }
285 final long duration = SystemClock.elapsedRealtime() - acquireTime;
286 if (duration >= WAKELOCK_TIMEOUT_MS) {
287 Slog.wtf(TAG, "WakeLock " + mDexoptWakeLock.getTag()
288 + " time out. Operation took " + duration + " ms. Thread: "
289 + Thread.currentThread().getName());
290 }
291 } catch (Exception e) {
292 Slog.wtf(TAG, "Error while releasing " + mDexoptWakeLock.getTag() + " lock", e);
293 }
294 }
295
296 @GuardedBy("mInstallLock")
Calin Juravlec22c30e2017-01-16 19:18:48 -0800297 private int dexOptSecondaryDexPathLI(ApplicationInfo info, String path, Set<String> isas,
298 String compilerFilter, boolean isUsedByOtherApps) {
Calin Juravleefb1c942017-04-04 20:31:44 -0700299 compilerFilter = getRealCompilerFilter(info, compilerFilter, isUsedByOtherApps);
300 // Get the dexopt flags after getRealCompilerFilter to make sure we get the correct flags.
Calin Juravlec22c30e2017-01-16 19:18:48 -0800301 int dexoptFlags = getDexFlags(info, compilerFilter) | DEXOPT_SECONDARY_DEX;
302 // Check the app storage and add the appropriate flags.
Calin Juravleadbadd52017-03-28 18:19:15 -0700303 if (info.deviceProtectedDataDir != null &&
304 FileUtils.contains(info.deviceProtectedDataDir, path)) {
Calin Juravlec22c30e2017-01-16 19:18:48 -0800305 dexoptFlags |= DEXOPT_STORAGE_DE;
Calin Juravleadbadd52017-03-28 18:19:15 -0700306 } else if (info.credentialProtectedDataDir != null &&
307 FileUtils.contains(info.credentialProtectedDataDir, path)) {
Calin Juravlec22c30e2017-01-16 19:18:48 -0800308 dexoptFlags |= DEXOPT_STORAGE_CE;
309 } else {
310 Slog.e(TAG, "Could not infer CE/DE storage for package " + info.packageName);
311 return DEX_OPT_FAILED;
312 }
Calin Juravlec22c30e2017-01-16 19:18:48 -0800313 Log.d(TAG, "Running dexopt on: " + path
314 + " pkg=" + info.packageName + " isa=" + isas
315 + " dexoptFlags=" + printDexoptFlags(dexoptFlags)
316 + " target-filter=" + compilerFilter);
317
318 try {
319 for (String isa : isas) {
320 // Reuse the same dexopt path as for the primary apks. We don't need all the
321 // arguments as some (dexopNeeded and oatDir) will be computed by installd because
322 // system server cannot read untrusted app content.
323 // TODO(calin): maybe add a separate call.
324 mInstaller.dexopt(path, info.uid, info.packageName, isa, /*dexoptNeeded*/ 0,
325 /*oatDir*/ null, dexoptFlags,
Calin Juravle811a75a2017-04-05 22:49:38 -0700326 compilerFilter, info.volumeUuid, SKIP_SHARED_LIBRARY_CHECK, info.seInfoUser);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800327 }
328
329 return DEX_OPT_PERFORMED;
330 } catch (InstallerException e) {
331 Slog.w(TAG, "Failed to dexopt", e);
332 return DEX_OPT_FAILED;
333 }
334 }
335
336 /**
Andreas Gampea8908752015-11-10 08:58:14 -0800337 * Adjust the given dexopt-needed value. Can be overridden to influence the decision to
338 * optimize or not (and in what way).
339 */
340 protected int adjustDexoptNeeded(int dexoptNeeded) {
341 return dexoptNeeded;
342 }
343
344 /**
345 * Adjust the given dexopt flags that will be passed to the installer.
346 */
347 protected int adjustDexoptFlags(int dexoptFlags) {
348 return dexoptFlags;
349 }
350
Narayan Kamath88eea9e2016-05-02 14:44:31 +0100351 /**
352 * Dumps the dexopt state of the given package {@code pkg} to the given {@code PrintWriter}.
353 */
354 void dumpDexoptState(IndentingPrintWriter pw, PackageParser.Package pkg) {
355 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
356 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
357
358 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
359
360 for (String instructionSet : dexCodeInstructionSets) {
361 pw.println("Instruction Set: " + instructionSet);
362 pw.increaseIndent();
363 for (String path : paths) {
364 String status = null;
365 try {
366 status = DexFile.getDexFileStatus(path, instructionSet);
367 } catch (IOException ioe) {
368 status = "[Exception]: " + ioe.getMessage();
369 }
370 pw.println("path: " + path);
371 pw.println("status: " + status);
372 }
373 pw.decreaseIndent();
374 }
375 }
376
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800377 /**
378 * Returns the compiler filter that should be used to optimize the package code.
379 * The target filter will be updated if the package code is used by other apps
380 * or if it has the safe mode flag set.
381 */
Calin Juravlec22c30e2017-01-16 19:18:48 -0800382 private String getRealCompilerFilter(ApplicationInfo info, String targetCompilerFilter,
383 boolean isUsedByOtherApps) {
384 int flags = info.flags;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800385 boolean vmSafeMode = (flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
Mathieu Chartier41e4a372016-09-02 16:36:42 -0700386 if (vmSafeMode) {
Nicolas Geoffrayd093b202017-05-03 13:11:58 +0100387 return getSafeModeCompilerFilter(targetCompilerFilter);
Mathieu Chartier41e4a372016-09-02 16:36:42 -0700388 }
389
Calin Juravlec22c30e2017-01-16 19:18:48 -0800390 if (isProfileGuidedCompilerFilter(targetCompilerFilter) && isUsedByOtherApps) {
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800391 // If the dex files is used by other apps, we cannot use profile-guided compilation.
392 return getNonProfileGuidedCompilerFilter(targetCompilerFilter);
Andreas Gampebdd30d82016-03-20 11:32:11 -0700393 }
394
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800395 return targetCompilerFilter;
Fyodor Kupolov74876572015-02-23 17:14:45 -0800396 }
397
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800398 /**
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800399 * Computes the dex flags that needs to be pass to installd for the given package and compiler
400 * filter.
401 */
402 private int getDexFlags(PackageParser.Package pkg, String compilerFilter) {
Calin Juravlec22c30e2017-01-16 19:18:48 -0800403 return getDexFlags(pkg.applicationInfo, compilerFilter);
404 }
405
406 private int getDexFlags(ApplicationInfo info, String compilerFilter) {
407 int flags = info.flags;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800408 boolean vmSafeMode = (flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
409 boolean debuggable = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
410 // Profile guide compiled oat files should not be public.
411 boolean isProfileGuidedFilter = isProfileGuidedCompilerFilter(compilerFilter);
Calin Juravlec22c30e2017-01-16 19:18:48 -0800412 boolean isPublic = !info.isForwardLocked() && !isProfileGuidedFilter;
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800413 int profileFlag = isProfileGuidedFilter ? DEXOPT_PROFILE_GUIDED : 0;
414 int dexFlags =
415 (isPublic ? DEXOPT_PUBLIC : 0)
416 | (vmSafeMode ? DEXOPT_SAFEMODE : 0)
417 | (debuggable ? DEXOPT_DEBUGGABLE : 0)
418 | profileFlag
419 | DEXOPT_BOOTCOMPLETE;
420 return adjustDexoptFlags(dexFlags);
421 }
422
423 /**
424 * Assesses if there's a need to perform dexopt on {@code path} for the given
425 * configuration (isa, compiler filter, profile).
426 */
427 private int getDexoptNeeded(String path, String isa, String compilerFilter,
428 boolean newProfile) {
429 int dexoptNeeded;
430 try {
431 dexoptNeeded = DexFile.getDexOptNeeded(path, isa, compilerFilter, newProfile);
432 } catch (IOException ioe) {
433 Slog.w(TAG, "IOException reading apk: " + path, ioe);
434 return DEX_OPT_FAILED;
435 }
436 return adjustDexoptNeeded(dexoptNeeded);
437 }
438
439 /**
440 * Computes the shared libraries path that should be passed to dexopt.
441 */
442 private String getSharedLibrariesPath(String[] sharedLibraries) {
443 if (sharedLibraries == null || sharedLibraries.length == 0) {
444 return null;
445 }
446 StringBuilder sb = new StringBuilder();
447 for (String lib : sharedLibraries) {
448 if (sb.length() != 0) {
449 sb.append(":");
450 }
451 sb.append(lib);
452 }
453 return sb.toString();
454 }
455
456 /**
Jeff Hao5def5e52017-04-19 14:42:16 -0700457 * Walks dependency tree and gathers the dependencies for each split in a split apk.
458 * The split paths are stored as relative paths, separated by colons.
459 */
460 private String[] getSplitDependencies(PackageParser.Package pkg) {
461 // Convert all the code paths to relative paths.
462 String baseCodePath = new File(pkg.baseCodePath).getParent();
463 List<String> paths = pkg.getAllCodePaths();
464 String[] splitDependencies = new String[paths.size()];
465 for (int i = 0; i < paths.size(); i++) {
466 File pathFile = new File(paths.get(i));
467 String fileName = pathFile.getName();
468 paths.set(i, fileName);
469
470 // Sanity check that the base paths of the splits are all the same.
471 String basePath = pathFile.getParent();
472 if (!basePath.equals(baseCodePath)) {
473 Slog.wtf(TAG, "Split paths have different base paths: " + basePath + " and " +
474 baseCodePath);
475 }
476 }
477
478 // If there are no other dependencies, fill in the implicit dependency on the base apk.
479 SparseArray<int[]> dependencies = pkg.applicationInfo.splitDependencies;
480 if (dependencies == null) {
481 for (int i = 1; i < paths.size(); i++) {
482 splitDependencies[i] = paths.get(0);
483 }
484 return splitDependencies;
485 }
486
487 // Fill in the dependencies, skipping the base apk which has no dependencies.
488 for (int i = 1; i < dependencies.size(); i++) {
489 getParentDependencies(dependencies.keyAt(i), paths, dependencies, splitDependencies);
490 }
491
492 return splitDependencies;
493 }
494
495 /**
496 * Recursive method to generate dependencies for a particular split.
497 * The index is a key from the package's splitDependencies.
498 */
499 private String getParentDependencies(int index, List<String> paths,
500 SparseArray<int[]> dependencies, String[] splitDependencies) {
501 // The base apk is always first, and has no dependencies.
502 if (index == 0) {
503 return null;
504 }
505 // Return the result if we've computed the dependencies for this index already.
506 if (splitDependencies[index] != null) {
507 return splitDependencies[index];
508 }
509 // Get the dependencies for the parent of this index and append its path to it.
510 int parent = dependencies.get(index)[0];
511 String parentDependencies =
512 getParentDependencies(parent, paths, dependencies, splitDependencies);
513 String path = parentDependencies == null ? paths.get(parent) :
514 parentDependencies + ":" + paths.get(parent);
515 splitDependencies[index] = path;
516 return path;
517 }
518
519 /**
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800520 * Checks if there is an update on the profile information of the {@code pkg}.
521 * If the compiler filter is not profile guided the method returns false.
522 *
523 * Note that this is a "destructive" operation with side effects. Under the hood the
524 * current profile and the reference profile will be merged and subsequent calls
525 * may return a different result.
526 */
527 private boolean isProfileUpdated(PackageParser.Package pkg, int uid, String compilerFilter) {
528 // Check if we are allowed to merge and if the compiler filter is profile guided.
529 if (!isProfileGuidedCompilerFilter(compilerFilter)) {
530 return false;
531 }
532 // Merge profiles. It returns whether or not there was an updated in the profile info.
533 try {
534 return mInstaller.mergeProfiles(uid, pkg.packageName);
535 } catch (InstallerException e) {
536 Slog.w(TAG, "Failed to merge profiles", e);
537 }
538 return false;
539 }
540
541 /**
542 * Creates oat dir for the specified package if needed and supported.
543 * In certain cases oat directory
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800544 * <strong>cannot</strong> be created:
545 * <ul>
546 * <li>{@code pkg} is a system app, which is not updated.</li>
547 * <li>Package location is not a directory, i.e. monolithic install.</li>
548 * </ul>
549 *
Richard Uhler7b08b352015-03-25 16:25:57 -0700550 * @return Absolute path to the oat directory or null, if oat directory
551 * cannot be created.
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800552 */
553 @Nullable
Todd Kennedy27c24fb2015-09-17 16:49:25 -0700554 private String createOatDirIfSupported(PackageParser.Package pkg, String dexInstructionSet) {
Fyodor Kupolovebcac162015-09-09 15:56:45 -0700555 if (!pkg.canHaveOatDir()) {
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800556 return null;
557 }
558 File codePath = new File(pkg.codePath);
559 if (codePath.isDirectory()) {
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800560 // TODO(calin): why do we create this only if the codePath is a directory? (i.e for
561 // cluster packages). It seems that the logic for the folder creation is
562 // split between installd and here.
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800563 File oatDir = getOatDir(codePath);
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -0700564 try {
Andreas Gampea8908752015-11-10 08:58:14 -0800565 mInstaller.createOatDir(oatDir.getAbsolutePath(), dexInstructionSet);
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -0700566 } catch (InstallerException e) {
567 Slog.w(TAG, "Failed to create oat dir", e);
568 return null;
569 }
Richard Uhler7b08b352015-03-25 16:25:57 -0700570 return oatDir.getAbsolutePath();
Fyodor Kupolovb94c1652015-03-03 12:25:30 -0800571 }
572 return null;
573 }
574
575 static File getOatDir(File codePath) {
576 return new File(codePath, OAT_DIR_NAME);
577 }
578
Fyodor Kupolova627c092015-05-05 18:44:39 -0700579 void systemReady() {
580 mSystemReady = true;
581 }
Andreas Gampea8908752015-11-10 08:58:14 -0800582
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800583 private String printDexoptFlags(int flags) {
584 ArrayList<String> flagsList = new ArrayList<>();
585
586 if ((flags & DEXOPT_BOOTCOMPLETE) == DEXOPT_BOOTCOMPLETE) {
587 flagsList.add("boot_complete");
588 }
589 if ((flags & DEXOPT_DEBUGGABLE) == DEXOPT_DEBUGGABLE) {
590 flagsList.add("debuggable");
591 }
592 if ((flags & DEXOPT_PROFILE_GUIDED) == DEXOPT_PROFILE_GUIDED) {
593 flagsList.add("profile_guided");
594 }
595 if ((flags & DEXOPT_PUBLIC) == DEXOPT_PUBLIC) {
596 flagsList.add("public");
597 }
598 if ((flags & DEXOPT_SAFEMODE) == DEXOPT_SAFEMODE) {
599 flagsList.add("safemode");
600 }
Calin Juravlec22c30e2017-01-16 19:18:48 -0800601 if ((flags & DEXOPT_SECONDARY_DEX) == DEXOPT_SECONDARY_DEX) {
602 flagsList.add("secondary");
603 }
604 if ((flags & DEXOPT_FORCE) == DEXOPT_FORCE) {
605 flagsList.add("force");
606 }
607 if ((flags & DEXOPT_STORAGE_CE) == DEXOPT_STORAGE_CE) {
608 flagsList.add("storage_ce");
609 }
610 if ((flags & DEXOPT_STORAGE_DE) == DEXOPT_STORAGE_DE) {
611 flagsList.add("storage_de");
612 }
613
Calin Juravle2d4b6ad72017-01-04 13:22:14 -0800614 return String.join(",", flagsList);
615 }
616
Andreas Gampea8908752015-11-10 08:58:14 -0800617 /**
618 * A specialized PackageDexOptimizer that overrides already-installed checks, forcing a
619 * dexopt path.
620 */
621 public static class ForcedUpdatePackageDexOptimizer extends PackageDexOptimizer {
622
623 public ForcedUpdatePackageDexOptimizer(Installer installer, Object installLock,
624 Context context, String wakeLockTag) {
625 super(installer, installLock, context, wakeLockTag);
626 }
627
628 public ForcedUpdatePackageDexOptimizer(PackageDexOptimizer from) {
629 super(from);
630 }
631
632 @Override
Andreas Gampea8908752015-11-10 08:58:14 -0800633 protected int adjustDexoptNeeded(int dexoptNeeded) {
Nicolas Geoffray96d12a92017-05-03 11:51:53 +0100634 if (dexoptNeeded == DexFile.NO_DEXOPT_NEEDED) {
635 // Ensure compilation by pretending a compiler filter change on the
636 // apk/odex location (the reason for the '-'. A positive value means
637 // the 'oat' location).
638 return -DexFile.DEX2OAT_FOR_FILTER;
639 }
640 return dexoptNeeded;
Andreas Gampea8908752015-11-10 08:58:14 -0800641 }
Calin Juravlec22c30e2017-01-16 19:18:48 -0800642
643 @Override
644 protected int adjustDexoptFlags(int flags) {
645 // Add DEXOPT_FORCE flag to signal installd that it should force compilation
646 // and discard dexoptanalyzer result.
647 return flags | DEXOPT_FORCE;
648 }
Andreas Gampea8908752015-11-10 08:58:14 -0800649 }
Fyodor Kupolov74876572015-02-23 17:14:45 -0800650}