1 /* 2 * Copyright (C) 2006 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 17 package com.android.server.pm; 18 19 import static android.Manifest.permission.DELETE_PACKAGES; 20 import static android.Manifest.permission.INSTALL_PACKAGES; 21 import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS; 22 import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 23 import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 24 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 25 import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 26 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 27 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 28 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 29 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 30 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 31 import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 32 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 33 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 34 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 35 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 36 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 37 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 38 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 39 import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 40 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 41 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 42 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 43 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 44 import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 45 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 46 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 47 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 48 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 49 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 50 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 51 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 52 import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE; 53 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 54 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 55 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 56 import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 57 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 58 import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 59 import static android.content.pm.PackageManager.INSTALL_INTERNAL; 60 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 61 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 62 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 63 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 64 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 65 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 66 import static android.content.pm.PackageManager.MATCH_ALL; 67 import static android.content.pm.PackageManager.MATCH_ANY_USER; 68 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 69 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 70 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 71 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 72 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 73 import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 74 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 75 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 76 import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 77 import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 78 import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 79 import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 80 import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER; 81 import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 82 import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 83 import static android.content.pm.PackageManager.PERMISSION_DENIED; 84 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 85 import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 86 import static android.content.pm.PackageParser.isApkFile; 87 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 88 import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 89 import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 90 import static android.system.OsConstants.O_CREAT; 91 import static android.system.OsConstants.O_RDWR; 92 93 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 94 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 95 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 96 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 97 import static com.android.internal.util.ArrayUtils.appendInt; 98 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 99 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 100 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 101 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 102 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 103 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 104 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 105 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 106 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 107 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 108 109 import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter; 110 111 import android.Manifest; 112 import android.annotation.IntDef; 113 import android.annotation.NonNull; 114 import android.annotation.Nullable; 115 import android.app.ActivityManager; 116 import android.app.AppOpsManager; 117 import android.app.IActivityManager; 118 import android.app.ResourcesManager; 119 import android.app.admin.IDevicePolicyManager; 120 import android.app.admin.SecurityLog; 121 import android.app.backup.IBackupManager; 122 import android.content.BroadcastReceiver; 123 import android.content.ComponentName; 124 import android.content.ContentResolver; 125 import android.content.Context; 126 import android.content.IIntentReceiver; 127 import android.content.Intent; 128 import android.content.IntentFilter; 129 import android.content.IntentSender; 130 import android.content.IntentSender.SendIntentException; 131 import android.content.ServiceConnection; 132 import android.content.pm.ActivityInfo; 133 import android.content.pm.ApplicationInfo; 134 import android.content.pm.AppsQueryHelper; 135 import android.content.pm.AuxiliaryResolveInfo; 136 import android.content.pm.ChangedPackages; 137 import android.content.pm.ComponentInfo; 138 import android.content.pm.FallbackCategoryProvider; 139 import android.content.pm.FeatureInfo; 140 import android.content.pm.IDexModuleRegisterCallback; 141 import android.content.pm.IOnPermissionsChangeListener; 142 import android.content.pm.IPackageDataObserver; 143 import android.content.pm.IPackageDeleteObserver; 144 import android.content.pm.IPackageDeleteObserver2; 145 import android.content.pm.IPackageInstallObserver2; 146 import android.content.pm.IPackageInstaller; 147 import android.content.pm.IPackageManager; 148 import android.content.pm.IPackageManagerNative; 149 import android.content.pm.IPackageMoveObserver; 150 import android.content.pm.IPackageStatsObserver; 151 import android.content.pm.InstantAppInfo; 152 import android.content.pm.InstantAppRequest; 153 import android.content.pm.InstantAppResolveInfo; 154 import android.content.pm.InstrumentationInfo; 155 import android.content.pm.IntentFilterVerificationInfo; 156 import android.content.pm.KeySet; 157 import android.content.pm.PackageCleanItem; 158 import android.content.pm.PackageInfo; 159 import android.content.pm.PackageInfoLite; 160 import android.content.pm.PackageInstaller; 161 import android.content.pm.PackageManager; 162 import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 163 import android.content.pm.PackageManagerInternal; 164 import android.content.pm.PackageParser; 165 import android.content.pm.PackageParser.ActivityIntentInfo; 166 import android.content.pm.PackageParser.PackageLite; 167 import android.content.pm.PackageParser.PackageParserException; 168 import android.content.pm.PackageStats; 169 import android.content.pm.PackageUserState; 170 import android.content.pm.ParceledListSlice; 171 import android.content.pm.PermissionGroupInfo; 172 import android.content.pm.PermissionInfo; 173 import android.content.pm.ProviderInfo; 174 import android.content.pm.ResolveInfo; 175 import android.content.pm.ServiceInfo; 176 import android.content.pm.SharedLibraryInfo; 177 import android.content.pm.Signature; 178 import android.content.pm.UserInfo; 179 import android.content.pm.VerifierDeviceIdentity; 180 import android.content.pm.VerifierInfo; 181 import android.content.pm.VersionedPackage; 182 import android.content.res.Resources; 183 import android.database.ContentObserver; 184 import android.graphics.Bitmap; 185 import android.hardware.display.DisplayManager; 186 import android.net.Uri; 187 import android.os.Binder; 188 import android.os.Build; 189 import android.os.Bundle; 190 import android.os.Debug; 191 import android.os.Environment; 192 import android.os.Environment.UserEnvironment; 193 import android.os.FileUtils; 194 import android.os.Handler; 195 import android.os.IBinder; 196 import android.os.Looper; 197 import android.os.Message; 198 import android.os.Parcel; 199 import android.os.ParcelFileDescriptor; 200 import android.os.PatternMatcher; 201 import android.os.Process; 202 import android.os.RemoteCallbackList; 203 import android.os.RemoteException; 204 import android.os.ResultReceiver; 205 import android.os.SELinux; 206 import android.os.ServiceManager; 207 import android.os.ShellCallback; 208 import android.os.SystemClock; 209 import android.os.SystemProperties; 210 import android.os.Trace; 211 import android.os.UserHandle; 212 import android.os.UserManager; 213 import android.os.UserManagerInternal; 214 import android.os.storage.IStorageManager; 215 import android.os.storage.StorageEventListener; 216 import android.os.storage.StorageManager; 217 import android.os.storage.StorageManagerInternal; 218 import android.os.storage.VolumeInfo; 219 import android.os.storage.VolumeRecord; 220 import android.provider.Settings.Global; 221 import android.provider.Settings.Secure; 222 import android.security.KeyStore; 223 import android.security.SystemKeyStore; 224 import android.service.pm.PackageServiceDumpProto; 225 import android.system.ErrnoException; 226 import android.system.Os; 227 import android.text.TextUtils; 228 import android.text.format.DateUtils; 229 import android.util.ArrayMap; 230 import android.util.ArraySet; 231 import android.util.Base64; 232 import android.util.TimingsTraceLog; 233 import android.util.DisplayMetrics; 234 import android.util.EventLog; 235 import android.util.ExceptionUtils; 236 import android.util.Log; 237 import android.util.LogPrinter; 238 import android.util.MathUtils; 239 import android.util.PackageUtils; 240 import android.util.Pair; 241 import android.util.PrintStreamPrinter; 242 import android.util.Slog; 243 import android.util.SparseArray; 244 import android.util.SparseBooleanArray; 245 import android.util.SparseIntArray; 246 import android.util.Xml; 247 import android.util.jar.StrictJarFile; 248 import android.util.proto.ProtoOutputStream; 249 import android.view.Display; 250 251 import com.android.internal.R; 252 import com.android.internal.annotations.GuardedBy; 253 import com.android.internal.app.IMediaContainerService; 254 import com.android.internal.app.ResolverActivity; 255 import com.android.internal.content.NativeLibraryHelper; 256 import com.android.internal.content.PackageHelper; 257 import com.android.internal.logging.MetricsLogger; 258 import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 259 import com.android.internal.os.IParcelFileDescriptorFactory; 260 import com.android.internal.os.RoSystemProperties; 261 import com.android.internal.os.SomeArgs; 262 import com.android.internal.os.Zygote; 263 import com.android.internal.telephony.CarrierAppUtils; 264 import com.android.internal.util.ArrayUtils; 265 import com.android.internal.util.ConcurrentUtils; 266 import com.android.internal.util.DumpUtils; 267 import com.android.internal.util.FastPrintWriter; 268 import com.android.internal.util.FastXmlSerializer; 269 import com.android.internal.util.IndentingPrintWriter; 270 import com.android.internal.util.Preconditions; 271 import com.android.internal.util.XmlUtils; 272 import com.android.server.AttributeCache; 273 import com.android.server.DeviceIdleController; 274 import com.android.server.EventLogTags; 275 import com.android.server.FgThread; 276 import com.android.server.IntentResolver; 277 import com.android.server.LocalServices; 278 import com.android.server.LockGuard; 279 import com.android.server.ServiceThread; 280 import com.android.server.SystemConfig; 281 import com.android.server.SystemServerInitThreadPool; 282 import com.android.server.Watchdog; 283 import com.android.server.net.NetworkPolicyManagerInternal; 284 import com.android.server.pm.Installer.InstallerException; 285 import com.android.server.pm.PermissionsState.PermissionState; 286 import com.android.server.pm.Settings.DatabaseVersion; 287 import com.android.server.pm.Settings.VersionInfo; 288 import com.android.server.pm.dex.DexManager; 289 import com.android.server.pm.dex.DexoptOptions; 290 import com.android.server.pm.dex.PackageDexUsage; 291 import com.android.server.storage.DeviceStorageMonitorInternal; 292 293 import dalvik.system.CloseGuard; 294 import dalvik.system.DexFile; 295 import dalvik.system.VMRuntime; 296 297 import libcore.io.IoUtils; 298 import libcore.io.Streams; 299 import libcore.util.EmptyArray; 300 301 import org.xmlpull.v1.XmlPullParser; 302 import org.xmlpull.v1.XmlPullParserException; 303 import org.xmlpull.v1.XmlSerializer; 304 305 import java.io.BufferedOutputStream; 306 import java.io.BufferedReader; 307 import java.io.ByteArrayInputStream; 308 import java.io.ByteArrayOutputStream; 309 import java.io.File; 310 import java.io.FileDescriptor; 311 import java.io.FileInputStream; 312 import java.io.FileOutputStream; 313 import java.io.FileReader; 314 import java.io.FilenameFilter; 315 import java.io.IOException; 316 import java.io.InputStream; 317 import java.io.OutputStream; 318 import java.io.PrintWriter; 319 import java.lang.annotation.Retention; 320 import java.lang.annotation.RetentionPolicy; 321 import java.nio.charset.StandardCharsets; 322 import java.security.DigestInputStream; 323 import java.security.MessageDigest; 324 import java.security.NoSuchAlgorithmException; 325 import java.security.PublicKey; 326 import java.security.SecureRandom; 327 import java.security.cert.Certificate; 328 import java.security.cert.CertificateEncodingException; 329 import java.security.cert.CertificateException; 330 import java.text.SimpleDateFormat; 331 import java.util.ArrayList; 332 import java.util.Arrays; 333 import java.util.Collection; 334 import java.util.Collections; 335 import java.util.Comparator; 336 import java.util.Date; 337 import java.util.HashMap; 338 import java.util.HashSet; 339 import java.util.Iterator; 340 import java.util.List; 341 import java.util.Map; 342 import java.util.Objects; 343 import java.util.Set; 344 import java.util.concurrent.CountDownLatch; 345 import java.util.concurrent.Future; 346 import java.util.concurrent.TimeUnit; 347 import java.util.concurrent.atomic.AtomicBoolean; 348 import java.util.concurrent.atomic.AtomicInteger; 349 import java.util.zip.GZIPInputStream; 350 351 /** 352 * Keep track of all those APKs everywhere. 353 * <p> 354 * Internally there are two important locks: 355 * <ul> 356 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 357 * and other related state. It is a fine-grained lock that should only be held 358 * momentarily, as it's one of the most contended locks in the system. 359 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 360 * operations typically involve heavy lifting of application data on disk. Since 361 * {@code installd} is single-threaded, and it's operations can often be slow, 362 * this lock should never be acquired while already holding {@link #mPackages}. 363 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 364 * holding {@link #mInstallLock}. 365 * </ul> 366 * Many internal methods rely on the caller to hold the appropriate locks, and 367 * this contract is expressed through method name suffixes: 368 * <ul> 369 * <li>fooLI(): the caller must hold {@link #mInstallLock} 370 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 371 * being modified must be frozen 372 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 373 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 374 * </ul> 375 * <p> 376 * Because this class is very central to the platform's security; please run all 377 * CTS and unit tests whenever making modifications: 378 * 379 * <pre> 380 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 381 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 382 * </pre> 383 */ 384 public class PackageManagerService extends IPackageManager.Stub 385 implements PackageSender { 386 static final String TAG = "PackageManager"; 387 static final boolean DEBUG_SETTINGS = false; 388 static final boolean DEBUG_PREFERRED = false; 389 static final boolean DEBUG_UPGRADE = false; 390 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 391 private static final boolean DEBUG_BACKUP = false; 392 private static final boolean DEBUG_INSTALL = false; 393 private static final boolean DEBUG_REMOVE = false; 394 private static final boolean DEBUG_BROADCASTS = false; 395 private static final boolean DEBUG_SHOW_INFO = false; 396 private static final boolean DEBUG_PACKAGE_INFO = false; 397 private static final boolean DEBUG_INTENT_MATCHING = false; 398 private static final boolean DEBUG_PACKAGE_SCANNING = false; 399 private static final boolean DEBUG_VERIFY = false; 400 private static final boolean DEBUG_FILTERS = false; 401 private static final boolean DEBUG_PERMISSIONS = false; 402 private static final boolean DEBUG_SHARED_LIBRARIES = false; 403 private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 404 405 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 406 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 407 // user, but by default initialize to this. 408 public static final boolean DEBUG_DEXOPT = false; 409 410 private static final boolean DEBUG_ABI_SELECTION = false; 411 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 412 private static final boolean DEBUG_TRIAGED_MISSING = false; 413 private static final boolean DEBUG_APP_DATA = false; 414 415 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 416 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 417 418 private static final boolean HIDE_EPHEMERAL_APIS = false; 419 420 private static final boolean ENABLE_FREE_CACHE_V2 = 421 SystemProperties.getBoolean("fw.free_cache_v2", true); 422 423 private static final int RADIO_UID = Process.PHONE_UID; 424 private static final int LOG_UID = Process.LOG_UID; 425 private static final int NFC_UID = Process.NFC_UID; 426 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 427 private static final int SHELL_UID = Process.SHELL_UID; 428 429 // Cap the size of permission trees that 3rd party apps can define 430 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 431 432 // Suffix used during package installation when copying/moving 433 // package apks to install directory. 434 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 435 436 static final int SCAN_NO_DEX = 1<<1; 437 static final int SCAN_FORCE_DEX = 1<<2; 438 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 439 static final int SCAN_NEW_INSTALL = 1<<4; 440 static final int SCAN_UPDATE_TIME = 1<<5; 441 static final int SCAN_BOOTING = 1<<6; 442 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 443 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 444 static final int SCAN_REPLACING = 1<<9; 445 static final int SCAN_REQUIRE_KNOWN = 1<<10; 446 static final int SCAN_MOVE = 1<<11; 447 static final int SCAN_INITIAL = 1<<12; 448 static final int SCAN_CHECK_ONLY = 1<<13; 449 static final int SCAN_DONT_KILL_APP = 1<<14; 450 static final int SCAN_IGNORE_FROZEN = 1<<15; 451 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 452 static final int SCAN_AS_INSTANT_APP = 1<<17; 453 static final int SCAN_AS_FULL_APP = 1<<18; 454 static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19; 455 /** Should not be with the scan flags */ 456 static final int FLAGS_REMOVE_CHATTY = 1<<31; 457 458 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 459 /** Extension of the compressed packages */ 460 private final static String COMPRESSED_EXTENSION = ".gz"; 461 /** Suffix of stub packages on the system partition */ 462 private final static String STUB_SUFFIX = "-Stub"; 463 464 private static final int[] EMPTY_INT_ARRAY = new int[0]; 465 466 private static final int TYPE_UNKNOWN = 0; 467 private static final int TYPE_ACTIVITY = 1; 468 private static final int TYPE_RECEIVER = 2; 469 private static final int TYPE_SERVICE = 3; 470 private static final int TYPE_PROVIDER = 4; 471 @IntDef(prefix = { "TYPE_" }, value = { 472 TYPE_UNKNOWN, 473 TYPE_ACTIVITY, 474 TYPE_RECEIVER, 475 TYPE_SERVICE, 476 TYPE_PROVIDER, 477 }) 478 @Retention(RetentionPolicy.SOURCE) 479 public @interface ComponentType {} 480 481 /** 482 * Timeout (in milliseconds) after which the watchdog should declare that 483 * our handler thread is wedged. The usual default for such things is one 484 * minute but we sometimes do very lengthy I/O operations on this thread, 485 * such as installing multi-gigabyte applications, so ours needs to be longer. 486 */ 487 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 488 489 /** 490 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 491 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 492 * settings entry if available, otherwise we use the hardcoded default. If it's been 493 * more than this long since the last fstrim, we force one during the boot sequence. 494 * 495 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 496 * one gets run at the next available charging+idle time. This final mandatory 497 * no-fstrim check kicks in only of the other scheduling criteria is never met. 498 */ 499 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 500 501 /** 502 * Whether verification is enabled by default. 503 */ 504 private static final boolean DEFAULT_VERIFY_ENABLE = true; 505 506 /** 507 * The default maximum time to wait for the verification agent to return in 508 * milliseconds. 509 */ 510 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 511 512 /** 513 * The default response for package verification timeout. 514 * 515 * This can be either PackageManager.VERIFICATION_ALLOW or 516 * PackageManager.VERIFICATION_REJECT. 517 */ 518 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 519 520 static final String PLATFORM_PACKAGE_NAME = "android"; 521 522 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 523 524 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 525 DEFAULT_CONTAINER_PACKAGE, 526 "com.android.defcontainer.DefaultContainerService"); 527 528 private static final String KILL_APP_REASON_GIDS_CHANGED = 529 "permission grant or revoke changed gids"; 530 531 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 532 "permissions revoked"; 533 534 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 535 536 private static final String PACKAGE_SCHEME = "package"; 537 538 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 539 540 /** Permission grant: not grant the permission. */ 541 private static final int GRANT_DENIED = 1; 542 543 /** Permission grant: grant the permission as an install permission. */ 544 private static final int GRANT_INSTALL = 2; 545 546 /** Permission grant: grant the permission as a runtime one. */ 547 private static final int GRANT_RUNTIME = 3; 548 549 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 550 private static final int GRANT_UPGRADE = 4; 551 552 /** Canonical intent used to identify what counts as a "web browser" app */ 553 private static final Intent sBrowserIntent; 554 static { 555 sBrowserIntent = new Intent(); 556 sBrowserIntent.setAction(Intent.ACTION_VIEW); 557 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 558 sBrowserIntent.setData(Uri.parse("http:")); 559 } 560 561 /** 562 * The set of all protected actions [i.e. those actions for which a high priority 563 * intent filter is disallowed]. 564 */ 565 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 566 static { 567 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 568 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 569 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 570 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 571 } 572 573 // Compilation reasons. 574 public static final int REASON_FIRST_BOOT = 0; 575 public static final int REASON_BOOT = 1; 576 public static final int REASON_INSTALL = 2; 577 public static final int REASON_BACKGROUND_DEXOPT = 3; 578 public static final int REASON_AB_OTA = 4; 579 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 580 public static final int REASON_SHARED = 6; 581 582 public static final int REASON_LAST = REASON_SHARED; 583 584 /** All dangerous permission names in the same order as the events in MetricsEvent */ 585 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 586 Manifest.permission.READ_CALENDAR, 587 Manifest.permission.WRITE_CALENDAR, 588 Manifest.permission.CAMERA, 589 Manifest.permission.READ_CONTACTS, 590 Manifest.permission.WRITE_CONTACTS, 591 Manifest.permission.GET_ACCOUNTS, 592 Manifest.permission.ACCESS_FINE_LOCATION, 593 Manifest.permission.ACCESS_COARSE_LOCATION, 594 Manifest.permission.RECORD_AUDIO, 595 Manifest.permission.READ_PHONE_STATE, 596 Manifest.permission.CALL_PHONE, 597 Manifest.permission.READ_CALL_LOG, 598 Manifest.permission.WRITE_CALL_LOG, 599 Manifest.permission.ADD_VOICEMAIL, 600 Manifest.permission.USE_SIP, 601 Manifest.permission.PROCESS_OUTGOING_CALLS, 602 Manifest.permission.READ_CELL_BROADCASTS, 603 Manifest.permission.BODY_SENSORS, 604 Manifest.permission.SEND_SMS, 605 Manifest.permission.RECEIVE_SMS, 606 Manifest.permission.READ_SMS, 607 Manifest.permission.RECEIVE_WAP_PUSH, 608 Manifest.permission.RECEIVE_MMS, 609 Manifest.permission.READ_EXTERNAL_STORAGE, 610 Manifest.permission.WRITE_EXTERNAL_STORAGE, 611 Manifest.permission.READ_PHONE_NUMBERS, 612 Manifest.permission.ANSWER_PHONE_CALLS); 613 614 615 /** 616 * Version number for the package parser cache. Increment this whenever the format or 617 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 618 */ 619 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 620 621 /** 622 * Whether the package parser cache is enabled. 623 */ 624 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 625 626 final ServiceThread mHandlerThread; 627 628 final PackageHandler mHandler; 629 630 private final ProcessLoggingHandler mProcessLoggingHandler; 631 632 /** 633 * Messages for {@link #mHandler} that need to wait for system ready before 634 * being dispatched. 635 */ 636 private ArrayList<Message> mPostSystemReadyMessages; 637 638 final int mSdkVersion = Build.VERSION.SDK_INT; 639 640 final Context mContext; 641 final boolean mFactoryTest; 642 final boolean mOnlyCore; 643 final DisplayMetrics mMetrics; 644 final int mDefParseFlags; 645 final String[] mSeparateProcesses; 646 final boolean mIsUpgrade; 647 final boolean mIsPreNUpgrade; 648 final boolean mIsPreNMR1Upgrade; 649 650 // Have we told the Activity Manager to whitelist the default container service by uid yet? 651 @GuardedBy("mPackages") 652 boolean mDefaultContainerWhitelisted = false; 653 654 @GuardedBy("mPackages") 655 private boolean mDexOptDialogShown; 656 657 /** The location for ASEC container files on internal storage. */ 658 final String mAsecInternalPath; 659 660 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 661 // LOCK HELD. Can be called with mInstallLock held. 662 @GuardedBy("mInstallLock") 663 final Installer mInstaller; 664 665 /** Directory where installed third-party apps stored */ 666 final File mAppInstallDir; 667 668 /** 669 * Directory to which applications installed internally have their 670 * 32 bit native libraries copied. 671 */ 672 private File mAppLib32InstallDir; 673 674 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 675 // apps. 676 final File mDrmAppPrivateInstallDir; 677 678 // ---------------------------------------------------------------- 679 680 // Lock for state used when installing and doing other long running 681 // operations. Methods that must be called with this lock held have 682 // the suffix "LI". 683 final Object mInstallLock = new Object(); 684 685 // ---------------------------------------------------------------- 686 687 // Keys are String (package name), values are Package. This also serves 688 // as the lock for the global state. Methods that must be called with 689 // this lock held have the prefix "LP". 690 @GuardedBy("mPackages") 691 final ArrayMap<String, PackageParser.Package> mPackages = 692 new ArrayMap<String, PackageParser.Package>(); 693 694 final ArrayMap<String, Set<String>> mKnownCodebase = 695 new ArrayMap<String, Set<String>>(); 696 697 // Keys are isolated uids and values are the uid of the application 698 // that created the isolated proccess. 699 @GuardedBy("mPackages") 700 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 701 702 /** 703 * Tracks new system packages [received in an OTA] that we expect to 704 * find updated user-installed versions. Keys are package name, values 705 * are package location. 706 */ 707 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 708 /** 709 * Tracks high priority intent filters for protected actions. During boot, certain 710 * filter actions are protected and should never be allowed to have a high priority 711 * intent filter for them. However, there is one, and only one exception -- the 712 * setup wizard. It must be able to define a high priority intent filter for these 713 * actions to ensure there are no escapes from the wizard. We need to delay processing 714 * of these during boot as we need to look at all of the system packages in order 715 * to know which component is the setup wizard. 716 */ 717 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 718 /** 719 * Whether or not processing protected filters should be deferred. 720 */ 721 private boolean mDeferProtectedFilters = true; 722 723 /** 724 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 725 */ 726 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 727 /** 728 * Whether or not system app permissions should be promoted from install to runtime. 729 */ 730 boolean mPromoteSystemApps; 731 732 @GuardedBy("mPackages") 733 final Settings mSettings; 734 735 /** 736 * Set of package names that are currently "frozen", which means active 737 * surgery is being done on the code/data for that package. The platform 738 * will refuse to launch frozen packages to avoid race conditions. 739 * 740 * @see PackageFreezer 741 */ 742 @GuardedBy("mPackages") 743 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 744 745 final ProtectedPackages mProtectedPackages; 746 747 @GuardedBy("mLoadedVolumes") 748 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 749 750 boolean mFirstBoot; 751 752 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 753 754 // System configuration read by SystemConfig. 755 final int[] mGlobalGids; 756 final SparseArray<ArraySet<String>> mSystemPermissions; 757 @GuardedBy("mAvailableFeatures") 758 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 759 760 // If mac_permissions.xml was found for seinfo labeling. 761 boolean mFoundPolicyFile; 762 763 private final InstantAppRegistry mInstantAppRegistry; 764 765 @GuardedBy("mPackages") 766 int mChangedPackagesSequenceNumber; 767 /** 768 * List of changed [installed, removed or updated] packages. 769 * mapping from user id -> sequence number -> package name 770 */ 771 @GuardedBy("mPackages") 772 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 773 /** 774 * The sequence number of the last change to a package. 775 * mapping from user id -> package name -> sequence number 776 */ 777 @GuardedBy("mPackages") 778 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 779 780 class PackageParserCallback implements PackageParser.Callback { 781 @Override public final boolean hasFeature(String feature) { 782 return PackageManagerService.this.hasSystemFeature(feature, 0); 783 } 784 785 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 786 Collection<PackageParser.Package> allPackages, String targetPackageName) { 787 List<PackageParser.Package> overlayPackages = null; 788 for (PackageParser.Package p : allPackages) { 789 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) { 790 if (overlayPackages == null) { 791 overlayPackages = new ArrayList<PackageParser.Package>(); 792 } 793 overlayPackages.add(p); 794 } 795 } 796 if (overlayPackages != null) { 797 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 798 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 799 return p1.mOverlayPriority - p2.mOverlayPriority; 800 } 801 }; 802 Collections.sort(overlayPackages, cmp); 803 } 804 return overlayPackages; 805 } 806 807 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 808 String targetPackageName, String targetPath) { 809 if ("android".equals(targetPackageName)) { 810 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 811 // native AssetManager. 812 return null; 813 } 814 List<PackageParser.Package> overlayPackages = 815 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 816 if (overlayPackages == null || overlayPackages.isEmpty()) { 817 return null; 818 } 819 List<String> overlayPathList = null; 820 for (PackageParser.Package overlayPackage : overlayPackages) { 821 if (targetPath == null) { 822 if (overlayPathList == null) { 823 overlayPathList = new ArrayList<String>(); 824 } 825 overlayPathList.add(overlayPackage.baseCodePath); 826 continue; 827 } 828 829 try { 830 // Creates idmaps for system to parse correctly the Android manifest of the 831 // target package. 832 // 833 // OverlayManagerService will update each of them with a correct gid from its 834 // target package app id. 835 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 836 UserHandle.getSharedAppGid( 837 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 838 if (overlayPathList == null) { 839 overlayPathList = new ArrayList<String>(); 840 } 841 overlayPathList.add(overlayPackage.baseCodePath); 842 } catch (InstallerException e) { 843 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 844 overlayPackage.baseCodePath); 845 } 846 } 847 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 848 } 849 850 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 851 synchronized (mPackages) { 852 return getStaticOverlayPathsLocked( 853 mPackages.values(), targetPackageName, targetPath); 854 } 855 } 856 857 @Override public final String[] getOverlayApks(String targetPackageName) { 858 return getStaticOverlayPaths(targetPackageName, null); 859 } 860 861 @Override public final String[] getOverlayPaths(String targetPackageName, 862 String targetPath) { 863 return getStaticOverlayPaths(targetPackageName, targetPath); 864 } 865 }; 866 867 class ParallelPackageParserCallback extends PackageParserCallback { 868 List<PackageParser.Package> mOverlayPackages = null; 869 870 void findStaticOverlayPackages() { 871 synchronized (mPackages) { 872 for (PackageParser.Package p : mPackages.values()) { 873 if (p.mIsStaticOverlay) { 874 if (mOverlayPackages == null) { 875 mOverlayPackages = new ArrayList<PackageParser.Package>(); 876 } 877 mOverlayPackages.add(p); 878 } 879 } 880 } 881 } 882 883 @Override 884 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 885 // We can trust mOverlayPackages without holding mPackages because package uninstall 886 // can't happen while running parallel parsing. 887 // Moreover holding mPackages on each parsing thread causes dead-lock. 888 return mOverlayPackages == null ? null : 889 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 890 } 891 } 892 893 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 894 final ParallelPackageParserCallback mParallelPackageParserCallback = 895 new ParallelPackageParserCallback(); 896 897 public static final class SharedLibraryEntry { 898 public final @Nullable String path; 899 public final @Nullable String apk; 900 public final @NonNull SharedLibraryInfo info; 901 902 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 903 String declaringPackageName, int declaringPackageVersionCode) { 904 path = _path; 905 apk = _apk; 906 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 907 declaringPackageName, declaringPackageVersionCode), null); 908 } 909 } 910 911 // Currently known shared libraries. 912 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 913 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 914 new ArrayMap<>(); 915 916 // All available activities, for your resolving pleasure. 917 final ActivityIntentResolver mActivities = 918 new ActivityIntentResolver(); 919 920 // All available receivers, for your resolving pleasure. 921 final ActivityIntentResolver mReceivers = 922 new ActivityIntentResolver(); 923 924 // All available services, for your resolving pleasure. 925 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 926 927 // All available providers, for your resolving pleasure. 928 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 929 930 // Mapping from provider base names (first directory in content URI codePath) 931 // to the provider information. 932 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 933 new ArrayMap<String, PackageParser.Provider>(); 934 935 // Mapping from instrumentation class names to info about them. 936 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 937 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 938 939 // Mapping from permission names to info about them. 940 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 941 new ArrayMap<String, PackageParser.PermissionGroup>(); 942 943 // Packages whose data we have transfered into another package, thus 944 // should no longer exist. 945 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 946 947 // Broadcast actions that are only available to the system. 948 @GuardedBy("mProtectedBroadcasts") 949 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 950 951 /** List of packages waiting for verification. */ 952 final SparseArray<PackageVerificationState> mPendingVerification 953 = new SparseArray<PackageVerificationState>(); 954 955 /** Set of packages associated with each app op permission. */ 956 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 957 958 final PackageInstallerService mInstallerService; 959 960 private final PackageDexOptimizer mPackageDexOptimizer; 961 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 962 // is used by other apps). 963 private final DexManager mDexManager; 964 965 private AtomicInteger mNextMoveId = new AtomicInteger(); 966 private final MoveCallbacks mMoveCallbacks; 967 968 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 969 970 // Cache of users who need badging. 971 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 972 973 /** Token for keys in mPendingVerification. */ 974 private int mPendingVerificationToken = 0; 975 976 volatile boolean mSystemReady; 977 volatile boolean mSafeMode; 978 volatile boolean mHasSystemUidErrors; 979 private volatile boolean mEphemeralAppsDisabled; 980 981 ApplicationInfo mAndroidApplication; 982 final ActivityInfo mResolveActivity = new ActivityInfo(); 983 final ResolveInfo mResolveInfo = new ResolveInfo(); 984 ComponentName mResolveComponentName; 985 PackageParser.Package mPlatformPackage; 986 ComponentName mCustomResolverComponentName; 987 988 boolean mResolverReplaced = false; 989 990 private final @Nullable ComponentName mIntentFilterVerifierComponent; 991 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 992 993 private int mIntentFilterVerificationToken = 0; 994 995 /** The service connection to the ephemeral resolver */ 996 final EphemeralResolverConnection mInstantAppResolverConnection; 997 /** Component used to show resolver settings for Instant Apps */ 998 final ComponentName mInstantAppResolverSettingsComponent; 999 1000 /** Activity used to install instant applications */ 1001 ActivityInfo mInstantAppInstallerActivity; 1002 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 1003 1004 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 1005 = new SparseArray<IntentFilterVerificationState>(); 1006 1007 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 1008 1009 // List of packages names to keep cached, even if they are uninstalled for all users 1010 private List<String> mKeepUninstalledPackages; 1011 1012 private UserManagerInternal mUserManagerInternal; 1013 1014 private DeviceIdleController.LocalService mDeviceIdleController; 1015 1016 private File mCacheDir; 1017 1018 private ArraySet<String> mPrivappPermissionsViolations; 1019 1020 private Future<?> mPrepareAppDataFuture; 1021 1022 private static class IFVerificationParams { 1023 PackageParser.Package pkg; 1024 boolean replacing; 1025 int userId; 1026 int verifierUid; 1027 1028 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1029 int _userId, int _verifierUid) { 1030 pkg = _pkg; 1031 replacing = _replacing; 1032 userId = _userId; 1033 replacing = _replacing; 1034 verifierUid = _verifierUid; 1035 } 1036 } 1037 1038 private interface IntentFilterVerifier<T extends IntentFilter> { 1039 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1040 T filter, String packageName); 1041 void startVerifications(int userId); 1042 void receiveVerificationResponse(int verificationId); 1043 } 1044 1045 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1046 private Context mContext; 1047 private ComponentName mIntentFilterVerifierComponent; 1048 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1049 1050 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1051 mContext = context; 1052 mIntentFilterVerifierComponent = verifierComponent; 1053 } 1054 1055 private String getDefaultScheme() { 1056 return IntentFilter.SCHEME_HTTPS; 1057 } 1058 1059 @Override 1060 public void startVerifications(int userId) { 1061 // Launch verifications requests 1062 int count = mCurrentIntentFilterVerifications.size(); 1063 for (int n=0; n<count; n++) { 1064 int verificationId = mCurrentIntentFilterVerifications.get(n); 1065 final IntentFilterVerificationState ivs = 1066 mIntentFilterVerificationStates.get(verificationId); 1067 1068 String packageName = ivs.getPackageName(); 1069 1070 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1071 final int filterCount = filters.size(); 1072 ArraySet<String> domainsSet = new ArraySet<>(); 1073 for (int m=0; m<filterCount; m++) { 1074 PackageParser.ActivityIntentInfo filter = filters.get(m); 1075 domainsSet.addAll(filter.getHostsList()); 1076 } 1077 synchronized (mPackages) { 1078 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1079 packageName, domainsSet) != null) { 1080 scheduleWriteSettingsLocked(); 1081 } 1082 } 1083 sendVerificationRequest(verificationId, ivs); 1084 } 1085 mCurrentIntentFilterVerifications.clear(); 1086 } 1087 1088 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1089 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1090 verificationIntent.putExtra( 1091 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1092 verificationId); 1093 verificationIntent.putExtra( 1094 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1095 getDefaultScheme()); 1096 verificationIntent.putExtra( 1097 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1098 ivs.getHostsString()); 1099 verificationIntent.putExtra( 1100 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1101 ivs.getPackageName()); 1102 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1103 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1104 1105 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1106 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1107 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1108 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1109 1110 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM); 1111 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1112 "Sending IntentFilter verification broadcast"); 1113 } 1114 1115 public void receiveVerificationResponse(int verificationId) { 1116 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1117 1118 final boolean verified = ivs.isVerified(); 1119 1120 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1121 final int count = filters.size(); 1122 if (DEBUG_DOMAIN_VERIFICATION) { 1123 Slog.i(TAG, "Received verification response " + verificationId 1124 + " for " + count + " filters, verified=" + verified); 1125 } 1126 for (int n=0; n<count; n++) { 1127 PackageParser.ActivityIntentInfo filter = filters.get(n); 1128 filter.setVerified(verified); 1129 1130 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1131 + " verified with result:" + verified + " and hosts:" 1132 + ivs.getHostsString()); 1133 } 1134 1135 mIntentFilterVerificationStates.remove(verificationId); 1136 1137 final String packageName = ivs.getPackageName(); 1138 IntentFilterVerificationInfo ivi = null; 1139 1140 synchronized (mPackages) { 1141 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1142 } 1143 if (ivi == null) { 1144 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1145 + verificationId + " packageName:" + packageName); 1146 return; 1147 } 1148 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1149 "Updating IntentFilterVerificationInfo for package " + packageName 1150 +" verificationId:" + verificationId); 1151 1152 synchronized (mPackages) { 1153 if (verified) { 1154 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1155 } else { 1156 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1157 } 1158 scheduleWriteSettingsLocked(); 1159 1160 final int userId = ivs.getUserId(); 1161 if (userId != UserHandle.USER_ALL) { 1162 final int userStatus = 1163 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1164 1165 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1166 boolean needUpdate = false; 1167 1168 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1169 // already been set by the User thru the Disambiguation dialog 1170 switch (userStatus) { 1171 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1172 if (verified) { 1173 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1174 } else { 1175 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1176 } 1177 needUpdate = true; 1178 break; 1179 1180 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1181 if (verified) { 1182 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1183 needUpdate = true; 1184 } 1185 break; 1186 1187 default: 1188 // Nothing to do 1189 } 1190 1191 if (needUpdate) { 1192 mSettings.updateIntentFilterVerificationStatusLPw( 1193 packageName, updatedStatus, userId); 1194 scheduleWritePackageRestrictionsLocked(userId); 1195 } 1196 } 1197 } 1198 } 1199 1200 @Override 1201 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1202 ActivityIntentInfo filter, String packageName) { 1203 if (!hasValidDomains(filter)) { 1204 return false; 1205 } 1206 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1207 if (ivs == null) { 1208 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1209 packageName); 1210 } 1211 if (DEBUG_DOMAIN_VERIFICATION) { 1212 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1213 } 1214 ivs.addFilter(filter); 1215 return true; 1216 } 1217 1218 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1219 int userId, int verificationId, String packageName) { 1220 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1221 verifierUid, userId, packageName); 1222 ivs.setPendingState(); 1223 synchronized (mPackages) { 1224 mIntentFilterVerificationStates.append(verificationId, ivs); 1225 mCurrentIntentFilterVerifications.add(verificationId); 1226 } 1227 return ivs; 1228 } 1229 } 1230 1231 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1232 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1233 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1234 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1235 } 1236 1237 // Set of pending broadcasts for aggregating enable/disable of components. 1238 static class PendingPackageBroadcasts { 1239 // for each user id, a map of <package name -> components within that package> 1240 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1241 1242 public PendingPackageBroadcasts() { 1243 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1244 } 1245 1246 public ArrayList<String> get(int userId, String packageName) { 1247 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1248 return packages.get(packageName); 1249 } 1250 1251 public void put(int userId, String packageName, ArrayList<String> components) { 1252 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1253 packages.put(packageName, components); 1254 } 1255 1256 public void remove(int userId, String packageName) { 1257 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1258 if (packages != null) { 1259 packages.remove(packageName); 1260 } 1261 } 1262 1263 public void remove(int userId) { 1264 mUidMap.remove(userId); 1265 } 1266 1267 public int userIdCount() { 1268 return mUidMap.size(); 1269 } 1270 1271 public int userIdAt(int n) { 1272 return mUidMap.keyAt(n); 1273 } 1274 1275 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1276 return mUidMap.get(userId); 1277 } 1278 1279 public int size() { 1280 // total number of pending broadcast entries across all userIds 1281 int num = 0; 1282 for (int i = 0; i< mUidMap.size(); i++) { 1283 num += mUidMap.valueAt(i).size(); 1284 } 1285 return num; 1286 } 1287 1288 public void clear() { 1289 mUidMap.clear(); 1290 } 1291 1292 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1293 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1294 if (map == null) { 1295 map = new ArrayMap<String, ArrayList<String>>(); 1296 mUidMap.put(userId, map); 1297 } 1298 return map; 1299 } 1300 } 1301 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1302 1303 // Service Connection to remote media container service to copy 1304 // package uri's from external media onto secure containers 1305 // or internal storage. 1306 private IMediaContainerService mContainerService = null; 1307 1308 static final int SEND_PENDING_BROADCAST = 1; 1309 static final int MCS_BOUND = 3; 1310 static final int END_COPY = 4; 1311 static final int INIT_COPY = 5; 1312 static final int MCS_UNBIND = 6; 1313 static final int START_CLEANING_PACKAGE = 7; 1314 static final int FIND_INSTALL_LOC = 8; 1315 static final int POST_INSTALL = 9; 1316 static final int MCS_RECONNECT = 10; 1317 static final int MCS_GIVE_UP = 11; 1318 static final int UPDATED_MEDIA_STATUS = 12; 1319 static final int WRITE_SETTINGS = 13; 1320 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1321 static final int PACKAGE_VERIFIED = 15; 1322 static final int CHECK_PENDING_VERIFICATION = 16; 1323 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1324 static final int INTENT_FILTER_VERIFIED = 18; 1325 static final int WRITE_PACKAGE_LIST = 19; 1326 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1327 1328 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1329 1330 // Delay time in millisecs 1331 static final int BROADCAST_DELAY = 10 * 1000; 1332 1333 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1334 2 * 60 * 60 * 1000L; /* two hours */ 1335 1336 static UserManagerService sUserManager; 1337 1338 // Stores a list of users whose package restrictions file needs to be updated 1339 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1340 1341 final private DefaultContainerConnection mDefContainerConn = 1342 new DefaultContainerConnection(); 1343 class DefaultContainerConnection implements ServiceConnection { 1344 public void onServiceConnected(ComponentName name, IBinder service) { 1345 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1346 final IMediaContainerService imcs = IMediaContainerService.Stub 1347 .asInterface(Binder.allowBlocking(service)); 1348 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1349 } 1350 1351 public void onServiceDisconnected(ComponentName name) { 1352 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1353 } 1354 } 1355 1356 // Recordkeeping of restore-after-install operations that are currently in flight 1357 // between the Package Manager and the Backup Manager 1358 static class PostInstallData { 1359 public InstallArgs args; 1360 public PackageInstalledInfo res; 1361 1362 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1363 args = _a; 1364 res = _r; 1365 } 1366 } 1367 1368 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1369 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1370 1371 // XML tags for backup/restore of various bits of state 1372 private static final String TAG_PREFERRED_BACKUP = "pa"; 1373 private static final String TAG_DEFAULT_APPS = "da"; 1374 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1375 1376 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1377 private static final String TAG_ALL_GRANTS = "rt-grants"; 1378 private static final String TAG_GRANT = "grant"; 1379 private static final String ATTR_PACKAGE_NAME = "pkg"; 1380 1381 private static final String TAG_PERMISSION = "perm"; 1382 private static final String ATTR_PERMISSION_NAME = "name"; 1383 private static final String ATTR_IS_GRANTED = "g"; 1384 private static final String ATTR_USER_SET = "set"; 1385 private static final String ATTR_USER_FIXED = "fixed"; 1386 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1387 1388 // System/policy permission grants are not backed up 1389 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1390 FLAG_PERMISSION_POLICY_FIXED 1391 | FLAG_PERMISSION_SYSTEM_FIXED 1392 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1393 1394 // And we back up these user-adjusted states 1395 private static final int USER_RUNTIME_GRANT_MASK = 1396 FLAG_PERMISSION_USER_SET 1397 | FLAG_PERMISSION_USER_FIXED 1398 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1399 1400 final @Nullable String mRequiredVerifierPackage; 1401 final @NonNull String mRequiredInstallerPackage; 1402 final @NonNull String mRequiredUninstallerPackage; 1403 final @Nullable String mSetupWizardPackage; 1404 final @Nullable String mStorageManagerPackage; 1405 final @NonNull String mServicesSystemSharedLibraryPackageName; 1406 final @NonNull String mSharedSystemSharedLibraryPackageName; 1407 1408 final boolean mPermissionReviewRequired; 1409 1410 private final PackageUsage mPackageUsage = new PackageUsage(); 1411 private final CompilerStats mCompilerStats = new CompilerStats(); 1412 1413 class PackageHandler extends Handler { 1414 private boolean mBound = false; 1415 final ArrayList<HandlerParams> mPendingInstalls = 1416 new ArrayList<HandlerParams>(); 1417 1418 private boolean connectToService() { 1419 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1420 " DefaultContainerService"); 1421 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1422 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1423 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1424 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1425 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1426 mBound = true; 1427 return true; 1428 } 1429 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1430 return false; 1431 } 1432 1433 private void disconnectService() { 1434 mContainerService = null; 1435 mBound = false; 1436 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1437 mContext.unbindService(mDefContainerConn); 1438 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1439 } 1440 1441 PackageHandler(Looper looper) { 1442 super(looper); 1443 } 1444 1445 public void handleMessage(Message msg) { 1446 try { 1447 doHandleMessage(msg); 1448 } finally { 1449 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1450 } 1451 } 1452 1453 void doHandleMessage(Message msg) { 1454 switch (msg.what) { 1455 case INIT_COPY: { 1456 HandlerParams params = (HandlerParams) msg.obj; 1457 int idx = mPendingInstalls.size(); 1458 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1459 // If a bind was already initiated we dont really 1460 // need to do anything. The pending install 1461 // will be processed later on. 1462 if (!mBound) { 1463 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1464 System.identityHashCode(mHandler)); 1465 // If this is the only one pending we might 1466 // have to bind to the service again. 1467 if (!connectToService()) { 1468 Slog.e(TAG, "Failed to bind to media container service"); 1469 params.serviceError(); 1470 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1471 System.identityHashCode(mHandler)); 1472 if (params.traceMethod != null) { 1473 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1474 params.traceCookie); 1475 } 1476 return; 1477 } else { 1478 // Once we bind to the service, the first 1479 // pending request will be processed. 1480 mPendingInstalls.add(idx, params); 1481 } 1482 } else { 1483 mPendingInstalls.add(idx, params); 1484 // Already bound to the service. Just make 1485 // sure we trigger off processing the first request. 1486 if (idx == 0) { 1487 mHandler.sendEmptyMessage(MCS_BOUND); 1488 } 1489 } 1490 break; 1491 } 1492 case MCS_BOUND: { 1493 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1494 if (msg.obj != null) { 1495 mContainerService = (IMediaContainerService) msg.obj; 1496 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1497 System.identityHashCode(mHandler)); 1498 } 1499 if (mContainerService == null) { 1500 if (!mBound) { 1501 // Something seriously wrong since we are not bound and we are not 1502 // waiting for connection. Bail out. 1503 Slog.e(TAG, "Cannot bind to media container service"); 1504 for (HandlerParams params : mPendingInstalls) { 1505 // Indicate service bind error 1506 params.serviceError(); 1507 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1508 System.identityHashCode(params)); 1509 if (params.traceMethod != null) { 1510 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1511 params.traceMethod, params.traceCookie); 1512 } 1513 return; 1514 } 1515 mPendingInstalls.clear(); 1516 } else { 1517 Slog.w(TAG, "Waiting to connect to media container service"); 1518 } 1519 } else if (mPendingInstalls.size() > 0) { 1520 HandlerParams params = mPendingInstalls.get(0); 1521 if (params != null) { 1522 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1523 System.identityHashCode(params)); 1524 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1525 if (params.startCopy()) { 1526 // We are done... look for more work or to 1527 // go idle. 1528 if (DEBUG_SD_INSTALL) Log.i(TAG, 1529 "Checking for more work or unbind..."); 1530 // Delete pending install 1531 if (mPendingInstalls.size() > 0) { 1532 mPendingInstalls.remove(0); 1533 } 1534 if (mPendingInstalls.size() == 0) { 1535 if (mBound) { 1536 if (DEBUG_SD_INSTALL) Log.i(TAG, 1537 "Posting delayed MCS_UNBIND"); 1538 removeMessages(MCS_UNBIND); 1539 Message ubmsg = obtainMessage(MCS_UNBIND); 1540 // Unbind after a little delay, to avoid 1541 // continual thrashing. 1542 sendMessageDelayed(ubmsg, 10000); 1543 } 1544 } else { 1545 // There are more pending requests in queue. 1546 // Just post MCS_BOUND message to trigger processing 1547 // of next pending install. 1548 if (DEBUG_SD_INSTALL) Log.i(TAG, 1549 "Posting MCS_BOUND for next work"); 1550 mHandler.sendEmptyMessage(MCS_BOUND); 1551 } 1552 } 1553 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1554 } 1555 } else { 1556 // Should never happen ideally. 1557 Slog.w(TAG, "Empty queue"); 1558 } 1559 break; 1560 } 1561 case MCS_RECONNECT: { 1562 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1563 if (mPendingInstalls.size() > 0) { 1564 if (mBound) { 1565 disconnectService(); 1566 } 1567 if (!connectToService()) { 1568 Slog.e(TAG, "Failed to bind to media container service"); 1569 for (HandlerParams params : mPendingInstalls) { 1570 // Indicate service bind error 1571 params.serviceError(); 1572 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1573 System.identityHashCode(params)); 1574 } 1575 mPendingInstalls.clear(); 1576 } 1577 } 1578 break; 1579 } 1580 case MCS_UNBIND: { 1581 // If there is no actual work left, then time to unbind. 1582 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1583 1584 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1585 if (mBound) { 1586 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1587 1588 disconnectService(); 1589 } 1590 } else if (mPendingInstalls.size() > 0) { 1591 // There are more pending requests in queue. 1592 // Just post MCS_BOUND message to trigger processing 1593 // of next pending install. 1594 mHandler.sendEmptyMessage(MCS_BOUND); 1595 } 1596 1597 break; 1598 } 1599 case MCS_GIVE_UP: { 1600 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1601 HandlerParams params = mPendingInstalls.remove(0); 1602 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1603 System.identityHashCode(params)); 1604 break; 1605 } 1606 case SEND_PENDING_BROADCAST: { 1607 String packages[]; 1608 ArrayList<String> components[]; 1609 int size = 0; 1610 int uids[]; 1611 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1612 synchronized (mPackages) { 1613 if (mPendingBroadcasts == null) { 1614 return; 1615 } 1616 size = mPendingBroadcasts.size(); 1617 if (size <= 0) { 1618 // Nothing to be done. Just return 1619 return; 1620 } 1621 packages = new String[size]; 1622 components = new ArrayList[size]; 1623 uids = new int[size]; 1624 int i = 0; // filling out the above arrays 1625 1626 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1627 int packageUserId = mPendingBroadcasts.userIdAt(n); 1628 Iterator<Map.Entry<String, ArrayList<String>>> it 1629 = mPendingBroadcasts.packagesForUserId(packageUserId) 1630 .entrySet().iterator(); 1631 while (it.hasNext() && i < size) { 1632 Map.Entry<String, ArrayList<String>> ent = it.next(); 1633 packages[i] = ent.getKey(); 1634 components[i] = ent.getValue(); 1635 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1636 uids[i] = (ps != null) 1637 ? UserHandle.getUid(packageUserId, ps.appId) 1638 : -1; 1639 i++; 1640 } 1641 } 1642 size = i; 1643 mPendingBroadcasts.clear(); 1644 } 1645 // Send broadcasts 1646 for (int i = 0; i < size; i++) { 1647 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1648 } 1649 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1650 break; 1651 } 1652 case START_CLEANING_PACKAGE: { 1653 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1654 final String packageName = (String)msg.obj; 1655 final int userId = msg.arg1; 1656 final boolean andCode = msg.arg2 != 0; 1657 synchronized (mPackages) { 1658 if (userId == UserHandle.USER_ALL) { 1659 int[] users = sUserManager.getUserIds(); 1660 for (int user : users) { 1661 mSettings.addPackageToCleanLPw( 1662 new PackageCleanItem(user, packageName, andCode)); 1663 } 1664 } else { 1665 mSettings.addPackageToCleanLPw( 1666 new PackageCleanItem(userId, packageName, andCode)); 1667 } 1668 } 1669 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1670 startCleaningPackages(); 1671 } break; 1672 case POST_INSTALL: { 1673 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1674 1675 PostInstallData data = mRunningInstalls.get(msg.arg1); 1676 final boolean didRestore = (msg.arg2 != 0); 1677 mRunningInstalls.delete(msg.arg1); 1678 1679 if (data != null) { 1680 InstallArgs args = data.args; 1681 PackageInstalledInfo parentRes = data.res; 1682 1683 final boolean grantPermissions = (args.installFlags 1684 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1685 final boolean killApp = (args.installFlags 1686 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1687 final boolean virtualPreload = ((args.installFlags 1688 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1689 final String[] grantedPermissions = args.installGrantPermissions; 1690 1691 // Handle the parent package 1692 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1693 virtualPreload, grantedPermissions, didRestore, 1694 args.installerPackageName, args.observer); 1695 1696 // Handle the child packages 1697 final int childCount = (parentRes.addedChildPackages != null) 1698 ? parentRes.addedChildPackages.size() : 0; 1699 for (int i = 0; i < childCount; i++) { 1700 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1701 handlePackagePostInstall(childRes, grantPermissions, killApp, 1702 virtualPreload, grantedPermissions, false /*didRestore*/, 1703 args.installerPackageName, args.observer); 1704 } 1705 1706 // Log tracing if needed 1707 if (args.traceMethod != null) { 1708 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1709 args.traceCookie); 1710 } 1711 } else { 1712 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1713 } 1714 1715 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1716 } break; 1717 case UPDATED_MEDIA_STATUS: { 1718 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1719 boolean reportStatus = msg.arg1 == 1; 1720 boolean doGc = msg.arg2 == 1; 1721 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1722 if (doGc) { 1723 // Force a gc to clear up stale containers. 1724 Runtime.getRuntime().gc(); 1725 } 1726 if (msg.obj != null) { 1727 @SuppressWarnings("unchecked") 1728 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1729 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1730 // Unload containers 1731 unloadAllContainers(args); 1732 } 1733 if (reportStatus) { 1734 try { 1735 if (DEBUG_SD_INSTALL) Log.i(TAG, 1736 "Invoking StorageManagerService call back"); 1737 PackageHelper.getStorageManager().finishMediaUpdate(); 1738 } catch (RemoteException e) { 1739 Log.e(TAG, "StorageManagerService not running?"); 1740 } 1741 } 1742 } break; 1743 case WRITE_SETTINGS: { 1744 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1745 synchronized (mPackages) { 1746 removeMessages(WRITE_SETTINGS); 1747 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1748 mSettings.writeLPr(); 1749 mDirtyUsers.clear(); 1750 } 1751 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1752 } break; 1753 case WRITE_PACKAGE_RESTRICTIONS: { 1754 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1755 synchronized (mPackages) { 1756 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1757 for (int userId : mDirtyUsers) { 1758 mSettings.writePackageRestrictionsLPr(userId); 1759 } 1760 mDirtyUsers.clear(); 1761 } 1762 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1763 } break; 1764 case WRITE_PACKAGE_LIST: { 1765 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1766 synchronized (mPackages) { 1767 removeMessages(WRITE_PACKAGE_LIST); 1768 mSettings.writePackageListLPr(msg.arg1); 1769 } 1770 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1771 } break; 1772 case CHECK_PENDING_VERIFICATION: { 1773 final int verificationId = msg.arg1; 1774 final PackageVerificationState state = mPendingVerification.get(verificationId); 1775 1776 if ((state != null) && !state.timeoutExtended()) { 1777 final InstallArgs args = state.getInstallArgs(); 1778 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1779 1780 Slog.i(TAG, "Verification timed out for " + originUri); 1781 mPendingVerification.remove(verificationId); 1782 1783 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1784 1785 final UserHandle user = args.getUser(); 1786 if (getDefaultVerificationResponse(user) 1787 == PackageManager.VERIFICATION_ALLOW) { 1788 Slog.i(TAG, "Continuing with installation of " + originUri); 1789 state.setVerifierResponse(Binder.getCallingUid(), 1790 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1791 broadcastPackageVerified(verificationId, originUri, 1792 PackageManager.VERIFICATION_ALLOW, user); 1793 try { 1794 ret = args.copyApk(mContainerService, true); 1795 } catch (RemoteException e) { 1796 Slog.e(TAG, "Could not contact the ContainerService"); 1797 } 1798 } else { 1799 broadcastPackageVerified(verificationId, originUri, 1800 PackageManager.VERIFICATION_REJECT, user); 1801 } 1802 1803 Trace.asyncTraceEnd( 1804 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1805 1806 processPendingInstall(args, ret); 1807 mHandler.sendEmptyMessage(MCS_UNBIND); 1808 } 1809 break; 1810 } 1811 case PACKAGE_VERIFIED: { 1812 final int verificationId = msg.arg1; 1813 1814 final PackageVerificationState state = mPendingVerification.get(verificationId); 1815 if (state == null) { 1816 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1817 break; 1818 } 1819 1820 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1821 1822 state.setVerifierResponse(response.callerUid, response.code); 1823 1824 if (state.isVerificationComplete()) { 1825 mPendingVerification.remove(verificationId); 1826 1827 final InstallArgs args = state.getInstallArgs(); 1828 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1829 1830 int ret; 1831 if (state.isInstallAllowed()) { 1832 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1833 broadcastPackageVerified(verificationId, originUri, 1834 response.code, state.getInstallArgs().getUser()); 1835 try { 1836 ret = args.copyApk(mContainerService, true); 1837 } catch (RemoteException e) { 1838 Slog.e(TAG, "Could not contact the ContainerService"); 1839 } 1840 } else { 1841 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1842 } 1843 1844 Trace.asyncTraceEnd( 1845 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1846 1847 processPendingInstall(args, ret); 1848 mHandler.sendEmptyMessage(MCS_UNBIND); 1849 } 1850 1851 break; 1852 } 1853 case START_INTENT_FILTER_VERIFICATIONS: { 1854 IFVerificationParams params = (IFVerificationParams) msg.obj; 1855 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1856 params.replacing, params.pkg); 1857 break; 1858 } 1859 case INTENT_FILTER_VERIFIED: { 1860 final int verificationId = msg.arg1; 1861 1862 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1863 verificationId); 1864 if (state == null) { 1865 Slog.w(TAG, "Invalid IntentFilter verification token " 1866 + verificationId + " received"); 1867 break; 1868 } 1869 1870 final int userId = state.getUserId(); 1871 1872 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1873 "Processing IntentFilter verification with token:" 1874 + verificationId + " and userId:" + userId); 1875 1876 final IntentFilterVerificationResponse response = 1877 (IntentFilterVerificationResponse) msg.obj; 1878 1879 state.setVerifierResponse(response.callerUid, response.code); 1880 1881 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1882 "IntentFilter verification with token:" + verificationId 1883 + " and userId:" + userId 1884 + " is settings verifier response with response code:" 1885 + response.code); 1886 1887 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1888 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1889 + response.getFailedDomainsString()); 1890 } 1891 1892 if (state.isVerificationComplete()) { 1893 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1894 } else { 1895 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1896 "IntentFilter verification with token:" + verificationId 1897 + " was not said to be complete"); 1898 } 1899 1900 break; 1901 } 1902 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1903 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1904 mInstantAppResolverConnection, 1905 (InstantAppRequest) msg.obj, 1906 mInstantAppInstallerActivity, 1907 mHandler); 1908 } 1909 } 1910 } 1911 } 1912 1913 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1914 boolean killApp, boolean virtualPreload, String[] grantedPermissions, 1915 boolean launchedForRestore, String installerPackage, 1916 IPackageInstallObserver2 installObserver) { 1917 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1918 // Send the removed broadcasts 1919 if (res.removedInfo != null) { 1920 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1921 } 1922 1923 // Now that we successfully installed the package, grant runtime 1924 // permissions if requested before broadcasting the install. Also 1925 // for legacy apps in permission review mode we clear the permission 1926 // review flag which is used to emulate runtime permissions for 1927 // legacy apps. 1928 if (grantPermissions) { 1929 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1930 } 1931 1932 final boolean update = res.removedInfo != null 1933 && res.removedInfo.removedPackage != null; 1934 final String installerPackageName = 1935 res.installerPackageName != null 1936 ? res.installerPackageName 1937 : res.removedInfo != null 1938 ? res.removedInfo.installerPackageName 1939 : null; 1940 1941 // If this is the first time we have child packages for a disabled privileged 1942 // app that had no children, we grant requested runtime permissions to the new 1943 // children if the parent on the system image had them already granted. 1944 if (res.pkg.parentPackage != null) { 1945 synchronized (mPackages) { 1946 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1947 } 1948 } 1949 1950 synchronized (mPackages) { 1951 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1952 } 1953 1954 final String packageName = res.pkg.applicationInfo.packageName; 1955 1956 // Determine the set of users who are adding this package for 1957 // the first time vs. those who are seeing an update. 1958 int[] firstUsers = EMPTY_INT_ARRAY; 1959 int[] updateUsers = EMPTY_INT_ARRAY; 1960 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1961 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1962 for (int newUser : res.newUsers) { 1963 if (ps.getInstantApp(newUser)) { 1964 continue; 1965 } 1966 if (allNewUsers) { 1967 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1968 continue; 1969 } 1970 boolean isNew = true; 1971 for (int origUser : res.origUsers) { 1972 if (origUser == newUser) { 1973 isNew = false; 1974 break; 1975 } 1976 } 1977 if (isNew) { 1978 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1979 } else { 1980 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1981 } 1982 } 1983 1984 // Send installed broadcasts if the package is not a static shared lib. 1985 if (res.pkg.staticSharedLibName == null) { 1986 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1987 1988 // Send added for users that see the package for the first time 1989 // sendPackageAddedForNewUsers also deals with system apps 1990 int appId = UserHandle.getAppId(res.uid); 1991 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1992 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 1993 virtualPreload /*startReceiver*/, appId, firstUsers); 1994 1995 // Send added for users that don't see the package for the first time 1996 Bundle extras = new Bundle(1); 1997 extras.putInt(Intent.EXTRA_UID, res.uid); 1998 if (update) { 1999 extras.putBoolean(Intent.EXTRA_REPLACING, true); 2000 } 2001 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2002 extras, 0 /*flags*/, 2003 null /*targetPackage*/, null /*finishedReceiver*/, updateUsers); 2004 if (installerPackageName != null) { 2005 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2006 extras, 0 /*flags*/, 2007 installerPackageName, null /*finishedReceiver*/, updateUsers); 2008 } 2009 2010 // Send replaced for users that don't see the package for the first time 2011 if (update) { 2012 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2013 packageName, extras, 0 /*flags*/, 2014 null /*targetPackage*/, null /*finishedReceiver*/, 2015 updateUsers); 2016 if (installerPackageName != null) { 2017 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2018 extras, 0 /*flags*/, 2019 installerPackageName, null /*finishedReceiver*/, updateUsers); 2020 } 2021 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2022 null /*package*/, null /*extras*/, 0 /*flags*/, 2023 packageName /*targetPackage*/, 2024 null /*finishedReceiver*/, updateUsers); 2025 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2026 // First-install and we did a restore, so we're responsible for the 2027 // first-launch broadcast. 2028 if (DEBUG_BACKUP) { 2029 Slog.i(TAG, "Post-restore of " + packageName 2030 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 2031 } 2032 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 2033 } 2034 2035 // Send broadcast package appeared if forward locked/external for all users 2036 // treat asec-hosted packages like removable media on upgrade 2037 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2038 if (DEBUG_INSTALL) { 2039 Slog.i(TAG, "upgrading pkg " + res.pkg 2040 + " is ASEC-hosted -> AVAILABLE"); 2041 } 2042 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2043 ArrayList<String> pkgList = new ArrayList<>(1); 2044 pkgList.add(packageName); 2045 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2046 } 2047 } 2048 2049 // Work that needs to happen on first install within each user 2050 if (firstUsers != null && firstUsers.length > 0) { 2051 synchronized (mPackages) { 2052 for (int userId : firstUsers) { 2053 // If this app is a browser and it's newly-installed for some 2054 // users, clear any default-browser state in those users. The 2055 // app's nature doesn't depend on the user, so we can just check 2056 // its browser nature in any user and generalize. 2057 if (packageIsBrowser(packageName, userId)) { 2058 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2059 } 2060 2061 // We may also need to apply pending (restored) runtime 2062 // permission grants within these users. 2063 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2064 } 2065 } 2066 } 2067 2068 // Log current value of "unknown sources" setting 2069 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2070 getUnknownSourcesSettings()); 2071 2072 // Remove the replaced package's older resources safely now 2073 // We delete after a gc for applications on sdcard. 2074 if (res.removedInfo != null && res.removedInfo.args != null) { 2075 Runtime.getRuntime().gc(); 2076 synchronized (mInstallLock) { 2077 res.removedInfo.args.doPostDeleteLI(true); 2078 } 2079 } else { 2080 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2081 // and not block here. 2082 VMRuntime.getRuntime().requestConcurrentGC(); 2083 } 2084 2085 // Notify DexManager that the package was installed for new users. 2086 // The updated users should already be indexed and the package code paths 2087 // should not change. 2088 // Don't notify the manager for ephemeral apps as they are not expected to 2089 // survive long enough to benefit of background optimizations. 2090 for (int userId : firstUsers) { 2091 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2092 // There's a race currently where some install events may interleave with an uninstall. 2093 // This can lead to package info being null (b/36642664). 2094 if (info != null) { 2095 mDexManager.notifyPackageInstalled(info, userId); 2096 } 2097 } 2098 } 2099 2100 // If someone is watching installs - notify them 2101 if (installObserver != null) { 2102 try { 2103 Bundle extras = extrasForInstallResult(res); 2104 installObserver.onPackageInstalled(res.name, res.returnCode, 2105 res.returnMsg, extras); 2106 } catch (RemoteException e) { 2107 Slog.i(TAG, "Observer no longer exists."); 2108 } 2109 } 2110 } 2111 2112 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 2113 PackageParser.Package pkg) { 2114 if (pkg.parentPackage == null) { 2115 return; 2116 } 2117 if (pkg.requestedPermissions == null) { 2118 return; 2119 } 2120 final PackageSetting disabledSysParentPs = mSettings 2121 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 2122 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 2123 || !disabledSysParentPs.isPrivileged() 2124 || (disabledSysParentPs.childPackageNames != null 2125 && !disabledSysParentPs.childPackageNames.isEmpty())) { 2126 return; 2127 } 2128 final int[] allUserIds = sUserManager.getUserIds(); 2129 final int permCount = pkg.requestedPermissions.size(); 2130 for (int i = 0; i < permCount; i++) { 2131 String permission = pkg.requestedPermissions.get(i); 2132 BasePermission bp = mSettings.mPermissions.get(permission); 2133 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 2134 continue; 2135 } 2136 for (int userId : allUserIds) { 2137 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2138 permission, userId)) { 2139 grantRuntimePermission(pkg.packageName, permission, userId); 2140 } 2141 } 2142 } 2143 } 2144 2145 private StorageEventListener mStorageListener = new StorageEventListener() { 2146 @Override 2147 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2148 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2149 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2150 final String volumeUuid = vol.getFsUuid(); 2151 2152 // Clean up any users or apps that were removed or recreated 2153 // while this volume was missing 2154 sUserManager.reconcileUsers(volumeUuid); 2155 reconcileApps(volumeUuid); 2156 2157 // Clean up any install sessions that expired or were 2158 // cancelled while this volume was missing 2159 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2160 2161 loadPrivatePackages(vol); 2162 2163 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2164 unloadPrivatePackages(vol); 2165 } 2166 } 2167 2168 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2169 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2170 updateExternalMediaStatus(true, false); 2171 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2172 updateExternalMediaStatus(false, false); 2173 } 2174 } 2175 } 2176 2177 @Override 2178 public void onVolumeForgotten(String fsUuid) { 2179 if (TextUtils.isEmpty(fsUuid)) { 2180 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2181 return; 2182 } 2183 2184 // Remove any apps installed on the forgotten volume 2185 synchronized (mPackages) { 2186 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2187 for (PackageSetting ps : packages) { 2188 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2189 deletePackageVersioned(new VersionedPackage(ps.name, 2190 PackageManager.VERSION_CODE_HIGHEST), 2191 new LegacyPackageDeleteObserver(null).getBinder(), 2192 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2193 // Try very hard to release any references to this package 2194 // so we don't risk the system server being killed due to 2195 // open FDs 2196 AttributeCache.instance().removePackage(ps.name); 2197 } 2198 2199 mSettings.onVolumeForgotten(fsUuid); 2200 mSettings.writeLPr(); 2201 } 2202 } 2203 }; 2204 2205 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2206 String[] grantedPermissions) { 2207 for (int userId : userIds) { 2208 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2209 } 2210 } 2211 2212 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2213 String[] grantedPermissions) { 2214 PackageSetting ps = (PackageSetting) pkg.mExtras; 2215 if (ps == null) { 2216 return; 2217 } 2218 2219 PermissionsState permissionsState = ps.getPermissionsState(); 2220 2221 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2222 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2223 2224 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2225 >= Build.VERSION_CODES.M; 2226 2227 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2228 2229 for (String permission : pkg.requestedPermissions) { 2230 final BasePermission bp; 2231 synchronized (mPackages) { 2232 bp = mSettings.mPermissions.get(permission); 2233 } 2234 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2235 && (!instantApp || bp.isInstant()) 2236 && (supportsRuntimePermissions || !bp.isRuntimeOnly()) 2237 && (grantedPermissions == null 2238 || ArrayUtils.contains(grantedPermissions, permission))) { 2239 final int flags = permissionsState.getPermissionFlags(permission, userId); 2240 if (supportsRuntimePermissions) { 2241 // Installer cannot change immutable permissions. 2242 if ((flags & immutableFlags) == 0) { 2243 grantRuntimePermission(pkg.packageName, permission, userId); 2244 } 2245 } else if (mPermissionReviewRequired) { 2246 // In permission review mode we clear the review flag when we 2247 // are asked to install the app with all permissions granted. 2248 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2249 updatePermissionFlags(permission, pkg.packageName, 2250 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2251 } 2252 } 2253 } 2254 } 2255 } 2256 2257 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2258 Bundle extras = null; 2259 switch (res.returnCode) { 2260 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2261 extras = new Bundle(); 2262 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2263 res.origPermission); 2264 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2265 res.origPackage); 2266 break; 2267 } 2268 case PackageManager.INSTALL_SUCCEEDED: { 2269 extras = new Bundle(); 2270 extras.putBoolean(Intent.EXTRA_REPLACING, 2271 res.removedInfo != null && res.removedInfo.removedPackage != null); 2272 break; 2273 } 2274 } 2275 return extras; 2276 } 2277 2278 void scheduleWriteSettingsLocked() { 2279 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2280 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2281 } 2282 } 2283 2284 void scheduleWritePackageListLocked(int userId) { 2285 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2286 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2287 msg.arg1 = userId; 2288 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2289 } 2290 } 2291 2292 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2293 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2294 scheduleWritePackageRestrictionsLocked(userId); 2295 } 2296 2297 void scheduleWritePackageRestrictionsLocked(int userId) { 2298 final int[] userIds = (userId == UserHandle.USER_ALL) 2299 ? sUserManager.getUserIds() : new int[]{userId}; 2300 for (int nextUserId : userIds) { 2301 if (!sUserManager.exists(nextUserId)) return; 2302 mDirtyUsers.add(nextUserId); 2303 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2304 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2305 } 2306 } 2307 } 2308 2309 public static PackageManagerService main(Context context, Installer installer, 2310 boolean factoryTest, boolean onlyCore) { 2311 // Self-check for initial settings. 2312 PackageManagerServiceCompilerMapping.checkProperties(); 2313 2314 PackageManagerService m = new PackageManagerService(context, installer, 2315 factoryTest, onlyCore); 2316 m.enableSystemUserPackages(); 2317 ServiceManager.addService("package", m); 2318 final PackageManagerNative pmn = m.new PackageManagerNative(); 2319 ServiceManager.addService("package_native", pmn); 2320 return m; 2321 } 2322 2323 private void enableSystemUserPackages() { 2324 if (!UserManager.isSplitSystemUser()) { 2325 return; 2326 } 2327 // For system user, enable apps based on the following conditions: 2328 // - app is whitelisted or belong to one of these groups: 2329 // -- system app which has no launcher icons 2330 // -- system app which has INTERACT_ACROSS_USERS permission 2331 // -- system IME app 2332 // - app is not in the blacklist 2333 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2334 Set<String> enableApps = new ArraySet<>(); 2335 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2336 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2337 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2338 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2339 enableApps.addAll(wlApps); 2340 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2341 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2342 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2343 enableApps.removeAll(blApps); 2344 Log.i(TAG, "Applications installed for system user: " + enableApps); 2345 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2346 UserHandle.SYSTEM); 2347 final int allAppsSize = allAps.size(); 2348 synchronized (mPackages) { 2349 for (int i = 0; i < allAppsSize; i++) { 2350 String pName = allAps.get(i); 2351 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2352 // Should not happen, but we shouldn't be failing if it does 2353 if (pkgSetting == null) { 2354 continue; 2355 } 2356 boolean install = enableApps.contains(pName); 2357 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2358 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2359 + " for system user"); 2360 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2361 } 2362 } 2363 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2364 } 2365 } 2366 2367 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2368 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2369 Context.DISPLAY_SERVICE); 2370 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2371 } 2372 2373 /** 2374 * Requests that files preopted on a secondary system partition be copied to the data partition 2375 * if possible. Note that the actual copying of the files is accomplished by init for security 2376 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2377 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2378 */ 2379 private static void requestCopyPreoptedFiles() { 2380 final int WAIT_TIME_MS = 100; 2381 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2382 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2383 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2384 // We will wait for up to 100 seconds. 2385 final long timeStart = SystemClock.uptimeMillis(); 2386 final long timeEnd = timeStart + 100 * 1000; 2387 long timeNow = timeStart; 2388 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2389 try { 2390 Thread.sleep(WAIT_TIME_MS); 2391 } catch (InterruptedException e) { 2392 // Do nothing 2393 } 2394 timeNow = SystemClock.uptimeMillis(); 2395 if (timeNow > timeEnd) { 2396 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2397 Slog.wtf(TAG, "cppreopt did not finish!"); 2398 break; 2399 } 2400 } 2401 2402 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2403 } 2404 } 2405 2406 public PackageManagerService(Context context, Installer installer, 2407 boolean factoryTest, boolean onlyCore) { 2408 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2409 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2410 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2411 SystemClock.uptimeMillis()); 2412 2413 if (mSdkVersion <= 0) { 2414 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2415 } 2416 2417 mContext = context; 2418 2419 mPermissionReviewRequired = context.getResources().getBoolean( 2420 R.bool.config_permissionReviewRequired); 2421 2422 mFactoryTest = factoryTest; 2423 mOnlyCore = onlyCore; 2424 mMetrics = new DisplayMetrics(); 2425 mSettings = new Settings(mPackages); 2426 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2427 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2428 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2429 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2430 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2431 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2432 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2433 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2434 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2435 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2436 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2437 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2438 2439 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2440 if (separateProcesses != null && separateProcesses.length() > 0) { 2441 if ("*".equals(separateProcesses)) { 2442 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2443 mSeparateProcesses = null; 2444 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2445 } else { 2446 mDefParseFlags = 0; 2447 mSeparateProcesses = separateProcesses.split(","); 2448 Slog.w(TAG, "Running with debug.separate_processes: " 2449 + separateProcesses); 2450 } 2451 } else { 2452 mDefParseFlags = 0; 2453 mSeparateProcesses = null; 2454 } 2455 2456 mInstaller = installer; 2457 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2458 "*dexopt*"); 2459 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2460 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2461 2462 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2463 FgThread.get().getLooper()); 2464 2465 getDefaultDisplayMetrics(context, mMetrics); 2466 2467 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2468 SystemConfig systemConfig = SystemConfig.getInstance(); 2469 mGlobalGids = systemConfig.getGlobalGids(); 2470 mSystemPermissions = systemConfig.getSystemPermissions(); 2471 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2472 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2473 2474 mProtectedPackages = new ProtectedPackages(mContext); 2475 2476 synchronized (mInstallLock) { 2477 // writer 2478 synchronized (mPackages) { 2479 mHandlerThread = new ServiceThread(TAG, 2480 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2481 mHandlerThread.start(); 2482 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2483 mProcessLoggingHandler = new ProcessLoggingHandler(); 2484 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2485 2486 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2487 mInstantAppRegistry = new InstantAppRegistry(this); 2488 2489 File dataDir = Environment.getDataDirectory(); 2490 mAppInstallDir = new File(dataDir, "app"); 2491 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2492 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2493 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2494 sUserManager = new UserManagerService(context, this, 2495 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2496 2497 // Propagate permission configuration in to package manager. 2498 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2499 = systemConfig.getPermissions(); 2500 for (int i=0; i<permConfig.size(); i++) { 2501 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2502 BasePermission bp = mSettings.mPermissions.get(perm.name); 2503 if (bp == null) { 2504 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2505 mSettings.mPermissions.put(perm.name, bp); 2506 } 2507 if (perm.gids != null) { 2508 bp.setGids(perm.gids, perm.perUser); 2509 } 2510 } 2511 2512 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2513 final int builtInLibCount = libConfig.size(); 2514 for (int i = 0; i < builtInLibCount; i++) { 2515 String name = libConfig.keyAt(i); 2516 String path = libConfig.valueAt(i); 2517 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2518 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2519 } 2520 2521 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2522 2523 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2524 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2525 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2526 2527 // Clean up orphaned packages for which the code path doesn't exist 2528 // and they are an update to a system app - caused by bug/32321269 2529 final int packageSettingCount = mSettings.mPackages.size(); 2530 for (int i = packageSettingCount - 1; i >= 0; i--) { 2531 PackageSetting ps = mSettings.mPackages.valueAt(i); 2532 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2533 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2534 mSettings.mPackages.removeAt(i); 2535 mSettings.enableSystemPackageLPw(ps.name); 2536 } 2537 } 2538 2539 if (mFirstBoot) { 2540 requestCopyPreoptedFiles(); 2541 } 2542 2543 String customResolverActivity = Resources.getSystem().getString( 2544 R.string.config_customResolverActivity); 2545 if (TextUtils.isEmpty(customResolverActivity)) { 2546 customResolverActivity = null; 2547 } else { 2548 mCustomResolverComponentName = ComponentName.unflattenFromString( 2549 customResolverActivity); 2550 } 2551 2552 long startTime = SystemClock.uptimeMillis(); 2553 2554 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2555 startTime); 2556 2557 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2558 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2559 2560 if (bootClassPath == null) { 2561 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2562 } 2563 2564 if (systemServerClassPath == null) { 2565 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2566 } 2567 2568 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2569 2570 final VersionInfo ver = mSettings.getInternalVersion(); 2571 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2572 if (mIsUpgrade) { 2573 logCriticalInfo(Log.INFO, 2574 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2575 } 2576 2577 // when upgrading from pre-M, promote system app permissions from install to runtime 2578 mPromoteSystemApps = 2579 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2580 2581 // When upgrading from pre-N, we need to handle package extraction like first boot, 2582 // as there is no profiling data available. 2583 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2584 2585 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2586 2587 // save off the names of pre-existing system packages prior to scanning; we don't 2588 // want to automatically grant runtime permissions for new system apps 2589 if (mPromoteSystemApps) { 2590 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2591 while (pkgSettingIter.hasNext()) { 2592 PackageSetting ps = pkgSettingIter.next(); 2593 if (isSystemApp(ps)) { 2594 mExistingSystemPackages.add(ps.name); 2595 } 2596 } 2597 } 2598 2599 mCacheDir = preparePackageParserCache(mIsUpgrade); 2600 2601 // Set flag to monitor and not change apk file paths when 2602 // scanning install directories. 2603 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2604 2605 if (mIsUpgrade || mFirstBoot) { 2606 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2607 } 2608 2609 // Collect vendor overlay packages. (Do this before scanning any apps.) 2610 // For security and version matching reason, only consider 2611 // overlay packages if they reside in the right directory. 2612 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2613 | PackageParser.PARSE_IS_SYSTEM 2614 | PackageParser.PARSE_IS_SYSTEM_DIR 2615 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2616 2617 mParallelPackageParserCallback.findStaticOverlayPackages(); 2618 2619 // Find base frameworks (resource packages without code). 2620 scanDirTracedLI(frameworkDir, mDefParseFlags 2621 | PackageParser.PARSE_IS_SYSTEM 2622 | PackageParser.PARSE_IS_SYSTEM_DIR 2623 | PackageParser.PARSE_IS_PRIVILEGED, 2624 scanFlags | SCAN_NO_DEX, 0); 2625 2626 // Collected privileged system packages. 2627 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2628 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2629 | PackageParser.PARSE_IS_SYSTEM 2630 | PackageParser.PARSE_IS_SYSTEM_DIR 2631 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2632 2633 // Collect ordinary system packages. 2634 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2635 scanDirTracedLI(systemAppDir, mDefParseFlags 2636 | PackageParser.PARSE_IS_SYSTEM 2637 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2638 2639 // Collect all vendor packages. 2640 File vendorAppDir = new File("/vendor/app"); 2641 try { 2642 vendorAppDir = vendorAppDir.getCanonicalFile(); 2643 } catch (IOException e) { 2644 // failed to look up canonical path, continue with original one 2645 } 2646 scanDirTracedLI(vendorAppDir, mDefParseFlags 2647 | PackageParser.PARSE_IS_SYSTEM 2648 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2649 2650 // Collect all OEM packages. 2651 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2652 scanDirTracedLI(oemAppDir, mDefParseFlags 2653 | PackageParser.PARSE_IS_SYSTEM 2654 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2655 2656 // Prune any system packages that no longer exist. 2657 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2658 // Stub packages must either be replaced with full versions in the /data 2659 // partition or be disabled. 2660 final List<String> stubSystemApps = new ArrayList<>(); 2661 if (!mOnlyCore) { 2662 // do this first before mucking with mPackages for the "expecting better" case 2663 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2664 while (pkgIterator.hasNext()) { 2665 final PackageParser.Package pkg = pkgIterator.next(); 2666 if (pkg.isStub) { 2667 stubSystemApps.add(pkg.packageName); 2668 } 2669 } 2670 2671 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2672 while (psit.hasNext()) { 2673 PackageSetting ps = psit.next(); 2674 2675 /* 2676 * If this is not a system app, it can't be a 2677 * disable system app. 2678 */ 2679 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2680 continue; 2681 } 2682 2683 /* 2684 * If the package is scanned, it's not erased. 2685 */ 2686 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2687 if (scannedPkg != null) { 2688 /* 2689 * If the system app is both scanned and in the 2690 * disabled packages list, then it must have been 2691 * added via OTA. Remove it from the currently 2692 * scanned package so the previously user-installed 2693 * application can be scanned. 2694 */ 2695 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2696 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2697 + ps.name + "; removing system app. Last known codePath=" 2698 + ps.codePathString + ", installStatus=" + ps.installStatus 2699 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2700 + scannedPkg.mVersionCode); 2701 removePackageLI(scannedPkg, true); 2702 mExpectingBetter.put(ps.name, ps.codePath); 2703 } 2704 2705 continue; 2706 } 2707 2708 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2709 psit.remove(); 2710 logCriticalInfo(Log.WARN, "System package " + ps.name 2711 + " no longer exists; it's data will be wiped"); 2712 // Actual deletion of code and data will be handled by later 2713 // reconciliation step 2714 } else { 2715 // we still have a disabled system package, but, it still might have 2716 // been removed. check the code path still exists and check there's 2717 // still a package. the latter can happen if an OTA keeps the same 2718 // code path, but, changes the package name. 2719 final PackageSetting disabledPs = 2720 mSettings.getDisabledSystemPkgLPr(ps.name); 2721 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2722 || disabledPs.pkg == null) { 2723 possiblyDeletedUpdatedSystemApps.add(ps.name); 2724 } 2725 } 2726 } 2727 } 2728 2729 //look for any incomplete package installations 2730 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2731 for (int i = 0; i < deletePkgsList.size(); i++) { 2732 // Actual deletion of code and data will be handled by later 2733 // reconciliation step 2734 final String packageName = deletePkgsList.get(i).name; 2735 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2736 synchronized (mPackages) { 2737 mSettings.removePackageLPw(packageName); 2738 } 2739 } 2740 2741 //delete tmp files 2742 deleteTempPackageFiles(); 2743 2744 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2745 2746 // Remove any shared userIDs that have no associated packages 2747 mSettings.pruneSharedUsersLPw(); 2748 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2749 final int systemPackagesCount = mPackages.size(); 2750 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2751 + " ms, packageCount: " + systemPackagesCount 2752 + " , timePerPackage: " 2753 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2754 + " , cached: " + cachedSystemApps); 2755 if (mIsUpgrade && systemPackagesCount > 0) { 2756 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2757 ((int) systemScanTime) / systemPackagesCount); 2758 } 2759 if (!mOnlyCore) { 2760 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2761 SystemClock.uptimeMillis()); 2762 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2763 2764 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2765 | PackageParser.PARSE_FORWARD_LOCK, 2766 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2767 2768 // Remove disable package settings for updated system apps that were 2769 // removed via an OTA. If the update is no longer present, remove the 2770 // app completely. Otherwise, revoke their system privileges. 2771 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2772 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2773 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2774 2775 final String msg; 2776 if (deletedPkg == null) { 2777 // should have found an update, but, we didn't; remove everything 2778 msg = "Updated system package " + deletedAppName 2779 + " no longer exists; removing its data"; 2780 // Actual deletion of code and data will be handled by later 2781 // reconciliation step 2782 } else { 2783 // found an update; revoke system privileges 2784 msg = "Updated system package + " + deletedAppName 2785 + " no longer exists; revoking system privileges"; 2786 2787 // Don't do anything if a stub is removed from the system image. If 2788 // we were to remove the uncompressed version from the /data partition, 2789 // this is where it'd be done. 2790 2791 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2792 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2793 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2794 } 2795 logCriticalInfo(Log.WARN, msg); 2796 } 2797 2798 /* 2799 * Make sure all system apps that we expected to appear on 2800 * the userdata partition actually showed up. If they never 2801 * appeared, crawl back and revive the system version. 2802 */ 2803 for (int i = 0; i < mExpectingBetter.size(); i++) { 2804 final String packageName = mExpectingBetter.keyAt(i); 2805 if (!mPackages.containsKey(packageName)) { 2806 final File scanFile = mExpectingBetter.valueAt(i); 2807 2808 logCriticalInfo(Log.WARN, "Expected better " + packageName 2809 + " but never showed up; reverting to system"); 2810 2811 int reparseFlags = mDefParseFlags; 2812 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2813 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2814 | PackageParser.PARSE_IS_SYSTEM_DIR 2815 | PackageParser.PARSE_IS_PRIVILEGED; 2816 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2817 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2818 | PackageParser.PARSE_IS_SYSTEM_DIR; 2819 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2820 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2821 | PackageParser.PARSE_IS_SYSTEM_DIR; 2822 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2823 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2824 | PackageParser.PARSE_IS_SYSTEM_DIR; 2825 } else { 2826 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2827 continue; 2828 } 2829 2830 mSettings.enableSystemPackageLPw(packageName); 2831 2832 try { 2833 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2834 } catch (PackageManagerException e) { 2835 Slog.e(TAG, "Failed to parse original system package: " 2836 + e.getMessage()); 2837 } 2838 } 2839 } 2840 2841 // Uncompress and install any stubbed system applications. 2842 // This must be done last to ensure all stubs are replaced or disabled. 2843 decompressSystemApplications(stubSystemApps, scanFlags); 2844 2845 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 2846 - cachedSystemApps; 2847 2848 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 2849 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 2850 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 2851 + " ms, packageCount: " + dataPackagesCount 2852 + " , timePerPackage: " 2853 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 2854 + " , cached: " + cachedNonSystemApps); 2855 if (mIsUpgrade && dataPackagesCount > 0) { 2856 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 2857 ((int) dataScanTime) / dataPackagesCount); 2858 } 2859 } 2860 mExpectingBetter.clear(); 2861 2862 // Resolve the storage manager. 2863 mStorageManagerPackage = getStorageManagerPackageName(); 2864 2865 // Resolve protected action filters. Only the setup wizard is allowed to 2866 // have a high priority filter for these actions. 2867 mSetupWizardPackage = getSetupWizardPackageName(); 2868 if (mProtectedFilters.size() > 0) { 2869 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2870 Slog.i(TAG, "No setup wizard;" 2871 + " All protected intents capped to priority 0"); 2872 } 2873 for (ActivityIntentInfo filter : mProtectedFilters) { 2874 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2875 if (DEBUG_FILTERS) { 2876 Slog.i(TAG, "Found setup wizard;" 2877 + " allow priority " + filter.getPriority() + ";" 2878 + " package: " + filter.activity.info.packageName 2879 + " activity: " + filter.activity.className 2880 + " priority: " + filter.getPriority()); 2881 } 2882 // skip setup wizard; allow it to keep the high priority filter 2883 continue; 2884 } 2885 if (DEBUG_FILTERS) { 2886 Slog.i(TAG, "Protected action; cap priority to 0;" 2887 + " package: " + filter.activity.info.packageName 2888 + " activity: " + filter.activity.className 2889 + " origPrio: " + filter.getPriority()); 2890 } 2891 filter.setPriority(0); 2892 } 2893 } 2894 mDeferProtectedFilters = false; 2895 mProtectedFilters.clear(); 2896 2897 // Now that we know all of the shared libraries, update all clients to have 2898 // the correct library paths. 2899 updateAllSharedLibrariesLPw(null); 2900 2901 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2902 // NOTE: We ignore potential failures here during a system scan (like 2903 // the rest of the commands above) because there's precious little we 2904 // can do about it. A settings error is reported, though. 2905 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2906 } 2907 2908 // Now that we know all the packages we are keeping, 2909 // read and update their last usage times. 2910 mPackageUsage.read(mPackages); 2911 mCompilerStats.read(); 2912 2913 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2914 SystemClock.uptimeMillis()); 2915 Slog.i(TAG, "Time to scan packages: " 2916 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2917 + " seconds"); 2918 2919 // If the platform SDK has changed since the last time we booted, 2920 // we need to re-grant app permission to catch any new ones that 2921 // appear. This is really a hack, and means that apps can in some 2922 // cases get permissions that the user didn't initially explicitly 2923 // allow... it would be nice to have some better way to handle 2924 // this situation. 2925 int updateFlags = UPDATE_PERMISSIONS_ALL; 2926 if (ver.sdkVersion != mSdkVersion) { 2927 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2928 + mSdkVersion + "; regranting permissions for internal storage"); 2929 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2930 } 2931 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2932 ver.sdkVersion = mSdkVersion; 2933 2934 // If this is the first boot or an update from pre-M, and it is a normal 2935 // boot, then we need to initialize the default preferred apps across 2936 // all defined users. 2937 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2938 for (UserInfo user : sUserManager.getUsers(true)) { 2939 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2940 applyFactoryDefaultBrowserLPw(user.id); 2941 primeDomainVerificationsLPw(user.id); 2942 } 2943 } 2944 2945 // Prepare storage for system user really early during boot, 2946 // since core system apps like SettingsProvider and SystemUI 2947 // can't wait for user to start 2948 final int storageFlags; 2949 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2950 storageFlags = StorageManager.FLAG_STORAGE_DE; 2951 } else { 2952 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2953 } 2954 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2955 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2956 true /* onlyCoreApps */); 2957 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2958 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 2959 Trace.TRACE_TAG_PACKAGE_MANAGER); 2960 traceLog.traceBegin("AppDataFixup"); 2961 try { 2962 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2963 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2964 } catch (InstallerException e) { 2965 Slog.w(TAG, "Trouble fixing GIDs", e); 2966 } 2967 traceLog.traceEnd(); 2968 2969 traceLog.traceBegin("AppDataPrepare"); 2970 if (deferPackages == null || deferPackages.isEmpty()) { 2971 return; 2972 } 2973 int count = 0; 2974 for (String pkgName : deferPackages) { 2975 PackageParser.Package pkg = null; 2976 synchronized (mPackages) { 2977 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2978 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2979 pkg = ps.pkg; 2980 } 2981 } 2982 if (pkg != null) { 2983 synchronized (mInstallLock) { 2984 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2985 true /* maybeMigrateAppData */); 2986 } 2987 count++; 2988 } 2989 } 2990 traceLog.traceEnd(); 2991 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2992 }, "prepareAppData"); 2993 2994 // If this is first boot after an OTA, and a normal boot, then 2995 // we need to clear code cache directories. 2996 // Note that we do *not* clear the application profiles. These remain valid 2997 // across OTAs and are used to drive profile verification (post OTA) and 2998 // profile compilation (without waiting to collect a fresh set of profiles). 2999 if (mIsUpgrade && !onlyCore) { 3000 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 3001 for (int i = 0; i < mSettings.mPackages.size(); i++) { 3002 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3003 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 3004 // No apps are running this early, so no need to freeze 3005 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 3006 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 3007 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3008 } 3009 } 3010 ver.fingerprint = Build.FINGERPRINT; 3011 } 3012 3013 checkDefaultBrowser(); 3014 3015 // clear only after permissions and other defaults have been updated 3016 mExistingSystemPackages.clear(); 3017 mPromoteSystemApps = false; 3018 3019 // All the changes are done during package scanning. 3020 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3021 3022 // can downgrade to reader 3023 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3024 mSettings.writeLPr(); 3025 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3026 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3027 SystemClock.uptimeMillis()); 3028 3029 if (!mOnlyCore) { 3030 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3031 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3032 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3033 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3034 if (mIntentFilterVerifierComponent != null) { 3035 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3036 mIntentFilterVerifierComponent); 3037 } else { 3038 mIntentFilterVerifier = null; 3039 } 3040 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3041 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3042 SharedLibraryInfo.VERSION_UNDEFINED); 3043 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3044 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3045 SharedLibraryInfo.VERSION_UNDEFINED); 3046 } else { 3047 mRequiredVerifierPackage = null; 3048 mRequiredInstallerPackage = null; 3049 mRequiredUninstallerPackage = null; 3050 mIntentFilterVerifierComponent = null; 3051 mIntentFilterVerifier = null; 3052 mServicesSystemSharedLibraryPackageName = null; 3053 mSharedSystemSharedLibraryPackageName = null; 3054 } 3055 3056 mInstallerService = new PackageInstallerService(context, this); 3057 final Pair<ComponentName, String> instantAppResolverComponent = 3058 getInstantAppResolverLPr(); 3059 if (instantAppResolverComponent != null) { 3060 if (DEBUG_EPHEMERAL) { 3061 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3062 } 3063 mInstantAppResolverConnection = new EphemeralResolverConnection( 3064 mContext, instantAppResolverComponent.first, 3065 instantAppResolverComponent.second); 3066 mInstantAppResolverSettingsComponent = 3067 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3068 } else { 3069 mInstantAppResolverConnection = null; 3070 mInstantAppResolverSettingsComponent = null; 3071 } 3072 updateInstantAppInstallerLocked(null); 3073 3074 // Read and update the usage of dex files. 3075 // Do this at the end of PM init so that all the packages have their 3076 // data directory reconciled. 3077 // At this point we know the code paths of the packages, so we can validate 3078 // the disk file and build the internal cache. 3079 // The usage file is expected to be small so loading and verifying it 3080 // should take a fairly small time compare to the other activities (e.g. package 3081 // scanning). 3082 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3083 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3084 for (int userId : currentUserIds) { 3085 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3086 } 3087 mDexManager.load(userPackages); 3088 if (mIsUpgrade) { 3089 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3090 (int) (SystemClock.uptimeMillis() - startTime)); 3091 } 3092 } // synchronized (mPackages) 3093 } // synchronized (mInstallLock) 3094 3095 // Now after opening every single application zip, make sure they 3096 // are all flushed. Not really needed, but keeps things nice and 3097 // tidy. 3098 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3099 Runtime.getRuntime().gc(); 3100 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3101 3102 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3103 FallbackCategoryProvider.loadFallbacks(); 3104 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3105 3106 // The initial scanning above does many calls into installd while 3107 // holding the mPackages lock, but we're mostly interested in yelling 3108 // once we have a booted system. 3109 mInstaller.setWarnIfHeld(mPackages); 3110 3111 // Expose private service for system components to use. 3112 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 3113 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3114 } 3115 3116 /** 3117 * Uncompress and install stub applications. 3118 * <p>In order to save space on the system partition, some applications are shipped in a 3119 * compressed form. In addition the compressed bits for the full application, the 3120 * system image contains a tiny stub comprised of only the Android manifest. 3121 * <p>During the first boot, attempt to uncompress and install the full application. If 3122 * the application can't be installed for any reason, disable the stub and prevent 3123 * uncompressing the full application during future boots. 3124 * <p>In order to forcefully attempt an installation of a full application, go to app 3125 * settings and enable the application. 3126 */ 3127 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) { 3128 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3129 final String pkgName = stubSystemApps.get(i); 3130 // skip if the system package is already disabled 3131 if (mSettings.isDisabledSystemPackageLPr(pkgName)) { 3132 stubSystemApps.remove(i); 3133 continue; 3134 } 3135 // skip if the package isn't installed (?!); this should never happen 3136 final PackageParser.Package pkg = mPackages.get(pkgName); 3137 if (pkg == null) { 3138 stubSystemApps.remove(i); 3139 continue; 3140 } 3141 // skip if the package has been disabled by the user 3142 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3143 if (ps != null) { 3144 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3145 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3146 stubSystemApps.remove(i); 3147 continue; 3148 } 3149 } 3150 3151 if (DEBUG_COMPRESSION) { 3152 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName); 3153 } 3154 3155 // uncompress the binary to its eventual destination on /data 3156 final File scanFile = decompressPackage(pkg); 3157 if (scanFile == null) { 3158 continue; 3159 } 3160 3161 // install the package to replace the stub on /system 3162 try { 3163 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/); 3164 removePackageLI(pkg, true /*chatty*/); 3165 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null); 3166 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3167 UserHandle.USER_SYSTEM, "android"); 3168 stubSystemApps.remove(i); 3169 continue; 3170 } catch (PackageManagerException e) { 3171 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3172 } 3173 3174 // any failed attempt to install the package will be cleaned up later 3175 } 3176 3177 // disable any stub still left; these failed to install the full application 3178 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3179 final String pkgName = stubSystemApps.get(i); 3180 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3181 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3182 UserHandle.USER_SYSTEM, "android"); 3183 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3184 } 3185 } 3186 3187 private int decompressFile(File srcFile, File dstFile) throws ErrnoException { 3188 if (DEBUG_COMPRESSION) { 3189 Slog.i(TAG, "Decompress file" 3190 + "; src: " + srcFile.getAbsolutePath() 3191 + ", dst: " + dstFile.getAbsolutePath()); 3192 } 3193 try ( 3194 InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile)); 3195 OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/); 3196 ) { 3197 Streams.copy(fileIn, fileOut); 3198 Os.chmod(dstFile.getAbsolutePath(), 0644); 3199 return PackageManager.INSTALL_SUCCEEDED; 3200 } catch (IOException e) { 3201 logCriticalInfo(Log.ERROR, "Failed to decompress file" 3202 + "; src: " + srcFile.getAbsolutePath() 3203 + ", dst: " + dstFile.getAbsolutePath()); 3204 } 3205 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3206 } 3207 3208 private File[] getCompressedFiles(String codePath) { 3209 final File stubCodePath = new File(codePath); 3210 final String stubName = stubCodePath.getName(); 3211 3212 // The layout of a compressed package on a given partition is as follows : 3213 // 3214 // Compressed artifacts: 3215 // 3216 // /partition/ModuleName/foo.gz 3217 // /partation/ModuleName/bar.gz 3218 // 3219 // Stub artifact: 3220 // 3221 // /partition/ModuleName-Stub/ModuleName-Stub.apk 3222 // 3223 // In other words, stub is on the same partition as the compressed artifacts 3224 // and in a directory that's suffixed with "-Stub". 3225 int idx = stubName.lastIndexOf(STUB_SUFFIX); 3226 if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) { 3227 return null; 3228 } 3229 3230 final File stubParentDir = stubCodePath.getParentFile(); 3231 if (stubParentDir == null) { 3232 Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath); 3233 return null; 3234 } 3235 3236 final File compressedPath = new File(stubParentDir, stubName.substring(0, idx)); 3237 final File[] files = compressedPath.listFiles(new FilenameFilter() { 3238 @Override 3239 public boolean accept(File dir, String name) { 3240 return name.toLowerCase().endsWith(COMPRESSED_EXTENSION); 3241 } 3242 }); 3243 3244 if (DEBUG_COMPRESSION && files != null && files.length > 0) { 3245 Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files)); 3246 } 3247 3248 return files; 3249 } 3250 3251 private boolean compressedFileExists(String codePath) { 3252 final File[] compressedFiles = getCompressedFiles(codePath); 3253 return compressedFiles != null && compressedFiles.length > 0; 3254 } 3255 3256 /** 3257 * Decompresses the given package on the system image onto 3258 * the /data partition. 3259 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3260 */ 3261 private File decompressPackage(PackageParser.Package pkg) { 3262 final File[] compressedFiles = getCompressedFiles(pkg.codePath); 3263 if (compressedFiles == null || compressedFiles.length == 0) { 3264 if (DEBUG_COMPRESSION) { 3265 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath); 3266 } 3267 return null; 3268 } 3269 final File dstCodePath = 3270 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName); 3271 int ret = PackageManager.INSTALL_SUCCEEDED; 3272 try { 3273 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3274 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3275 for (File srcFile : compressedFiles) { 3276 final String srcFileName = srcFile.getName(); 3277 final String dstFileName = srcFileName.substring( 3278 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3279 final File dstFile = new File(dstCodePath, dstFileName); 3280 ret = decompressFile(srcFile, dstFile); 3281 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3282 logCriticalInfo(Log.ERROR, "Failed to decompress" 3283 + "; pkg: " + pkg.packageName 3284 + ", file: " + dstFileName); 3285 break; 3286 } 3287 } 3288 } catch (ErrnoException e) { 3289 logCriticalInfo(Log.ERROR, "Failed to decompress" 3290 + "; pkg: " + pkg.packageName 3291 + ", err: " + e.errno); 3292 } 3293 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3294 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3295 NativeLibraryHelper.Handle handle = null; 3296 try { 3297 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3298 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3299 null /*abiOverride*/); 3300 } catch (IOException e) { 3301 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3302 + "; pkg: " + pkg.packageName); 3303 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3304 } finally { 3305 IoUtils.closeQuietly(handle); 3306 } 3307 } 3308 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3309 if (dstCodePath == null || !dstCodePath.exists()) { 3310 return null; 3311 } 3312 removeCodePathLI(dstCodePath); 3313 return null; 3314 } 3315 3316 return dstCodePath; 3317 } 3318 3319 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3320 // we're only interested in updating the installer appliction when 1) it's not 3321 // already set or 2) the modified package is the installer 3322 if (mInstantAppInstallerActivity != null 3323 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3324 .equals(modifiedPackage)) { 3325 return; 3326 } 3327 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3328 } 3329 3330 private static File preparePackageParserCache(boolean isUpgrade) { 3331 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3332 return null; 3333 } 3334 3335 // Disable package parsing on eng builds to allow for faster incremental development. 3336 if (Build.IS_ENG) { 3337 return null; 3338 } 3339 3340 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3341 Slog.i(TAG, "Disabling package parser cache due to system property."); 3342 return null; 3343 } 3344 3345 // The base directory for the package parser cache lives under /data/system/. 3346 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3347 "package_cache"); 3348 if (cacheBaseDir == null) { 3349 return null; 3350 } 3351 3352 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3353 // This also serves to "GC" unused entries when the package cache version changes (which 3354 // can only happen during upgrades). 3355 if (isUpgrade) { 3356 FileUtils.deleteContents(cacheBaseDir); 3357 } 3358 3359 3360 // Return the versioned package cache directory. This is something like 3361 // "/data/system/package_cache/1" 3362 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3363 3364 // The following is a workaround to aid development on non-numbered userdebug 3365 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3366 // the system partition is newer. 3367 // 3368 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3369 // that starts with "eng." to signify that this is an engineering build and not 3370 // destined for release. 3371 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3372 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3373 3374 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3375 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3376 // in general and should not be used for production changes. In this specific case, 3377 // we know that they will work. 3378 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3379 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3380 FileUtils.deleteContents(cacheBaseDir); 3381 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3382 } 3383 } 3384 3385 return cacheDir; 3386 } 3387 3388 @Override 3389 public boolean isFirstBoot() { 3390 // allow instant applications 3391 return mFirstBoot; 3392 } 3393 3394 @Override 3395 public boolean isOnlyCoreApps() { 3396 // allow instant applications 3397 return mOnlyCore; 3398 } 3399 3400 @Override 3401 public boolean isUpgrade() { 3402 // allow instant applications 3403 return mIsUpgrade; 3404 } 3405 3406 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3407 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3408 3409 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3410 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3411 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3412 if (matches.size() == 1) { 3413 return matches.get(0).getComponentInfo().packageName; 3414 } else if (matches.size() == 0) { 3415 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3416 return null; 3417 } 3418 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3419 } 3420 3421 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3422 synchronized (mPackages) { 3423 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3424 if (libraryEntry == null) { 3425 throw new IllegalStateException("Missing required shared library:" + name); 3426 } 3427 return libraryEntry.apk; 3428 } 3429 } 3430 3431 private @NonNull String getRequiredInstallerLPr() { 3432 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3433 intent.addCategory(Intent.CATEGORY_DEFAULT); 3434 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3435 3436 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3437 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3438 UserHandle.USER_SYSTEM); 3439 if (matches.size() == 1) { 3440 ResolveInfo resolveInfo = matches.get(0); 3441 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3442 throw new RuntimeException("The installer must be a privileged app"); 3443 } 3444 return matches.get(0).getComponentInfo().packageName; 3445 } else { 3446 throw new RuntimeException("There must be exactly one installer; found " + matches); 3447 } 3448 } 3449 3450 private @NonNull String getRequiredUninstallerLPr() { 3451 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3452 intent.addCategory(Intent.CATEGORY_DEFAULT); 3453 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3454 3455 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3456 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3457 UserHandle.USER_SYSTEM); 3458 if (resolveInfo == null || 3459 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3460 throw new RuntimeException("There must be exactly one uninstaller; found " 3461 + resolveInfo); 3462 } 3463 return resolveInfo.getComponentInfo().packageName; 3464 } 3465 3466 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3467 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3468 3469 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3470 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3471 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3472 ResolveInfo best = null; 3473 final int N = matches.size(); 3474 for (int i = 0; i < N; i++) { 3475 final ResolveInfo cur = matches.get(i); 3476 final String packageName = cur.getComponentInfo().packageName; 3477 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3478 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3479 continue; 3480 } 3481 3482 if (best == null || cur.priority > best.priority) { 3483 best = cur; 3484 } 3485 } 3486 3487 if (best != null) { 3488 return best.getComponentInfo().getComponentName(); 3489 } 3490 Slog.w(TAG, "Intent filter verifier not found"); 3491 return null; 3492 } 3493 3494 @Override 3495 public @Nullable ComponentName getInstantAppResolverComponent() { 3496 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3497 return null; 3498 } 3499 synchronized (mPackages) { 3500 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3501 if (instantAppResolver == null) { 3502 return null; 3503 } 3504 return instantAppResolver.first; 3505 } 3506 } 3507 3508 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3509 final String[] packageArray = 3510 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3511 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3512 if (DEBUG_EPHEMERAL) { 3513 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3514 } 3515 return null; 3516 } 3517 3518 final int callingUid = Binder.getCallingUid(); 3519 final int resolveFlags = 3520 MATCH_DIRECT_BOOT_AWARE 3521 | MATCH_DIRECT_BOOT_UNAWARE 3522 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3523 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3524 final Intent resolverIntent = new Intent(actionName); 3525 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3526 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3527 // temporarily look for the old action 3528 if (resolvers.size() == 0) { 3529 if (DEBUG_EPHEMERAL) { 3530 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3531 } 3532 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3533 resolverIntent.setAction(actionName); 3534 resolvers = queryIntentServicesInternal(resolverIntent, null, 3535 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3536 } 3537 final int N = resolvers.size(); 3538 if (N == 0) { 3539 if (DEBUG_EPHEMERAL) { 3540 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3541 } 3542 return null; 3543 } 3544 3545 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3546 for (int i = 0; i < N; i++) { 3547 final ResolveInfo info = resolvers.get(i); 3548 3549 if (info.serviceInfo == null) { 3550 continue; 3551 } 3552 3553 final String packageName = info.serviceInfo.packageName; 3554 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3555 if (DEBUG_EPHEMERAL) { 3556 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3557 + " pkg: " + packageName + ", info:" + info); 3558 } 3559 continue; 3560 } 3561 3562 if (DEBUG_EPHEMERAL) { 3563 Slog.v(TAG, "Ephemeral resolver found;" 3564 + " pkg: " + packageName + ", info:" + info); 3565 } 3566 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3567 } 3568 if (DEBUG_EPHEMERAL) { 3569 Slog.v(TAG, "Ephemeral resolver NOT found"); 3570 } 3571 return null; 3572 } 3573 3574 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3575 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3576 intent.addCategory(Intent.CATEGORY_DEFAULT); 3577 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3578 3579 final int resolveFlags = 3580 MATCH_DIRECT_BOOT_AWARE 3581 | MATCH_DIRECT_BOOT_UNAWARE 3582 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3583 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3584 resolveFlags, UserHandle.USER_SYSTEM); 3585 // temporarily look for the old action 3586 if (matches.isEmpty()) { 3587 if (DEBUG_EPHEMERAL) { 3588 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3589 } 3590 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3591 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3592 resolveFlags, UserHandle.USER_SYSTEM); 3593 } 3594 Iterator<ResolveInfo> iter = matches.iterator(); 3595 while (iter.hasNext()) { 3596 final ResolveInfo rInfo = iter.next(); 3597 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3598 if (ps != null) { 3599 final PermissionsState permissionsState = ps.getPermissionsState(); 3600 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3601 continue; 3602 } 3603 } 3604 iter.remove(); 3605 } 3606 if (matches.size() == 0) { 3607 return null; 3608 } else if (matches.size() == 1) { 3609 return (ActivityInfo) matches.get(0).getComponentInfo(); 3610 } else { 3611 throw new RuntimeException( 3612 "There must be at most one ephemeral installer; found " + matches); 3613 } 3614 } 3615 3616 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3617 @NonNull ComponentName resolver) { 3618 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3619 .addCategory(Intent.CATEGORY_DEFAULT) 3620 .setPackage(resolver.getPackageName()); 3621 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3622 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3623 UserHandle.USER_SYSTEM); 3624 // temporarily look for the old action 3625 if (matches.isEmpty()) { 3626 if (DEBUG_EPHEMERAL) { 3627 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3628 } 3629 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3630 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3631 UserHandle.USER_SYSTEM); 3632 } 3633 if (matches.isEmpty()) { 3634 return null; 3635 } 3636 return matches.get(0).getComponentInfo().getComponentName(); 3637 } 3638 3639 private void primeDomainVerificationsLPw(int userId) { 3640 if (DEBUG_DOMAIN_VERIFICATION) { 3641 Slog.d(TAG, "Priming domain verifications in user " + userId); 3642 } 3643 3644 SystemConfig systemConfig = SystemConfig.getInstance(); 3645 ArraySet<String> packages = systemConfig.getLinkedApps(); 3646 3647 for (String packageName : packages) { 3648 PackageParser.Package pkg = mPackages.get(packageName); 3649 if (pkg != null) { 3650 if (!pkg.isSystemApp()) { 3651 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3652 continue; 3653 } 3654 3655 ArraySet<String> domains = null; 3656 for (PackageParser.Activity a : pkg.activities) { 3657 for (ActivityIntentInfo filter : a.intents) { 3658 if (hasValidDomains(filter)) { 3659 if (domains == null) { 3660 domains = new ArraySet<String>(); 3661 } 3662 domains.addAll(filter.getHostsList()); 3663 } 3664 } 3665 } 3666 3667 if (domains != null && domains.size() > 0) { 3668 if (DEBUG_DOMAIN_VERIFICATION) { 3669 Slog.v(TAG, " + " + packageName); 3670 } 3671 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3672 // state w.r.t. the formal app-linkage "no verification attempted" state; 3673 // and then 'always' in the per-user state actually used for intent resolution. 3674 final IntentFilterVerificationInfo ivi; 3675 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3676 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3677 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3678 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3679 } else { 3680 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3681 + "' does not handle web links"); 3682 } 3683 } else { 3684 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3685 } 3686 } 3687 3688 scheduleWritePackageRestrictionsLocked(userId); 3689 scheduleWriteSettingsLocked(); 3690 } 3691 3692 private void applyFactoryDefaultBrowserLPw(int userId) { 3693 // The default browser app's package name is stored in a string resource, 3694 // with a product-specific overlay used for vendor customization. 3695 String browserPkg = mContext.getResources().getString( 3696 com.android.internal.R.string.default_browser); 3697 if (!TextUtils.isEmpty(browserPkg)) { 3698 // non-empty string => required to be a known package 3699 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3700 if (ps == null) { 3701 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3702 browserPkg = null; 3703 } else { 3704 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3705 } 3706 } 3707 3708 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3709 // default. If there's more than one, just leave everything alone. 3710 if (browserPkg == null) { 3711 calculateDefaultBrowserLPw(userId); 3712 } 3713 } 3714 3715 private void calculateDefaultBrowserLPw(int userId) { 3716 List<String> allBrowsers = resolveAllBrowserApps(userId); 3717 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3718 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3719 } 3720 3721 private List<String> resolveAllBrowserApps(int userId) { 3722 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3723 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3724 PackageManager.MATCH_ALL, userId); 3725 3726 final int count = list.size(); 3727 List<String> result = new ArrayList<String>(count); 3728 for (int i=0; i<count; i++) { 3729 ResolveInfo info = list.get(i); 3730 if (info.activityInfo == null 3731 || !info.handleAllWebDataURI 3732 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3733 || result.contains(info.activityInfo.packageName)) { 3734 continue; 3735 } 3736 result.add(info.activityInfo.packageName); 3737 } 3738 3739 return result; 3740 } 3741 3742 private boolean packageIsBrowser(String packageName, int userId) { 3743 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3744 PackageManager.MATCH_ALL, userId); 3745 final int N = list.size(); 3746 for (int i = 0; i < N; i++) { 3747 ResolveInfo info = list.get(i); 3748 if (packageName.equals(info.activityInfo.packageName)) { 3749 return true; 3750 } 3751 } 3752 return false; 3753 } 3754 3755 private void checkDefaultBrowser() { 3756 final int myUserId = UserHandle.myUserId(); 3757 final String packageName = getDefaultBrowserPackageName(myUserId); 3758 if (packageName != null) { 3759 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3760 if (info == null) { 3761 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3762 synchronized (mPackages) { 3763 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3764 } 3765 } 3766 } 3767 } 3768 3769 @Override 3770 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3771 throws RemoteException { 3772 try { 3773 return super.onTransact(code, data, reply, flags); 3774 } catch (RuntimeException e) { 3775 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3776 Slog.wtf(TAG, "Package Manager Crash", e); 3777 } 3778 throw e; 3779 } 3780 } 3781 3782 static int[] appendInts(int[] cur, int[] add) { 3783 if (add == null) return cur; 3784 if (cur == null) return add; 3785 final int N = add.length; 3786 for (int i=0; i<N; i++) { 3787 cur = appendInt(cur, add[i]); 3788 } 3789 return cur; 3790 } 3791 3792 /** 3793 * Returns whether or not a full application can see an instant application. 3794 * <p> 3795 * Currently, there are three cases in which this can occur: 3796 * <ol> 3797 * <li>The calling application is a "special" process. Special processes 3798 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3799 * <li>The calling application has the permission 3800 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3801 * <li>The calling application is the default launcher on the 3802 * system partition.</li> 3803 * </ol> 3804 */ 3805 private boolean canViewInstantApps(int callingUid, int userId) { 3806 if (callingUid < Process.FIRST_APPLICATION_UID) { 3807 return true; 3808 } 3809 if (mContext.checkCallingOrSelfPermission( 3810 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3811 return true; 3812 } 3813 if (mContext.checkCallingOrSelfPermission( 3814 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3815 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3816 if (homeComponent != null 3817 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3818 return true; 3819 } 3820 } 3821 return false; 3822 } 3823 3824 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3825 if (!sUserManager.exists(userId)) return null; 3826 if (ps == null) { 3827 return null; 3828 } 3829 PackageParser.Package p = ps.pkg; 3830 if (p == null) { 3831 return null; 3832 } 3833 final int callingUid = Binder.getCallingUid(); 3834 // Filter out ephemeral app metadata: 3835 // * The system/shell/root can see metadata for any app 3836 // * An installed app can see metadata for 1) other installed apps 3837 // and 2) ephemeral apps that have explicitly interacted with it 3838 // * Ephemeral apps can only see their own data and exposed installed apps 3839 // * Holding a signature permission allows seeing instant apps 3840 if (filterAppAccessLPr(ps, callingUid, userId)) { 3841 return null; 3842 } 3843 3844 final PermissionsState permissionsState = ps.getPermissionsState(); 3845 3846 // Compute GIDs only if requested 3847 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3848 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3849 // Compute granted permissions only if package has requested permissions 3850 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3851 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3852 final PackageUserState state = ps.readUserState(userId); 3853 3854 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3855 && ps.isSystem()) { 3856 flags |= MATCH_ANY_USER; 3857 } 3858 3859 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3860 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3861 3862 if (packageInfo == null) { 3863 return null; 3864 } 3865 3866 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3867 resolveExternalPackageNameLPr(p); 3868 3869 return packageInfo; 3870 } 3871 3872 @Override 3873 public void checkPackageStartable(String packageName, int userId) { 3874 final int callingUid = Binder.getCallingUid(); 3875 if (getInstantAppPackageName(callingUid) != null) { 3876 throw new SecurityException("Instant applications don't have access to this method"); 3877 } 3878 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3879 synchronized (mPackages) { 3880 final PackageSetting ps = mSettings.mPackages.get(packageName); 3881 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3882 throw new SecurityException("Package " + packageName + " was not found!"); 3883 } 3884 3885 if (!ps.getInstalled(userId)) { 3886 throw new SecurityException( 3887 "Package " + packageName + " was not installed for user " + userId + "!"); 3888 } 3889 3890 if (mSafeMode && !ps.isSystem()) { 3891 throw new SecurityException("Package " + packageName + " not a system app!"); 3892 } 3893 3894 if (mFrozenPackages.contains(packageName)) { 3895 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3896 } 3897 3898 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3899 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3900 } 3901 } 3902 } 3903 3904 @Override 3905 public boolean isPackageAvailable(String packageName, int userId) { 3906 if (!sUserManager.exists(userId)) return false; 3907 final int callingUid = Binder.getCallingUid(); 3908 enforceCrossUserPermission(callingUid, userId, 3909 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3910 synchronized (mPackages) { 3911 PackageParser.Package p = mPackages.get(packageName); 3912 if (p != null) { 3913 final PackageSetting ps = (PackageSetting) p.mExtras; 3914 if (filterAppAccessLPr(ps, callingUid, userId)) { 3915 return false; 3916 } 3917 if (ps != null) { 3918 final PackageUserState state = ps.readUserState(userId); 3919 if (state != null) { 3920 return PackageParser.isAvailable(state); 3921 } 3922 } 3923 } 3924 } 3925 return false; 3926 } 3927 3928 @Override 3929 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3930 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3931 flags, Binder.getCallingUid(), userId); 3932 } 3933 3934 @Override 3935 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3936 int flags, int userId) { 3937 return getPackageInfoInternal(versionedPackage.getPackageName(), 3938 versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId); 3939 } 3940 3941 /** 3942 * Important: The provided filterCallingUid is used exclusively to filter out packages 3943 * that can be seen based on user state. It's typically the original caller uid prior 3944 * to clearing. Because it can only be provided by trusted code, it's value can be 3945 * trusted and will be used as-is; unlike userId which will be validated by this method. 3946 */ 3947 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3948 int flags, int filterCallingUid, int userId) { 3949 if (!sUserManager.exists(userId)) return null; 3950 flags = updateFlagsForPackage(flags, userId, packageName); 3951 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3952 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3953 3954 // reader 3955 synchronized (mPackages) { 3956 // Normalize package name to handle renamed packages and static libs 3957 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3958 3959 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3960 if (matchFactoryOnly) { 3961 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3962 if (ps != null) { 3963 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3964 return null; 3965 } 3966 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3967 return null; 3968 } 3969 return generatePackageInfo(ps, flags, userId); 3970 } 3971 } 3972 3973 PackageParser.Package p = mPackages.get(packageName); 3974 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3975 return null; 3976 } 3977 if (DEBUG_PACKAGE_INFO) 3978 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3979 if (p != null) { 3980 final PackageSetting ps = (PackageSetting) p.mExtras; 3981 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3982 return null; 3983 } 3984 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 3985 return null; 3986 } 3987 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3988 } 3989 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3990 final PackageSetting ps = mSettings.mPackages.get(packageName); 3991 if (ps == null) return null; 3992 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3993 return null; 3994 } 3995 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3996 return null; 3997 } 3998 return generatePackageInfo(ps, flags, userId); 3999 } 4000 } 4001 return null; 4002 } 4003 4004 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 4005 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 4006 return true; 4007 } 4008 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 4009 return true; 4010 } 4011 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 4012 return true; 4013 } 4014 return false; 4015 } 4016 4017 private boolean isComponentVisibleToInstantApp( 4018 @Nullable ComponentName component, @ComponentType int type) { 4019 if (type == TYPE_ACTIVITY) { 4020 final PackageParser.Activity activity = mActivities.mActivities.get(component); 4021 return activity != null 4022 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4023 : false; 4024 } else if (type == TYPE_RECEIVER) { 4025 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 4026 return activity != null 4027 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4028 : false; 4029 } else if (type == TYPE_SERVICE) { 4030 final PackageParser.Service service = mServices.mServices.get(component); 4031 return service != null 4032 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4033 : false; 4034 } else if (type == TYPE_PROVIDER) { 4035 final PackageParser.Provider provider = mProviders.mProviders.get(component); 4036 return provider != null 4037 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4038 : false; 4039 } else if (type == TYPE_UNKNOWN) { 4040 return isComponentVisibleToInstantApp(component); 4041 } 4042 return false; 4043 } 4044 4045 /** 4046 * Returns whether or not access to the application should be filtered. 4047 * <p> 4048 * Access may be limited based upon whether the calling or target applications 4049 * are instant applications. 4050 * 4051 * @see #canAccessInstantApps(int) 4052 */ 4053 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4054 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4055 // if we're in an isolated process, get the real calling UID 4056 if (Process.isIsolated(callingUid)) { 4057 callingUid = mIsolatedOwners.get(callingUid); 4058 } 4059 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4060 final boolean callerIsInstantApp = instantAppPkgName != null; 4061 if (ps == null) { 4062 if (callerIsInstantApp) { 4063 // pretend the application exists, but, needs to be filtered 4064 return true; 4065 } 4066 return false; 4067 } 4068 // if the target and caller are the same application, don't filter 4069 if (isCallerSameApp(ps.name, callingUid)) { 4070 return false; 4071 } 4072 if (callerIsInstantApp) { 4073 // request for a specific component; if it hasn't been explicitly exposed, filter 4074 if (component != null) { 4075 return !isComponentVisibleToInstantApp(component, componentType); 4076 } 4077 // request for application; if no components have been explicitly exposed, filter 4078 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps; 4079 } 4080 if (ps.getInstantApp(userId)) { 4081 // caller can see all components of all instant applications, don't filter 4082 if (canViewInstantApps(callingUid, userId)) { 4083 return false; 4084 } 4085 // request for a specific instant application component, filter 4086 if (component != null) { 4087 return true; 4088 } 4089 // request for an instant application; if the caller hasn't been granted access, filter 4090 return !mInstantAppRegistry.isInstantAccessGranted( 4091 userId, UserHandle.getAppId(callingUid), ps.appId); 4092 } 4093 return false; 4094 } 4095 4096 /** 4097 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4098 */ 4099 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4100 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4101 } 4102 4103 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4104 int flags) { 4105 // Callers can access only the libs they depend on, otherwise they need to explicitly 4106 // ask for the shared libraries given the caller is allowed to access all static libs. 4107 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4108 // System/shell/root get to see all static libs 4109 final int appId = UserHandle.getAppId(uid); 4110 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4111 || appId == Process.ROOT_UID) { 4112 return false; 4113 } 4114 } 4115 4116 // No package means no static lib as it is always on internal storage 4117 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4118 return false; 4119 } 4120 4121 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4122 ps.pkg.staticSharedLibVersion); 4123 if (libEntry == null) { 4124 return false; 4125 } 4126 4127 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4128 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4129 if (uidPackageNames == null) { 4130 return true; 4131 } 4132 4133 for (String uidPackageName : uidPackageNames) { 4134 if (ps.name.equals(uidPackageName)) { 4135 return false; 4136 } 4137 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4138 if (uidPs != null) { 4139 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4140 libEntry.info.getName()); 4141 if (index < 0) { 4142 continue; 4143 } 4144 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 4145 return false; 4146 } 4147 } 4148 } 4149 return true; 4150 } 4151 4152 @Override 4153 public String[] currentToCanonicalPackageNames(String[] names) { 4154 final int callingUid = Binder.getCallingUid(); 4155 if (getInstantAppPackageName(callingUid) != null) { 4156 return names; 4157 } 4158 final String[] out = new String[names.length]; 4159 // reader 4160 synchronized (mPackages) { 4161 final int callingUserId = UserHandle.getUserId(callingUid); 4162 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4163 for (int i=names.length-1; i>=0; i--) { 4164 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4165 boolean translateName = false; 4166 if (ps != null && ps.realName != null) { 4167 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4168 translateName = !targetIsInstantApp 4169 || canViewInstantApps 4170 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4171 UserHandle.getAppId(callingUid), ps.appId); 4172 } 4173 out[i] = translateName ? ps.realName : names[i]; 4174 } 4175 } 4176 return out; 4177 } 4178 4179 @Override 4180 public String[] canonicalToCurrentPackageNames(String[] names) { 4181 final int callingUid = Binder.getCallingUid(); 4182 if (getInstantAppPackageName(callingUid) != null) { 4183 return names; 4184 } 4185 final String[] out = new String[names.length]; 4186 // reader 4187 synchronized (mPackages) { 4188 final int callingUserId = UserHandle.getUserId(callingUid); 4189 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4190 for (int i=names.length-1; i>=0; i--) { 4191 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4192 boolean translateName = false; 4193 if (cur != null) { 4194 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4195 final boolean targetIsInstantApp = 4196 ps != null && ps.getInstantApp(callingUserId); 4197 translateName = !targetIsInstantApp 4198 || canViewInstantApps 4199 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4200 UserHandle.getAppId(callingUid), ps.appId); 4201 } 4202 out[i] = translateName ? cur : names[i]; 4203 } 4204 } 4205 return out; 4206 } 4207 4208 @Override 4209 public int getPackageUid(String packageName, int flags, int userId) { 4210 if (!sUserManager.exists(userId)) return -1; 4211 final int callingUid = Binder.getCallingUid(); 4212 flags = updateFlagsForPackage(flags, userId, packageName); 4213 enforceCrossUserPermission(callingUid, userId, 4214 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4215 4216 // reader 4217 synchronized (mPackages) { 4218 final PackageParser.Package p = mPackages.get(packageName); 4219 if (p != null && p.isMatch(flags)) { 4220 PackageSetting ps = (PackageSetting) p.mExtras; 4221 if (filterAppAccessLPr(ps, callingUid, userId)) { 4222 return -1; 4223 } 4224 return UserHandle.getUid(userId, p.applicationInfo.uid); 4225 } 4226 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4227 final PackageSetting ps = mSettings.mPackages.get(packageName); 4228 if (ps != null && ps.isMatch(flags) 4229 && !filterAppAccessLPr(ps, callingUid, userId)) { 4230 return UserHandle.getUid(userId, ps.appId); 4231 } 4232 } 4233 } 4234 4235 return -1; 4236 } 4237 4238 @Override 4239 public int[] getPackageGids(String packageName, int flags, int userId) { 4240 if (!sUserManager.exists(userId)) return null; 4241 final int callingUid = Binder.getCallingUid(); 4242 flags = updateFlagsForPackage(flags, userId, packageName); 4243 enforceCrossUserPermission(callingUid, userId, 4244 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4245 4246 // reader 4247 synchronized (mPackages) { 4248 final PackageParser.Package p = mPackages.get(packageName); 4249 if (p != null && p.isMatch(flags)) { 4250 PackageSetting ps = (PackageSetting) p.mExtras; 4251 if (filterAppAccessLPr(ps, callingUid, userId)) { 4252 return null; 4253 } 4254 // TODO: Shouldn't this be checking for package installed state for userId and 4255 // return null? 4256 return ps.getPermissionsState().computeGids(userId); 4257 } 4258 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4259 final PackageSetting ps = mSettings.mPackages.get(packageName); 4260 if (ps != null && ps.isMatch(flags) 4261 && !filterAppAccessLPr(ps, callingUid, userId)) { 4262 return ps.getPermissionsState().computeGids(userId); 4263 } 4264 } 4265 } 4266 4267 return null; 4268 } 4269 4270 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 4271 if (bp.perm != null) { 4272 return PackageParser.generatePermissionInfo(bp.perm, flags); 4273 } 4274 PermissionInfo pi = new PermissionInfo(); 4275 pi.name = bp.name; 4276 pi.packageName = bp.sourcePackage; 4277 pi.nonLocalizedLabel = bp.name; 4278 pi.protectionLevel = bp.protectionLevel; 4279 return pi; 4280 } 4281 4282 @Override 4283 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4284 final int callingUid = Binder.getCallingUid(); 4285 if (getInstantAppPackageName(callingUid) != null) { 4286 return null; 4287 } 4288 // reader 4289 synchronized (mPackages) { 4290 final BasePermission p = mSettings.mPermissions.get(name); 4291 if (p == null) { 4292 return null; 4293 } 4294 // If the caller is an app that targets pre 26 SDK drop protection flags. 4295 PermissionInfo permissionInfo = generatePermissionInfo(p, flags); 4296 if (permissionInfo != null) { 4297 final int protectionLevel = adjustPermissionProtectionFlagsLPr( 4298 permissionInfo.protectionLevel, packageName, callingUid); 4299 if (permissionInfo.protectionLevel != protectionLevel) { 4300 // If we return different protection level, don't use the cached info 4301 if (p.perm != null && p.perm.info == permissionInfo) { 4302 permissionInfo = new PermissionInfo(permissionInfo); 4303 } 4304 permissionInfo.protectionLevel = protectionLevel; 4305 } 4306 } 4307 return permissionInfo; 4308 } 4309 } 4310 4311 private int adjustPermissionProtectionFlagsLPr(int protectionLevel, 4312 String packageName, int uid) { 4313 // Signature permission flags area always reported 4314 final int protectionLevelMasked = protectionLevel 4315 & (PermissionInfo.PROTECTION_NORMAL 4316 | PermissionInfo.PROTECTION_DANGEROUS 4317 | PermissionInfo.PROTECTION_SIGNATURE); 4318 if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) { 4319 return protectionLevel; 4320 } 4321 4322 // System sees all flags. 4323 final int appId = UserHandle.getAppId(uid); 4324 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID 4325 || appId == Process.SHELL_UID) { 4326 return protectionLevel; 4327 } 4328 4329 // Normalize package name to handle renamed packages and static libs 4330 packageName = resolveInternalPackageNameLPr(packageName, 4331 PackageManager.VERSION_CODE_HIGHEST); 4332 4333 // Apps that target O see flags for all protection levels. 4334 final PackageSetting ps = mSettings.mPackages.get(packageName); 4335 if (ps == null) { 4336 return protectionLevel; 4337 } 4338 if (ps.appId != appId) { 4339 return protectionLevel; 4340 } 4341 4342 final PackageParser.Package pkg = mPackages.get(packageName); 4343 if (pkg == null) { 4344 return protectionLevel; 4345 } 4346 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 4347 return protectionLevelMasked; 4348 } 4349 4350 return protectionLevel; 4351 } 4352 4353 @Override 4354 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 4355 int flags) { 4356 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4357 return null; 4358 } 4359 // reader 4360 synchronized (mPackages) { 4361 if (group != null && !mPermissionGroups.containsKey(group)) { 4362 // This is thrown as NameNotFoundException 4363 return null; 4364 } 4365 4366 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 4367 for (BasePermission p : mSettings.mPermissions.values()) { 4368 if (group == null) { 4369 if (p.perm == null || p.perm.info.group == null) { 4370 out.add(generatePermissionInfo(p, flags)); 4371 } 4372 } else { 4373 if (p.perm != null && group.equals(p.perm.info.group)) { 4374 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 4375 } 4376 } 4377 } 4378 return new ParceledListSlice<>(out); 4379 } 4380 } 4381 4382 @Override 4383 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 4384 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4385 return null; 4386 } 4387 // reader 4388 synchronized (mPackages) { 4389 return PackageParser.generatePermissionGroupInfo( 4390 mPermissionGroups.get(name), flags); 4391 } 4392 } 4393 4394 @Override 4395 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4396 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4397 return ParceledListSlice.emptyList(); 4398 } 4399 // reader 4400 synchronized (mPackages) { 4401 final int N = mPermissionGroups.size(); 4402 ArrayList<PermissionGroupInfo> out 4403 = new ArrayList<PermissionGroupInfo>(N); 4404 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 4405 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 4406 } 4407 return new ParceledListSlice<>(out); 4408 } 4409 } 4410 4411 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4412 int filterCallingUid, int userId) { 4413 if (!sUserManager.exists(userId)) return null; 4414 PackageSetting ps = mSettings.mPackages.get(packageName); 4415 if (ps != null) { 4416 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4417 return null; 4418 } 4419 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4420 return null; 4421 } 4422 if (ps.pkg == null) { 4423 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4424 if (pInfo != null) { 4425 return pInfo.applicationInfo; 4426 } 4427 return null; 4428 } 4429 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4430 ps.readUserState(userId), userId); 4431 if (ai != null) { 4432 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4433 } 4434 return ai; 4435 } 4436 return null; 4437 } 4438 4439 @Override 4440 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4441 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4442 } 4443 4444 /** 4445 * Important: The provided filterCallingUid is used exclusively to filter out applications 4446 * that can be seen based on user state. It's typically the original caller uid prior 4447 * to clearing. Because it can only be provided by trusted code, it's value can be 4448 * trusted and will be used as-is; unlike userId which will be validated by this method. 4449 */ 4450 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4451 int filterCallingUid, int userId) { 4452 if (!sUserManager.exists(userId)) return null; 4453 flags = updateFlagsForApplication(flags, userId, packageName); 4454 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4455 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4456 4457 // writer 4458 synchronized (mPackages) { 4459 // Normalize package name to handle renamed packages and static libs 4460 packageName = resolveInternalPackageNameLPr(packageName, 4461 PackageManager.VERSION_CODE_HIGHEST); 4462 4463 PackageParser.Package p = mPackages.get(packageName); 4464 if (DEBUG_PACKAGE_INFO) Log.v( 4465 TAG, "getApplicationInfo " + packageName 4466 + ": " + p); 4467 if (p != null) { 4468 PackageSetting ps = mSettings.mPackages.get(packageName); 4469 if (ps == null) return null; 4470 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4471 return null; 4472 } 4473 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4474 return null; 4475 } 4476 // Note: isEnabledLP() does not apply here - always return info 4477 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4478 p, flags, ps.readUserState(userId), userId); 4479 if (ai != null) { 4480 ai.packageName = resolveExternalPackageNameLPr(p); 4481 } 4482 return ai; 4483 } 4484 if ("android".equals(packageName)||"system".equals(packageName)) { 4485 return mAndroidApplication; 4486 } 4487 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4488 // Already generates the external package name 4489 return generateApplicationInfoFromSettingsLPw(packageName, 4490 flags, filterCallingUid, userId); 4491 } 4492 } 4493 return null; 4494 } 4495 4496 private String normalizePackageNameLPr(String packageName) { 4497 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4498 return normalizedPackageName != null ? normalizedPackageName : packageName; 4499 } 4500 4501 @Override 4502 public void deletePreloadsFileCache() { 4503 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4504 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4505 } 4506 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4507 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4508 FileUtils.deleteContents(dir); 4509 } 4510 4511 @Override 4512 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4513 final int storageFlags, final IPackageDataObserver observer) { 4514 mContext.enforceCallingOrSelfPermission( 4515 android.Manifest.permission.CLEAR_APP_CACHE, null); 4516 mHandler.post(() -> { 4517 boolean success = false; 4518 try { 4519 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4520 success = true; 4521 } catch (IOException e) { 4522 Slog.w(TAG, e); 4523 } 4524 if (observer != null) { 4525 try { 4526 observer.onRemoveCompleted(null, success); 4527 } catch (RemoteException e) { 4528 Slog.w(TAG, e); 4529 } 4530 } 4531 }); 4532 } 4533 4534 @Override 4535 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4536 final int storageFlags, final IntentSender pi) { 4537 mContext.enforceCallingOrSelfPermission( 4538 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4539 mHandler.post(() -> { 4540 boolean success = false; 4541 try { 4542 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4543 success = true; 4544 } catch (IOException e) { 4545 Slog.w(TAG, e); 4546 } 4547 if (pi != null) { 4548 try { 4549 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4550 } catch (SendIntentException e) { 4551 Slog.w(TAG, e); 4552 } 4553 } 4554 }); 4555 } 4556 4557 /** 4558 * Blocking call to clear various types of cached data across the system 4559 * until the requested bytes are available. 4560 */ 4561 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4562 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4563 final File file = storage.findPathForUuid(volumeUuid); 4564 if (file.getUsableSpace() >= bytes) return; 4565 4566 if (ENABLE_FREE_CACHE_V2) { 4567 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4568 volumeUuid); 4569 final boolean aggressive = (storageFlags 4570 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4571 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4572 4573 // 1. Pre-flight to determine if we have any chance to succeed 4574 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4575 if (internalVolume && (aggressive || SystemProperties 4576 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4577 deletePreloadsFileCache(); 4578 if (file.getUsableSpace() >= bytes) return; 4579 } 4580 4581 // 3. Consider parsed APK data (aggressive only) 4582 if (internalVolume && aggressive) { 4583 FileUtils.deleteContents(mCacheDir); 4584 if (file.getUsableSpace() >= bytes) return; 4585 } 4586 4587 // 4. Consider cached app data (above quotas) 4588 try { 4589 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4590 Installer.FLAG_FREE_CACHE_V2); 4591 } catch (InstallerException ignored) { 4592 } 4593 if (file.getUsableSpace() >= bytes) return; 4594 4595 // 5. Consider shared libraries with refcount=0 and age>min cache period 4596 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4597 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4598 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4599 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4600 return; 4601 } 4602 4603 // 6. Consider dexopt output (aggressive only) 4604 // TODO: Implement 4605 4606 // 7. Consider installed instant apps unused longer than min cache period 4607 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4608 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4609 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4610 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4611 return; 4612 } 4613 4614 // 8. Consider cached app data (below quotas) 4615 try { 4616 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4617 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4618 } catch (InstallerException ignored) { 4619 } 4620 if (file.getUsableSpace() >= bytes) return; 4621 4622 // 9. Consider DropBox entries 4623 // TODO: Implement 4624 4625 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4626 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4627 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4628 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4629 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4630 return; 4631 } 4632 } else { 4633 try { 4634 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4635 } catch (InstallerException ignored) { 4636 } 4637 if (file.getUsableSpace() >= bytes) return; 4638 } 4639 4640 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4641 } 4642 4643 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4644 throws IOException { 4645 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4646 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4647 4648 List<VersionedPackage> packagesToDelete = null; 4649 final long now = System.currentTimeMillis(); 4650 4651 synchronized (mPackages) { 4652 final int[] allUsers = sUserManager.getUserIds(); 4653 final int libCount = mSharedLibraries.size(); 4654 for (int i = 0; i < libCount; i++) { 4655 final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4656 if (versionedLib == null) { 4657 continue; 4658 } 4659 final int versionCount = versionedLib.size(); 4660 for (int j = 0; j < versionCount; j++) { 4661 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4662 // Skip packages that are not static shared libs. 4663 if (!libInfo.isStatic()) { 4664 break; 4665 } 4666 // Important: We skip static shared libs used for some user since 4667 // in such a case we need to keep the APK on the device. The check for 4668 // a lib being used for any user is performed by the uninstall call. 4669 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4670 // Resolve the package name - we use synthetic package names internally 4671 final String internalPackageName = resolveInternalPackageNameLPr( 4672 declaringPackage.getPackageName(), declaringPackage.getVersionCode()); 4673 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4674 // Skip unused static shared libs cached less than the min period 4675 // to prevent pruning a lib needed by a subsequently installed package. 4676 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4677 continue; 4678 } 4679 if (packagesToDelete == null) { 4680 packagesToDelete = new ArrayList<>(); 4681 } 4682 packagesToDelete.add(new VersionedPackage(internalPackageName, 4683 declaringPackage.getVersionCode())); 4684 } 4685 } 4686 } 4687 4688 if (packagesToDelete != null) { 4689 final int packageCount = packagesToDelete.size(); 4690 for (int i = 0; i < packageCount; i++) { 4691 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4692 // Delete the package synchronously (will fail of the lib used for any user). 4693 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(), 4694 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4695 == PackageManager.DELETE_SUCCEEDED) { 4696 if (volume.getUsableSpace() >= neededSpace) { 4697 return true; 4698 } 4699 } 4700 } 4701 } 4702 4703 return false; 4704 } 4705 4706 /** 4707 * Update given flags based on encryption status of current user. 4708 */ 4709 private int updateFlags(int flags, int userId) { 4710 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4711 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4712 // Caller expressed an explicit opinion about what encryption 4713 // aware/unaware components they want to see, so fall through and 4714 // give them what they want 4715 } else { 4716 // Caller expressed no opinion, so match based on user state 4717 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4718 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4719 } else { 4720 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4721 } 4722 } 4723 return flags; 4724 } 4725 4726 private UserManagerInternal getUserManagerInternal() { 4727 if (mUserManagerInternal == null) { 4728 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4729 } 4730 return mUserManagerInternal; 4731 } 4732 4733 private DeviceIdleController.LocalService getDeviceIdleController() { 4734 if (mDeviceIdleController == null) { 4735 mDeviceIdleController = 4736 LocalServices.getService(DeviceIdleController.LocalService.class); 4737 } 4738 return mDeviceIdleController; 4739 } 4740 4741 /** 4742 * Update given flags when being used to request {@link PackageInfo}. 4743 */ 4744 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4745 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4746 boolean triaged = true; 4747 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4748 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4749 // Caller is asking for component details, so they'd better be 4750 // asking for specific encryption matching behavior, or be triaged 4751 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4752 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4753 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4754 triaged = false; 4755 } 4756 } 4757 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4758 | PackageManager.MATCH_SYSTEM_ONLY 4759 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4760 triaged = false; 4761 } 4762 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4763 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 4764 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4765 + Debug.getCallers(5)); 4766 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4767 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4768 // If the caller wants all packages and has a restricted profile associated with it, 4769 // then match all users. This is to make sure that launchers that need to access work 4770 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4771 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4772 flags |= PackageManager.MATCH_ANY_USER; 4773 } 4774 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4775 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4776 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4777 } 4778 return updateFlags(flags, userId); 4779 } 4780 4781 /** 4782 * Update given flags when being used to request {@link ApplicationInfo}. 4783 */ 4784 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4785 return updateFlagsForPackage(flags, userId, cookie); 4786 } 4787 4788 /** 4789 * Update given flags when being used to request {@link ComponentInfo}. 4790 */ 4791 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4792 if (cookie instanceof Intent) { 4793 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4794 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4795 } 4796 } 4797 4798 boolean triaged = true; 4799 // Caller is asking for component details, so they'd better be 4800 // asking for specific encryption matching behavior, or be triaged 4801 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4802 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4803 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4804 triaged = false; 4805 } 4806 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4807 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4808 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4809 } 4810 4811 return updateFlags(flags, userId); 4812 } 4813 4814 /** 4815 * Update given intent when being used to request {@link ResolveInfo}. 4816 */ 4817 private Intent updateIntentForResolve(Intent intent) { 4818 if (intent.getSelector() != null) { 4819 intent = intent.getSelector(); 4820 } 4821 if (DEBUG_PREFERRED) { 4822 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4823 } 4824 return intent; 4825 } 4826 4827 /** 4828 * Update given flags when being used to request {@link ResolveInfo}. 4829 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4830 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4831 * flag set. However, this flag is only honoured in three circumstances: 4832 * <ul> 4833 * <li>when called from a system process</li> 4834 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4835 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4836 * action and a {@code android.intent.category.BROWSABLE} category</li> 4837 * </ul> 4838 */ 4839 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4840 return updateFlagsForResolve(flags, userId, intent, callingUid, 4841 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4842 } 4843 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4844 boolean wantInstantApps) { 4845 return updateFlagsForResolve(flags, userId, intent, callingUid, 4846 wantInstantApps, false /*onlyExposedExplicitly*/); 4847 } 4848 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4849 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4850 // Safe mode means we shouldn't match any third-party components 4851 if (mSafeMode) { 4852 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4853 } 4854 if (getInstantAppPackageName(callingUid) != null) { 4855 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4856 if (onlyExposedExplicitly) { 4857 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4858 } 4859 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4860 flags |= PackageManager.MATCH_INSTANT; 4861 } else { 4862 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4863 final boolean allowMatchInstant = 4864 (wantInstantApps 4865 && Intent.ACTION_VIEW.equals(intent.getAction()) 4866 && hasWebURI(intent)) 4867 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4868 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4869 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4870 if (!allowMatchInstant) { 4871 flags &= ~PackageManager.MATCH_INSTANT; 4872 } 4873 } 4874 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4875 } 4876 4877 @Override 4878 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4879 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4880 } 4881 4882 /** 4883 * Important: The provided filterCallingUid is used exclusively to filter out activities 4884 * that can be seen based on user state. It's typically the original caller uid prior 4885 * to clearing. Because it can only be provided by trusted code, it's value can be 4886 * trusted and will be used as-is; unlike userId which will be validated by this method. 4887 */ 4888 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4889 int filterCallingUid, int userId) { 4890 if (!sUserManager.exists(userId)) return null; 4891 flags = updateFlagsForComponent(flags, userId, component); 4892 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4893 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4894 synchronized (mPackages) { 4895 PackageParser.Activity a = mActivities.mActivities.get(component); 4896 4897 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4898 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4899 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4900 if (ps == null) return null; 4901 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4902 return null; 4903 } 4904 return PackageParser.generateActivityInfo( 4905 a, flags, ps.readUserState(userId), userId); 4906 } 4907 if (mResolveComponentName.equals(component)) { 4908 return PackageParser.generateActivityInfo( 4909 mResolveActivity, flags, new PackageUserState(), userId); 4910 } 4911 } 4912 return null; 4913 } 4914 4915 @Override 4916 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4917 String resolvedType) { 4918 synchronized (mPackages) { 4919 if (component.equals(mResolveComponentName)) { 4920 // The resolver supports EVERYTHING! 4921 return true; 4922 } 4923 final int callingUid = Binder.getCallingUid(); 4924 final int callingUserId = UserHandle.getUserId(callingUid); 4925 PackageParser.Activity a = mActivities.mActivities.get(component); 4926 if (a == null) { 4927 return false; 4928 } 4929 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4930 if (ps == null) { 4931 return false; 4932 } 4933 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4934 return false; 4935 } 4936 for (int i=0; i<a.intents.size(); i++) { 4937 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4938 intent.getData(), intent.getCategories(), TAG) >= 0) { 4939 return true; 4940 } 4941 } 4942 return false; 4943 } 4944 } 4945 4946 @Override 4947 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4948 if (!sUserManager.exists(userId)) return null; 4949 final int callingUid = Binder.getCallingUid(); 4950 flags = updateFlagsForComponent(flags, userId, component); 4951 enforceCrossUserPermission(callingUid, userId, 4952 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4953 synchronized (mPackages) { 4954 PackageParser.Activity a = mReceivers.mActivities.get(component); 4955 if (DEBUG_PACKAGE_INFO) Log.v( 4956 TAG, "getReceiverInfo " + component + ": " + a); 4957 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4958 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4959 if (ps == null) return null; 4960 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4961 return null; 4962 } 4963 return PackageParser.generateActivityInfo( 4964 a, flags, ps.readUserState(userId), userId); 4965 } 4966 } 4967 return null; 4968 } 4969 4970 @Override 4971 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4972 int flags, int userId) { 4973 if (!sUserManager.exists(userId)) return null; 4974 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4975 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4976 return null; 4977 } 4978 4979 flags = updateFlagsForPackage(flags, userId, null); 4980 4981 final boolean canSeeStaticLibraries = 4982 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4983 == PERMISSION_GRANTED 4984 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4985 == PERMISSION_GRANTED 4986 || canRequestPackageInstallsInternal(packageName, 4987 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4988 false /* throwIfPermNotDeclared*/) 4989 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4990 == PERMISSION_GRANTED; 4991 4992 synchronized (mPackages) { 4993 List<SharedLibraryInfo> result = null; 4994 4995 final int libCount = mSharedLibraries.size(); 4996 for (int i = 0; i < libCount; i++) { 4997 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4998 if (versionedLib == null) { 4999 continue; 5000 } 5001 5002 final int versionCount = versionedLib.size(); 5003 for (int j = 0; j < versionCount; j++) { 5004 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 5005 if (!canSeeStaticLibraries && libInfo.isStatic()) { 5006 break; 5007 } 5008 final long identity = Binder.clearCallingIdentity(); 5009 try { 5010 PackageInfo packageInfo = getPackageInfoVersioned( 5011 libInfo.getDeclaringPackage(), flags 5012 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 5013 if (packageInfo == null) { 5014 continue; 5015 } 5016 } finally { 5017 Binder.restoreCallingIdentity(identity); 5018 } 5019 5020 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 5021 libInfo.getVersion(), libInfo.getType(), 5022 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 5023 flags, userId)); 5024 5025 if (result == null) { 5026 result = new ArrayList<>(); 5027 } 5028 result.add(resLibInfo); 5029 } 5030 } 5031 5032 return result != null ? new ParceledListSlice<>(result) : null; 5033 } 5034 } 5035 5036 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 5037 SharedLibraryInfo libInfo, int flags, int userId) { 5038 List<VersionedPackage> versionedPackages = null; 5039 final int packageCount = mSettings.mPackages.size(); 5040 for (int i = 0; i < packageCount; i++) { 5041 PackageSetting ps = mSettings.mPackages.valueAt(i); 5042 5043 if (ps == null) { 5044 continue; 5045 } 5046 5047 if (!ps.getUserState().get(userId).isAvailable(flags)) { 5048 continue; 5049 } 5050 5051 final String libName = libInfo.getName(); 5052 if (libInfo.isStatic()) { 5053 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 5054 if (libIdx < 0) { 5055 continue; 5056 } 5057 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 5058 continue; 5059 } 5060 if (versionedPackages == null) { 5061 versionedPackages = new ArrayList<>(); 5062 } 5063 // If the dependent is a static shared lib, use the public package name 5064 String dependentPackageName = ps.name; 5065 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 5066 dependentPackageName = ps.pkg.manifestPackageName; 5067 } 5068 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 5069 } else if (ps.pkg != null) { 5070 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 5071 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 5072 if (versionedPackages == null) { 5073 versionedPackages = new ArrayList<>(); 5074 } 5075 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 5076 } 5077 } 5078 } 5079 5080 return versionedPackages; 5081 } 5082 5083 @Override 5084 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 5085 if (!sUserManager.exists(userId)) return null; 5086 final int callingUid = Binder.getCallingUid(); 5087 flags = updateFlagsForComponent(flags, userId, component); 5088 enforceCrossUserPermission(callingUid, userId, 5089 false /* requireFullPermission */, false /* checkShell */, "get service info"); 5090 synchronized (mPackages) { 5091 PackageParser.Service s = mServices.mServices.get(component); 5092 if (DEBUG_PACKAGE_INFO) Log.v( 5093 TAG, "getServiceInfo " + component + ": " + s); 5094 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 5095 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5096 if (ps == null) return null; 5097 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 5098 return null; 5099 } 5100 return PackageParser.generateServiceInfo( 5101 s, flags, ps.readUserState(userId), userId); 5102 } 5103 } 5104 return null; 5105 } 5106 5107 @Override 5108 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 5109 if (!sUserManager.exists(userId)) return null; 5110 final int callingUid = Binder.getCallingUid(); 5111 flags = updateFlagsForComponent(flags, userId, component); 5112 enforceCrossUserPermission(callingUid, userId, 5113 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 5114 synchronized (mPackages) { 5115 PackageParser.Provider p = mProviders.mProviders.get(component); 5116 if (DEBUG_PACKAGE_INFO) Log.v( 5117 TAG, "getProviderInfo " + component + ": " + p); 5118 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 5119 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5120 if (ps == null) return null; 5121 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 5122 return null; 5123 } 5124 return PackageParser.generateProviderInfo( 5125 p, flags, ps.readUserState(userId), userId); 5126 } 5127 } 5128 return null; 5129 } 5130 5131 @Override 5132 public String[] getSystemSharedLibraryNames() { 5133 // allow instant applications 5134 synchronized (mPackages) { 5135 Set<String> libs = null; 5136 final int libCount = mSharedLibraries.size(); 5137 for (int i = 0; i < libCount; i++) { 5138 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 5139 if (versionedLib == null) { 5140 continue; 5141 } 5142 final int versionCount = versionedLib.size(); 5143 for (int j = 0; j < versionCount; j++) { 5144 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 5145 if (!libEntry.info.isStatic()) { 5146 if (libs == null) { 5147 libs = new ArraySet<>(); 5148 } 5149 libs.add(libEntry.info.getName()); 5150 break; 5151 } 5152 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 5153 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 5154 UserHandle.getUserId(Binder.getCallingUid()), 5155 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 5156 if (libs == null) { 5157 libs = new ArraySet<>(); 5158 } 5159 libs.add(libEntry.info.getName()); 5160 break; 5161 } 5162 } 5163 } 5164 5165 if (libs != null) { 5166 String[] libsArray = new String[libs.size()]; 5167 libs.toArray(libsArray); 5168 return libsArray; 5169 } 5170 5171 return null; 5172 } 5173 } 5174 5175 @Override 5176 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5177 // allow instant applications 5178 synchronized (mPackages) { 5179 return mServicesSystemSharedLibraryPackageName; 5180 } 5181 } 5182 5183 @Override 5184 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5185 // allow instant applications 5186 synchronized (mPackages) { 5187 return mSharedSystemSharedLibraryPackageName; 5188 } 5189 } 5190 5191 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5192 for (int i = userList.length - 1; i >= 0; --i) { 5193 final int userId = userList[i]; 5194 // don't add instant app to the list of updates 5195 if (pkgSetting.getInstantApp(userId)) { 5196 continue; 5197 } 5198 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5199 if (changedPackages == null) { 5200 changedPackages = new SparseArray<>(); 5201 mChangedPackages.put(userId, changedPackages); 5202 } 5203 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5204 if (sequenceNumbers == null) { 5205 sequenceNumbers = new HashMap<>(); 5206 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5207 } 5208 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5209 if (sequenceNumber != null) { 5210 changedPackages.remove(sequenceNumber); 5211 } 5212 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5213 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5214 } 5215 mChangedPackagesSequenceNumber++; 5216 } 5217 5218 @Override 5219 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5220 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5221 return null; 5222 } 5223 synchronized (mPackages) { 5224 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5225 return null; 5226 } 5227 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5228 if (changedPackages == null) { 5229 return null; 5230 } 5231 final List<String> packageNames = 5232 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5233 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5234 final String packageName = changedPackages.get(i); 5235 if (packageName != null) { 5236 packageNames.add(packageName); 5237 } 5238 } 5239 return packageNames.isEmpty() 5240 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5241 } 5242 } 5243 5244 @Override 5245 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5246 // allow instant applications 5247 ArrayList<FeatureInfo> res; 5248 synchronized (mAvailableFeatures) { 5249 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5250 res.addAll(mAvailableFeatures.values()); 5251 } 5252 final FeatureInfo fi = new FeatureInfo(); 5253 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5254 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5255 res.add(fi); 5256 5257 return new ParceledListSlice<>(res); 5258 } 5259 5260 @Override 5261 public boolean hasSystemFeature(String name, int version) { 5262 // allow instant applications 5263 synchronized (mAvailableFeatures) { 5264 final FeatureInfo feat = mAvailableFeatures.get(name); 5265 if (feat == null) { 5266 return false; 5267 } else { 5268 return feat.version >= version; 5269 } 5270 } 5271 } 5272 5273 @Override 5274 public int checkPermission(String permName, String pkgName, int userId) { 5275 if (!sUserManager.exists(userId)) { 5276 return PackageManager.PERMISSION_DENIED; 5277 } 5278 final int callingUid = Binder.getCallingUid(); 5279 5280 synchronized (mPackages) { 5281 final PackageParser.Package p = mPackages.get(pkgName); 5282 if (p != null && p.mExtras != null) { 5283 final PackageSetting ps = (PackageSetting) p.mExtras; 5284 if (filterAppAccessLPr(ps, callingUid, userId)) { 5285 return PackageManager.PERMISSION_DENIED; 5286 } 5287 final boolean instantApp = ps.getInstantApp(userId); 5288 final PermissionsState permissionsState = ps.getPermissionsState(); 5289 if (permissionsState.hasPermission(permName, userId)) { 5290 if (instantApp) { 5291 BasePermission bp = mSettings.mPermissions.get(permName); 5292 if (bp != null && bp.isInstant()) { 5293 return PackageManager.PERMISSION_GRANTED; 5294 } 5295 } else { 5296 return PackageManager.PERMISSION_GRANTED; 5297 } 5298 } 5299 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 5300 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 5301 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 5302 return PackageManager.PERMISSION_GRANTED; 5303 } 5304 } 5305 } 5306 5307 return PackageManager.PERMISSION_DENIED; 5308 } 5309 5310 @Override 5311 public int checkUidPermission(String permName, int uid) { 5312 final int callingUid = Binder.getCallingUid(); 5313 final int callingUserId = UserHandle.getUserId(callingUid); 5314 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5315 final boolean isUidInstantApp = getInstantAppPackageName(uid) != null; 5316 final int userId = UserHandle.getUserId(uid); 5317 if (!sUserManager.exists(userId)) { 5318 return PackageManager.PERMISSION_DENIED; 5319 } 5320 5321 synchronized (mPackages) { 5322 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5323 if (obj != null) { 5324 if (obj instanceof SharedUserSetting) { 5325 if (isCallerInstantApp) { 5326 return PackageManager.PERMISSION_DENIED; 5327 } 5328 } else if (obj instanceof PackageSetting) { 5329 final PackageSetting ps = (PackageSetting) obj; 5330 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5331 return PackageManager.PERMISSION_DENIED; 5332 } 5333 } 5334 final SettingBase settingBase = (SettingBase) obj; 5335 final PermissionsState permissionsState = settingBase.getPermissionsState(); 5336 if (permissionsState.hasPermission(permName, userId)) { 5337 if (isUidInstantApp) { 5338 BasePermission bp = mSettings.mPermissions.get(permName); 5339 if (bp != null && bp.isInstant()) { 5340 return PackageManager.PERMISSION_GRANTED; 5341 } 5342 } else { 5343 return PackageManager.PERMISSION_GRANTED; 5344 } 5345 } 5346 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 5347 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 5348 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 5349 return PackageManager.PERMISSION_GRANTED; 5350 } 5351 } else { 5352 ArraySet<String> perms = mSystemPermissions.get(uid); 5353 if (perms != null) { 5354 if (perms.contains(permName)) { 5355 return PackageManager.PERMISSION_GRANTED; 5356 } 5357 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 5358 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 5359 return PackageManager.PERMISSION_GRANTED; 5360 } 5361 } 5362 } 5363 } 5364 5365 return PackageManager.PERMISSION_DENIED; 5366 } 5367 5368 @Override 5369 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5370 if (UserHandle.getCallingUserId() != userId) { 5371 mContext.enforceCallingPermission( 5372 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5373 "isPermissionRevokedByPolicy for user " + userId); 5374 } 5375 5376 if (checkPermission(permission, packageName, userId) 5377 == PackageManager.PERMISSION_GRANTED) { 5378 return false; 5379 } 5380 5381 final int callingUid = Binder.getCallingUid(); 5382 if (getInstantAppPackageName(callingUid) != null) { 5383 if (!isCallerSameApp(packageName, callingUid)) { 5384 return false; 5385 } 5386 } else { 5387 if (isInstantApp(packageName, userId)) { 5388 return false; 5389 } 5390 } 5391 5392 final long identity = Binder.clearCallingIdentity(); 5393 try { 5394 final int flags = getPermissionFlags(permission, packageName, userId); 5395 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5396 } finally { 5397 Binder.restoreCallingIdentity(identity); 5398 } 5399 } 5400 5401 @Override 5402 public String getPermissionControllerPackageName() { 5403 synchronized (mPackages) { 5404 return mRequiredInstallerPackage; 5405 } 5406 } 5407 5408 /** 5409 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 5410 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 5411 * @param checkShell whether to prevent shell from access if there's a debugging restriction 5412 * @param message the message to log on security exception 5413 */ 5414 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 5415 boolean checkShell, String message) { 5416 if (userId < 0) { 5417 throw new IllegalArgumentException("Invalid userId " + userId); 5418 } 5419 if (checkShell) { 5420 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 5421 } 5422 if (userId == UserHandle.getUserId(callingUid)) return; 5423 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5424 if (requireFullPermission) { 5425 mContext.enforceCallingOrSelfPermission( 5426 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 5427 } else { 5428 try { 5429 mContext.enforceCallingOrSelfPermission( 5430 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 5431 } catch (SecurityException se) { 5432 mContext.enforceCallingOrSelfPermission( 5433 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 5434 } 5435 } 5436 } 5437 } 5438 5439 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 5440 if (callingUid == Process.SHELL_UID) { 5441 if (userHandle >= 0 5442 && sUserManager.hasUserRestriction(restriction, userHandle)) { 5443 throw new SecurityException("Shell does not have permission to access user " 5444 + userHandle); 5445 } else if (userHandle < 0) { 5446 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 5447 + Debug.getCallers(3)); 5448 } 5449 } 5450 } 5451 5452 private BasePermission findPermissionTreeLP(String permName) { 5453 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 5454 if (permName.startsWith(bp.name) && 5455 permName.length() > bp.name.length() && 5456 permName.charAt(bp.name.length()) == '.') { 5457 return bp; 5458 } 5459 } 5460 return null; 5461 } 5462 5463 private BasePermission checkPermissionTreeLP(String permName) { 5464 if (permName != null) { 5465 BasePermission bp = findPermissionTreeLP(permName); 5466 if (bp != null) { 5467 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 5468 return bp; 5469 } 5470 throw new SecurityException("Calling uid " 5471 + Binder.getCallingUid() 5472 + " is not allowed to add to permission tree " 5473 + bp.name + " owned by uid " + bp.uid); 5474 } 5475 } 5476 throw new SecurityException("No permission tree found for " + permName); 5477 } 5478 5479 static boolean compareStrings(CharSequence s1, CharSequence s2) { 5480 if (s1 == null) { 5481 return s2 == null; 5482 } 5483 if (s2 == null) { 5484 return false; 5485 } 5486 if (s1.getClass() != s2.getClass()) { 5487 return false; 5488 } 5489 return s1.equals(s2); 5490 } 5491 5492 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 5493 if (pi1.icon != pi2.icon) return false; 5494 if (pi1.logo != pi2.logo) return false; 5495 if (pi1.protectionLevel != pi2.protectionLevel) return false; 5496 if (!compareStrings(pi1.name, pi2.name)) return false; 5497 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 5498 // We'll take care of setting this one. 5499 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 5500 // These are not currently stored in settings. 5501 //if (!compareStrings(pi1.group, pi2.group)) return false; 5502 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 5503 //if (pi1.labelRes != pi2.labelRes) return false; 5504 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 5505 return true; 5506 } 5507 5508 int permissionInfoFootprint(PermissionInfo info) { 5509 int size = info.name.length(); 5510 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 5511 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 5512 return size; 5513 } 5514 5515 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 5516 int size = 0; 5517 for (BasePermission perm : mSettings.mPermissions.values()) { 5518 if (perm.uid == tree.uid) { 5519 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 5520 } 5521 } 5522 return size; 5523 } 5524 5525 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 5526 // We calculate the max size of permissions defined by this uid and throw 5527 // if that plus the size of 'info' would exceed our stated maximum. 5528 if (tree.uid != Process.SYSTEM_UID) { 5529 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 5530 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 5531 throw new SecurityException("Permission tree size cap exceeded"); 5532 } 5533 } 5534 } 5535 5536 boolean addPermissionLocked(PermissionInfo info, boolean async) { 5537 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5538 throw new SecurityException("Instant apps can't add permissions"); 5539 } 5540 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 5541 throw new SecurityException("Label must be specified in permission"); 5542 } 5543 BasePermission tree = checkPermissionTreeLP(info.name); 5544 BasePermission bp = mSettings.mPermissions.get(info.name); 5545 boolean added = bp == null; 5546 boolean changed = true; 5547 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 5548 if (added) { 5549 enforcePermissionCapLocked(info, tree); 5550 bp = new BasePermission(info.name, tree.sourcePackage, 5551 BasePermission.TYPE_DYNAMIC); 5552 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 5553 throw new SecurityException( 5554 "Not allowed to modify non-dynamic permission " 5555 + info.name); 5556 } else { 5557 if (bp.protectionLevel == fixedLevel 5558 && bp.perm.owner.equals(tree.perm.owner) 5559 && bp.uid == tree.uid 5560 && comparePermissionInfos(bp.perm.info, info)) { 5561 changed = false; 5562 } 5563 } 5564 bp.protectionLevel = fixedLevel; 5565 info = new PermissionInfo(info); 5566 info.protectionLevel = fixedLevel; 5567 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 5568 bp.perm.info.packageName = tree.perm.info.packageName; 5569 bp.uid = tree.uid; 5570 if (added) { 5571 mSettings.mPermissions.put(info.name, bp); 5572 } 5573 if (changed) { 5574 if (!async) { 5575 mSettings.writeLPr(); 5576 } else { 5577 scheduleWriteSettingsLocked(); 5578 } 5579 } 5580 return added; 5581 } 5582 5583 @Override 5584 public boolean addPermission(PermissionInfo info) { 5585 synchronized (mPackages) { 5586 return addPermissionLocked(info, false); 5587 } 5588 } 5589 5590 @Override 5591 public boolean addPermissionAsync(PermissionInfo info) { 5592 synchronized (mPackages) { 5593 return addPermissionLocked(info, true); 5594 } 5595 } 5596 5597 @Override 5598 public void removePermission(String name) { 5599 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5600 throw new SecurityException("Instant applications don't have access to this method"); 5601 } 5602 synchronized (mPackages) { 5603 checkPermissionTreeLP(name); 5604 BasePermission bp = mSettings.mPermissions.get(name); 5605 if (bp != null) { 5606 if (bp.type != BasePermission.TYPE_DYNAMIC) { 5607 throw new SecurityException( 5608 "Not allowed to modify non-dynamic permission " 5609 + name); 5610 } 5611 mSettings.mPermissions.remove(name); 5612 mSettings.writeLPr(); 5613 } 5614 } 5615 } 5616 5617 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission( 5618 PackageParser.Package pkg, BasePermission bp) { 5619 int index = pkg.requestedPermissions.indexOf(bp.name); 5620 if (index == -1) { 5621 throw new SecurityException("Package " + pkg.packageName 5622 + " has not requested permission " + bp.name); 5623 } 5624 if (!bp.isRuntime() && !bp.isDevelopment()) { 5625 throw new SecurityException("Permission " + bp.name 5626 + " is not a changeable permission type"); 5627 } 5628 } 5629 5630 @Override 5631 public void grantRuntimePermission(String packageName, String name, final int userId) { 5632 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 5633 } 5634 5635 private void grantRuntimePermission(String packageName, String name, final int userId, 5636 boolean overridePolicy) { 5637 if (!sUserManager.exists(userId)) { 5638 Log.e(TAG, "No such user:" + userId); 5639 return; 5640 } 5641 final int callingUid = Binder.getCallingUid(); 5642 5643 mContext.enforceCallingOrSelfPermission( 5644 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 5645 "grantRuntimePermission"); 5646 5647 enforceCrossUserPermission(callingUid, userId, 5648 true /* requireFullPermission */, true /* checkShell */, 5649 "grantRuntimePermission"); 5650 5651 final int uid; 5652 final PackageSetting ps; 5653 5654 synchronized (mPackages) { 5655 final PackageParser.Package pkg = mPackages.get(packageName); 5656 if (pkg == null) { 5657 throw new IllegalArgumentException("Unknown package: " + packageName); 5658 } 5659 final BasePermission bp = mSettings.mPermissions.get(name); 5660 if (bp == null) { 5661 throw new IllegalArgumentException("Unknown permission: " + name); 5662 } 5663 ps = (PackageSetting) pkg.mExtras; 5664 if (ps == null 5665 || filterAppAccessLPr(ps, callingUid, userId)) { 5666 throw new IllegalArgumentException("Unknown package: " + packageName); 5667 } 5668 5669 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 5670 5671 // If a permission review is required for legacy apps we represent 5672 // their permissions as always granted runtime ones since we need 5673 // to keep the review required permission flag per user while an 5674 // install permission's state is shared across all users. 5675 if (mPermissionReviewRequired 5676 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 5677 && bp.isRuntime()) { 5678 return; 5679 } 5680 5681 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 5682 5683 final PermissionsState permissionsState = ps.getPermissionsState(); 5684 5685 final int flags = permissionsState.getPermissionFlags(name, userId); 5686 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 5687 throw new SecurityException("Cannot grant system fixed permission " 5688 + name + " for package " + packageName); 5689 } 5690 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 5691 throw new SecurityException("Cannot grant policy fixed permission " 5692 + name + " for package " + packageName); 5693 } 5694 5695 if (bp.isDevelopment()) { 5696 // Development permissions must be handled specially, since they are not 5697 // normal runtime permissions. For now they apply to all users. 5698 if (permissionsState.grantInstallPermission(bp) != 5699 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5700 scheduleWriteSettingsLocked(); 5701 } 5702 return; 5703 } 5704 5705 if (ps.getInstantApp(userId) && !bp.isInstant()) { 5706 throw new SecurityException("Cannot grant non-ephemeral permission" 5707 + name + " for package " + packageName); 5708 } 5709 5710 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 5711 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 5712 return; 5713 } 5714 5715 final int result = permissionsState.grantRuntimePermission(bp, userId); 5716 switch (result) { 5717 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 5718 return; 5719 } 5720 5721 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 5722 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 5723 mHandler.post(new Runnable() { 5724 @Override 5725 public void run() { 5726 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 5727 } 5728 }); 5729 } 5730 break; 5731 } 5732 5733 if (bp.isRuntime()) { 5734 logPermissionGranted(mContext, name, packageName); 5735 } 5736 5737 mOnPermissionChangeListeners.onPermissionsChanged(uid); 5738 5739 // Not critical if that is lost - app has to request again. 5740 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5741 } 5742 5743 // Only need to do this if user is initialized. Otherwise it's a new user 5744 // and there are no processes running as the user yet and there's no need 5745 // to make an expensive call to remount processes for the changed permissions. 5746 if (READ_EXTERNAL_STORAGE.equals(name) 5747 || WRITE_EXTERNAL_STORAGE.equals(name)) { 5748 final long token = Binder.clearCallingIdentity(); 5749 try { 5750 if (sUserManager.isInitialized(userId)) { 5751 StorageManagerInternal storageManagerInternal = LocalServices.getService( 5752 StorageManagerInternal.class); 5753 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 5754 } 5755 } finally { 5756 Binder.restoreCallingIdentity(token); 5757 } 5758 } 5759 } 5760 5761 @Override 5762 public void revokeRuntimePermission(String packageName, String name, int userId) { 5763 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 5764 } 5765 5766 private void revokeRuntimePermission(String packageName, String name, int userId, 5767 boolean overridePolicy) { 5768 if (!sUserManager.exists(userId)) { 5769 Log.e(TAG, "No such user:" + userId); 5770 return; 5771 } 5772 5773 mContext.enforceCallingOrSelfPermission( 5774 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5775 "revokeRuntimePermission"); 5776 5777 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5778 true /* requireFullPermission */, true /* checkShell */, 5779 "revokeRuntimePermission"); 5780 5781 final int appId; 5782 5783 synchronized (mPackages) { 5784 final PackageParser.Package pkg = mPackages.get(packageName); 5785 if (pkg == null) { 5786 throw new IllegalArgumentException("Unknown package: " + packageName); 5787 } 5788 final PackageSetting ps = (PackageSetting) pkg.mExtras; 5789 if (ps == null 5790 || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 5791 throw new IllegalArgumentException("Unknown package: " + packageName); 5792 } 5793 final BasePermission bp = mSettings.mPermissions.get(name); 5794 if (bp == null) { 5795 throw new IllegalArgumentException("Unknown permission: " + name); 5796 } 5797 5798 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 5799 5800 // If a permission review is required for legacy apps we represent 5801 // their permissions as always granted runtime ones since we need 5802 // to keep the review required permission flag per user while an 5803 // install permission's state is shared across all users. 5804 if (mPermissionReviewRequired 5805 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 5806 && bp.isRuntime()) { 5807 return; 5808 } 5809 5810 final PermissionsState permissionsState = ps.getPermissionsState(); 5811 5812 final int flags = permissionsState.getPermissionFlags(name, userId); 5813 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 5814 throw new SecurityException("Cannot revoke system fixed permission " 5815 + name + " for package " + packageName); 5816 } 5817 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 5818 throw new SecurityException("Cannot revoke policy fixed permission " 5819 + name + " for package " + packageName); 5820 } 5821 5822 if (bp.isDevelopment()) { 5823 // Development permissions must be handled specially, since they are not 5824 // normal runtime permissions. For now they apply to all users. 5825 if (permissionsState.revokeInstallPermission(bp) != 5826 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5827 scheduleWriteSettingsLocked(); 5828 } 5829 return; 5830 } 5831 5832 if (permissionsState.revokeRuntimePermission(bp, userId) == 5833 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5834 return; 5835 } 5836 5837 if (bp.isRuntime()) { 5838 logPermissionRevoked(mContext, name, packageName); 5839 } 5840 5841 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 5842 5843 // Critical, after this call app should never have the permission. 5844 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 5845 5846 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 5847 } 5848 5849 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 5850 } 5851 5852 /** 5853 * Get the first event id for the permission. 5854 * 5855 * <p>There are four events for each permission: <ul> 5856 * <li>Request permission: first id + 0</li> 5857 * <li>Grant permission: first id + 1</li> 5858 * <li>Request for permission denied: first id + 2</li> 5859 * <li>Revoke permission: first id + 3</li> 5860 * </ul></p> 5861 * 5862 * @param name name of the permission 5863 * 5864 * @return The first event id for the permission 5865 */ 5866 private static int getBaseEventId(@NonNull String name) { 5867 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 5868 5869 if (eventIdIndex == -1) { 5870 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 5871 || Build.IS_USER) { 5872 Log.i(TAG, "Unknown permission " + name); 5873 5874 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 5875 } else { 5876 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 5877 // 5878 // Also update 5879 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 5880 // - metrics_constants.proto 5881 throw new IllegalStateException("Unknown permission " + name); 5882 } 5883 } 5884 5885 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 5886 } 5887 5888 /** 5889 * Log that a permission was revoked. 5890 * 5891 * @param context Context of the caller 5892 * @param name name of the permission 5893 * @param packageName package permission if for 5894 */ 5895 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5896 @NonNull String packageName) { 5897 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5898 } 5899 5900 /** 5901 * Log that a permission request was granted. 5902 * 5903 * @param context Context of the caller 5904 * @param name name of the permission 5905 * @param packageName package permission if for 5906 */ 5907 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5908 @NonNull String packageName) { 5909 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5910 } 5911 5912 @Override 5913 public void resetRuntimePermissions() { 5914 mContext.enforceCallingOrSelfPermission( 5915 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5916 "revokeRuntimePermission"); 5917 5918 int callingUid = Binder.getCallingUid(); 5919 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5920 mContext.enforceCallingOrSelfPermission( 5921 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5922 "resetRuntimePermissions"); 5923 } 5924 5925 synchronized (mPackages) { 5926 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5927 for (int userId : UserManagerService.getInstance().getUserIds()) { 5928 final int packageCount = mPackages.size(); 5929 for (int i = 0; i < packageCount; i++) { 5930 PackageParser.Package pkg = mPackages.valueAt(i); 5931 if (!(pkg.mExtras instanceof PackageSetting)) { 5932 continue; 5933 } 5934 PackageSetting ps = (PackageSetting) pkg.mExtras; 5935 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5936 } 5937 } 5938 } 5939 } 5940 5941 @Override 5942 public int getPermissionFlags(String name, String packageName, int userId) { 5943 if (!sUserManager.exists(userId)) { 5944 return 0; 5945 } 5946 5947 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5948 5949 final int callingUid = Binder.getCallingUid(); 5950 enforceCrossUserPermission(callingUid, userId, 5951 true /* requireFullPermission */, false /* checkShell */, 5952 "getPermissionFlags"); 5953 5954 synchronized (mPackages) { 5955 final PackageParser.Package pkg = mPackages.get(packageName); 5956 if (pkg == null) { 5957 return 0; 5958 } 5959 final BasePermission bp = mSettings.mPermissions.get(name); 5960 if (bp == null) { 5961 return 0; 5962 } 5963 final PackageSetting ps = (PackageSetting) pkg.mExtras; 5964 if (ps == null 5965 || filterAppAccessLPr(ps, callingUid, userId)) { 5966 return 0; 5967 } 5968 PermissionsState permissionsState = ps.getPermissionsState(); 5969 return permissionsState.getPermissionFlags(name, userId); 5970 } 5971 } 5972 5973 @Override 5974 public void updatePermissionFlags(String name, String packageName, int flagMask, 5975 int flagValues, int userId) { 5976 if (!sUserManager.exists(userId)) { 5977 return; 5978 } 5979 5980 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5981 5982 final int callingUid = Binder.getCallingUid(); 5983 enforceCrossUserPermission(callingUid, userId, 5984 true /* requireFullPermission */, true /* checkShell */, 5985 "updatePermissionFlags"); 5986 5987 // Only the system can change these flags and nothing else. 5988 if (getCallingUid() != Process.SYSTEM_UID) { 5989 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5990 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5991 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5992 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5993 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5994 } 5995 5996 synchronized (mPackages) { 5997 final PackageParser.Package pkg = mPackages.get(packageName); 5998 if (pkg == null) { 5999 throw new IllegalArgumentException("Unknown package: " + packageName); 6000 } 6001 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6002 if (ps == null 6003 || filterAppAccessLPr(ps, callingUid, userId)) { 6004 throw new IllegalArgumentException("Unknown package: " + packageName); 6005 } 6006 6007 final BasePermission bp = mSettings.mPermissions.get(name); 6008 if (bp == null) { 6009 throw new IllegalArgumentException("Unknown permission: " + name); 6010 } 6011 6012 PermissionsState permissionsState = ps.getPermissionsState(); 6013 6014 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 6015 6016 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 6017 // Install and runtime permissions are stored in different places, 6018 // so figure out what permission changed and persist the change. 6019 if (permissionsState.getInstallPermissionState(name) != null) { 6020 scheduleWriteSettingsLocked(); 6021 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 6022 || hadState) { 6023 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 6024 } 6025 } 6026 } 6027 } 6028 6029 /** 6030 * Update the permission flags for all packages and runtime permissions of a user in order 6031 * to allow device or profile owner to remove POLICY_FIXED. 6032 */ 6033 @Override 6034 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 6035 if (!sUserManager.exists(userId)) { 6036 return; 6037 } 6038 6039 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 6040 6041 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6042 true /* requireFullPermission */, true /* checkShell */, 6043 "updatePermissionFlagsForAllApps"); 6044 6045 // Only the system can change system fixed flags. 6046 if (getCallingUid() != Process.SYSTEM_UID) { 6047 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 6048 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 6049 } 6050 6051 synchronized (mPackages) { 6052 boolean changed = false; 6053 final int packageCount = mPackages.size(); 6054 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 6055 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 6056 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6057 if (ps == null) { 6058 continue; 6059 } 6060 PermissionsState permissionsState = ps.getPermissionsState(); 6061 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 6062 userId, flagMask, flagValues); 6063 } 6064 if (changed) { 6065 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 6066 } 6067 } 6068 } 6069 6070 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 6071 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 6072 != PackageManager.PERMISSION_GRANTED 6073 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 6074 != PackageManager.PERMISSION_GRANTED) { 6075 throw new SecurityException(message + " requires " 6076 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 6077 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 6078 } 6079 } 6080 6081 @Override 6082 public boolean shouldShowRequestPermissionRationale(String permissionName, 6083 String packageName, int userId) { 6084 if (UserHandle.getCallingUserId() != userId) { 6085 mContext.enforceCallingPermission( 6086 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 6087 "canShowRequestPermissionRationale for user " + userId); 6088 } 6089 6090 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 6091 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 6092 return false; 6093 } 6094 6095 if (checkPermission(permissionName, packageName, userId) 6096 == PackageManager.PERMISSION_GRANTED) { 6097 return false; 6098 } 6099 6100 final int flags; 6101 6102 final long identity = Binder.clearCallingIdentity(); 6103 try { 6104 flags = getPermissionFlags(permissionName, 6105 packageName, userId); 6106 } finally { 6107 Binder.restoreCallingIdentity(identity); 6108 } 6109 6110 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 6111 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 6112 | PackageManager.FLAG_PERMISSION_USER_FIXED; 6113 6114 if ((flags & fixedFlags) != 0) { 6115 return false; 6116 } 6117 6118 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 6119 } 6120 6121 @Override 6122 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 6123 mContext.enforceCallingOrSelfPermission( 6124 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 6125 "addOnPermissionsChangeListener"); 6126 6127 synchronized (mPackages) { 6128 mOnPermissionChangeListeners.addListenerLocked(listener); 6129 } 6130 } 6131 6132 @Override 6133 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 6134 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6135 throw new SecurityException("Instant applications don't have access to this method"); 6136 } 6137 synchronized (mPackages) { 6138 mOnPermissionChangeListeners.removeListenerLocked(listener); 6139 } 6140 } 6141 6142 @Override 6143 public boolean isProtectedBroadcast(String actionName) { 6144 // allow instant applications 6145 synchronized (mProtectedBroadcasts) { 6146 if (mProtectedBroadcasts.contains(actionName)) { 6147 return true; 6148 } else if (actionName != null) { 6149 // TODO: remove these terrible hacks 6150 if (actionName.startsWith("android.net.netmon.lingerExpired") 6151 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 6152 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 6153 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 6154 return true; 6155 } 6156 } 6157 } 6158 return false; 6159 } 6160 6161 @Override 6162 public int checkSignatures(String pkg1, String pkg2) { 6163 synchronized (mPackages) { 6164 final PackageParser.Package p1 = mPackages.get(pkg1); 6165 final PackageParser.Package p2 = mPackages.get(pkg2); 6166 if (p1 == null || p1.mExtras == null 6167 || p2 == null || p2.mExtras == null) { 6168 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6169 } 6170 final int callingUid = Binder.getCallingUid(); 6171 final int callingUserId = UserHandle.getUserId(callingUid); 6172 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 6173 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 6174 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 6175 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 6176 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6177 } 6178 return compareSignatures(p1.mSignatures, p2.mSignatures); 6179 } 6180 } 6181 6182 @Override 6183 public int checkUidSignatures(int uid1, int uid2) { 6184 final int callingUid = Binder.getCallingUid(); 6185 final int callingUserId = UserHandle.getUserId(callingUid); 6186 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 6187 // Map to base uids. 6188 uid1 = UserHandle.getAppId(uid1); 6189 uid2 = UserHandle.getAppId(uid2); 6190 // reader 6191 synchronized (mPackages) { 6192 Signature[] s1; 6193 Signature[] s2; 6194 Object obj = mSettings.getUserIdLPr(uid1); 6195 if (obj != null) { 6196 if (obj instanceof SharedUserSetting) { 6197 if (isCallerInstantApp) { 6198 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6199 } 6200 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 6201 } else if (obj instanceof PackageSetting) { 6202 final PackageSetting ps = (PackageSetting) obj; 6203 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 6204 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6205 } 6206 s1 = ps.signatures.mSignatures; 6207 } else { 6208 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6209 } 6210 } else { 6211 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6212 } 6213 obj = mSettings.getUserIdLPr(uid2); 6214 if (obj != null) { 6215 if (obj instanceof SharedUserSetting) { 6216 if (isCallerInstantApp) { 6217 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6218 } 6219 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 6220 } else if (obj instanceof PackageSetting) { 6221 final PackageSetting ps = (PackageSetting) obj; 6222 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 6223 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6224 } 6225 s2 = ps.signatures.mSignatures; 6226 } else { 6227 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6228 } 6229 } else { 6230 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6231 } 6232 return compareSignatures(s1, s2); 6233 } 6234 } 6235 6236 /** 6237 * This method should typically only be used when granting or revoking 6238 * permissions, since the app may immediately restart after this call. 6239 * <p> 6240 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 6241 * guard your work against the app being relaunched. 6242 */ 6243 private void killUid(int appId, int userId, String reason) { 6244 final long identity = Binder.clearCallingIdentity(); 6245 try { 6246 IActivityManager am = ActivityManager.getService(); 6247 if (am != null) { 6248 try { 6249 am.killUid(appId, userId, reason); 6250 } catch (RemoteException e) { 6251 /* ignore - same process */ 6252 } 6253 } 6254 } finally { 6255 Binder.restoreCallingIdentity(identity); 6256 } 6257 } 6258 6259 /** 6260 * Compares two sets of signatures. Returns: 6261 * <br /> 6262 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 6263 * <br /> 6264 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 6265 * <br /> 6266 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 6267 * <br /> 6268 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 6269 * <br /> 6270 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 6271 */ 6272 static int compareSignatures(Signature[] s1, Signature[] s2) { 6273 if (s1 == null) { 6274 return s2 == null 6275 ? PackageManager.SIGNATURE_NEITHER_SIGNED 6276 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 6277 } 6278 6279 if (s2 == null) { 6280 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 6281 } 6282 6283 if (s1.length != s2.length) { 6284 return PackageManager.SIGNATURE_NO_MATCH; 6285 } 6286 6287 // Since both signature sets are of size 1, we can compare without HashSets. 6288 if (s1.length == 1) { 6289 return s1[0].equals(s2[0]) ? 6290 PackageManager.SIGNATURE_MATCH : 6291 PackageManager.SIGNATURE_NO_MATCH; 6292 } 6293 6294 ArraySet<Signature> set1 = new ArraySet<Signature>(); 6295 for (Signature sig : s1) { 6296 set1.add(sig); 6297 } 6298 ArraySet<Signature> set2 = new ArraySet<Signature>(); 6299 for (Signature sig : s2) { 6300 set2.add(sig); 6301 } 6302 // Make sure s2 contains all signatures in s1. 6303 if (set1.equals(set2)) { 6304 return PackageManager.SIGNATURE_MATCH; 6305 } 6306 return PackageManager.SIGNATURE_NO_MATCH; 6307 } 6308 6309 /** 6310 * If the database version for this type of package (internal storage or 6311 * external storage) is less than the version where package signatures 6312 * were updated, return true. 6313 */ 6314 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 6315 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 6316 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 6317 } 6318 6319 /** 6320 * Used for backward compatibility to make sure any packages with 6321 * certificate chains get upgraded to the new style. {@code existingSigs} 6322 * will be in the old format (since they were stored on disk from before the 6323 * system upgrade) and {@code scannedSigs} will be in the newer format. 6324 */ 6325 private int compareSignaturesCompat(PackageSignatures existingSigs, 6326 PackageParser.Package scannedPkg) { 6327 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 6328 return PackageManager.SIGNATURE_NO_MATCH; 6329 } 6330 6331 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 6332 for (Signature sig : existingSigs.mSignatures) { 6333 existingSet.add(sig); 6334 } 6335 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 6336 for (Signature sig : scannedPkg.mSignatures) { 6337 try { 6338 Signature[] chainSignatures = sig.getChainSignatures(); 6339 for (Signature chainSig : chainSignatures) { 6340 scannedCompatSet.add(chainSig); 6341 } 6342 } catch (CertificateEncodingException e) { 6343 scannedCompatSet.add(sig); 6344 } 6345 } 6346 /* 6347 * Make sure the expanded scanned set contains all signatures in the 6348 * existing one. 6349 */ 6350 if (scannedCompatSet.equals(existingSet)) { 6351 // Migrate the old signatures to the new scheme. 6352 existingSigs.assignSignatures(scannedPkg.mSignatures); 6353 // The new KeySets will be re-added later in the scanning process. 6354 synchronized (mPackages) { 6355 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 6356 } 6357 return PackageManager.SIGNATURE_MATCH; 6358 } 6359 return PackageManager.SIGNATURE_NO_MATCH; 6360 } 6361 6362 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 6363 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 6364 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 6365 } 6366 6367 private int compareSignaturesRecover(PackageSignatures existingSigs, 6368 PackageParser.Package scannedPkg) { 6369 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 6370 return PackageManager.SIGNATURE_NO_MATCH; 6371 } 6372 6373 String msg = null; 6374 try { 6375 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 6376 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 6377 + scannedPkg.packageName); 6378 return PackageManager.SIGNATURE_MATCH; 6379 } 6380 } catch (CertificateException e) { 6381 msg = e.getMessage(); 6382 } 6383 6384 logCriticalInfo(Log.INFO, 6385 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 6386 return PackageManager.SIGNATURE_NO_MATCH; 6387 } 6388 6389 @Override 6390 public List<String> getAllPackages() { 6391 final int callingUid = Binder.getCallingUid(); 6392 final int callingUserId = UserHandle.getUserId(callingUid); 6393 synchronized (mPackages) { 6394 if (canViewInstantApps(callingUid, callingUserId)) { 6395 return new ArrayList<String>(mPackages.keySet()); 6396 } 6397 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6398 final List<String> result = new ArrayList<>(); 6399 if (instantAppPkgName != null) { 6400 // caller is an instant application; filter unexposed applications 6401 for (PackageParser.Package pkg : mPackages.values()) { 6402 if (!pkg.visibleToInstantApps) { 6403 continue; 6404 } 6405 result.add(pkg.packageName); 6406 } 6407 } else { 6408 // caller is a normal application; filter instant applications 6409 for (PackageParser.Package pkg : mPackages.values()) { 6410 final PackageSetting ps = 6411 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 6412 if (ps != null 6413 && ps.getInstantApp(callingUserId) 6414 && !mInstantAppRegistry.isInstantAccessGranted( 6415 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 6416 continue; 6417 } 6418 result.add(pkg.packageName); 6419 } 6420 } 6421 return result; 6422 } 6423 } 6424 6425 @Override 6426 public String[] getPackagesForUid(int uid) { 6427 final int callingUid = Binder.getCallingUid(); 6428 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 6429 final int userId = UserHandle.getUserId(uid); 6430 uid = UserHandle.getAppId(uid); 6431 // reader 6432 synchronized (mPackages) { 6433 Object obj = mSettings.getUserIdLPr(uid); 6434 if (obj instanceof SharedUserSetting) { 6435 if (isCallerInstantApp) { 6436 return null; 6437 } 6438 final SharedUserSetting sus = (SharedUserSetting) obj; 6439 final int N = sus.packages.size(); 6440 String[] res = new String[N]; 6441 final Iterator<PackageSetting> it = sus.packages.iterator(); 6442 int i = 0; 6443 while (it.hasNext()) { 6444 PackageSetting ps = it.next(); 6445 if (ps.getInstalled(userId)) { 6446 res[i++] = ps.name; 6447 } else { 6448 res = ArrayUtils.removeElement(String.class, res, res[i]); 6449 } 6450 } 6451 return res; 6452 } else if (obj instanceof PackageSetting) { 6453 final PackageSetting ps = (PackageSetting) obj; 6454 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 6455 return new String[]{ps.name}; 6456 } 6457 } 6458 } 6459 return null; 6460 } 6461 6462 @Override 6463 public String getNameForUid(int uid) { 6464 final int callingUid = Binder.getCallingUid(); 6465 if (getInstantAppPackageName(callingUid) != null) { 6466 return null; 6467 } 6468 synchronized (mPackages) { 6469 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 6470 if (obj instanceof SharedUserSetting) { 6471 final SharedUserSetting sus = (SharedUserSetting) obj; 6472 return sus.name + ":" + sus.userId; 6473 } else if (obj instanceof PackageSetting) { 6474 final PackageSetting ps = (PackageSetting) obj; 6475 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6476 return null; 6477 } 6478 return ps.name; 6479 } 6480 return null; 6481 } 6482 } 6483 6484 @Override 6485 public String[] getNamesForUids(int[] uids) { 6486 if (uids == null || uids.length == 0) { 6487 return null; 6488 } 6489 final int callingUid = Binder.getCallingUid(); 6490 if (getInstantAppPackageName(callingUid) != null) { 6491 return null; 6492 } 6493 final String[] names = new String[uids.length]; 6494 synchronized (mPackages) { 6495 for (int i = uids.length - 1; i >= 0; i--) { 6496 final int uid = uids[i]; 6497 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 6498 if (obj instanceof SharedUserSetting) { 6499 final SharedUserSetting sus = (SharedUserSetting) obj; 6500 names[i] = "shared:" + sus.name; 6501 } else if (obj instanceof PackageSetting) { 6502 final PackageSetting ps = (PackageSetting) obj; 6503 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6504 names[i] = null; 6505 } else { 6506 names[i] = ps.name; 6507 } 6508 } else { 6509 names[i] = null; 6510 } 6511 } 6512 } 6513 return names; 6514 } 6515 6516 @Override 6517 public int getUidForSharedUser(String sharedUserName) { 6518 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6519 return -1; 6520 } 6521 if (sharedUserName == null) { 6522 return -1; 6523 } 6524 // reader 6525 synchronized (mPackages) { 6526 SharedUserSetting suid; 6527 try { 6528 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 6529 if (suid != null) { 6530 return suid.userId; 6531 } 6532 } catch (PackageManagerException ignore) { 6533 // can't happen, but, still need to catch it 6534 } 6535 return -1; 6536 } 6537 } 6538 6539 @Override 6540 public int getFlagsForUid(int uid) { 6541 final int callingUid = Binder.getCallingUid(); 6542 if (getInstantAppPackageName(callingUid) != null) { 6543 return 0; 6544 } 6545 synchronized (mPackages) { 6546 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 6547 if (obj instanceof SharedUserSetting) { 6548 final SharedUserSetting sus = (SharedUserSetting) obj; 6549 return sus.pkgFlags; 6550 } else if (obj instanceof PackageSetting) { 6551 final PackageSetting ps = (PackageSetting) obj; 6552 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6553 return 0; 6554 } 6555 return ps.pkgFlags; 6556 } 6557 } 6558 return 0; 6559 } 6560 6561 @Override 6562 public int getPrivateFlagsForUid(int uid) { 6563 final int callingUid = Binder.getCallingUid(); 6564 if (getInstantAppPackageName(callingUid) != null) { 6565 return 0; 6566 } 6567 synchronized (mPackages) { 6568 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 6569 if (obj instanceof SharedUserSetting) { 6570 final SharedUserSetting sus = (SharedUserSetting) obj; 6571 return sus.pkgPrivateFlags; 6572 } else if (obj instanceof PackageSetting) { 6573 final PackageSetting ps = (PackageSetting) obj; 6574 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6575 return 0; 6576 } 6577 return ps.pkgPrivateFlags; 6578 } 6579 } 6580 return 0; 6581 } 6582 6583 @Override 6584 public boolean isUidPrivileged(int uid) { 6585 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6586 return false; 6587 } 6588 uid = UserHandle.getAppId(uid); 6589 // reader 6590 synchronized (mPackages) { 6591 Object obj = mSettings.getUserIdLPr(uid); 6592 if (obj instanceof SharedUserSetting) { 6593 final SharedUserSetting sus = (SharedUserSetting) obj; 6594 final Iterator<PackageSetting> it = sus.packages.iterator(); 6595 while (it.hasNext()) { 6596 if (it.next().isPrivileged()) { 6597 return true; 6598 } 6599 } 6600 } else if (obj instanceof PackageSetting) { 6601 final PackageSetting ps = (PackageSetting) obj; 6602 return ps.isPrivileged(); 6603 } 6604 } 6605 return false; 6606 } 6607 6608 @Override 6609 public String[] getAppOpPermissionPackages(String permissionName) { 6610 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6611 return null; 6612 } 6613 synchronized (mPackages) { 6614 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 6615 if (pkgs == null) { 6616 return null; 6617 } 6618 return pkgs.toArray(new String[pkgs.size()]); 6619 } 6620 } 6621 6622 @Override 6623 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 6624 int flags, int userId) { 6625 return resolveIntentInternal( 6626 intent, resolvedType, flags, userId, false /*includeInstantApps*/); 6627 } 6628 6629 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 6630 int flags, int userId, boolean resolveForStart) { 6631 try { 6632 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 6633 6634 if (!sUserManager.exists(userId)) return null; 6635 final int callingUid = Binder.getCallingUid(); 6636 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 6637 enforceCrossUserPermission(callingUid, userId, 6638 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 6639 6640 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6641 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 6642 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 6643 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6644 6645 final ResolveInfo bestChoice = 6646 chooseBestActivity(intent, resolvedType, flags, query, userId); 6647 return bestChoice; 6648 } finally { 6649 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6650 } 6651 } 6652 6653 @Override 6654 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 6655 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 6656 throw new SecurityException( 6657 "findPersistentPreferredActivity can only be run by the system"); 6658 } 6659 if (!sUserManager.exists(userId)) { 6660 return null; 6661 } 6662 final int callingUid = Binder.getCallingUid(); 6663 intent = updateIntentForResolve(intent); 6664 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 6665 final int flags = updateFlagsForResolve( 6666 0, userId, intent, callingUid, false /*includeInstantApps*/); 6667 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6668 userId); 6669 synchronized (mPackages) { 6670 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 6671 userId); 6672 } 6673 } 6674 6675 @Override 6676 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 6677 IntentFilter filter, int match, ComponentName activity) { 6678 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6679 return; 6680 } 6681 final int userId = UserHandle.getCallingUserId(); 6682 if (DEBUG_PREFERRED) { 6683 Log.v(TAG, "setLastChosenActivity intent=" + intent 6684 + " resolvedType=" + resolvedType 6685 + " flags=" + flags 6686 + " filter=" + filter 6687 + " match=" + match 6688 + " activity=" + activity); 6689 filter.dump(new PrintStreamPrinter(System.out), " "); 6690 } 6691 intent.setComponent(null); 6692 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6693 userId); 6694 // Find any earlier preferred or last chosen entries and nuke them 6695 findPreferredActivity(intent, resolvedType, 6696 flags, query, 0, false, true, false, userId); 6697 // Add the new activity as the last chosen for this filter 6698 addPreferredActivityInternal(filter, match, null, activity, false, userId, 6699 "Setting last chosen"); 6700 } 6701 6702 @Override 6703 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 6704 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6705 return null; 6706 } 6707 final int userId = UserHandle.getCallingUserId(); 6708 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 6709 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6710 userId); 6711 return findPreferredActivity(intent, resolvedType, flags, query, 0, 6712 false, false, false, userId); 6713 } 6714 6715 /** 6716 * Returns whether or not instant apps have been disabled remotely. 6717 */ 6718 private boolean isEphemeralDisabled() { 6719 return mEphemeralAppsDisabled; 6720 } 6721 6722 private boolean isInstantAppAllowed( 6723 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 6724 boolean skipPackageCheck) { 6725 if (mInstantAppResolverConnection == null) { 6726 return false; 6727 } 6728 if (mInstantAppInstallerActivity == null) { 6729 return false; 6730 } 6731 if (intent.getComponent() != null) { 6732 return false; 6733 } 6734 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 6735 return false; 6736 } 6737 if (!skipPackageCheck && intent.getPackage() != null) { 6738 return false; 6739 } 6740 final boolean isWebUri = hasWebURI(intent); 6741 if (!isWebUri || intent.getData().getHost() == null) { 6742 return false; 6743 } 6744 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 6745 // Or if there's already an ephemeral app installed that handles the action 6746 synchronized (mPackages) { 6747 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 6748 for (int n = 0; n < count; n++) { 6749 final ResolveInfo info = resolvedActivities.get(n); 6750 final String packageName = info.activityInfo.packageName; 6751 final PackageSetting ps = mSettings.mPackages.get(packageName); 6752 if (ps != null) { 6753 // only check domain verification status if the app is not a browser 6754 if (!info.handleAllWebDataURI) { 6755 // Try to get the status from User settings first 6756 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6757 final int status = (int) (packedStatus >> 32); 6758 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 6759 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6760 if (DEBUG_EPHEMERAL) { 6761 Slog.v(TAG, "DENY instant app;" 6762 + " pkg: " + packageName + ", status: " + status); 6763 } 6764 return false; 6765 } 6766 } 6767 if (ps.getInstantApp(userId)) { 6768 if (DEBUG_EPHEMERAL) { 6769 Slog.v(TAG, "DENY instant app installed;" 6770 + " pkg: " + packageName); 6771 } 6772 return false; 6773 } 6774 } 6775 } 6776 } 6777 // We've exhausted all ways to deny ephemeral application; let the system look for them. 6778 return true; 6779 } 6780 6781 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 6782 Intent origIntent, String resolvedType, String callingPackage, 6783 Bundle verificationBundle, int userId) { 6784 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 6785 new InstantAppRequest(responseObj, origIntent, resolvedType, 6786 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 6787 mHandler.sendMessage(msg); 6788 } 6789 6790 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 6791 int flags, List<ResolveInfo> query, int userId) { 6792 if (query != null) { 6793 final int N = query.size(); 6794 if (N == 1) { 6795 return query.get(0); 6796 } else if (N > 1) { 6797 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 6798 // If there is more than one activity with the same priority, 6799 // then let the user decide between them. 6800 ResolveInfo r0 = query.get(0); 6801 ResolveInfo r1 = query.get(1); 6802 if (DEBUG_INTENT_MATCHING || debug) { 6803 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 6804 + r1.activityInfo.name + "=" + r1.priority); 6805 } 6806 // If the first activity has a higher priority, or a different 6807 // default, then it is always desirable to pick it. 6808 if (r0.priority != r1.priority 6809 || r0.preferredOrder != r1.preferredOrder 6810 || r0.isDefault != r1.isDefault) { 6811 return query.get(0); 6812 } 6813 // If we have saved a preference for a preferred activity for 6814 // this Intent, use that. 6815 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 6816 flags, query, r0.priority, true, false, debug, userId); 6817 if (ri != null) { 6818 return ri; 6819 } 6820 // If we have an ephemeral app, use it 6821 for (int i = 0; i < N; i++) { 6822 ri = query.get(i); 6823 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6824 final String packageName = ri.activityInfo.packageName; 6825 final PackageSetting ps = mSettings.mPackages.get(packageName); 6826 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6827 final int status = (int)(packedStatus >> 32); 6828 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6829 return ri; 6830 } 6831 } 6832 } 6833 ri = new ResolveInfo(mResolveInfo); 6834 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6835 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6836 // If all of the options come from the same package, show the application's 6837 // label and icon instead of the generic resolver's. 6838 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6839 // and then throw away the ResolveInfo itself, meaning that the caller loses 6840 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6841 // a fallback for this case; we only set the target package's resources on 6842 // the ResolveInfo, not the ActivityInfo. 6843 final String intentPackage = intent.getPackage(); 6844 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6845 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6846 ri.resolvePackageName = intentPackage; 6847 if (userNeedsBadging(userId)) { 6848 ri.noResourceId = true; 6849 } else { 6850 ri.icon = appi.icon; 6851 } 6852 ri.iconResourceId = appi.icon; 6853 ri.labelRes = appi.labelRes; 6854 } 6855 ri.activityInfo.applicationInfo = new ApplicationInfo( 6856 ri.activityInfo.applicationInfo); 6857 if (userId != 0) { 6858 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6859 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6860 } 6861 // Make sure that the resolver is displayable in car mode 6862 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6863 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6864 return ri; 6865 } 6866 } 6867 return null; 6868 } 6869 6870 /** 6871 * Return true if the given list is not empty and all of its contents have 6872 * an activityInfo with the given package name. 6873 */ 6874 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6875 if (ArrayUtils.isEmpty(list)) { 6876 return false; 6877 } 6878 for (int i = 0, N = list.size(); i < N; i++) { 6879 final ResolveInfo ri = list.get(i); 6880 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6881 if (ai == null || !packageName.equals(ai.packageName)) { 6882 return false; 6883 } 6884 } 6885 return true; 6886 } 6887 6888 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6889 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6890 final int N = query.size(); 6891 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6892 .get(userId); 6893 // Get the list of persistent preferred activities that handle the intent 6894 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6895 List<PersistentPreferredActivity> pprefs = ppir != null 6896 ? ppir.queryIntent(intent, resolvedType, 6897 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6898 userId) 6899 : null; 6900 if (pprefs != null && pprefs.size() > 0) { 6901 final int M = pprefs.size(); 6902 for (int i=0; i<M; i++) { 6903 final PersistentPreferredActivity ppa = pprefs.get(i); 6904 if (DEBUG_PREFERRED || debug) { 6905 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6906 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6907 + "\n component=" + ppa.mComponent); 6908 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6909 } 6910 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6911 flags | MATCH_DISABLED_COMPONENTS, userId); 6912 if (DEBUG_PREFERRED || debug) { 6913 Slog.v(TAG, "Found persistent preferred activity:"); 6914 if (ai != null) { 6915 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6916 } else { 6917 Slog.v(TAG, " null"); 6918 } 6919 } 6920 if (ai == null) { 6921 // This previously registered persistent preferred activity 6922 // component is no longer known. Ignore it and do NOT remove it. 6923 continue; 6924 } 6925 for (int j=0; j<N; j++) { 6926 final ResolveInfo ri = query.get(j); 6927 if (!ri.activityInfo.applicationInfo.packageName 6928 .equals(ai.applicationInfo.packageName)) { 6929 continue; 6930 } 6931 if (!ri.activityInfo.name.equals(ai.name)) { 6932 continue; 6933 } 6934 // Found a persistent preference that can handle the intent. 6935 if (DEBUG_PREFERRED || debug) { 6936 Slog.v(TAG, "Returning persistent preferred activity: " + 6937 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6938 } 6939 return ri; 6940 } 6941 } 6942 } 6943 return null; 6944 } 6945 6946 // TODO: handle preferred activities missing while user has amnesia 6947 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6948 List<ResolveInfo> query, int priority, boolean always, 6949 boolean removeMatches, boolean debug, int userId) { 6950 if (!sUserManager.exists(userId)) return null; 6951 final int callingUid = Binder.getCallingUid(); 6952 flags = updateFlagsForResolve( 6953 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6954 intent = updateIntentForResolve(intent); 6955 // writer 6956 synchronized (mPackages) { 6957 // Try to find a matching persistent preferred activity. 6958 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6959 debug, userId); 6960 6961 // If a persistent preferred activity matched, use it. 6962 if (pri != null) { 6963 return pri; 6964 } 6965 6966 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6967 // Get the list of preferred activities that handle the intent 6968 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6969 List<PreferredActivity> prefs = pir != null 6970 ? pir.queryIntent(intent, resolvedType, 6971 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6972 userId) 6973 : null; 6974 if (prefs != null && prefs.size() > 0) { 6975 boolean changed = false; 6976 try { 6977 // First figure out how good the original match set is. 6978 // We will only allow preferred activities that came 6979 // from the same match quality. 6980 int match = 0; 6981 6982 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6983 6984 final int N = query.size(); 6985 for (int j=0; j<N; j++) { 6986 final ResolveInfo ri = query.get(j); 6987 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6988 + ": 0x" + Integer.toHexString(match)); 6989 if (ri.match > match) { 6990 match = ri.match; 6991 } 6992 } 6993 6994 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6995 + Integer.toHexString(match)); 6996 6997 match &= IntentFilter.MATCH_CATEGORY_MASK; 6998 final int M = prefs.size(); 6999 for (int i=0; i<M; i++) { 7000 final PreferredActivity pa = prefs.get(i); 7001 if (DEBUG_PREFERRED || debug) { 7002 Slog.v(TAG, "Checking PreferredActivity ds=" 7003 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 7004 + "\n component=" + pa.mPref.mComponent); 7005 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 7006 } 7007 if (pa.mPref.mMatch != match) { 7008 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 7009 + Integer.toHexString(pa.mPref.mMatch)); 7010 continue; 7011 } 7012 // If it's not an "always" type preferred activity and that's what we're 7013 // looking for, skip it. 7014 if (always && !pa.mPref.mAlways) { 7015 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 7016 continue; 7017 } 7018 final ActivityInfo ai = getActivityInfo( 7019 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 7020 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 7021 userId); 7022 if (DEBUG_PREFERRED || debug) { 7023 Slog.v(TAG, "Found preferred activity:"); 7024 if (ai != null) { 7025 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 7026 } else { 7027 Slog.v(TAG, " null"); 7028 } 7029 } 7030 if (ai == null) { 7031 // This previously registered preferred activity 7032 // component is no longer known. Most likely an update 7033 // to the app was installed and in the new version this 7034 // component no longer exists. Clean it up by removing 7035 // it from the preferred activities list, and skip it. 7036 Slog.w(TAG, "Removing dangling preferred activity: " 7037 + pa.mPref.mComponent); 7038 pir.removeFilter(pa); 7039 changed = true; 7040 continue; 7041 } 7042 for (int j=0; j<N; j++) { 7043 final ResolveInfo ri = query.get(j); 7044 if (!ri.activityInfo.applicationInfo.packageName 7045 .equals(ai.applicationInfo.packageName)) { 7046 continue; 7047 } 7048 if (!ri.activityInfo.name.equals(ai.name)) { 7049 continue; 7050 } 7051 7052 if (removeMatches) { 7053 pir.removeFilter(pa); 7054 changed = true; 7055 if (DEBUG_PREFERRED) { 7056 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 7057 } 7058 break; 7059 } 7060 7061 // Okay we found a previously set preferred or last chosen app. 7062 // If the result set is different from when this 7063 // was created, and is not a subset of the preferred set, we need to 7064 // clear it and re-ask the user their preference, if we're looking for 7065 // an "always" type entry. 7066 if (always && !pa.mPref.sameSet(query)) { 7067 if (pa.mPref.isSuperset(query)) { 7068 // some components of the set are no longer present in 7069 // the query, but the preferred activity can still be reused 7070 if (DEBUG_PREFERRED) { 7071 Slog.i(TAG, "Result set changed, but PreferredActivity is" 7072 + " still valid as only non-preferred components" 7073 + " were removed for " + intent + " type " 7074 + resolvedType); 7075 } 7076 // remove obsolete components and re-add the up-to-date filter 7077 PreferredActivity freshPa = new PreferredActivity(pa, 7078 pa.mPref.mMatch, 7079 pa.mPref.discardObsoleteComponents(query), 7080 pa.mPref.mComponent, 7081 pa.mPref.mAlways); 7082 pir.removeFilter(pa); 7083 pir.addFilter(freshPa); 7084 changed = true; 7085 } else { 7086 Slog.i(TAG, 7087 "Result set changed, dropping preferred activity for " 7088 + intent + " type " + resolvedType); 7089 if (DEBUG_PREFERRED) { 7090 Slog.v(TAG, "Removing preferred activity since set changed " 7091 + pa.mPref.mComponent); 7092 } 7093 pir.removeFilter(pa); 7094 // Re-add the filter as a "last chosen" entry (!always) 7095 PreferredActivity lastChosen = new PreferredActivity( 7096 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 7097 pir.addFilter(lastChosen); 7098 changed = true; 7099 return null; 7100 } 7101 } 7102 7103 // Yay! Either the set matched or we're looking for the last chosen 7104 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 7105 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 7106 return ri; 7107 } 7108 } 7109 } finally { 7110 if (changed) { 7111 if (DEBUG_PREFERRED) { 7112 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 7113 } 7114 scheduleWritePackageRestrictionsLocked(userId); 7115 } 7116 } 7117 } 7118 } 7119 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 7120 return null; 7121 } 7122 7123 /* 7124 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 7125 */ 7126 @Override 7127 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 7128 int targetUserId) { 7129 mContext.enforceCallingOrSelfPermission( 7130 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 7131 List<CrossProfileIntentFilter> matches = 7132 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 7133 if (matches != null) { 7134 int size = matches.size(); 7135 for (int i = 0; i < size; i++) { 7136 if (matches.get(i).getTargetUserId() == targetUserId) return true; 7137 } 7138 } 7139 if (hasWebURI(intent)) { 7140 // cross-profile app linking works only towards the parent. 7141 final int callingUid = Binder.getCallingUid(); 7142 final UserInfo parent = getProfileParent(sourceUserId); 7143 synchronized(mPackages) { 7144 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 7145 false /*includeInstantApps*/); 7146 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 7147 intent, resolvedType, flags, sourceUserId, parent.id); 7148 return xpDomainInfo != null; 7149 } 7150 } 7151 return false; 7152 } 7153 7154 private UserInfo getProfileParent(int userId) { 7155 final long identity = Binder.clearCallingIdentity(); 7156 try { 7157 return sUserManager.getProfileParent(userId); 7158 } finally { 7159 Binder.restoreCallingIdentity(identity); 7160 } 7161 } 7162 7163 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 7164 String resolvedType, int userId) { 7165 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 7166 if (resolver != null) { 7167 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 7168 } 7169 return null; 7170 } 7171 7172 @Override 7173 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 7174 String resolvedType, int flags, int userId) { 7175 try { 7176 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 7177 7178 return new ParceledListSlice<>( 7179 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 7180 } finally { 7181 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7182 } 7183 } 7184 7185 /** 7186 * Returns the package name of the calling Uid if it's an instant app. If it isn't 7187 * instant, returns {@code null}. 7188 */ 7189 private String getInstantAppPackageName(int callingUid) { 7190 synchronized (mPackages) { 7191 // If the caller is an isolated app use the owner's uid for the lookup. 7192 if (Process.isIsolated(callingUid)) { 7193 callingUid = mIsolatedOwners.get(callingUid); 7194 } 7195 final int appId = UserHandle.getAppId(callingUid); 7196 final Object obj = mSettings.getUserIdLPr(appId); 7197 if (obj instanceof PackageSetting) { 7198 final PackageSetting ps = (PackageSetting) obj; 7199 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 7200 return isInstantApp ? ps.pkg.packageName : null; 7201 } 7202 } 7203 return null; 7204 } 7205 7206 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 7207 String resolvedType, int flags, int userId) { 7208 return queryIntentActivitiesInternal( 7209 intent, resolvedType, flags, Binder.getCallingUid(), userId, 7210 false /*resolveForStart*/, true /*allowDynamicSplits*/); 7211 } 7212 7213 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 7214 String resolvedType, int flags, int filterCallingUid, int userId, 7215 boolean resolveForStart, boolean allowDynamicSplits) { 7216 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7217 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 7218 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7219 false /* requireFullPermission */, false /* checkShell */, 7220 "query intent activities"); 7221 final String pkgName = intent.getPackage(); 7222 ComponentName comp = intent.getComponent(); 7223 if (comp == null) { 7224 if (intent.getSelector() != null) { 7225 intent = intent.getSelector(); 7226 comp = intent.getComponent(); 7227 } 7228 } 7229 7230 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 7231 comp != null || pkgName != null /*onlyExposedExplicitly*/); 7232 if (comp != null) { 7233 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7234 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 7235 if (ai != null) { 7236 // When specifying an explicit component, we prevent the activity from being 7237 // used when either 1) the calling package is normal and the activity is within 7238 // an ephemeral application or 2) the calling package is ephemeral and the 7239 // activity is not visible to ephemeral applications. 7240 final boolean matchInstantApp = 7241 (flags & PackageManager.MATCH_INSTANT) != 0; 7242 final boolean matchVisibleToInstantAppOnly = 7243 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7244 final boolean matchExplicitlyVisibleOnly = 7245 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7246 final boolean isCallerInstantApp = 7247 instantAppPkgName != null; 7248 final boolean isTargetSameInstantApp = 7249 comp.getPackageName().equals(instantAppPkgName); 7250 final boolean isTargetInstantApp = 7251 (ai.applicationInfo.privateFlags 7252 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7253 final boolean isTargetVisibleToInstantApp = 7254 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7255 final boolean isTargetExplicitlyVisibleToInstantApp = 7256 isTargetVisibleToInstantApp 7257 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7258 final boolean isTargetHiddenFromInstantApp = 7259 !isTargetVisibleToInstantApp 7260 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7261 final boolean blockResolution = 7262 !isTargetSameInstantApp 7263 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7264 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7265 && isTargetHiddenFromInstantApp)); 7266 if (!blockResolution) { 7267 final ResolveInfo ri = new ResolveInfo(); 7268 ri.activityInfo = ai; 7269 list.add(ri); 7270 } 7271 } 7272 return applyPostResolutionFilter( 7273 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 7274 } 7275 7276 // reader 7277 boolean sortResult = false; 7278 boolean addEphemeral = false; 7279 List<ResolveInfo> result; 7280 final boolean ephemeralDisabled = isEphemeralDisabled(); 7281 synchronized (mPackages) { 7282 if (pkgName == null) { 7283 List<CrossProfileIntentFilter> matchingFilters = 7284 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 7285 // Check for results that need to skip the current profile. 7286 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 7287 resolvedType, flags, userId); 7288 if (xpResolveInfo != null) { 7289 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 7290 xpResult.add(xpResolveInfo); 7291 return applyPostResolutionFilter( 7292 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 7293 allowDynamicSplits, filterCallingUid, userId); 7294 } 7295 7296 // Check for results in the current profile. 7297 result = filterIfNotSystemUser(mActivities.queryIntent( 7298 intent, resolvedType, flags, userId), userId); 7299 addEphemeral = !ephemeralDisabled 7300 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 7301 // Check for cross profile results. 7302 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 7303 xpResolveInfo = queryCrossProfileIntents( 7304 matchingFilters, intent, resolvedType, flags, userId, 7305 hasNonNegativePriorityResult); 7306 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 7307 boolean isVisibleToUser = filterIfNotSystemUser( 7308 Collections.singletonList(xpResolveInfo), userId).size() > 0; 7309 if (isVisibleToUser) { 7310 result.add(xpResolveInfo); 7311 sortResult = true; 7312 } 7313 } 7314 if (hasWebURI(intent)) { 7315 CrossProfileDomainInfo xpDomainInfo = null; 7316 final UserInfo parent = getProfileParent(userId); 7317 if (parent != null) { 7318 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 7319 flags, userId, parent.id); 7320 } 7321 if (xpDomainInfo != null) { 7322 if (xpResolveInfo != null) { 7323 // If we didn't remove it, the cross-profile ResolveInfo would be twice 7324 // in the result. 7325 result.remove(xpResolveInfo); 7326 } 7327 if (result.size() == 0 && !addEphemeral) { 7328 // No result in current profile, but found candidate in parent user. 7329 // And we are not going to add emphemeral app, so we can return the 7330 // result straight away. 7331 result.add(xpDomainInfo.resolveInfo); 7332 return applyPostResolutionFilter(result, instantAppPkgName, 7333 allowDynamicSplits, filterCallingUid, userId); 7334 } 7335 } else if (result.size() <= 1 && !addEphemeral) { 7336 // No result in parent user and <= 1 result in current profile, and we 7337 // are not going to add emphemeral app, so we can return the result without 7338 // further processing. 7339 return applyPostResolutionFilter(result, instantAppPkgName, 7340 allowDynamicSplits, filterCallingUid, userId); 7341 } 7342 // We have more than one candidate (combining results from current and parent 7343 // profile), so we need filtering and sorting. 7344 result = filterCandidatesWithDomainPreferredActivitiesLPr( 7345 intent, flags, result, xpDomainInfo, userId); 7346 sortResult = true; 7347 } 7348 } else { 7349 final PackageParser.Package pkg = mPackages.get(pkgName); 7350 result = null; 7351 if (pkg != null) { 7352 result = filterIfNotSystemUser( 7353 mActivities.queryIntentForPackage( 7354 intent, resolvedType, flags, pkg.activities, userId), 7355 userId); 7356 } 7357 if (result == null || result.size() == 0) { 7358 // the caller wants to resolve for a particular package; however, there 7359 // were no installed results, so, try to find an ephemeral result 7360 addEphemeral = !ephemeralDisabled 7361 && isInstantAppAllowed( 7362 intent, null /*result*/, userId, true /*skipPackageCheck*/); 7363 if (result == null) { 7364 result = new ArrayList<>(); 7365 } 7366 } 7367 } 7368 } 7369 if (addEphemeral) { 7370 result = maybeAddInstantAppInstaller( 7371 result, intent, resolvedType, flags, userId, resolveForStart); 7372 } 7373 if (sortResult) { 7374 Collections.sort(result, mResolvePrioritySorter); 7375 } 7376 return applyPostResolutionFilter( 7377 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 7378 } 7379 7380 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 7381 String resolvedType, int flags, int userId, boolean resolveForStart) { 7382 // first, check to see if we've got an instant app already installed 7383 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 7384 ResolveInfo localInstantApp = null; 7385 boolean blockResolution = false; 7386 if (!alreadyResolvedLocally) { 7387 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 7388 flags 7389 | PackageManager.GET_RESOLVED_FILTER 7390 | PackageManager.MATCH_INSTANT 7391 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 7392 userId); 7393 for (int i = instantApps.size() - 1; i >= 0; --i) { 7394 final ResolveInfo info = instantApps.get(i); 7395 final String packageName = info.activityInfo.packageName; 7396 final PackageSetting ps = mSettings.mPackages.get(packageName); 7397 if (ps.getInstantApp(userId)) { 7398 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 7399 final int status = (int)(packedStatus >> 32); 7400 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 7401 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7402 // there's a local instant application installed, but, the user has 7403 // chosen to never use it; skip resolution and don't acknowledge 7404 // an instant application is even available 7405 if (DEBUG_EPHEMERAL) { 7406 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 7407 } 7408 blockResolution = true; 7409 break; 7410 } else { 7411 // we have a locally installed instant application; skip resolution 7412 // but acknowledge there's an instant application available 7413 if (DEBUG_EPHEMERAL) { 7414 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 7415 } 7416 localInstantApp = info; 7417 break; 7418 } 7419 } 7420 } 7421 } 7422 // no app installed, let's see if one's available 7423 AuxiliaryResolveInfo auxiliaryResponse = null; 7424 if (!blockResolution) { 7425 if (localInstantApp == null) { 7426 // we don't have an instant app locally, resolve externally 7427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 7428 final InstantAppRequest requestObject = new InstantAppRequest( 7429 null /*responseObj*/, intent /*origIntent*/, resolvedType, 7430 null /*callingPackage*/, userId, null /*verificationBundle*/, 7431 resolveForStart); 7432 auxiliaryResponse = 7433 InstantAppResolver.doInstantAppResolutionPhaseOne( 7434 mContext, mInstantAppResolverConnection, requestObject); 7435 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7436 } else { 7437 // we have an instant application locally, but, we can't admit that since 7438 // callers shouldn't be able to determine prior browsing. create a dummy 7439 // auxiliary response so the downstream code behaves as if there's an 7440 // instant application available externally. when it comes time to start 7441 // the instant application, we'll do the right thing. 7442 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 7443 auxiliaryResponse = new AuxiliaryResolveInfo( 7444 ai.packageName, null /*splitName*/, null /*failureActivity*/, 7445 ai.versionCode, null /*failureIntent*/); 7446 } 7447 } 7448 if (auxiliaryResponse != null) { 7449 if (DEBUG_EPHEMERAL) { 7450 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7451 } 7452 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 7453 final PackageSetting ps = 7454 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 7455 if (ps != null) { 7456 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 7457 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 7458 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 7459 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 7460 // make sure this resolver is the default 7461 ephemeralInstaller.isDefault = true; 7462 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7463 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7464 // add a non-generic filter 7465 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 7466 ephemeralInstaller.filter.addDataPath( 7467 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 7468 ephemeralInstaller.isInstantAppAvailable = true; 7469 result.add(ephemeralInstaller); 7470 } 7471 } 7472 return result; 7473 } 7474 7475 private static class CrossProfileDomainInfo { 7476 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 7477 ResolveInfo resolveInfo; 7478 /* Best domain verification status of the activities found in the other profile */ 7479 int bestDomainVerificationStatus; 7480 } 7481 7482 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 7483 String resolvedType, int flags, int sourceUserId, int parentUserId) { 7484 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 7485 sourceUserId)) { 7486 return null; 7487 } 7488 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7489 resolvedType, flags, parentUserId); 7490 7491 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 7492 return null; 7493 } 7494 CrossProfileDomainInfo result = null; 7495 int size = resultTargetUser.size(); 7496 for (int i = 0; i < size; i++) { 7497 ResolveInfo riTargetUser = resultTargetUser.get(i); 7498 // Intent filter verification is only for filters that specify a host. So don't return 7499 // those that handle all web uris. 7500 if (riTargetUser.handleAllWebDataURI) { 7501 continue; 7502 } 7503 String packageName = riTargetUser.activityInfo.packageName; 7504 PackageSetting ps = mSettings.mPackages.get(packageName); 7505 if (ps == null) { 7506 continue; 7507 } 7508 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 7509 int status = (int)(verificationState >> 32); 7510 if (result == null) { 7511 result = new CrossProfileDomainInfo(); 7512 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 7513 sourceUserId, parentUserId); 7514 result.bestDomainVerificationStatus = status; 7515 } else { 7516 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 7517 result.bestDomainVerificationStatus); 7518 } 7519 } 7520 // Don't consider matches with status NEVER across profiles. 7521 if (result != null && result.bestDomainVerificationStatus 7522 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7523 return null; 7524 } 7525 return result; 7526 } 7527 7528 /** 7529 * Verification statuses are ordered from the worse to the best, except for 7530 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 7531 */ 7532 private int bestDomainVerificationStatus(int status1, int status2) { 7533 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7534 return status2; 7535 } 7536 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7537 return status1; 7538 } 7539 return (int) MathUtils.max(status1, status2); 7540 } 7541 7542 private boolean isUserEnabled(int userId) { 7543 long callingId = Binder.clearCallingIdentity(); 7544 try { 7545 UserInfo userInfo = sUserManager.getUserInfo(userId); 7546 return userInfo != null && userInfo.isEnabled(); 7547 } finally { 7548 Binder.restoreCallingIdentity(callingId); 7549 } 7550 } 7551 7552 /** 7553 * Filter out activities with systemUserOnly flag set, when current user is not System. 7554 * 7555 * @return filtered list 7556 */ 7557 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 7558 if (userId == UserHandle.USER_SYSTEM) { 7559 return resolveInfos; 7560 } 7561 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7562 ResolveInfo info = resolveInfos.get(i); 7563 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 7564 resolveInfos.remove(i); 7565 } 7566 } 7567 return resolveInfos; 7568 } 7569 7570 /** 7571 * Filters out ephemeral activities. 7572 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 7573 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 7574 * 7575 * @param resolveInfos The pre-filtered list of resolved activities 7576 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 7577 * is performed. 7578 * @return A filtered list of resolved activities. 7579 */ 7580 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 7581 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) { 7582 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7583 final ResolveInfo info = resolveInfos.get(i); 7584 // allow activities that are defined in the provided package 7585 if (allowDynamicSplits 7586 && info.activityInfo.splitName != null 7587 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 7588 info.activityInfo.splitName)) { 7589 if (mInstantAppInstallerInfo == null) { 7590 if (DEBUG_INSTALL) { 7591 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 7592 } 7593 resolveInfos.remove(i); 7594 continue; 7595 } 7596 // requested activity is defined in a split that hasn't been installed yet. 7597 // add the installer to the resolve list 7598 if (DEBUG_INSTALL) { 7599 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 7600 } 7601 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7602 final ComponentName installFailureActivity = findInstallFailureActivity( 7603 info.activityInfo.packageName, filterCallingUid, userId); 7604 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7605 info.activityInfo.packageName, info.activityInfo.splitName, 7606 installFailureActivity, 7607 info.activityInfo.applicationInfo.versionCode, 7608 null /*failureIntent*/); 7609 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7610 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7611 // add a non-generic filter 7612 installerInfo.filter = new IntentFilter(); 7613 7614 // This resolve info may appear in the chooser UI, so let us make it 7615 // look as the one it replaces as far as the user is concerned which 7616 // requires loading the correct label and icon for the resolve info. 7617 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7618 installerInfo.labelRes = info.resolveLabelResId(); 7619 installerInfo.icon = info.resolveIconResId(); 7620 7621 // propagate priority/preferred order/default 7622 installerInfo.priority = info.priority; 7623 installerInfo.preferredOrder = info.preferredOrder; 7624 installerInfo.isDefault = info.isDefault; 7625 resolveInfos.set(i, installerInfo); 7626 continue; 7627 } 7628 // caller is a full app, don't need to apply any other filtering 7629 if (ephemeralPkgName == null) { 7630 continue; 7631 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 7632 // caller is same app; don't need to apply any other filtering 7633 continue; 7634 } 7635 // allow activities that have been explicitly exposed to ephemeral apps 7636 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 7637 if (!isEphemeralApp 7638 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7639 continue; 7640 } 7641 resolveInfos.remove(i); 7642 } 7643 return resolveInfos; 7644 } 7645 7646 /** 7647 * Returns the activity component that can handle install failures. 7648 * <p>By default, the instant application installer handles failures. However, an 7649 * application may want to handle failures on its own. Applications do this by 7650 * creating an activity with an intent filter that handles the action 7651 * {@link Intent#ACTION_INSTALL_FAILURE}. 7652 */ 7653 private @Nullable ComponentName findInstallFailureActivity( 7654 String packageName, int filterCallingUid, int userId) { 7655 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 7656 failureActivityIntent.setPackage(packageName); 7657 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 7658 final List<ResolveInfo> result = queryIntentActivitiesInternal( 7659 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 7660 false /*resolveForStart*/, false /*allowDynamicSplits*/); 7661 final int NR = result.size(); 7662 if (NR > 0) { 7663 for (int i = 0; i < NR; i++) { 7664 final ResolveInfo info = result.get(i); 7665 if (info.activityInfo.splitName != null) { 7666 continue; 7667 } 7668 return new ComponentName(packageName, info.activityInfo.name); 7669 } 7670 } 7671 return null; 7672 } 7673 7674 /** 7675 * @param resolveInfos list of resolve infos in descending priority order 7676 * @return if the list contains a resolve info with non-negative priority 7677 */ 7678 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 7679 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 7680 } 7681 7682 private static boolean hasWebURI(Intent intent) { 7683 if (intent.getData() == null) { 7684 return false; 7685 } 7686 final String scheme = intent.getScheme(); 7687 if (TextUtils.isEmpty(scheme)) { 7688 return false; 7689 } 7690 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 7691 } 7692 7693 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 7694 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 7695 int userId) { 7696 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 7697 7698 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7699 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 7700 candidates.size()); 7701 } 7702 7703 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 7704 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 7705 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 7706 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 7707 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 7708 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 7709 7710 synchronized (mPackages) { 7711 final int count = candidates.size(); 7712 // First, try to use linked apps. Partition the candidates into four lists: 7713 // one for the final results, one for the "do not use ever", one for "undefined status" 7714 // and finally one for "browser app type". 7715 for (int n=0; n<count; n++) { 7716 ResolveInfo info = candidates.get(n); 7717 String packageName = info.activityInfo.packageName; 7718 PackageSetting ps = mSettings.mPackages.get(packageName); 7719 if (ps != null) { 7720 // Add to the special match all list (Browser use case) 7721 if (info.handleAllWebDataURI) { 7722 matchAllList.add(info); 7723 continue; 7724 } 7725 // Try to get the status from User settings first 7726 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 7727 int status = (int)(packedStatus >> 32); 7728 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 7729 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 7730 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7731 Slog.i(TAG, " + always: " + info.activityInfo.packageName 7732 + " : linkgen=" + linkGeneration); 7733 } 7734 // Use link-enabled generation as preferredOrder, i.e. 7735 // prefer newly-enabled over earlier-enabled. 7736 info.preferredOrder = linkGeneration; 7737 alwaysList.add(info); 7738 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7739 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7740 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 7741 } 7742 neverList.add(info); 7743 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 7744 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7745 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 7746 } 7747 alwaysAskList.add(info); 7748 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 7749 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 7750 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7751 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 7752 } 7753 undefinedList.add(info); 7754 } 7755 } 7756 } 7757 7758 // We'll want to include browser possibilities in a few cases 7759 boolean includeBrowser = false; 7760 7761 // First try to add the "always" resolution(s) for the current user, if any 7762 if (alwaysList.size() > 0) { 7763 result.addAll(alwaysList); 7764 } else { 7765 // Add all undefined apps as we want them to appear in the disambiguation dialog. 7766 result.addAll(undefinedList); 7767 // Maybe add one for the other profile. 7768 if (xpDomainInfo != null && ( 7769 xpDomainInfo.bestDomainVerificationStatus 7770 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 7771 result.add(xpDomainInfo.resolveInfo); 7772 } 7773 includeBrowser = true; 7774 } 7775 7776 // The presence of any 'always ask' alternatives means we'll also offer browsers. 7777 // If there were 'always' entries their preferred order has been set, so we also 7778 // back that off to make the alternatives equivalent 7779 if (alwaysAskList.size() > 0) { 7780 for (ResolveInfo i : result) { 7781 i.preferredOrder = 0; 7782 } 7783 result.addAll(alwaysAskList); 7784 includeBrowser = true; 7785 } 7786 7787 if (includeBrowser) { 7788 // Also add browsers (all of them or only the default one) 7789 if (DEBUG_DOMAIN_VERIFICATION) { 7790 Slog.v(TAG, " ...including browsers in candidate set"); 7791 } 7792 if ((matchFlags & MATCH_ALL) != 0) { 7793 result.addAll(matchAllList); 7794 } else { 7795 // Browser/generic handling case. If there's a default browser, go straight 7796 // to that (but only if there is no other higher-priority match). 7797 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7798 int maxMatchPrio = 0; 7799 ResolveInfo defaultBrowserMatch = null; 7800 final int numCandidates = matchAllList.size(); 7801 for (int n = 0; n < numCandidates; n++) { 7802 ResolveInfo info = matchAllList.get(n); 7803 // track the highest overall match priority... 7804 if (info.priority > maxMatchPrio) { 7805 maxMatchPrio = info.priority; 7806 } 7807 // ...and the highest-priority default browser match 7808 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7809 if (defaultBrowserMatch == null 7810 || (defaultBrowserMatch.priority < info.priority)) { 7811 if (debug) { 7812 Slog.v(TAG, "Considering default browser match " + info); 7813 } 7814 defaultBrowserMatch = info; 7815 } 7816 } 7817 } 7818 if (defaultBrowserMatch != null 7819 && defaultBrowserMatch.priority >= maxMatchPrio 7820 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7821 { 7822 if (debug) { 7823 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7824 } 7825 result.add(defaultBrowserMatch); 7826 } else { 7827 result.addAll(matchAllList); 7828 } 7829 } 7830 7831 // If there is nothing selected, add all candidates and remove the ones that the user 7832 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7833 if (result.size() == 0) { 7834 result.addAll(candidates); 7835 result.removeAll(neverList); 7836 } 7837 } 7838 } 7839 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7840 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7841 result.size()); 7842 for (ResolveInfo info : result) { 7843 Slog.v(TAG, " + " + info.activityInfo); 7844 } 7845 } 7846 return result; 7847 } 7848 7849 // Returns a packed value as a long: 7850 // 7851 // high 'int'-sized word: link status: undefined/ask/never/always. 7852 // low 'int'-sized word: relative priority among 'always' results. 7853 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7854 long result = ps.getDomainVerificationStatusForUser(userId); 7855 // if none available, get the master status 7856 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7857 if (ps.getIntentFilterVerificationInfo() != null) { 7858 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7859 } 7860 } 7861 return result; 7862 } 7863 7864 private ResolveInfo querySkipCurrentProfileIntents( 7865 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7866 int flags, int sourceUserId) { 7867 if (matchingFilters != null) { 7868 int size = matchingFilters.size(); 7869 for (int i = 0; i < size; i ++) { 7870 CrossProfileIntentFilter filter = matchingFilters.get(i); 7871 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7872 // Checking if there are activities in the target user that can handle the 7873 // intent. 7874 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7875 resolvedType, flags, sourceUserId); 7876 if (resolveInfo != null) { 7877 return resolveInfo; 7878 } 7879 } 7880 } 7881 } 7882 return null; 7883 } 7884 7885 // Return matching ResolveInfo in target user if any. 7886 private ResolveInfo queryCrossProfileIntents( 7887 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7888 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7889 if (matchingFilters != null) { 7890 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7891 // match the same intent. For performance reasons, it is better not to 7892 // run queryIntent twice for the same userId 7893 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7894 int size = matchingFilters.size(); 7895 for (int i = 0; i < size; i++) { 7896 CrossProfileIntentFilter filter = matchingFilters.get(i); 7897 int targetUserId = filter.getTargetUserId(); 7898 boolean skipCurrentProfile = 7899 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7900 boolean skipCurrentProfileIfNoMatchFound = 7901 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7902 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7903 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7904 // Checking if there are activities in the target user that can handle the 7905 // intent. 7906 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7907 resolvedType, flags, sourceUserId); 7908 if (resolveInfo != null) return resolveInfo; 7909 alreadyTriedUserIds.put(targetUserId, true); 7910 } 7911 } 7912 } 7913 return null; 7914 } 7915 7916 /** 7917 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7918 * will forward the intent to the filter's target user. 7919 * Otherwise, returns null. 7920 */ 7921 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7922 String resolvedType, int flags, int sourceUserId) { 7923 int targetUserId = filter.getTargetUserId(); 7924 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7925 resolvedType, flags, targetUserId); 7926 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7927 // If all the matches in the target profile are suspended, return null. 7928 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7929 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7930 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7931 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7932 targetUserId); 7933 } 7934 } 7935 } 7936 return null; 7937 } 7938 7939 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7940 int sourceUserId, int targetUserId) { 7941 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7942 long ident = Binder.clearCallingIdentity(); 7943 boolean targetIsProfile; 7944 try { 7945 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7946 } finally { 7947 Binder.restoreCallingIdentity(ident); 7948 } 7949 String className; 7950 if (targetIsProfile) { 7951 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7952 } else { 7953 className = FORWARD_INTENT_TO_PARENT; 7954 } 7955 ComponentName forwardingActivityComponentName = new ComponentName( 7956 mAndroidApplication.packageName, className); 7957 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7958 sourceUserId); 7959 if (!targetIsProfile) { 7960 forwardingActivityInfo.showUserIcon = targetUserId; 7961 forwardingResolveInfo.noResourceId = true; 7962 } 7963 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7964 forwardingResolveInfo.priority = 0; 7965 forwardingResolveInfo.preferredOrder = 0; 7966 forwardingResolveInfo.match = 0; 7967 forwardingResolveInfo.isDefault = true; 7968 forwardingResolveInfo.filter = filter; 7969 forwardingResolveInfo.targetUserId = targetUserId; 7970 return forwardingResolveInfo; 7971 } 7972 7973 @Override 7974 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7975 Intent[] specifics, String[] specificTypes, Intent intent, 7976 String resolvedType, int flags, int userId) { 7977 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7978 specificTypes, intent, resolvedType, flags, userId)); 7979 } 7980 7981 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7982 Intent[] specifics, String[] specificTypes, Intent intent, 7983 String resolvedType, int flags, int userId) { 7984 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7985 final int callingUid = Binder.getCallingUid(); 7986 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7987 false /*includeInstantApps*/); 7988 enforceCrossUserPermission(callingUid, userId, 7989 false /*requireFullPermission*/, false /*checkShell*/, 7990 "query intent activity options"); 7991 final String resultsAction = intent.getAction(); 7992 7993 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7994 | PackageManager.GET_RESOLVED_FILTER, userId); 7995 7996 if (DEBUG_INTENT_MATCHING) { 7997 Log.v(TAG, "Query " + intent + ": " + results); 7998 } 7999 8000 int specificsPos = 0; 8001 int N; 8002 8003 // todo: note that the algorithm used here is O(N^2). This 8004 // isn't a problem in our current environment, but if we start running 8005 // into situations where we have more than 5 or 10 matches then this 8006 // should probably be changed to something smarter... 8007 8008 // First we go through and resolve each of the specific items 8009 // that were supplied, taking care of removing any corresponding 8010 // duplicate items in the generic resolve list. 8011 if (specifics != null) { 8012 for (int i=0; i<specifics.length; i++) { 8013 final Intent sintent = specifics[i]; 8014 if (sintent == null) { 8015 continue; 8016 } 8017 8018 if (DEBUG_INTENT_MATCHING) { 8019 Log.v(TAG, "Specific #" + i + ": " + sintent); 8020 } 8021 8022 String action = sintent.getAction(); 8023 if (resultsAction != null && resultsAction.equals(action)) { 8024 // If this action was explicitly requested, then don't 8025 // remove things that have it. 8026 action = null; 8027 } 8028 8029 ResolveInfo ri = null; 8030 ActivityInfo ai = null; 8031 8032 ComponentName comp = sintent.getComponent(); 8033 if (comp == null) { 8034 ri = resolveIntent( 8035 sintent, 8036 specificTypes != null ? specificTypes[i] : null, 8037 flags, userId); 8038 if (ri == null) { 8039 continue; 8040 } 8041 if (ri == mResolveInfo) { 8042 // ACK! Must do something better with this. 8043 } 8044 ai = ri.activityInfo; 8045 comp = new ComponentName(ai.applicationInfo.packageName, 8046 ai.name); 8047 } else { 8048 ai = getActivityInfo(comp, flags, userId); 8049 if (ai == null) { 8050 continue; 8051 } 8052 } 8053 8054 // Look for any generic query activities that are duplicates 8055 // of this specific one, and remove them from the results. 8056 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 8057 N = results.size(); 8058 int j; 8059 for (j=specificsPos; j<N; j++) { 8060 ResolveInfo sri = results.get(j); 8061 if ((sri.activityInfo.name.equals(comp.getClassName()) 8062 && sri.activityInfo.applicationInfo.packageName.equals( 8063 comp.getPackageName())) 8064 || (action != null && sri.filter.matchAction(action))) { 8065 results.remove(j); 8066 if (DEBUG_INTENT_MATCHING) Log.v( 8067 TAG, "Removing duplicate item from " + j 8068 + " due to specific " + specificsPos); 8069 if (ri == null) { 8070 ri = sri; 8071 } 8072 j--; 8073 N--; 8074 } 8075 } 8076 8077 // Add this specific item to its proper place. 8078 if (ri == null) { 8079 ri = new ResolveInfo(); 8080 ri.activityInfo = ai; 8081 } 8082 results.add(specificsPos, ri); 8083 ri.specificIndex = i; 8084 specificsPos++; 8085 } 8086 } 8087 8088 // Now we go through the remaining generic results and remove any 8089 // duplicate actions that are found here. 8090 N = results.size(); 8091 for (int i=specificsPos; i<N-1; i++) { 8092 final ResolveInfo rii = results.get(i); 8093 if (rii.filter == null) { 8094 continue; 8095 } 8096 8097 // Iterate over all of the actions of this result's intent 8098 // filter... typically this should be just one. 8099 final Iterator<String> it = rii.filter.actionsIterator(); 8100 if (it == null) { 8101 continue; 8102 } 8103 while (it.hasNext()) { 8104 final String action = it.next(); 8105 if (resultsAction != null && resultsAction.equals(action)) { 8106 // If this action was explicitly requested, then don't 8107 // remove things that have it. 8108 continue; 8109 } 8110 for (int j=i+1; j<N; j++) { 8111 final ResolveInfo rij = results.get(j); 8112 if (rij.filter != null && rij.filter.hasAction(action)) { 8113 results.remove(j); 8114 if (DEBUG_INTENT_MATCHING) Log.v( 8115 TAG, "Removing duplicate item from " + j 8116 + " due to action " + action + " at " + i); 8117 j--; 8118 N--; 8119 } 8120 } 8121 } 8122 8123 // If the caller didn't request filter information, drop it now 8124 // so we don't have to marshall/unmarshall it. 8125 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 8126 rii.filter = null; 8127 } 8128 } 8129 8130 // Filter out the caller activity if so requested. 8131 if (caller != null) { 8132 N = results.size(); 8133 for (int i=0; i<N; i++) { 8134 ActivityInfo ainfo = results.get(i).activityInfo; 8135 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 8136 && caller.getClassName().equals(ainfo.name)) { 8137 results.remove(i); 8138 break; 8139 } 8140 } 8141 } 8142 8143 // If the caller didn't request filter information, 8144 // drop them now so we don't have to 8145 // marshall/unmarshall it. 8146 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 8147 N = results.size(); 8148 for (int i=0; i<N; i++) { 8149 results.get(i).filter = null; 8150 } 8151 } 8152 8153 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 8154 return results; 8155 } 8156 8157 @Override 8158 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 8159 String resolvedType, int flags, int userId) { 8160 return new ParceledListSlice<>( 8161 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 8162 false /*allowDynamicSplits*/)); 8163 } 8164 8165 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 8166 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 8167 if (!sUserManager.exists(userId)) return Collections.emptyList(); 8168 final int callingUid = Binder.getCallingUid(); 8169 enforceCrossUserPermission(callingUid, userId, 8170 false /*requireFullPermission*/, false /*checkShell*/, 8171 "query intent receivers"); 8172 final String instantAppPkgName = getInstantAppPackageName(callingUid); 8173 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 8174 false /*includeInstantApps*/); 8175 ComponentName comp = intent.getComponent(); 8176 if (comp == null) { 8177 if (intent.getSelector() != null) { 8178 intent = intent.getSelector(); 8179 comp = intent.getComponent(); 8180 } 8181 } 8182 if (comp != null) { 8183 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 8184 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 8185 if (ai != null) { 8186 // When specifying an explicit component, we prevent the activity from being 8187 // used when either 1) the calling package is normal and the activity is within 8188 // an instant application or 2) the calling package is ephemeral and the 8189 // activity is not visible to instant applications. 8190 final boolean matchInstantApp = 8191 (flags & PackageManager.MATCH_INSTANT) != 0; 8192 final boolean matchVisibleToInstantAppOnly = 8193 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 8194 final boolean matchExplicitlyVisibleOnly = 8195 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 8196 final boolean isCallerInstantApp = 8197 instantAppPkgName != null; 8198 final boolean isTargetSameInstantApp = 8199 comp.getPackageName().equals(instantAppPkgName); 8200 final boolean isTargetInstantApp = 8201 (ai.applicationInfo.privateFlags 8202 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 8203 final boolean isTargetVisibleToInstantApp = 8204 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 8205 final boolean isTargetExplicitlyVisibleToInstantApp = 8206 isTargetVisibleToInstantApp 8207 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 8208 final boolean isTargetHiddenFromInstantApp = 8209 !isTargetVisibleToInstantApp 8210 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 8211 final boolean blockResolution = 8212 !isTargetSameInstantApp 8213 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 8214 || (matchVisibleToInstantAppOnly && isCallerInstantApp 8215 && isTargetHiddenFromInstantApp)); 8216 if (!blockResolution) { 8217 ResolveInfo ri = new ResolveInfo(); 8218 ri.activityInfo = ai; 8219 list.add(ri); 8220 } 8221 } 8222 return applyPostResolutionFilter( 8223 list, instantAppPkgName, allowDynamicSplits, callingUid, userId); 8224 } 8225 8226 // reader 8227 synchronized (mPackages) { 8228 String pkgName = intent.getPackage(); 8229 if (pkgName == null) { 8230 final List<ResolveInfo> result = 8231 mReceivers.queryIntent(intent, resolvedType, flags, userId); 8232 return applyPostResolutionFilter( 8233 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 8234 } 8235 final PackageParser.Package pkg = mPackages.get(pkgName); 8236 if (pkg != null) { 8237 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 8238 intent, resolvedType, flags, pkg.receivers, userId); 8239 return applyPostResolutionFilter( 8240 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 8241 } 8242 return Collections.emptyList(); 8243 } 8244 } 8245 8246 @Override 8247 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 8248 final int callingUid = Binder.getCallingUid(); 8249 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 8250 } 8251 8252 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 8253 int userId, int callingUid) { 8254 if (!sUserManager.exists(userId)) return null; 8255 flags = updateFlagsForResolve( 8256 flags, userId, intent, callingUid, false /*includeInstantApps*/); 8257 List<ResolveInfo> query = queryIntentServicesInternal( 8258 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 8259 if (query != null) { 8260 if (query.size() >= 1) { 8261 // If there is more than one service with the same priority, 8262 // just arbitrarily pick the first one. 8263 return query.get(0); 8264 } 8265 } 8266 return null; 8267 } 8268 8269 @Override 8270 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 8271 String resolvedType, int flags, int userId) { 8272 final int callingUid = Binder.getCallingUid(); 8273 return new ParceledListSlice<>(queryIntentServicesInternal( 8274 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 8275 } 8276 8277 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 8278 String resolvedType, int flags, int userId, int callingUid, 8279 boolean includeInstantApps) { 8280 if (!sUserManager.exists(userId)) return Collections.emptyList(); 8281 enforceCrossUserPermission(callingUid, userId, 8282 false /*requireFullPermission*/, false /*checkShell*/, 8283 "query intent receivers"); 8284 final String instantAppPkgName = getInstantAppPackageName(callingUid); 8285 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 8286 ComponentName comp = intent.getComponent(); 8287 if (comp == null) { 8288 if (intent.getSelector() != null) { 8289 intent = intent.getSelector(); 8290 comp = intent.getComponent(); 8291 } 8292 } 8293 if (comp != null) { 8294 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 8295 final ServiceInfo si = getServiceInfo(comp, flags, userId); 8296 if (si != null) { 8297 // When specifying an explicit component, we prevent the service from being 8298 // used when either 1) the service is in an instant application and the 8299 // caller is not the same instant application or 2) the calling package is 8300 // ephemeral and the activity is not visible to ephemeral applications. 8301 final boolean matchInstantApp = 8302 (flags & PackageManager.MATCH_INSTANT) != 0; 8303 final boolean matchVisibleToInstantAppOnly = 8304 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 8305 final boolean isCallerInstantApp = 8306 instantAppPkgName != null; 8307 final boolean isTargetSameInstantApp = 8308 comp.getPackageName().equals(instantAppPkgName); 8309 final boolean isTargetInstantApp = 8310 (si.applicationInfo.privateFlags 8311 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 8312 final boolean isTargetHiddenFromInstantApp = 8313 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 8314 final boolean blockResolution = 8315 !isTargetSameInstantApp 8316 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 8317 || (matchVisibleToInstantAppOnly && isCallerInstantApp 8318 && isTargetHiddenFromInstantApp)); 8319 if (!blockResolution) { 8320 final ResolveInfo ri = new ResolveInfo(); 8321 ri.serviceInfo = si; 8322 list.add(ri); 8323 } 8324 } 8325 return list; 8326 } 8327 8328 // reader 8329 synchronized (mPackages) { 8330 String pkgName = intent.getPackage(); 8331 if (pkgName == null) { 8332 return applyPostServiceResolutionFilter( 8333 mServices.queryIntent(intent, resolvedType, flags, userId), 8334 instantAppPkgName); 8335 } 8336 final PackageParser.Package pkg = mPackages.get(pkgName); 8337 if (pkg != null) { 8338 return applyPostServiceResolutionFilter( 8339 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 8340 userId), 8341 instantAppPkgName); 8342 } 8343 return Collections.emptyList(); 8344 } 8345 } 8346 8347 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 8348 String instantAppPkgName) { 8349 if (instantAppPkgName == null) { 8350 return resolveInfos; 8351 } 8352 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 8353 final ResolveInfo info = resolveInfos.get(i); 8354 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 8355 // allow services that are defined in the provided package 8356 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 8357 if (info.serviceInfo.splitName != null 8358 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 8359 info.serviceInfo.splitName)) { 8360 // requested service is defined in a split that hasn't been installed yet. 8361 // add the installer to the resolve list 8362 if (DEBUG_EPHEMERAL) { 8363 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 8364 } 8365 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 8366 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 8367 info.serviceInfo.packageName, info.serviceInfo.splitName, 8368 null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode, 8369 null /*failureIntent*/); 8370 // make sure this resolver is the default 8371 installerInfo.isDefault = true; 8372 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 8373 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 8374 // add a non-generic filter 8375 installerInfo.filter = new IntentFilter(); 8376 // load resources from the correct package 8377 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 8378 resolveInfos.set(i, installerInfo); 8379 } 8380 continue; 8381 } 8382 // allow services that have been explicitly exposed to ephemeral apps 8383 if (!isEphemeralApp 8384 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 8385 continue; 8386 } 8387 resolveInfos.remove(i); 8388 } 8389 return resolveInfos; 8390 } 8391 8392 @Override 8393 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 8394 String resolvedType, int flags, int userId) { 8395 return new ParceledListSlice<>( 8396 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 8397 } 8398 8399 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 8400 Intent intent, String resolvedType, int flags, int userId) { 8401 if (!sUserManager.exists(userId)) return Collections.emptyList(); 8402 final int callingUid = Binder.getCallingUid(); 8403 final String instantAppPkgName = getInstantAppPackageName(callingUid); 8404 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 8405 false /*includeInstantApps*/); 8406 ComponentName comp = intent.getComponent(); 8407 if (comp == null) { 8408 if (intent.getSelector() != null) { 8409 intent = intent.getSelector(); 8410 comp = intent.getComponent(); 8411 } 8412 } 8413 if (comp != null) { 8414 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 8415 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 8416 if (pi != null) { 8417 // When specifying an explicit component, we prevent the provider from being 8418 // used when either 1) the provider is in an instant application and the 8419 // caller is not the same instant application or 2) the calling package is an 8420 // instant application and the provider is not visible to instant applications. 8421 final boolean matchInstantApp = 8422 (flags & PackageManager.MATCH_INSTANT) != 0; 8423 final boolean matchVisibleToInstantAppOnly = 8424 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 8425 final boolean isCallerInstantApp = 8426 instantAppPkgName != null; 8427 final boolean isTargetSameInstantApp = 8428 comp.getPackageName().equals(instantAppPkgName); 8429 final boolean isTargetInstantApp = 8430 (pi.applicationInfo.privateFlags 8431 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 8432 final boolean isTargetHiddenFromInstantApp = 8433 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 8434 final boolean blockResolution = 8435 !isTargetSameInstantApp 8436 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 8437 || (matchVisibleToInstantAppOnly && isCallerInstantApp 8438 && isTargetHiddenFromInstantApp)); 8439 if (!blockResolution) { 8440 final ResolveInfo ri = new ResolveInfo(); 8441 ri.providerInfo = pi; 8442 list.add(ri); 8443 } 8444 } 8445 return list; 8446 } 8447 8448 // reader 8449 synchronized (mPackages) { 8450 String pkgName = intent.getPackage(); 8451 if (pkgName == null) { 8452 return applyPostContentProviderResolutionFilter( 8453 mProviders.queryIntent(intent, resolvedType, flags, userId), 8454 instantAppPkgName); 8455 } 8456 final PackageParser.Package pkg = mPackages.get(pkgName); 8457 if (pkg != null) { 8458 return applyPostContentProviderResolutionFilter( 8459 mProviders.queryIntentForPackage( 8460 intent, resolvedType, flags, pkg.providers, userId), 8461 instantAppPkgName); 8462 } 8463 return Collections.emptyList(); 8464 } 8465 } 8466 8467 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 8468 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 8469 if (instantAppPkgName == null) { 8470 return resolveInfos; 8471 } 8472 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 8473 final ResolveInfo info = resolveInfos.get(i); 8474 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 8475 // allow providers that are defined in the provided package 8476 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 8477 if (info.providerInfo.splitName != null 8478 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 8479 info.providerInfo.splitName)) { 8480 // requested provider is defined in a split that hasn't been installed yet. 8481 // add the installer to the resolve list 8482 if (DEBUG_EPHEMERAL) { 8483 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 8484 } 8485 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 8486 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 8487 info.providerInfo.packageName, info.providerInfo.splitName, 8488 null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode, 8489 null /*failureIntent*/); 8490 // make sure this resolver is the default 8491 installerInfo.isDefault = true; 8492 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 8493 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 8494 // add a non-generic filter 8495 installerInfo.filter = new IntentFilter(); 8496 // load resources from the correct package 8497 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 8498 resolveInfos.set(i, installerInfo); 8499 } 8500 continue; 8501 } 8502 // allow providers that have been explicitly exposed to instant applications 8503 if (!isEphemeralApp 8504 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 8505 continue; 8506 } 8507 resolveInfos.remove(i); 8508 } 8509 return resolveInfos; 8510 } 8511 8512 @Override 8513 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 8514 final int callingUid = Binder.getCallingUid(); 8515 if (getInstantAppPackageName(callingUid) != null) { 8516 return ParceledListSlice.emptyList(); 8517 } 8518 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8519 flags = updateFlagsForPackage(flags, userId, null); 8520 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8521 enforceCrossUserPermission(callingUid, userId, 8522 true /* requireFullPermission */, false /* checkShell */, 8523 "get installed packages"); 8524 8525 // writer 8526 synchronized (mPackages) { 8527 ArrayList<PackageInfo> list; 8528 if (listUninstalled) { 8529 list = new ArrayList<>(mSettings.mPackages.size()); 8530 for (PackageSetting ps : mSettings.mPackages.values()) { 8531 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 8532 continue; 8533 } 8534 if (filterAppAccessLPr(ps, callingUid, userId)) { 8535 continue; 8536 } 8537 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 8538 if (pi != null) { 8539 list.add(pi); 8540 } 8541 } 8542 } else { 8543 list = new ArrayList<>(mPackages.size()); 8544 for (PackageParser.Package p : mPackages.values()) { 8545 final PackageSetting ps = (PackageSetting) p.mExtras; 8546 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 8547 continue; 8548 } 8549 if (filterAppAccessLPr(ps, callingUid, userId)) { 8550 continue; 8551 } 8552 final PackageInfo pi = generatePackageInfo((PackageSetting) 8553 p.mExtras, flags, userId); 8554 if (pi != null) { 8555 list.add(pi); 8556 } 8557 } 8558 } 8559 8560 return new ParceledListSlice<>(list); 8561 } 8562 } 8563 8564 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 8565 String[] permissions, boolean[] tmp, int flags, int userId) { 8566 int numMatch = 0; 8567 final PermissionsState permissionsState = ps.getPermissionsState(); 8568 for (int i=0; i<permissions.length; i++) { 8569 final String permission = permissions[i]; 8570 if (permissionsState.hasPermission(permission, userId)) { 8571 tmp[i] = true; 8572 numMatch++; 8573 } else { 8574 tmp[i] = false; 8575 } 8576 } 8577 if (numMatch == 0) { 8578 return; 8579 } 8580 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 8581 8582 // The above might return null in cases of uninstalled apps or install-state 8583 // skew across users/profiles. 8584 if (pi != null) { 8585 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 8586 if (numMatch == permissions.length) { 8587 pi.requestedPermissions = permissions; 8588 } else { 8589 pi.requestedPermissions = new String[numMatch]; 8590 numMatch = 0; 8591 for (int i=0; i<permissions.length; i++) { 8592 if (tmp[i]) { 8593 pi.requestedPermissions[numMatch] = permissions[i]; 8594 numMatch++; 8595 } 8596 } 8597 } 8598 } 8599 list.add(pi); 8600 } 8601 } 8602 8603 @Override 8604 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 8605 String[] permissions, int flags, int userId) { 8606 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8607 flags = updateFlagsForPackage(flags, userId, permissions); 8608 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8609 true /* requireFullPermission */, false /* checkShell */, 8610 "get packages holding permissions"); 8611 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8612 8613 // writer 8614 synchronized (mPackages) { 8615 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 8616 boolean[] tmpBools = new boolean[permissions.length]; 8617 if (listUninstalled) { 8618 for (PackageSetting ps : mSettings.mPackages.values()) { 8619 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 8620 userId); 8621 } 8622 } else { 8623 for (PackageParser.Package pkg : mPackages.values()) { 8624 PackageSetting ps = (PackageSetting)pkg.mExtras; 8625 if (ps != null) { 8626 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 8627 userId); 8628 } 8629 } 8630 } 8631 8632 return new ParceledListSlice<PackageInfo>(list); 8633 } 8634 } 8635 8636 @Override 8637 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 8638 final int callingUid = Binder.getCallingUid(); 8639 if (getInstantAppPackageName(callingUid) != null) { 8640 return ParceledListSlice.emptyList(); 8641 } 8642 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8643 flags = updateFlagsForApplication(flags, userId, null); 8644 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8645 8646 // writer 8647 synchronized (mPackages) { 8648 ArrayList<ApplicationInfo> list; 8649 if (listUninstalled) { 8650 list = new ArrayList<>(mSettings.mPackages.size()); 8651 for (PackageSetting ps : mSettings.mPackages.values()) { 8652 ApplicationInfo ai; 8653 int effectiveFlags = flags; 8654 if (ps.isSystem()) { 8655 effectiveFlags |= PackageManager.MATCH_ANY_USER; 8656 } 8657 if (ps.pkg != null) { 8658 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 8659 continue; 8660 } 8661 if (filterAppAccessLPr(ps, callingUid, userId)) { 8662 continue; 8663 } 8664 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 8665 ps.readUserState(userId), userId); 8666 if (ai != null) { 8667 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 8668 } 8669 } else { 8670 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 8671 // and already converts to externally visible package name 8672 ai = generateApplicationInfoFromSettingsLPw(ps.name, 8673 callingUid, effectiveFlags, userId); 8674 } 8675 if (ai != null) { 8676 list.add(ai); 8677 } 8678 } 8679 } else { 8680 list = new ArrayList<>(mPackages.size()); 8681 for (PackageParser.Package p : mPackages.values()) { 8682 if (p.mExtras != null) { 8683 PackageSetting ps = (PackageSetting) p.mExtras; 8684 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 8685 continue; 8686 } 8687 if (filterAppAccessLPr(ps, callingUid, userId)) { 8688 continue; 8689 } 8690 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8691 ps.readUserState(userId), userId); 8692 if (ai != null) { 8693 ai.packageName = resolveExternalPackageNameLPr(p); 8694 list.add(ai); 8695 } 8696 } 8697 } 8698 } 8699 8700 return new ParceledListSlice<>(list); 8701 } 8702 } 8703 8704 @Override 8705 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 8706 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8707 return null; 8708 } 8709 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8710 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8711 "getEphemeralApplications"); 8712 } 8713 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8714 true /* requireFullPermission */, false /* checkShell */, 8715 "getEphemeralApplications"); 8716 synchronized (mPackages) { 8717 List<InstantAppInfo> instantApps = mInstantAppRegistry 8718 .getInstantAppsLPr(userId); 8719 if (instantApps != null) { 8720 return new ParceledListSlice<>(instantApps); 8721 } 8722 } 8723 return null; 8724 } 8725 8726 @Override 8727 public boolean isInstantApp(String packageName, int userId) { 8728 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8729 true /* requireFullPermission */, false /* checkShell */, 8730 "isInstantApp"); 8731 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8732 return false; 8733 } 8734 8735 synchronized (mPackages) { 8736 int callingUid = Binder.getCallingUid(); 8737 if (Process.isIsolated(callingUid)) { 8738 callingUid = mIsolatedOwners.get(callingUid); 8739 } 8740 final PackageSetting ps = mSettings.mPackages.get(packageName); 8741 PackageParser.Package pkg = mPackages.get(packageName); 8742 final boolean returnAllowed = 8743 ps != null 8744 && (isCallerSameApp(packageName, callingUid) 8745 || canViewInstantApps(callingUid, userId) 8746 || mInstantAppRegistry.isInstantAccessGranted( 8747 userId, UserHandle.getAppId(callingUid), ps.appId)); 8748 if (returnAllowed) { 8749 return ps.getInstantApp(userId); 8750 } 8751 } 8752 return false; 8753 } 8754 8755 @Override 8756 public byte[] getInstantAppCookie(String packageName, int userId) { 8757 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8758 return null; 8759 } 8760 8761 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8762 true /* requireFullPermission */, false /* checkShell */, 8763 "getInstantAppCookie"); 8764 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8765 return null; 8766 } 8767 synchronized (mPackages) { 8768 return mInstantAppRegistry.getInstantAppCookieLPw( 8769 packageName, userId); 8770 } 8771 } 8772 8773 @Override 8774 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 8775 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8776 return true; 8777 } 8778 8779 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8780 true /* requireFullPermission */, true /* checkShell */, 8781 "setInstantAppCookie"); 8782 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8783 return false; 8784 } 8785 synchronized (mPackages) { 8786 return mInstantAppRegistry.setInstantAppCookieLPw( 8787 packageName, cookie, userId); 8788 } 8789 } 8790 8791 @Override 8792 public Bitmap getInstantAppIcon(String packageName, int userId) { 8793 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8794 return null; 8795 } 8796 8797 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8798 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8799 "getInstantAppIcon"); 8800 } 8801 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8802 true /* requireFullPermission */, false /* checkShell */, 8803 "getInstantAppIcon"); 8804 8805 synchronized (mPackages) { 8806 return mInstantAppRegistry.getInstantAppIconLPw( 8807 packageName, userId); 8808 } 8809 } 8810 8811 private boolean isCallerSameApp(String packageName, int uid) { 8812 PackageParser.Package pkg = mPackages.get(packageName); 8813 return pkg != null 8814 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8815 } 8816 8817 @Override 8818 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8819 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8820 return ParceledListSlice.emptyList(); 8821 } 8822 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8823 } 8824 8825 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8826 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 8827 8828 // reader 8829 synchronized (mPackages) { 8830 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8831 final int userId = UserHandle.getCallingUserId(); 8832 while (i.hasNext()) { 8833 final PackageParser.Package p = i.next(); 8834 if (p.applicationInfo == null) continue; 8835 8836 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8837 && !p.applicationInfo.isDirectBootAware(); 8838 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8839 && p.applicationInfo.isDirectBootAware(); 8840 8841 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8842 && (!mSafeMode || isSystemApp(p)) 8843 && (matchesUnaware || matchesAware)) { 8844 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8845 if (ps != null) { 8846 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8847 ps.readUserState(userId), userId); 8848 if (ai != null) { 8849 finalList.add(ai); 8850 } 8851 } 8852 } 8853 } 8854 } 8855 8856 return finalList; 8857 } 8858 8859 @Override 8860 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8861 if (!sUserManager.exists(userId)) return null; 8862 flags = updateFlagsForComponent(flags, userId, name); 8863 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 8864 // reader 8865 synchronized (mPackages) { 8866 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8867 PackageSetting ps = provider != null 8868 ? mSettings.mPackages.get(provider.owner.packageName) 8869 : null; 8870 if (ps != null) { 8871 final boolean isInstantApp = ps.getInstantApp(userId); 8872 // normal application; filter out instant application provider 8873 if (instantAppPkgName == null && isInstantApp) { 8874 return null; 8875 } 8876 // instant application; filter out other instant applications 8877 if (instantAppPkgName != null 8878 && isInstantApp 8879 && !provider.owner.packageName.equals(instantAppPkgName)) { 8880 return null; 8881 } 8882 // instant application; filter out non-exposed provider 8883 if (instantAppPkgName != null 8884 && !isInstantApp 8885 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 8886 return null; 8887 } 8888 // provider not enabled 8889 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8890 return null; 8891 } 8892 return PackageParser.generateProviderInfo( 8893 provider, flags, ps.readUserState(userId), userId); 8894 } 8895 return null; 8896 } 8897 } 8898 8899 /** 8900 * @deprecated 8901 */ 8902 @Deprecated 8903 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8904 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8905 return; 8906 } 8907 // reader 8908 synchronized (mPackages) { 8909 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8910 .entrySet().iterator(); 8911 final int userId = UserHandle.getCallingUserId(); 8912 while (i.hasNext()) { 8913 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8914 PackageParser.Provider p = entry.getValue(); 8915 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8916 8917 if (ps != null && p.syncable 8918 && (!mSafeMode || (p.info.applicationInfo.flags 8919 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8920 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8921 ps.readUserState(userId), userId); 8922 if (info != null) { 8923 outNames.add(entry.getKey()); 8924 outInfo.add(info); 8925 } 8926 } 8927 } 8928 } 8929 } 8930 8931 @Override 8932 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8933 int uid, int flags, String metaDataKey) { 8934 final int callingUid = Binder.getCallingUid(); 8935 final int userId = processName != null ? UserHandle.getUserId(uid) 8936 : UserHandle.getCallingUserId(); 8937 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8938 flags = updateFlagsForComponent(flags, userId, processName); 8939 ArrayList<ProviderInfo> finalList = null; 8940 // reader 8941 synchronized (mPackages) { 8942 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8943 while (i.hasNext()) { 8944 final PackageParser.Provider p = i.next(); 8945 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8946 if (ps != null && p.info.authority != null 8947 && (processName == null 8948 || (p.info.processName.equals(processName) 8949 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8950 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8951 8952 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8953 // parameter. 8954 if (metaDataKey != null 8955 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8956 continue; 8957 } 8958 final ComponentName component = 8959 new ComponentName(p.info.packageName, p.info.name); 8960 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8961 continue; 8962 } 8963 if (finalList == null) { 8964 finalList = new ArrayList<ProviderInfo>(3); 8965 } 8966 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8967 ps.readUserState(userId), userId); 8968 if (info != null) { 8969 finalList.add(info); 8970 } 8971 } 8972 } 8973 } 8974 8975 if (finalList != null) { 8976 Collections.sort(finalList, mProviderInitOrderSorter); 8977 return new ParceledListSlice<ProviderInfo>(finalList); 8978 } 8979 8980 return ParceledListSlice.emptyList(); 8981 } 8982 8983 @Override 8984 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8985 // reader 8986 synchronized (mPackages) { 8987 final int callingUid = Binder.getCallingUid(); 8988 final int callingUserId = UserHandle.getUserId(callingUid); 8989 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8990 if (ps == null) return null; 8991 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8992 return null; 8993 } 8994 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8995 return PackageParser.generateInstrumentationInfo(i, flags); 8996 } 8997 } 8998 8999 @Override 9000 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 9001 String targetPackage, int flags) { 9002 final int callingUid = Binder.getCallingUid(); 9003 final int callingUserId = UserHandle.getUserId(callingUid); 9004 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 9005 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 9006 return ParceledListSlice.emptyList(); 9007 } 9008 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 9009 } 9010 9011 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 9012 int flags) { 9013 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 9014 9015 // reader 9016 synchronized (mPackages) { 9017 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 9018 while (i.hasNext()) { 9019 final PackageParser.Instrumentation p = i.next(); 9020 if (targetPackage == null 9021 || targetPackage.equals(p.info.targetPackage)) { 9022 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 9023 flags); 9024 if (ii != null) { 9025 finalList.add(ii); 9026 } 9027 } 9028 } 9029 } 9030 9031 return finalList; 9032 } 9033 9034 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 9035 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 9036 try { 9037 scanDirLI(dir, parseFlags, scanFlags, currentTime); 9038 } finally { 9039 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9040 } 9041 } 9042 9043 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 9044 final File[] files = dir.listFiles(); 9045 if (ArrayUtils.isEmpty(files)) { 9046 Log.d(TAG, "No files in app dir " + dir); 9047 return; 9048 } 9049 9050 if (DEBUG_PACKAGE_SCANNING) { 9051 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 9052 + " flags=0x" + Integer.toHexString(parseFlags)); 9053 } 9054 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 9055 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 9056 mParallelPackageParserCallback); 9057 9058 // Submit files for parsing in parallel 9059 int fileCount = 0; 9060 for (File file : files) { 9061 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 9062 && !PackageInstallerService.isStageName(file.getName()); 9063 if (!isPackage) { 9064 // Ignore entries which are not packages 9065 continue; 9066 } 9067 parallelPackageParser.submit(file, parseFlags); 9068 fileCount++; 9069 } 9070 9071 // Process results one by one 9072 for (; fileCount > 0; fileCount--) { 9073 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 9074 Throwable throwable = parseResult.throwable; 9075 int errorCode = PackageManager.INSTALL_SUCCEEDED; 9076 9077 if (throwable == null) { 9078 // Static shared libraries have synthetic package names 9079 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 9080 renameStaticSharedLibraryPackage(parseResult.pkg); 9081 } 9082 try { 9083 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 9084 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 9085 currentTime, null); 9086 } 9087 } catch (PackageManagerException e) { 9088 errorCode = e.error; 9089 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 9090 } 9091 } else if (throwable instanceof PackageParser.PackageParserException) { 9092 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 9093 throwable; 9094 errorCode = e.error; 9095 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 9096 } else { 9097 throw new IllegalStateException("Unexpected exception occurred while parsing " 9098 + parseResult.scanFile, throwable); 9099 } 9100 9101 // Delete invalid userdata apps 9102 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 9103 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 9104 logCriticalInfo(Log.WARN, 9105 "Deleting invalid package at " + parseResult.scanFile); 9106 removeCodePathLI(parseResult.scanFile); 9107 } 9108 } 9109 parallelPackageParser.close(); 9110 } 9111 9112 private static File getSettingsProblemFile() { 9113 File dataDir = Environment.getDataDirectory(); 9114 File systemDir = new File(dataDir, "system"); 9115 File fname = new File(systemDir, "uiderrors.txt"); 9116 return fname; 9117 } 9118 9119 static void reportSettingsProblem(int priority, String msg) { 9120 logCriticalInfo(priority, msg); 9121 } 9122 9123 public static void logCriticalInfo(int priority, String msg) { 9124 Slog.println(priority, TAG, msg); 9125 EventLogTags.writePmCriticalInfo(msg); 9126 try { 9127 File fname = getSettingsProblemFile(); 9128 FileOutputStream out = new FileOutputStream(fname, true); 9129 PrintWriter pw = new FastPrintWriter(out); 9130 SimpleDateFormat formatter = new SimpleDateFormat(); 9131 String dateString = formatter.format(new Date(System.currentTimeMillis())); 9132 pw.println(dateString + ": " + msg); 9133 pw.close(); 9134 FileUtils.setPermissions( 9135 fname.toString(), 9136 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 9137 -1, -1); 9138 } catch (java.io.IOException e) { 9139 } 9140 } 9141 9142 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 9143 if (srcFile.isDirectory()) { 9144 final File baseFile = new File(pkg.baseCodePath); 9145 long maxModifiedTime = baseFile.lastModified(); 9146 if (pkg.splitCodePaths != null) { 9147 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 9148 final File splitFile = new File(pkg.splitCodePaths[i]); 9149 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 9150 } 9151 } 9152 return maxModifiedTime; 9153 } 9154 return srcFile.lastModified(); 9155 } 9156 9157 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 9158 final int policyFlags) throws PackageManagerException { 9159 // When upgrading from pre-N MR1, verify the package time stamp using the package 9160 // directory and not the APK file. 9161 final long lastModifiedTime = mIsPreNMR1Upgrade 9162 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 9163 if (ps != null 9164 && ps.codePath.equals(srcFile) 9165 && ps.timeStamp == lastModifiedTime 9166 && !isCompatSignatureUpdateNeeded(pkg) 9167 && !isRecoverSignatureUpdateNeeded(pkg)) { 9168 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 9169 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9170 ArraySet<PublicKey> signingKs; 9171 synchronized (mPackages) { 9172 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 9173 } 9174 if (ps.signatures.mSignatures != null 9175 && ps.signatures.mSignatures.length != 0 9176 && signingKs != null) { 9177 // Optimization: reuse the existing cached certificates 9178 // if the package appears to be unchanged. 9179 pkg.mSignatures = ps.signatures.mSignatures; 9180 pkg.mSigningKeys = signingKs; 9181 return; 9182 } 9183 9184 Slog.w(TAG, "PackageSetting for " + ps.name 9185 + " is missing signatures. Collecting certs again to recover them."); 9186 } else { 9187 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 9188 } 9189 9190 try { 9191 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 9192 PackageParser.collectCertificates(pkg, policyFlags); 9193 } catch (PackageParserException e) { 9194 throw PackageManagerException.from(e); 9195 } finally { 9196 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9197 } 9198 } 9199 9200 /** 9201 * Traces a package scan. 9202 * @see #scanPackageLI(File, int, int, long, UserHandle) 9203 */ 9204 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 9205 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 9206 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 9207 try { 9208 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 9209 } finally { 9210 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9211 } 9212 } 9213 9214 /** 9215 * Scans a package and returns the newly parsed package. 9216 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 9217 */ 9218 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 9219 long currentTime, UserHandle user) throws PackageManagerException { 9220 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 9221 PackageParser pp = new PackageParser(); 9222 pp.setSeparateProcesses(mSeparateProcesses); 9223 pp.setOnlyCoreApps(mOnlyCore); 9224 pp.setDisplayMetrics(mMetrics); 9225 pp.setCallback(mPackageParserCallback); 9226 9227 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 9228 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 9229 } 9230 9231 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 9232 final PackageParser.Package pkg; 9233 try { 9234 pkg = pp.parsePackage(scanFile, parseFlags); 9235 } catch (PackageParserException e) { 9236 throw PackageManagerException.from(e); 9237 } finally { 9238 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9239 } 9240 9241 // Static shared libraries have synthetic package names 9242 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9243 renameStaticSharedLibraryPackage(pkg); 9244 } 9245 9246 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 9247 } 9248 9249 /** 9250 * Scans a package and returns the newly parsed package. 9251 * @throws PackageManagerException on a parse error. 9252 */ 9253 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 9254 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9255 throws PackageManagerException { 9256 // If the package has children and this is the first dive in the function 9257 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 9258 // packages (parent and children) would be successfully scanned before the 9259 // actual scan since scanning mutates internal state and we want to atomically 9260 // install the package and its children. 9261 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9262 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9263 scanFlags |= SCAN_CHECK_ONLY; 9264 } 9265 } else { 9266 scanFlags &= ~SCAN_CHECK_ONLY; 9267 } 9268 9269 // Scan the parent 9270 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 9271 scanFlags, currentTime, user); 9272 9273 // Scan the children 9274 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9275 for (int i = 0; i < childCount; i++) { 9276 PackageParser.Package childPackage = pkg.childPackages.get(i); 9277 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 9278 currentTime, user); 9279 } 9280 9281 9282 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9283 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 9284 } 9285 9286 return scannedPkg; 9287 } 9288 9289 /** 9290 * Scans a package and returns the newly parsed package. 9291 * @throws PackageManagerException on a parse error. 9292 */ 9293 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 9294 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9295 throws PackageManagerException { 9296 PackageSetting ps = null; 9297 PackageSetting updatedPkg; 9298 // reader 9299 synchronized (mPackages) { 9300 // Look to see if we already know about this package. 9301 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 9302 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 9303 // This package has been renamed to its original name. Let's 9304 // use that. 9305 ps = mSettings.getPackageLPr(oldName); 9306 } 9307 // If there was no original package, see one for the real package name. 9308 if (ps == null) { 9309 ps = mSettings.getPackageLPr(pkg.packageName); 9310 } 9311 // Check to see if this package could be hiding/updating a system 9312 // package. Must look for it either under the original or real 9313 // package name depending on our state. 9314 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 9315 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 9316 9317 // If this is a package we don't know about on the system partition, we 9318 // may need to remove disabled child packages on the system partition 9319 // or may need to not add child packages if the parent apk is updated 9320 // on the data partition and no longer defines this child package. 9321 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 9322 // If this is a parent package for an updated system app and this system 9323 // app got an OTA update which no longer defines some of the child packages 9324 // we have to prune them from the disabled system packages. 9325 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9326 if (disabledPs != null) { 9327 final int scannedChildCount = (pkg.childPackages != null) 9328 ? pkg.childPackages.size() : 0; 9329 final int disabledChildCount = disabledPs.childPackageNames != null 9330 ? disabledPs.childPackageNames.size() : 0; 9331 for (int i = 0; i < disabledChildCount; i++) { 9332 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 9333 boolean disabledPackageAvailable = false; 9334 for (int j = 0; j < scannedChildCount; j++) { 9335 PackageParser.Package childPkg = pkg.childPackages.get(j); 9336 if (childPkg.packageName.equals(disabledChildPackageName)) { 9337 disabledPackageAvailable = true; 9338 break; 9339 } 9340 } 9341 if (!disabledPackageAvailable) { 9342 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 9343 } 9344 } 9345 } 9346 } 9347 } 9348 9349 final boolean isUpdatedPkg = updatedPkg != null; 9350 final boolean isUpdatedSystemPkg = isUpdatedPkg 9351 && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0; 9352 boolean isUpdatedPkgBetter = false; 9353 // First check if this is a system package that may involve an update 9354 if (isUpdatedSystemPkg) { 9355 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 9356 // it needs to drop FLAG_PRIVILEGED. 9357 if (locationIsPrivileged(scanFile)) { 9358 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9359 } else { 9360 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9361 } 9362 9363 if (ps != null && !ps.codePath.equals(scanFile)) { 9364 // The path has changed from what was last scanned... check the 9365 // version of the new path against what we have stored to determine 9366 // what to do. 9367 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 9368 if (pkg.mVersionCode <= ps.versionCode) { 9369 // The system package has been updated and the code path does not match 9370 // Ignore entry. Skip it. 9371 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 9372 + " ignored: updated version " + ps.versionCode 9373 + " better than this " + pkg.mVersionCode); 9374 if (!updatedPkg.codePath.equals(scanFile)) { 9375 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 9376 + ps.name + " changing from " + updatedPkg.codePathString 9377 + " to " + scanFile); 9378 updatedPkg.codePath = scanFile; 9379 updatedPkg.codePathString = scanFile.toString(); 9380 updatedPkg.resourcePath = scanFile; 9381 updatedPkg.resourcePathString = scanFile.toString(); 9382 } 9383 updatedPkg.pkg = pkg; 9384 updatedPkg.versionCode = pkg.mVersionCode; 9385 9386 // Update the disabled system child packages to point to the package too. 9387 final int childCount = updatedPkg.childPackageNames != null 9388 ? updatedPkg.childPackageNames.size() : 0; 9389 for (int i = 0; i < childCount; i++) { 9390 String childPackageName = updatedPkg.childPackageNames.get(i); 9391 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 9392 childPackageName); 9393 if (updatedChildPkg != null) { 9394 updatedChildPkg.pkg = pkg; 9395 updatedChildPkg.versionCode = pkg.mVersionCode; 9396 } 9397 } 9398 } else { 9399 // The current app on the system partition is better than 9400 // what we have updated to on the data partition; switch 9401 // back to the system partition version. 9402 // At this point, its safely assumed that package installation for 9403 // apps in system partition will go through. If not there won't be a working 9404 // version of the app 9405 // writer 9406 synchronized (mPackages) { 9407 // Just remove the loaded entries from package lists. 9408 mPackages.remove(ps.name); 9409 } 9410 9411 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 9412 + " reverting from " + ps.codePathString 9413 + ": new version " + pkg.mVersionCode 9414 + " better than installed " + ps.versionCode); 9415 9416 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 9417 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 9418 synchronized (mInstallLock) { 9419 args.cleanUpResourcesLI(); 9420 } 9421 synchronized (mPackages) { 9422 mSettings.enableSystemPackageLPw(ps.name); 9423 } 9424 isUpdatedPkgBetter = true; 9425 } 9426 } 9427 } 9428 9429 String resourcePath = null; 9430 String baseResourcePath = null; 9431 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) { 9432 if (ps != null && ps.resourcePathString != null) { 9433 resourcePath = ps.resourcePathString; 9434 baseResourcePath = ps.resourcePathString; 9435 } else { 9436 // Should not happen at all. Just log an error. 9437 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 9438 } 9439 } else { 9440 resourcePath = pkg.codePath; 9441 baseResourcePath = pkg.baseCodePath; 9442 } 9443 9444 // Set application objects path explicitly. 9445 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 9446 pkg.setApplicationInfoCodePath(pkg.codePath); 9447 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 9448 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 9449 pkg.setApplicationInfoResourcePath(resourcePath); 9450 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 9451 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 9452 9453 // throw an exception if we have an update to a system application, but, it's not more 9454 // recent than the package we've already scanned 9455 if (isUpdatedSystemPkg && !isUpdatedPkgBetter) { 9456 // Set CPU Abis to application info. 9457 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9458 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg); 9459 derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir); 9460 } else { 9461 pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString; 9462 pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString; 9463 } 9464 9465 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 9466 + scanFile + " ignored: updated version " + ps.versionCode 9467 + " better than this " + pkg.mVersionCode); 9468 } 9469 9470 if (isUpdatedPkg) { 9471 // An updated system app will not have the PARSE_IS_SYSTEM flag set 9472 // initially 9473 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 9474 9475 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 9476 // flag set initially 9477 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 9478 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9479 } 9480 } 9481 9482 // Verify certificates against what was last scanned 9483 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 9484 9485 /* 9486 * A new system app appeared, but we already had a non-system one of the 9487 * same name installed earlier. 9488 */ 9489 boolean shouldHideSystemApp = false; 9490 if (!isUpdatedPkg && ps != null 9491 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 9492 /* 9493 * Check to make sure the signatures match first. If they don't, 9494 * wipe the installed application and its data. 9495 */ 9496 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 9497 != PackageManager.SIGNATURE_MATCH) { 9498 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 9499 + " signatures don't match existing userdata copy; removing"); 9500 try (PackageFreezer freezer = freezePackage(pkg.packageName, 9501 "scanPackageInternalLI")) { 9502 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 9503 } 9504 ps = null; 9505 } else { 9506 /* 9507 * If the newly-added system app is an older version than the 9508 * already installed version, hide it. It will be scanned later 9509 * and re-added like an update. 9510 */ 9511 if (pkg.mVersionCode <= ps.versionCode) { 9512 shouldHideSystemApp = true; 9513 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 9514 + " but new version " + pkg.mVersionCode + " better than installed " 9515 + ps.versionCode + "; hiding system"); 9516 } else { 9517 /* 9518 * The newly found system app is a newer version that the 9519 * one previously installed. Simply remove the 9520 * already-installed application and replace it with our own 9521 * while keeping the application data. 9522 */ 9523 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 9524 + " reverting from " + ps.codePathString + ": new version " 9525 + pkg.mVersionCode + " better than installed " + ps.versionCode); 9526 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 9527 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 9528 synchronized (mInstallLock) { 9529 args.cleanUpResourcesLI(); 9530 } 9531 } 9532 } 9533 } 9534 9535 // The apk is forward locked (not public) if its code and resources 9536 // are kept in different files. (except for app in either system or 9537 // vendor path). 9538 // TODO grab this value from PackageSettings 9539 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9540 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 9541 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 9542 } 9543 } 9544 9545 final int userId = ((user == null) ? 0 : user.getIdentifier()); 9546 if (ps != null && ps.getInstantApp(userId)) { 9547 scanFlags |= SCAN_AS_INSTANT_APP; 9548 } 9549 if (ps != null && ps.getVirtulalPreload(userId)) { 9550 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 9551 } 9552 9553 // Note that we invoke the following method only if we are about to unpack an application 9554 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 9555 | SCAN_UPDATE_SIGNATURE, currentTime, user); 9556 9557 /* 9558 * If the system app should be overridden by a previously installed 9559 * data, hide the system app now and let the /data/app scan pick it up 9560 * again. 9561 */ 9562 if (shouldHideSystemApp) { 9563 synchronized (mPackages) { 9564 mSettings.disableSystemPackageLPw(pkg.packageName, true); 9565 } 9566 } 9567 9568 return scannedPkg; 9569 } 9570 9571 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 9572 // Derive the new package synthetic package name 9573 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 9574 + pkg.staticSharedLibVersion); 9575 } 9576 9577 private static String fixProcessName(String defProcessName, 9578 String processName) { 9579 if (processName == null) { 9580 return defProcessName; 9581 } 9582 return processName; 9583 } 9584 9585 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 9586 throws PackageManagerException { 9587 if (pkgSetting.signatures.mSignatures != null) { 9588 // Already existing package. Make sure signatures match 9589 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 9590 == PackageManager.SIGNATURE_MATCH; 9591 if (!match) { 9592 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 9593 == PackageManager.SIGNATURE_MATCH; 9594 } 9595 if (!match) { 9596 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 9597 == PackageManager.SIGNATURE_MATCH; 9598 } 9599 if (!match) { 9600 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 9601 + pkg.packageName + " signatures do not match the " 9602 + "previously installed version; ignoring!"); 9603 } 9604 } 9605 9606 // Check for shared user signatures 9607 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 9608 // Already existing package. Make sure signatures match 9609 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 9610 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 9611 if (!match) { 9612 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 9613 == PackageManager.SIGNATURE_MATCH; 9614 } 9615 if (!match) { 9616 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 9617 == PackageManager.SIGNATURE_MATCH; 9618 } 9619 if (!match) { 9620 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 9621 "Package " + pkg.packageName 9622 + " has no signatures that match those in shared user " 9623 + pkgSetting.sharedUser.name + "; ignoring!"); 9624 } 9625 } 9626 } 9627 9628 /** 9629 * Enforces that only the system UID or root's UID can call a method exposed 9630 * via Binder. 9631 * 9632 * @param message used as message if SecurityException is thrown 9633 * @throws SecurityException if the caller is not system or root 9634 */ 9635 private static final void enforceSystemOrRoot(String message) { 9636 final int uid = Binder.getCallingUid(); 9637 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 9638 throw new SecurityException(message); 9639 } 9640 } 9641 9642 @Override 9643 public void performFstrimIfNeeded() { 9644 enforceSystemOrRoot("Only the system can request fstrim"); 9645 9646 // Before everything else, see whether we need to fstrim. 9647 try { 9648 IStorageManager sm = PackageHelper.getStorageManager(); 9649 if (sm != null) { 9650 boolean doTrim = false; 9651 final long interval = android.provider.Settings.Global.getLong( 9652 mContext.getContentResolver(), 9653 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 9654 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 9655 if (interval > 0) { 9656 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 9657 if (timeSinceLast > interval) { 9658 doTrim = true; 9659 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 9660 + "; running immediately"); 9661 } 9662 } 9663 if (doTrim) { 9664 final boolean dexOptDialogShown; 9665 synchronized (mPackages) { 9666 dexOptDialogShown = mDexOptDialogShown; 9667 } 9668 if (!isFirstBoot() && dexOptDialogShown) { 9669 try { 9670 ActivityManager.getService().showBootMessage( 9671 mContext.getResources().getString( 9672 R.string.android_upgrading_fstrim), true); 9673 } catch (RemoteException e) { 9674 } 9675 } 9676 sm.runMaintenance(); 9677 } 9678 } else { 9679 Slog.e(TAG, "storageManager service unavailable!"); 9680 } 9681 } catch (RemoteException e) { 9682 // Can't happen; StorageManagerService is local 9683 } 9684 } 9685 9686 @Override 9687 public void updatePackagesIfNeeded() { 9688 enforceSystemOrRoot("Only the system can request package update"); 9689 9690 // We need to re-extract after an OTA. 9691 boolean causeUpgrade = isUpgrade(); 9692 9693 // First boot or factory reset. 9694 // Note: we also handle devices that are upgrading to N right now as if it is their 9695 // first boot, as they do not have profile data. 9696 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 9697 9698 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 9699 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 9700 9701 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 9702 return; 9703 } 9704 9705 List<PackageParser.Package> pkgs; 9706 synchronized (mPackages) { 9707 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 9708 } 9709 9710 final long startTime = System.nanoTime(); 9711 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 9712 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 9713 false /* bootComplete */); 9714 9715 final int elapsedTimeSeconds = 9716 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 9717 9718 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 9719 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 9720 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 9721 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 9722 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 9723 } 9724 9725 /* 9726 * Return the prebuilt profile path given a package base code path. 9727 */ 9728 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 9729 return pkg.baseCodePath + ".prof"; 9730 } 9731 9732 /** 9733 * Performs dexopt on the set of packages in {@code packages} and returns an int array 9734 * containing statistics about the invocation. The array consists of three elements, 9735 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 9736 * and {@code numberOfPackagesFailed}. 9737 */ 9738 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 9739 final String compilerFilter, boolean bootComplete) { 9740 9741 int numberOfPackagesVisited = 0; 9742 int numberOfPackagesOptimized = 0; 9743 int numberOfPackagesSkipped = 0; 9744 int numberOfPackagesFailed = 0; 9745 final int numberOfPackagesToDexopt = pkgs.size(); 9746 9747 for (PackageParser.Package pkg : pkgs) { 9748 numberOfPackagesVisited++; 9749 9750 boolean useProfileForDexopt = false; 9751 9752 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 9753 // Copy over initial preopt profiles since we won't get any JIT samples for methods 9754 // that are already compiled. 9755 File profileFile = new File(getPrebuildProfilePath(pkg)); 9756 // Copy profile if it exists. 9757 if (profileFile.exists()) { 9758 try { 9759 // We could also do this lazily before calling dexopt in 9760 // PackageDexOptimizer to prevent this happening on first boot. The issue 9761 // is that we don't have a good way to say "do this only once". 9762 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 9763 pkg.applicationInfo.uid, pkg.packageName)) { 9764 Log.e(TAG, "Installer failed to copy system profile!"); 9765 } else { 9766 // Disabled as this causes speed-profile compilation during first boot 9767 // even if things are already compiled. 9768 // useProfileForDexopt = true; 9769 } 9770 } catch (Exception e) { 9771 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 9772 e); 9773 } 9774 } else { 9775 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9776 // Handle compressed APKs in this path. Only do this for stubs with profiles to 9777 // minimize the number off apps being speed-profile compiled during first boot. 9778 // The other paths will not change the filter. 9779 if (disabledPs != null && disabledPs.pkg.isStub) { 9780 // The package is the stub one, remove the stub suffix to get the normal 9781 // package and APK names. 9782 String systemProfilePath = 9783 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 9784 profileFile = new File(systemProfilePath); 9785 // If we have a profile for a compressed APK, copy it to the reference 9786 // location. 9787 // Note that copying the profile here will cause it to override the 9788 // reference profile every OTA even though the existing reference profile 9789 // may have more data. We can't copy during decompression since the 9790 // directories are not set up at that point. 9791 if (profileFile.exists()) { 9792 try { 9793 // We could also do this lazily before calling dexopt in 9794 // PackageDexOptimizer to prevent this happening on first boot. The 9795 // issue is that we don't have a good way to say "do this only 9796 // once". 9797 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 9798 pkg.applicationInfo.uid, pkg.packageName)) { 9799 Log.e(TAG, "Failed to copy system profile for stub package!"); 9800 } else { 9801 useProfileForDexopt = true; 9802 } 9803 } catch (Exception e) { 9804 Log.e(TAG, "Failed to copy profile " + 9805 profileFile.getAbsolutePath() + " ", e); 9806 } 9807 } 9808 } 9809 } 9810 } 9811 9812 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 9813 if (DEBUG_DEXOPT) { 9814 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 9815 } 9816 numberOfPackagesSkipped++; 9817 continue; 9818 } 9819 9820 if (DEBUG_DEXOPT) { 9821 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 9822 numberOfPackagesToDexopt + ": " + pkg.packageName); 9823 } 9824 9825 if (showDialog) { 9826 try { 9827 ActivityManager.getService().showBootMessage( 9828 mContext.getResources().getString(R.string.android_upgrading_apk, 9829 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 9830 } catch (RemoteException e) { 9831 } 9832 synchronized (mPackages) { 9833 mDexOptDialogShown = true; 9834 } 9835 } 9836 9837 String pkgCompilerFilter = compilerFilter; 9838 if (useProfileForDexopt) { 9839 // Use background dexopt mode to try and use the profile. Note that this does not 9840 // guarantee usage of the profile. 9841 pkgCompilerFilter = 9842 PackageManagerServiceCompilerMapping.getCompilerFilterForReason( 9843 PackageManagerService.REASON_BACKGROUND_DEXOPT); 9844 } 9845 9846 // checkProfiles is false to avoid merging profiles during boot which 9847 // might interfere with background compilation (b/28612421). 9848 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 9849 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 9850 // trade-off worth doing to save boot time work. 9851 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 9852 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 9853 pkg.packageName, 9854 pkgCompilerFilter, 9855 dexoptFlags)); 9856 9857 switch (primaryDexOptStaus) { 9858 case PackageDexOptimizer.DEX_OPT_PERFORMED: 9859 numberOfPackagesOptimized++; 9860 break; 9861 case PackageDexOptimizer.DEX_OPT_SKIPPED: 9862 numberOfPackagesSkipped++; 9863 break; 9864 case PackageDexOptimizer.DEX_OPT_FAILED: 9865 numberOfPackagesFailed++; 9866 break; 9867 default: 9868 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 9869 break; 9870 } 9871 } 9872 9873 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9874 numberOfPackagesFailed }; 9875 } 9876 9877 @Override 9878 public void notifyPackageUse(String packageName, int reason) { 9879 synchronized (mPackages) { 9880 final int callingUid = Binder.getCallingUid(); 9881 final int callingUserId = UserHandle.getUserId(callingUid); 9882 if (getInstantAppPackageName(callingUid) != null) { 9883 if (!isCallerSameApp(packageName, callingUid)) { 9884 return; 9885 } 9886 } else { 9887 if (isInstantApp(packageName, callingUserId)) { 9888 return; 9889 } 9890 } 9891 notifyPackageUseLocked(packageName, reason); 9892 } 9893 } 9894 9895 private void notifyPackageUseLocked(String packageName, int reason) { 9896 final PackageParser.Package p = mPackages.get(packageName); 9897 if (p == null) { 9898 return; 9899 } 9900 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9901 } 9902 9903 @Override 9904 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 9905 List<String> classPaths, String loaderIsa) { 9906 int userId = UserHandle.getCallingUserId(); 9907 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9908 if (ai == null) { 9909 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9910 + loadingPackageName + ", user=" + userId); 9911 return; 9912 } 9913 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 9914 } 9915 9916 @Override 9917 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 9918 IDexModuleRegisterCallback callback) { 9919 int userId = UserHandle.getCallingUserId(); 9920 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 9921 DexManager.RegisterDexModuleResult result; 9922 if (ai == null) { 9923 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 9924 " calling user. package=" + packageName + ", user=" + userId); 9925 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 9926 } else { 9927 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 9928 } 9929 9930 if (callback != null) { 9931 mHandler.post(() -> { 9932 try { 9933 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 9934 } catch (RemoteException e) { 9935 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 9936 } 9937 }); 9938 } 9939 } 9940 9941 /** 9942 * Ask the package manager to perform a dex-opt with the given compiler filter. 9943 * 9944 * Note: exposed only for the shell command to allow moving packages explicitly to a 9945 * definite state. 9946 */ 9947 @Override 9948 public boolean performDexOptMode(String packageName, 9949 boolean checkProfiles, String targetCompilerFilter, boolean force, 9950 boolean bootComplete, String splitName) { 9951 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 9952 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 9953 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 9954 return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter, 9955 splitName, flags)); 9956 } 9957 9958 /** 9959 * Ask the package manager to perform a dex-opt with the given compiler filter on the 9960 * secondary dex files belonging to the given package. 9961 * 9962 * Note: exposed only for the shell command to allow moving packages explicitly to a 9963 * definite state. 9964 */ 9965 @Override 9966 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9967 boolean force) { 9968 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 9969 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 9970 DexoptOptions.DEXOPT_BOOT_COMPLETE | 9971 (force ? DexoptOptions.DEXOPT_FORCE : 0); 9972 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 9973 } 9974 9975 /*package*/ boolean performDexOpt(DexoptOptions options) { 9976 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9977 return false; 9978 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 9979 return false; 9980 } 9981 9982 if (options.isDexoptOnlySecondaryDex()) { 9983 return mDexManager.dexoptSecondaryDex(options); 9984 } else { 9985 int dexoptStatus = performDexOptWithStatus(options); 9986 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9987 } 9988 } 9989 9990 /** 9991 * Perform dexopt on the given package and return one of following result: 9992 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9993 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9994 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9995 */ 9996 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9997 return performDexOptTraced(options); 9998 } 9999 10000 private int performDexOptTraced(DexoptOptions options) { 10001 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 10002 try { 10003 return performDexOptInternal(options); 10004 } finally { 10005 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10006 } 10007 } 10008 10009 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 10010 // if the package can now be considered up to date for the given filter. 10011 private int performDexOptInternal(DexoptOptions options) { 10012 PackageParser.Package p; 10013 synchronized (mPackages) { 10014 p = mPackages.get(options.getPackageName()); 10015 if (p == null) { 10016 // Package could not be found. Report failure. 10017 return PackageDexOptimizer.DEX_OPT_FAILED; 10018 } 10019 mPackageUsage.maybeWriteAsync(mPackages); 10020 mCompilerStats.maybeWriteAsync(); 10021 } 10022 long callingId = Binder.clearCallingIdentity(); 10023 try { 10024 synchronized (mInstallLock) { 10025 return performDexOptInternalWithDependenciesLI(p, options); 10026 } 10027 } finally { 10028 Binder.restoreCallingIdentity(callingId); 10029 } 10030 } 10031 10032 public ArraySet<String> getOptimizablePackages() { 10033 ArraySet<String> pkgs = new ArraySet<String>(); 10034 synchronized (mPackages) { 10035 for (PackageParser.Package p : mPackages.values()) { 10036 if (PackageDexOptimizer.canOptimizePackage(p)) { 10037 pkgs.add(p.packageName); 10038 } 10039 } 10040 } 10041 return pkgs; 10042 } 10043 10044 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 10045 DexoptOptions options) { 10046 // Select the dex optimizer based on the force parameter. 10047 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 10048 // allocate an object here. 10049 PackageDexOptimizer pdo = options.isForce() 10050 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 10051 : mPackageDexOptimizer; 10052 10053 // Dexopt all dependencies first. Note: we ignore the return value and march on 10054 // on errors. 10055 // Note that we are going to call performDexOpt on those libraries as many times as 10056 // they are referenced in packages. When we do a batch of performDexOpt (for example 10057 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 10058 // and the first package that uses the library will dexopt it. The 10059 // others will see that the compiled code for the library is up to date. 10060 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 10061 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 10062 if (!deps.isEmpty()) { 10063 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 10064 options.getCompilerFilter(), options.getSplitName(), 10065 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 10066 for (PackageParser.Package depPackage : deps) { 10067 // TODO: Analyze and investigate if we (should) profile libraries. 10068 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 10069 getOrCreateCompilerPackageStats(depPackage), 10070 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 10071 } 10072 } 10073 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 10074 getOrCreateCompilerPackageStats(p), 10075 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 10076 } 10077 10078 /** 10079 * Reconcile the information we have about the secondary dex files belonging to 10080 * {@code packagName} and the actual dex files. For all dex files that were 10081 * deleted, update the internal records and delete the generated oat files. 10082 */ 10083 @Override 10084 public void reconcileSecondaryDexFiles(String packageName) { 10085 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 10086 return; 10087 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 10088 return; 10089 } 10090 mDexManager.reconcileSecondaryDexFiles(packageName); 10091 } 10092 10093 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 10094 // a reference there. 10095 /*package*/ DexManager getDexManager() { 10096 return mDexManager; 10097 } 10098 10099 /** 10100 * Execute the background dexopt job immediately. 10101 */ 10102 @Override 10103 public boolean runBackgroundDexoptJob() { 10104 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 10105 return false; 10106 } 10107 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 10108 } 10109 10110 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 10111 if (p.usesLibraries != null || p.usesOptionalLibraries != null 10112 || p.usesStaticLibraries != null) { 10113 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 10114 Set<String> collectedNames = new HashSet<>(); 10115 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 10116 10117 retValue.remove(p); 10118 10119 return retValue; 10120 } else { 10121 return Collections.emptyList(); 10122 } 10123 } 10124 10125 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 10126 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 10127 if (!collectedNames.contains(p.packageName)) { 10128 collectedNames.add(p.packageName); 10129 collected.add(p); 10130 10131 if (p.usesLibraries != null) { 10132 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 10133 null, collected, collectedNames); 10134 } 10135 if (p.usesOptionalLibraries != null) { 10136 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 10137 null, collected, collectedNames); 10138 } 10139 if (p.usesStaticLibraries != null) { 10140 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 10141 p.usesStaticLibrariesVersions, collected, collectedNames); 10142 } 10143 } 10144 } 10145 10146 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 10147 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 10148 final int libNameCount = libs.size(); 10149 for (int i = 0; i < libNameCount; i++) { 10150 String libName = libs.get(i); 10151 int version = (versions != null && versions.length == libNameCount) 10152 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 10153 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 10154 if (libPkg != null) { 10155 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 10156 } 10157 } 10158 } 10159 10160 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 10161 synchronized (mPackages) { 10162 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 10163 if (libEntry != null) { 10164 return mPackages.get(libEntry.apk); 10165 } 10166 return null; 10167 } 10168 } 10169 10170 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 10171 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10172 if (versionedLib == null) { 10173 return null; 10174 } 10175 return versionedLib.get(version); 10176 } 10177 10178 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 10179 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10180 pkg.staticSharedLibName); 10181 if (versionedLib == null) { 10182 return null; 10183 } 10184 int previousLibVersion = -1; 10185 final int versionCount = versionedLib.size(); 10186 for (int i = 0; i < versionCount; i++) { 10187 final int libVersion = versionedLib.keyAt(i); 10188 if (libVersion < pkg.staticSharedLibVersion) { 10189 previousLibVersion = Math.max(previousLibVersion, libVersion); 10190 } 10191 } 10192 if (previousLibVersion >= 0) { 10193 return versionedLib.get(previousLibVersion); 10194 } 10195 return null; 10196 } 10197 10198 public void shutdown() { 10199 mPackageUsage.writeNow(mPackages); 10200 mCompilerStats.writeNow(); 10201 mDexManager.writePackageDexUsageNow(); 10202 } 10203 10204 @Override 10205 public void dumpProfiles(String packageName) { 10206 PackageParser.Package pkg; 10207 synchronized (mPackages) { 10208 pkg = mPackages.get(packageName); 10209 if (pkg == null) { 10210 throw new IllegalArgumentException("Unknown package: " + packageName); 10211 } 10212 } 10213 /* Only the shell, root, or the app user should be able to dump profiles. */ 10214 int callingUid = Binder.getCallingUid(); 10215 if (callingUid != Process.SHELL_UID && 10216 callingUid != Process.ROOT_UID && 10217 callingUid != pkg.applicationInfo.uid) { 10218 throw new SecurityException("dumpProfiles"); 10219 } 10220 10221 synchronized (mInstallLock) { 10222 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 10223 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 10224 try { 10225 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 10226 String codePaths = TextUtils.join(";", allCodePaths); 10227 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 10228 } catch (InstallerException e) { 10229 Slog.w(TAG, "Failed to dump profiles", e); 10230 } 10231 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10232 } 10233 } 10234 10235 @Override 10236 public void forceDexOpt(String packageName) { 10237 enforceSystemOrRoot("forceDexOpt"); 10238 10239 PackageParser.Package pkg; 10240 synchronized (mPackages) { 10241 pkg = mPackages.get(packageName); 10242 if (pkg == null) { 10243 throw new IllegalArgumentException("Unknown package: " + packageName); 10244 } 10245 } 10246 10247 synchronized (mInstallLock) { 10248 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 10249 10250 // Whoever is calling forceDexOpt wants a compiled package. 10251 // Don't use profiles since that may cause compilation to be skipped. 10252 final int res = performDexOptInternalWithDependenciesLI( 10253 pkg, 10254 new DexoptOptions(packageName, 10255 getDefaultCompilerFilter(), 10256 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 10257 10258 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10259 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 10260 throw new IllegalStateException("Failed to dexopt: " + res); 10261 } 10262 } 10263 } 10264 10265 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 10266 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 10267 Slog.w(TAG, "Unable to update from " + oldPkg.name 10268 + " to " + newPkg.packageName 10269 + ": old package not in system partition"); 10270 return false; 10271 } else if (mPackages.get(oldPkg.name) != null) { 10272 Slog.w(TAG, "Unable to update from " + oldPkg.name 10273 + " to " + newPkg.packageName 10274 + ": old package still exists"); 10275 return false; 10276 } 10277 return true; 10278 } 10279 10280 void removeCodePathLI(File codePath) { 10281 if (codePath.isDirectory()) { 10282 try { 10283 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 10284 } catch (InstallerException e) { 10285 Slog.w(TAG, "Failed to remove code path", e); 10286 } 10287 } else { 10288 codePath.delete(); 10289 } 10290 } 10291 10292 private int[] resolveUserIds(int userId) { 10293 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 10294 } 10295 10296 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 10297 if (pkg == null) { 10298 Slog.wtf(TAG, "Package was null!", new Throwable()); 10299 return; 10300 } 10301 clearAppDataLeafLIF(pkg, userId, flags); 10302 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10303 for (int i = 0; i < childCount; i++) { 10304 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 10305 } 10306 } 10307 10308 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 10309 final PackageSetting ps; 10310 synchronized (mPackages) { 10311 ps = mSettings.mPackages.get(pkg.packageName); 10312 } 10313 for (int realUserId : resolveUserIds(userId)) { 10314 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 10315 try { 10316 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 10317 ceDataInode); 10318 } catch (InstallerException e) { 10319 Slog.w(TAG, String.valueOf(e)); 10320 } 10321 } 10322 } 10323 10324 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 10325 if (pkg == null) { 10326 Slog.wtf(TAG, "Package was null!", new Throwable()); 10327 return; 10328 } 10329 destroyAppDataLeafLIF(pkg, userId, flags); 10330 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10331 for (int i = 0; i < childCount; i++) { 10332 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 10333 } 10334 } 10335 10336 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 10337 final PackageSetting ps; 10338 synchronized (mPackages) { 10339 ps = mSettings.mPackages.get(pkg.packageName); 10340 } 10341 for (int realUserId : resolveUserIds(userId)) { 10342 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 10343 try { 10344 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 10345 ceDataInode); 10346 } catch (InstallerException e) { 10347 Slog.w(TAG, String.valueOf(e)); 10348 } 10349 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 10350 } 10351 } 10352 10353 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 10354 if (pkg == null) { 10355 Slog.wtf(TAG, "Package was null!", new Throwable()); 10356 return; 10357 } 10358 destroyAppProfilesLeafLIF(pkg); 10359 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10360 for (int i = 0; i < childCount; i++) { 10361 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 10362 } 10363 } 10364 10365 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 10366 try { 10367 mInstaller.destroyAppProfiles(pkg.packageName); 10368 } catch (InstallerException e) { 10369 Slog.w(TAG, String.valueOf(e)); 10370 } 10371 } 10372 10373 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 10374 if (pkg == null) { 10375 Slog.wtf(TAG, "Package was null!", new Throwable()); 10376 return; 10377 } 10378 clearAppProfilesLeafLIF(pkg); 10379 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10380 for (int i = 0; i < childCount; i++) { 10381 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 10382 } 10383 } 10384 10385 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 10386 try { 10387 mInstaller.clearAppProfiles(pkg.packageName); 10388 } catch (InstallerException e) { 10389 Slog.w(TAG, String.valueOf(e)); 10390 } 10391 } 10392 10393 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 10394 long lastUpdateTime) { 10395 // Set parent install/update time 10396 PackageSetting ps = (PackageSetting) pkg.mExtras; 10397 if (ps != null) { 10398 ps.firstInstallTime = firstInstallTime; 10399 ps.lastUpdateTime = lastUpdateTime; 10400 } 10401 // Set children install/update time 10402 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10403 for (int i = 0; i < childCount; i++) { 10404 PackageParser.Package childPkg = pkg.childPackages.get(i); 10405 ps = (PackageSetting) childPkg.mExtras; 10406 if (ps != null) { 10407 ps.firstInstallTime = firstInstallTime; 10408 ps.lastUpdateTime = lastUpdateTime; 10409 } 10410 } 10411 } 10412 10413 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 10414 PackageParser.Package changingLib) { 10415 if (file.path != null) { 10416 usesLibraryFiles.add(file.path); 10417 return; 10418 } 10419 PackageParser.Package p = mPackages.get(file.apk); 10420 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 10421 // If we are doing this while in the middle of updating a library apk, 10422 // then we need to make sure to use that new apk for determining the 10423 // dependencies here. (We haven't yet finished committing the new apk 10424 // to the package manager state.) 10425 if (p == null || p.packageName.equals(changingLib.packageName)) { 10426 p = changingLib; 10427 } 10428 } 10429 if (p != null) { 10430 usesLibraryFiles.addAll(p.getAllCodePaths()); 10431 if (p.usesLibraryFiles != null) { 10432 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 10433 } 10434 } 10435 } 10436 10437 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 10438 PackageParser.Package changingLib) throws PackageManagerException { 10439 if (pkg == null) { 10440 return; 10441 } 10442 ArraySet<String> usesLibraryFiles = null; 10443 if (pkg.usesLibraries != null) { 10444 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 10445 null, null, pkg.packageName, changingLib, true, 10446 pkg.applicationInfo.targetSdkVersion, null); 10447 } 10448 if (pkg.usesStaticLibraries != null) { 10449 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 10450 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 10451 pkg.packageName, changingLib, true, 10452 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 10453 } 10454 if (pkg.usesOptionalLibraries != null) { 10455 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 10456 null, null, pkg.packageName, changingLib, false, 10457 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 10458 } 10459 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 10460 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 10461 } else { 10462 pkg.usesLibraryFiles = null; 10463 } 10464 } 10465 10466 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 10467 @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests, 10468 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 10469 boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries) 10470 throws PackageManagerException { 10471 final int libCount = requestedLibraries.size(); 10472 for (int i = 0; i < libCount; i++) { 10473 final String libName = requestedLibraries.get(i); 10474 final int libVersion = requiredVersions != null ? requiredVersions[i] 10475 : SharedLibraryInfo.VERSION_UNDEFINED; 10476 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 10477 if (libEntry == null) { 10478 if (required) { 10479 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10480 "Package " + packageName + " requires unavailable shared library " 10481 + libName + "; failing!"); 10482 } else if (DEBUG_SHARED_LIBRARIES) { 10483 Slog.i(TAG, "Package " + packageName 10484 + " desires unavailable shared library " 10485 + libName + "; ignoring!"); 10486 } 10487 } else { 10488 if (requiredVersions != null && requiredCertDigests != null) { 10489 if (libEntry.info.getVersion() != requiredVersions[i]) { 10490 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10491 "Package " + packageName + " requires unavailable static shared" 10492 + " library " + libName + " version " 10493 + libEntry.info.getVersion() + "; failing!"); 10494 } 10495 10496 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 10497 if (libPkg == null) { 10498 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10499 "Package " + packageName + " requires unavailable static shared" 10500 + " library; failing!"); 10501 } 10502 10503 final String[] expectedCertDigests = requiredCertDigests[i]; 10504 // For apps targeting O MR1 we require explicit enumeration of all certs. 10505 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 10506 ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures) 10507 : PackageUtils.computeSignaturesSha256Digests( 10508 new Signature[]{libPkg.mSignatures[0]}); 10509 10510 // Take a shortcut if sizes don't match. Note that if an app doesn't 10511 // target O we don't parse the "additional-certificate" tags similarly 10512 // how we only consider all certs only for apps targeting O (see above). 10513 // Therefore, the size check is safe to make. 10514 if (expectedCertDigests.length != libCertDigests.length) { 10515 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10516 "Package " + packageName + " requires differently signed" + 10517 " static sDexLoadReporter.java:45.19hared library; failing!"); 10518 } 10519 10520 // Use a predictable order as signature order may vary 10521 Arrays.sort(libCertDigests); 10522 Arrays.sort(expectedCertDigests); 10523 10524 final int certCount = libCertDigests.length; 10525 for (int j = 0; j < certCount; j++) { 10526 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 10527 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10528 "Package " + packageName + " requires differently signed" + 10529 " static shared library; failing!"); 10530 } 10531 } 10532 } 10533 10534 if (outUsedLibraries == null) { 10535 outUsedLibraries = new ArraySet<>(); 10536 } 10537 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 10538 } 10539 } 10540 return outUsedLibraries; 10541 } 10542 10543 private static boolean hasString(List<String> list, List<String> which) { 10544 if (list == null) { 10545 return false; 10546 } 10547 for (int i=list.size()-1; i>=0; i--) { 10548 for (int j=which.size()-1; j>=0; j--) { 10549 if (which.get(j).equals(list.get(i))) { 10550 return true; 10551 } 10552 } 10553 } 10554 return false; 10555 } 10556 10557 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 10558 PackageParser.Package changingPkg) { 10559 ArrayList<PackageParser.Package> res = null; 10560 for (PackageParser.Package pkg : mPackages.values()) { 10561 if (changingPkg != null 10562 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 10563 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 10564 && !ArrayUtils.contains(pkg.usesStaticLibraries, 10565 changingPkg.staticSharedLibName)) { 10566 return null; 10567 } 10568 if (res == null) { 10569 res = new ArrayList<>(); 10570 } 10571 res.add(pkg); 10572 try { 10573 updateSharedLibrariesLPr(pkg, changingPkg); 10574 } catch (PackageManagerException e) { 10575 // If a system app update or an app and a required lib missing we 10576 // delete the package and for updated system apps keep the data as 10577 // it is better for the user to reinstall than to be in an limbo 10578 // state. Also libs disappearing under an app should never happen 10579 // - just in case. 10580 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 10581 final int flags = pkg.isUpdatedSystemApp() 10582 ? PackageManager.DELETE_KEEP_DATA : 0; 10583 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 10584 flags , null, true, null); 10585 } 10586 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 10587 } 10588 } 10589 return res; 10590 } 10591 10592 /** 10593 * Derive the value of the {@code cpuAbiOverride} based on the provided 10594 * value and an optional stored value from the package settings. 10595 */ 10596 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 10597 String cpuAbiOverride = null; 10598 10599 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 10600 cpuAbiOverride = null; 10601 } else if (abiOverride != null) { 10602 cpuAbiOverride = abiOverride; 10603 } else if (settings != null) { 10604 cpuAbiOverride = settings.cpuAbiOverrideString; 10605 } 10606 10607 return cpuAbiOverride; 10608 } 10609 10610 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 10611 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 10612 throws PackageManagerException { 10613 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 10614 // If the package has children and this is the first dive in the function 10615 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 10616 // whether all packages (parent and children) would be successfully scanned 10617 // before the actual scan since scanning mutates internal state and we want 10618 // to atomically install the package and its children. 10619 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10620 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 10621 scanFlags |= SCAN_CHECK_ONLY; 10622 } 10623 } else { 10624 scanFlags &= ~SCAN_CHECK_ONLY; 10625 } 10626 10627 final PackageParser.Package scannedPkg; 10628 try { 10629 // Scan the parent 10630 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 10631 // Scan the children 10632 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10633 for (int i = 0; i < childCount; i++) { 10634 PackageParser.Package childPkg = pkg.childPackages.get(i); 10635 scanPackageLI(childPkg, policyFlags, 10636 scanFlags, currentTime, user); 10637 } 10638 } finally { 10639 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10640 } 10641 10642 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10643 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 10644 } 10645 10646 return scannedPkg; 10647 } 10648 10649 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 10650 int scanFlags, long currentTime, @Nullable UserHandle user) 10651 throws PackageManagerException { 10652 boolean success = false; 10653 try { 10654 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 10655 currentTime, user); 10656 success = true; 10657 return res; 10658 } finally { 10659 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 10660 // DELETE_DATA_ON_FAILURES is only used by frozen paths 10661 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 10662 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 10663 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 10664 } 10665 } 10666 } 10667 10668 /** 10669 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10670 */ 10671 private static boolean apkHasCode(String fileName) { 10672 StrictJarFile jarFile = null; 10673 try { 10674 jarFile = new StrictJarFile(fileName, 10675 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10676 return jarFile.findEntry("classes.dex") != null; 10677 } catch (IOException ignore) { 10678 } finally { 10679 try { 10680 if (jarFile != null) { 10681 jarFile.close(); 10682 } 10683 } catch (IOException ignore) {} 10684 } 10685 return false; 10686 } 10687 10688 /** 10689 * Enforces code policy for the package. This ensures that if an APK has 10690 * declared hasCode="true" in its manifest that the APK actually contains 10691 * code. 10692 * 10693 * @throws PackageManagerException If bytecode could not be found when it should exist 10694 */ 10695 private static void assertCodePolicy(PackageParser.Package pkg) 10696 throws PackageManagerException { 10697 final boolean shouldHaveCode = 10698 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10699 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10700 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10701 "Package " + pkg.baseCodePath + " code is missing"); 10702 } 10703 10704 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10705 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10706 final boolean splitShouldHaveCode = 10707 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10708 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10709 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10710 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10711 } 10712 } 10713 } 10714 } 10715 10716 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 10717 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 10718 throws PackageManagerException { 10719 if (DEBUG_PACKAGE_SCANNING) { 10720 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 10721 Log.d(TAG, "Scanning package " + pkg.packageName); 10722 } 10723 10724 applyPolicy(pkg, policyFlags); 10725 10726 assertPackageIsValid(pkg, policyFlags, scanFlags); 10727 10728 // Initialize package source and resource directories 10729 final File scanFile = new File(pkg.codePath); 10730 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10731 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10732 10733 SharedUserSetting suid = null; 10734 PackageSetting pkgSetting = null; 10735 10736 // Getting the package setting may have a side-effect, so if we 10737 // are only checking if scan would succeed, stash a copy of the 10738 // old setting to restore at the end. 10739 PackageSetting nonMutatedPs = null; 10740 10741 // We keep references to the derived CPU Abis from settings in oder to reuse 10742 // them in the case where we're not upgrading or booting for the first time. 10743 String primaryCpuAbiFromSettings = null; 10744 String secondaryCpuAbiFromSettings = null; 10745 10746 // writer 10747 synchronized (mPackages) { 10748 if (pkg.mSharedUserId != null) { 10749 // SIDE EFFECTS; may potentially allocate a new shared user 10750 suid = mSettings.getSharedUserLPw( 10751 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 10752 if (DEBUG_PACKAGE_SCANNING) { 10753 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 10754 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 10755 + "): packages=" + suid.packages); 10756 } 10757 } 10758 10759 // Check if we are renaming from an original package name. 10760 PackageSetting origPackage = null; 10761 String realName = null; 10762 if (pkg.mOriginalPackages != null) { 10763 // This package may need to be renamed to a previously 10764 // installed name. Let's check on that... 10765 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 10766 if (pkg.mOriginalPackages.contains(renamed)) { 10767 // This package had originally been installed as the 10768 // original name, and we have already taken care of 10769 // transitioning to the new one. Just update the new 10770 // one to continue using the old name. 10771 realName = pkg.mRealPackage; 10772 if (!pkg.packageName.equals(renamed)) { 10773 // Callers into this function may have already taken 10774 // care of renaming the package; only do it here if 10775 // it is not already done. 10776 pkg.setPackageName(renamed); 10777 } 10778 } else { 10779 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 10780 if ((origPackage = mSettings.getPackageLPr( 10781 pkg.mOriginalPackages.get(i))) != null) { 10782 // We do have the package already installed under its 10783 // original name... should we use it? 10784 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 10785 // New package is not compatible with original. 10786 origPackage = null; 10787 continue; 10788 } else if (origPackage.sharedUser != null) { 10789 // Make sure uid is compatible between packages. 10790 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 10791 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 10792 + " to " + pkg.packageName + ": old uid " 10793 + origPackage.sharedUser.name 10794 + " differs from " + pkg.mSharedUserId); 10795 origPackage = null; 10796 continue; 10797 } 10798 // TODO: Add case when shared user id is added [b/28144775] 10799 } else { 10800 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10801 + pkg.packageName + " to old name " + origPackage.name); 10802 } 10803 break; 10804 } 10805 } 10806 } 10807 } 10808 10809 if (mTransferedPackages.contains(pkg.packageName)) { 10810 Slog.w(TAG, "Package " + pkg.packageName 10811 + " was transferred to another, but its .apk remains"); 10812 } 10813 10814 // See comments in nonMutatedPs declaration 10815 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10816 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 10817 if (foundPs != null) { 10818 nonMutatedPs = new PackageSetting(foundPs); 10819 } 10820 } 10821 10822 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 10823 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 10824 if (foundPs != null) { 10825 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 10826 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 10827 } 10828 } 10829 10830 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 10831 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 10832 PackageManagerService.reportSettingsProblem(Log.WARN, 10833 "Package " + pkg.packageName + " shared user changed from " 10834 + (pkgSetting.sharedUser != null 10835 ? pkgSetting.sharedUser.name : "<nothing>") 10836 + " to " 10837 + (suid != null ? suid.name : "<nothing>") 10838 + "; replacing with new"); 10839 pkgSetting = null; 10840 } 10841 final PackageSetting oldPkgSetting = 10842 pkgSetting == null ? null : new PackageSetting(pkgSetting); 10843 final PackageSetting disabledPkgSetting = 10844 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 10845 10846 String[] usesStaticLibraries = null; 10847 if (pkg.usesStaticLibraries != null) { 10848 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10849 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10850 } 10851 10852 if (pkgSetting == null) { 10853 final String parentPackageName = (pkg.parentPackage != null) 10854 ? pkg.parentPackage.packageName : null; 10855 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10856 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 10857 // REMOVE SharedUserSetting from method; update in a separate call 10858 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 10859 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 10860 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 10861 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 10862 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 10863 true /*allowInstall*/, instantApp, virtualPreload, 10864 parentPackageName, pkg.getChildPackageNames(), 10865 UserManagerService.getInstance(), usesStaticLibraries, 10866 pkg.usesStaticLibrariesVersions); 10867 // SIDE EFFECTS; updates system state; move elsewhere 10868 if (origPackage != null) { 10869 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 10870 } 10871 mSettings.addUserToSettingLPw(pkgSetting); 10872 } else { 10873 // REMOVE SharedUserSetting from method; update in a separate call. 10874 // 10875 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10876 // secondaryCpuAbi are not known at this point so we always update them 10877 // to null here, only to reset them at a later point. 10878 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 10879 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 10880 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 10881 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 10882 UserManagerService.getInstance(), usesStaticLibraries, 10883 pkg.usesStaticLibrariesVersions); 10884 } 10885 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 10886 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 10887 10888 // SIDE EFFECTS; modifies system state; move elsewhere 10889 if (pkgSetting.origPackage != null) { 10890 // If we are first transitioning from an original package, 10891 // fix up the new package's name now. We need to do this after 10892 // looking up the package under its new name, so getPackageLP 10893 // can take care of fiddling things correctly. 10894 pkg.setPackageName(origPackage.name); 10895 10896 // File a report about this. 10897 String msg = "New package " + pkgSetting.realName 10898 + " renamed to replace old package " + pkgSetting.name; 10899 reportSettingsProblem(Log.WARN, msg); 10900 10901 // Make a note of it. 10902 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10903 mTransferedPackages.add(origPackage.name); 10904 } 10905 10906 // No longer need to retain this. 10907 pkgSetting.origPackage = null; 10908 } 10909 10910 // SIDE EFFECTS; modifies system state; move elsewhere 10911 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 10912 // Make a note of it. 10913 mTransferedPackages.add(pkg.packageName); 10914 } 10915 10916 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 10917 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10918 } 10919 10920 if ((scanFlags & SCAN_BOOTING) == 0 10921 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10922 // Check all shared libraries and map to their actual file path. 10923 // We only do this here for apps not on a system dir, because those 10924 // are the only ones that can fail an install due to this. We 10925 // will take care of the system apps by updating all of their 10926 // library paths after the scan is done. Also during the initial 10927 // scan don't update any libs as we do this wholesale after all 10928 // apps are scanned to avoid dependency based scanning. 10929 updateSharedLibrariesLPr(pkg, null); 10930 } 10931 10932 if (mFoundPolicyFile) { 10933 SELinuxMMAC.assignSeInfoValue(pkg); 10934 } 10935 pkg.applicationInfo.uid = pkgSetting.appId; 10936 pkg.mExtras = pkgSetting; 10937 10938 10939 // Static shared libs have same package with different versions where 10940 // we internally use a synthetic package name to allow multiple versions 10941 // of the same package, therefore we need to compare signatures against 10942 // the package setting for the latest library version. 10943 PackageSetting signatureCheckPs = pkgSetting; 10944 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10945 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 10946 if (libraryEntry != null) { 10947 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 10948 } 10949 } 10950 10951 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 10952 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 10953 // We just determined the app is signed correctly, so bring 10954 // over the latest parsed certs. 10955 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10956 } else { 10957 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10958 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10959 "Package " + pkg.packageName + " upgrade keys do not match the " 10960 + "previously installed version"); 10961 } else { 10962 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10963 String msg = "System package " + pkg.packageName 10964 + " signature changed; retaining data."; 10965 reportSettingsProblem(Log.WARN, msg); 10966 } 10967 } 10968 } else { 10969 try { 10970 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 10971 verifySignaturesLP(signatureCheckPs, pkg); 10972 // We just determined the app is signed correctly, so bring 10973 // over the latest parsed certs. 10974 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10975 } catch (PackageManagerException e) { 10976 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10977 throw e; 10978 } 10979 // The signature has changed, but this package is in the system 10980 // image... let's recover! 10981 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10982 // However... if this package is part of a shared user, but it 10983 // doesn't match the signature of the shared user, let's fail. 10984 // What this means is that you can't change the signatures 10985 // associated with an overall shared user, which doesn't seem all 10986 // that unreasonable. 10987 if (signatureCheckPs.sharedUser != null) { 10988 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 10989 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10990 throw new PackageManagerException( 10991 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10992 "Signature mismatch for shared user: " 10993 + pkgSetting.sharedUser); 10994 } 10995 } 10996 // File a report about this. 10997 String msg = "System package " + pkg.packageName 10998 + " signature changed; retaining data."; 10999 reportSettingsProblem(Log.WARN, msg); 11000 } 11001 } 11002 11003 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 11004 // This package wants to adopt ownership of permissions from 11005 // another package. 11006 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 11007 final String origName = pkg.mAdoptPermissions.get(i); 11008 final PackageSetting orig = mSettings.getPackageLPr(origName); 11009 if (orig != null) { 11010 if (verifyPackageUpdateLPr(orig, pkg)) { 11011 Slog.i(TAG, "Adopting permissions from " + origName + " to " 11012 + pkg.packageName); 11013 // SIDE EFFECTS; updates permissions system state; move elsewhere 11014 mSettings.transferPermissionsLPw(origName, pkg.packageName); 11015 } 11016 } 11017 } 11018 } 11019 } 11020 11021 pkg.applicationInfo.processName = fixProcessName( 11022 pkg.applicationInfo.packageName, 11023 pkg.applicationInfo.processName); 11024 11025 if (pkg != mPlatformPackage) { 11026 // Get all of our default paths setup 11027 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 11028 } 11029 11030 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 11031 11032 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 11033 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 11034 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 11035 final boolean extractNativeLibs = !pkg.isLibrary(); 11036 derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs, 11037 mAppLib32InstallDir); 11038 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11039 11040 // Some system apps still use directory structure for native libraries 11041 // in which case we might end up not detecting abi solely based on apk 11042 // structure. Try to detect abi based on directory structure. 11043 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 11044 pkg.applicationInfo.primaryCpuAbi == null) { 11045 setBundledAppAbisAndRoots(pkg, pkgSetting); 11046 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 11047 } 11048 } else { 11049 // This is not a first boot or an upgrade, don't bother deriving the 11050 // ABI during the scan. Instead, trust the value that was stored in the 11051 // package setting. 11052 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 11053 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 11054 11055 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 11056 11057 if (DEBUG_ABI_SELECTION) { 11058 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 11059 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 11060 pkg.applicationInfo.secondaryCpuAbi); 11061 } 11062 } 11063 } else { 11064 if ((scanFlags & SCAN_MOVE) != 0) { 11065 // We haven't run dex-opt for this move (since we've moved the compiled output too) 11066 // but we already have this packages package info in the PackageSetting. We just 11067 // use that and derive the native library path based on the new codepath. 11068 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 11069 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 11070 } 11071 11072 // Set native library paths again. For moves, the path will be updated based on the 11073 // ABIs we've determined above. For non-moves, the path will be updated based on the 11074 // ABIs we determined during compilation, but the path will depend on the final 11075 // package path (after the rename away from the stage path). 11076 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 11077 } 11078 11079 // This is a special case for the "system" package, where the ABI is 11080 // dictated by the zygote configuration (and init.rc). We should keep track 11081 // of this ABI so that we can deal with "normal" applications that run under 11082 // the same UID correctly. 11083 if (mPlatformPackage == pkg) { 11084 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 11085 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 11086 } 11087 11088 // If there's a mismatch between the abi-override in the package setting 11089 // and the abiOverride specified for the install. Warn about this because we 11090 // would've already compiled the app without taking the package setting into 11091 // account. 11092 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 11093 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 11094 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 11095 " for package " + pkg.packageName); 11096 } 11097 } 11098 11099 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11100 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11101 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 11102 11103 // Copy the derived override back to the parsed package, so that we can 11104 // update the package settings accordingly. 11105 pkg.cpuAbiOverride = cpuAbiOverride; 11106 11107 if (DEBUG_ABI_SELECTION) { 11108 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 11109 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 11110 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 11111 } 11112 11113 // Push the derived path down into PackageSettings so we know what to 11114 // clean up at uninstall time. 11115 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 11116 11117 if (DEBUG_ABI_SELECTION) { 11118 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 11119 " primary=" + pkg.applicationInfo.primaryCpuAbi + 11120 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 11121 } 11122 11123 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 11124 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 11125 // We don't do this here during boot because we can do it all 11126 // at once after scanning all existing packages. 11127 // 11128 // We also do this *before* we perform dexopt on this package, so that 11129 // we can avoid redundant dexopts, and also to make sure we've got the 11130 // code and package path correct. 11131 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 11132 } 11133 11134 if (mFactoryTest && pkg.requestedPermissions.contains( 11135 android.Manifest.permission.FACTORY_TEST)) { 11136 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 11137 } 11138 11139 if (isSystemApp(pkg)) { 11140 pkgSetting.isOrphaned = true; 11141 } 11142 11143 // Take care of first install / last update times. 11144 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 11145 if (currentTime != 0) { 11146 if (pkgSetting.firstInstallTime == 0) { 11147 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 11148 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 11149 pkgSetting.lastUpdateTime = currentTime; 11150 } 11151 } else if (pkgSetting.firstInstallTime == 0) { 11152 // We need *something*. Take time time stamp of the file. 11153 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 11154 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 11155 if (scanFileTime != pkgSetting.timeStamp) { 11156 // A package on the system image has changed; consider this 11157 // to be an update. 11158 pkgSetting.lastUpdateTime = scanFileTime; 11159 } 11160 } 11161 pkgSetting.setTimeStamp(scanFileTime); 11162 11163 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 11164 if (nonMutatedPs != null) { 11165 synchronized (mPackages) { 11166 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 11167 } 11168 } 11169 } else { 11170 final int userId = user == null ? 0 : user.getIdentifier(); 11171 // Modify state for the given package setting 11172 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 11173 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 11174 if (pkgSetting.getInstantApp(userId)) { 11175 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 11176 } 11177 } 11178 return pkg; 11179 } 11180 11181 /** 11182 * Applies policy to the parsed package based upon the given policy flags. 11183 * Ensures the package is in a good state. 11184 * <p> 11185 * Implementation detail: This method must NOT have any side effect. It would 11186 * ideally be static, but, it requires locks to read system state. 11187 */ 11188 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 11189 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 11190 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 11191 if (pkg.applicationInfo.isDirectBootAware()) { 11192 // we're direct boot aware; set for all components 11193 for (PackageParser.Service s : pkg.services) { 11194 s.info.encryptionAware = s.info.directBootAware = true; 11195 } 11196 for (PackageParser.Provider p : pkg.providers) { 11197 p.info.encryptionAware = p.info.directBootAware = true; 11198 } 11199 for (PackageParser.Activity a : pkg.activities) { 11200 a.info.encryptionAware = a.info.directBootAware = true; 11201 } 11202 for (PackageParser.Activity r : pkg.receivers) { 11203 r.info.encryptionAware = r.info.directBootAware = true; 11204 } 11205 } 11206 if (compressedFileExists(pkg.codePath)) { 11207 pkg.isStub = true; 11208 } 11209 } else { 11210 // Only allow system apps to be flagged as core apps. 11211 pkg.coreApp = false; 11212 // clear flags not applicable to regular apps 11213 pkg.applicationInfo.privateFlags &= 11214 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 11215 pkg.applicationInfo.privateFlags &= 11216 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 11217 } 11218 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 11219 11220 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 11221 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 11222 } 11223 11224 if (!isSystemApp(pkg)) { 11225 // Only system apps can use these features. 11226 pkg.mOriginalPackages = null; 11227 pkg.mRealPackage = null; 11228 pkg.mAdoptPermissions = null; 11229 } 11230 } 11231 11232 /** 11233 * Asserts the parsed package is valid according to the given policy. If the 11234 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 11235 * <p> 11236 * Implementation detail: This method must NOT have any side effects. It would 11237 * ideally be static, but, it requires locks to read system state. 11238 * 11239 * @throws PackageManagerException If the package fails any of the validation checks 11240 */ 11241 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 11242 throws PackageManagerException { 11243 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 11244 assertCodePolicy(pkg); 11245 } 11246 11247 if (pkg.applicationInfo.getCodePath() == null || 11248 pkg.applicationInfo.getResourcePath() == null) { 11249 // Bail out. The resource and code paths haven't been set. 11250 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 11251 "Code and resource paths haven't been set correctly"); 11252 } 11253 11254 // Make sure we're not adding any bogus keyset info 11255 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11256 ksms.assertScannedPackageValid(pkg); 11257 11258 synchronized (mPackages) { 11259 // The special "android" package can only be defined once 11260 if (pkg.packageName.equals("android")) { 11261 if (mAndroidApplication != null) { 11262 Slog.w(TAG, "*************************************************"); 11263 Slog.w(TAG, "Core android package being redefined. Skipping."); 11264 Slog.w(TAG, " codePath=" + pkg.codePath); 11265 Slog.w(TAG, "*************************************************"); 11266 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 11267 "Core android package being redefined. Skipping."); 11268 } 11269 } 11270 11271 // A package name must be unique; don't allow duplicates 11272 if (mPackages.containsKey(pkg.packageName)) { 11273 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 11274 "Application package " + pkg.packageName 11275 + " already installed. Skipping duplicate."); 11276 } 11277 11278 if (pkg.applicationInfo.isStaticSharedLibrary()) { 11279 // Static libs have a synthetic package name containing the version 11280 // but we still want the base name to be unique. 11281 if (mPackages.containsKey(pkg.manifestPackageName)) { 11282 throw new PackageManagerException( 11283 "Duplicate static shared lib provider package"); 11284 } 11285 11286 // Static shared libraries should have at least O target SDK 11287 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 11288 throw new PackageManagerException( 11289 "Packages declaring static-shared libs must target O SDK or higher"); 11290 } 11291 11292 // Package declaring static a shared lib cannot be instant apps 11293 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11294 throw new PackageManagerException( 11295 "Packages declaring static-shared libs cannot be instant apps"); 11296 } 11297 11298 // Package declaring static a shared lib cannot be renamed since the package 11299 // name is synthetic and apps can't code around package manager internals. 11300 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 11301 throw new PackageManagerException( 11302 "Packages declaring static-shared libs cannot be renamed"); 11303 } 11304 11305 // Package declaring static a shared lib cannot declare child packages 11306 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 11307 throw new PackageManagerException( 11308 "Packages declaring static-shared libs cannot have child packages"); 11309 } 11310 11311 // Package declaring static a shared lib cannot declare dynamic libs 11312 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 11313 throw new PackageManagerException( 11314 "Packages declaring static-shared libs cannot declare dynamic libs"); 11315 } 11316 11317 // Package declaring static a shared lib cannot declare shared users 11318 if (pkg.mSharedUserId != null) { 11319 throw new PackageManagerException( 11320 "Packages declaring static-shared libs cannot declare shared users"); 11321 } 11322 11323 // Static shared libs cannot declare activities 11324 if (!pkg.activities.isEmpty()) { 11325 throw new PackageManagerException( 11326 "Static shared libs cannot declare activities"); 11327 } 11328 11329 // Static shared libs cannot declare services 11330 if (!pkg.services.isEmpty()) { 11331 throw new PackageManagerException( 11332 "Static shared libs cannot declare services"); 11333 } 11334 11335 // Static shared libs cannot declare providers 11336 if (!pkg.providers.isEmpty()) { 11337 throw new PackageManagerException( 11338 "Static shared libs cannot declare content providers"); 11339 } 11340 11341 // Static shared libs cannot declare receivers 11342 if (!pkg.receivers.isEmpty()) { 11343 throw new PackageManagerException( 11344 "Static shared libs cannot declare broadcast receivers"); 11345 } 11346 11347 // Static shared libs cannot declare permission groups 11348 if (!pkg.permissionGroups.isEmpty()) { 11349 throw new PackageManagerException( 11350 "Static shared libs cannot declare permission groups"); 11351 } 11352 11353 // Static shared libs cannot declare permissions 11354 if (!pkg.permissions.isEmpty()) { 11355 throw new PackageManagerException( 11356 "Static shared libs cannot declare permissions"); 11357 } 11358 11359 // Static shared libs cannot declare protected broadcasts 11360 if (pkg.protectedBroadcasts != null) { 11361 throw new PackageManagerException( 11362 "Static shared libs cannot declare protected broadcasts"); 11363 } 11364 11365 // Static shared libs cannot be overlay targets 11366 if (pkg.mOverlayTarget != null) { 11367 throw new PackageManagerException( 11368 "Static shared libs cannot be overlay targets"); 11369 } 11370 11371 // The version codes must be ordered as lib versions 11372 int minVersionCode = Integer.MIN_VALUE; 11373 int maxVersionCode = Integer.MAX_VALUE; 11374 11375 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 11376 pkg.staticSharedLibName); 11377 if (versionedLib != null) { 11378 final int versionCount = versionedLib.size(); 11379 for (int i = 0; i < versionCount; i++) { 11380 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 11381 final int libVersionCode = libInfo.getDeclaringPackage() 11382 .getVersionCode(); 11383 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 11384 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 11385 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 11386 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 11387 } else { 11388 minVersionCode = maxVersionCode = libVersionCode; 11389 break; 11390 } 11391 } 11392 } 11393 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 11394 throw new PackageManagerException("Static shared" 11395 + " lib version codes must be ordered as lib versions"); 11396 } 11397 } 11398 11399 // Only privileged apps and updated privileged apps can add child packages. 11400 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 11401 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 11402 throw new PackageManagerException("Only privileged apps can add child " 11403 + "packages. Ignoring package " + pkg.packageName); 11404 } 11405 final int childCount = pkg.childPackages.size(); 11406 for (int i = 0; i < childCount; i++) { 11407 PackageParser.Package childPkg = pkg.childPackages.get(i); 11408 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 11409 childPkg.packageName)) { 11410 throw new PackageManagerException("Can't override child of " 11411 + "another disabled app. Ignoring package " + pkg.packageName); 11412 } 11413 } 11414 } 11415 11416 // If we're only installing presumed-existing packages, require that the 11417 // scanned APK is both already known and at the path previously established 11418 // for it. Previously unknown packages we pick up normally, but if we have an 11419 // a priori expectation about this package's install presence, enforce it. 11420 // With a singular exception for new system packages. When an OTA contains 11421 // a new system package, we allow the codepath to change from a system location 11422 // to the user-installed location. If we don't allow this change, any newer, 11423 // user-installed version of the application will be ignored. 11424 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 11425 if (mExpectingBetter.containsKey(pkg.packageName)) { 11426 logCriticalInfo(Log.WARN, 11427 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 11428 } else { 11429 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 11430 if (known != null) { 11431 if (DEBUG_PACKAGE_SCANNING) { 11432 Log.d(TAG, "Examining " + pkg.codePath 11433 + " and requiring known paths " + known.codePathString 11434 + " & " + known.resourcePathString); 11435 } 11436 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 11437 || !pkg.applicationInfo.getResourcePath().equals( 11438 known.resourcePathString)) { 11439 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 11440 "Application package " + pkg.packageName 11441 + " found at " + pkg.applicationInfo.getCodePath() 11442 + " but expected at " + known.codePathString 11443 + "; ignoring."); 11444 } 11445 } else { 11446 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11447 "Application package " + pkg.packageName 11448 + " not found; ignoring."); 11449 } 11450 } 11451 } 11452 11453 // Verify that this new package doesn't have any content providers 11454 // that conflict with existing packages. Only do this if the 11455 // package isn't already installed, since we don't want to break 11456 // things that are installed. 11457 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 11458 final int N = pkg.providers.size(); 11459 int i; 11460 for (i=0; i<N; i++) { 11461 PackageParser.Provider p = pkg.providers.get(i); 11462 if (p.info.authority != null) { 11463 String names[] = p.info.authority.split(";"); 11464 for (int j = 0; j < names.length; j++) { 11465 if (mProvidersByAuthority.containsKey(names[j])) { 11466 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11467 final String otherPackageName = 11468 ((other != null && other.getComponentName() != null) ? 11469 other.getComponentName().getPackageName() : "?"); 11470 throw new PackageManagerException( 11471 INSTALL_FAILED_CONFLICTING_PROVIDER, 11472 "Can't install because provider name " + names[j] 11473 + " (in package " + pkg.applicationInfo.packageName 11474 + ") is already used by " + otherPackageName); 11475 } 11476 } 11477 } 11478 } 11479 } 11480 } 11481 } 11482 11483 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 11484 int type, String declaringPackageName, int declaringVersionCode) { 11485 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11486 if (versionedLib == null) { 11487 versionedLib = new SparseArray<>(); 11488 mSharedLibraries.put(name, versionedLib); 11489 if (type == SharedLibraryInfo.TYPE_STATIC) { 11490 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 11491 } 11492 } else if (versionedLib.indexOfKey(version) >= 0) { 11493 return false; 11494 } 11495 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 11496 version, type, declaringPackageName, declaringVersionCode); 11497 versionedLib.put(version, libEntry); 11498 return true; 11499 } 11500 11501 private boolean removeSharedLibraryLPw(String name, int version) { 11502 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11503 if (versionedLib == null) { 11504 return false; 11505 } 11506 final int libIdx = versionedLib.indexOfKey(version); 11507 if (libIdx < 0) { 11508 return false; 11509 } 11510 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 11511 versionedLib.remove(version); 11512 if (versionedLib.size() <= 0) { 11513 mSharedLibraries.remove(name); 11514 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 11515 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 11516 .getPackageName()); 11517 } 11518 } 11519 return true; 11520 } 11521 11522 /** 11523 * Adds a scanned package to the system. When this method is finished, the package will 11524 * be available for query, resolution, etc... 11525 */ 11526 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 11527 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 11528 final String pkgName = pkg.packageName; 11529 if (mCustomResolverComponentName != null && 11530 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 11531 setUpCustomResolverActivity(pkg); 11532 } 11533 11534 if (pkg.packageName.equals("android")) { 11535 synchronized (mPackages) { 11536 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 11537 // Set up information for our fall-back user intent resolution activity. 11538 mPlatformPackage = pkg; 11539 pkg.mVersionCode = mSdkVersion; 11540 mAndroidApplication = pkg.applicationInfo; 11541 if (!mResolverReplaced) { 11542 mResolveActivity.applicationInfo = mAndroidApplication; 11543 mResolveActivity.name = ResolverActivity.class.getName(); 11544 mResolveActivity.packageName = mAndroidApplication.packageName; 11545 mResolveActivity.processName = "system:ui"; 11546 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11547 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 11548 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 11549 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 11550 mResolveActivity.exported = true; 11551 mResolveActivity.enabled = true; 11552 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 11553 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 11554 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 11555 | ActivityInfo.CONFIG_SCREEN_LAYOUT 11556 | ActivityInfo.CONFIG_ORIENTATION 11557 | ActivityInfo.CONFIG_KEYBOARD 11558 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 11559 mResolveInfo.activityInfo = mResolveActivity; 11560 mResolveInfo.priority = 0; 11561 mResolveInfo.preferredOrder = 0; 11562 mResolveInfo.match = 0; 11563 mResolveComponentName = new ComponentName( 11564 mAndroidApplication.packageName, mResolveActivity.name); 11565 } 11566 } 11567 } 11568 } 11569 11570 ArrayList<PackageParser.Package> clientLibPkgs = null; 11571 // writer 11572 synchronized (mPackages) { 11573 boolean hasStaticSharedLibs = false; 11574 11575 // Any app can add new static shared libraries 11576 if (pkg.staticSharedLibName != null) { 11577 // Static shared libs don't allow renaming as they have synthetic package 11578 // names to allow install of multiple versions, so use name from manifest. 11579 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 11580 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 11581 pkg.manifestPackageName, pkg.mVersionCode)) { 11582 hasStaticSharedLibs = true; 11583 } else { 11584 Slog.w(TAG, "Package " + pkg.packageName + " library " 11585 + pkg.staticSharedLibName + " already exists; skipping"); 11586 } 11587 // Static shared libs cannot be updated once installed since they 11588 // use synthetic package name which includes the version code, so 11589 // not need to update other packages's shared lib dependencies. 11590 } 11591 11592 if (!hasStaticSharedLibs 11593 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11594 // Only system apps can add new dynamic shared libraries. 11595 if (pkg.libraryNames != null) { 11596 for (int i = 0; i < pkg.libraryNames.size(); i++) { 11597 String name = pkg.libraryNames.get(i); 11598 boolean allowed = false; 11599 if (pkg.isUpdatedSystemApp()) { 11600 // New library entries can only be added through the 11601 // system image. This is important to get rid of a lot 11602 // of nasty edge cases: for example if we allowed a non- 11603 // system update of the app to add a library, then uninstalling 11604 // the update would make the library go away, and assumptions 11605 // we made such as through app install filtering would now 11606 // have allowed apps on the device which aren't compatible 11607 // with it. Better to just have the restriction here, be 11608 // conservative, and create many fewer cases that can negatively 11609 // impact the user experience. 11610 final PackageSetting sysPs = mSettings 11611 .getDisabledSystemPkgLPr(pkg.packageName); 11612 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 11613 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 11614 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 11615 allowed = true; 11616 break; 11617 } 11618 } 11619 } 11620 } else { 11621 allowed = true; 11622 } 11623 if (allowed) { 11624 if (!addSharedLibraryLPw(null, pkg.packageName, name, 11625 SharedLibraryInfo.VERSION_UNDEFINED, 11626 SharedLibraryInfo.TYPE_DYNAMIC, 11627 pkg.packageName, pkg.mVersionCode)) { 11628 Slog.w(TAG, "Package " + pkg.packageName + " library " 11629 + name + " already exists; skipping"); 11630 } 11631 } else { 11632 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 11633 + name + " that is not declared on system image; skipping"); 11634 } 11635 } 11636 11637 if ((scanFlags & SCAN_BOOTING) == 0) { 11638 // If we are not booting, we need to update any applications 11639 // that are clients of our shared library. If we are booting, 11640 // this will all be done once the scan is complete. 11641 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 11642 } 11643 } 11644 } 11645 } 11646 11647 if ((scanFlags & SCAN_BOOTING) != 0) { 11648 // No apps can run during boot scan, so they don't need to be frozen 11649 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 11650 // Caller asked to not kill app, so it's probably not frozen 11651 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 11652 // Caller asked us to ignore frozen check for some reason; they 11653 // probably didn't know the package name 11654 } else { 11655 // We're doing major surgery on this package, so it better be frozen 11656 // right now to keep it from launching 11657 checkPackageFrozen(pkgName); 11658 } 11659 11660 // Also need to kill any apps that are dependent on the library. 11661 if (clientLibPkgs != null) { 11662 for (int i=0; i<clientLibPkgs.size(); i++) { 11663 PackageParser.Package clientPkg = clientLibPkgs.get(i); 11664 killApplication(clientPkg.applicationInfo.packageName, 11665 clientPkg.applicationInfo.uid, "update lib"); 11666 } 11667 } 11668 11669 // writer 11670 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 11671 11672 synchronized (mPackages) { 11673 // We don't expect installation to fail beyond this point 11674 11675 // Add the new setting to mSettings 11676 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 11677 // Add the new setting to mPackages 11678 mPackages.put(pkg.applicationInfo.packageName, pkg); 11679 // Make sure we don't accidentally delete its data. 11680 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 11681 while (iter.hasNext()) { 11682 PackageCleanItem item = iter.next(); 11683 if (pkgName.equals(item.packageName)) { 11684 iter.remove(); 11685 } 11686 } 11687 11688 // Add the package's KeySets to the global KeySetManagerService 11689 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11690 ksms.addScannedPackageLPw(pkg); 11691 11692 int N = pkg.providers.size(); 11693 StringBuilder r = null; 11694 int i; 11695 for (i=0; i<N; i++) { 11696 PackageParser.Provider p = pkg.providers.get(i); 11697 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 11698 p.info.processName); 11699 mProviders.addProvider(p); 11700 p.syncable = p.info.isSyncable; 11701 if (p.info.authority != null) { 11702 String names[] = p.info.authority.split(";"); 11703 p.info.authority = null; 11704 for (int j = 0; j < names.length; j++) { 11705 if (j == 1 && p.syncable) { 11706 // We only want the first authority for a provider to possibly be 11707 // syncable, so if we already added this provider using a different 11708 // authority clear the syncable flag. We copy the provider before 11709 // changing it because the mProviders object contains a reference 11710 // to a provider that we don't want to change. 11711 // Only do this for the second authority since the resulting provider 11712 // object can be the same for all future authorities for this provider. 11713 p = new PackageParser.Provider(p); 11714 p.syncable = false; 11715 } 11716 if (!mProvidersByAuthority.containsKey(names[j])) { 11717 mProvidersByAuthority.put(names[j], p); 11718 if (p.info.authority == null) { 11719 p.info.authority = names[j]; 11720 } else { 11721 p.info.authority = p.info.authority + ";" + names[j]; 11722 } 11723 if (DEBUG_PACKAGE_SCANNING) { 11724 if (chatty) 11725 Log.d(TAG, "Registered content provider: " + names[j] 11726 + ", className = " + p.info.name + ", isSyncable = " 11727 + p.info.isSyncable); 11728 } 11729 } else { 11730 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11731 Slog.w(TAG, "Skipping provider name " + names[j] + 11732 " (in package " + pkg.applicationInfo.packageName + 11733 "): name already used by " 11734 + ((other != null && other.getComponentName() != null) 11735 ? other.getComponentName().getPackageName() : "?")); 11736 } 11737 } 11738 } 11739 if (chatty) { 11740 if (r == null) { 11741 r = new StringBuilder(256); 11742 } else { 11743 r.append(' '); 11744 } 11745 r.append(p.info.name); 11746 } 11747 } 11748 if (r != null) { 11749 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11750 } 11751 11752 N = pkg.services.size(); 11753 r = null; 11754 for (i=0; i<N; i++) { 11755 PackageParser.Service s = pkg.services.get(i); 11756 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11757 s.info.processName); 11758 mServices.addService(s); 11759 if (chatty) { 11760 if (r == null) { 11761 r = new StringBuilder(256); 11762 } else { 11763 r.append(' '); 11764 } 11765 r.append(s.info.name); 11766 } 11767 } 11768 if (r != null) { 11769 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11770 } 11771 11772 N = pkg.receivers.size(); 11773 r = null; 11774 for (i=0; i<N; i++) { 11775 PackageParser.Activity a = pkg.receivers.get(i); 11776 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11777 a.info.processName); 11778 mReceivers.addActivity(a, "receiver"); 11779 if (chatty) { 11780 if (r == null) { 11781 r = new StringBuilder(256); 11782 } else { 11783 r.append(' '); 11784 } 11785 r.append(a.info.name); 11786 } 11787 } 11788 if (r != null) { 11789 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11790 } 11791 11792 N = pkg.activities.size(); 11793 r = null; 11794 for (i=0; i<N; i++) { 11795 PackageParser.Activity a = pkg.activities.get(i); 11796 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11797 a.info.processName); 11798 mActivities.addActivity(a, "activity"); 11799 if (chatty) { 11800 if (r == null) { 11801 r = new StringBuilder(256); 11802 } else { 11803 r.append(' '); 11804 } 11805 r.append(a.info.name); 11806 } 11807 } 11808 if (r != null) { 11809 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11810 } 11811 11812 N = pkg.permissionGroups.size(); 11813 r = null; 11814 for (i=0; i<N; i++) { 11815 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 11816 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 11817 final String curPackageName = cur == null ? null : cur.info.packageName; 11818 // Dont allow ephemeral apps to define new permission groups. 11819 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11820 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 11821 + pg.info.packageName 11822 + " ignored: instant apps cannot define new permission groups."); 11823 continue; 11824 } 11825 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 11826 if (cur == null || isPackageUpdate) { 11827 mPermissionGroups.put(pg.info.name, pg); 11828 if (chatty) { 11829 if (r == null) { 11830 r = new StringBuilder(256); 11831 } else { 11832 r.append(' '); 11833 } 11834 if (isPackageUpdate) { 11835 r.append("UPD:"); 11836 } 11837 r.append(pg.info.name); 11838 } 11839 } else { 11840 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 11841 + pg.info.packageName + " ignored: original from " 11842 + cur.info.packageName); 11843 if (chatty) { 11844 if (r == null) { 11845 r = new StringBuilder(256); 11846 } else { 11847 r.append(' '); 11848 } 11849 r.append("DUP:"); 11850 r.append(pg.info.name); 11851 } 11852 } 11853 } 11854 if (r != null) { 11855 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 11856 } 11857 11858 N = pkg.permissions.size(); 11859 r = null; 11860 for (i=0; i<N; i++) { 11861 PackageParser.Permission p = pkg.permissions.get(i); 11862 11863 // Dont allow ephemeral apps to define new permissions. 11864 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11865 Slog.w(TAG, "Permission " + p.info.name + " from package " 11866 + p.info.packageName 11867 + " ignored: instant apps cannot define new permissions."); 11868 continue; 11869 } 11870 11871 // Assume by default that we did not install this permission into the system. 11872 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 11873 11874 // Now that permission groups have a special meaning, we ignore permission 11875 // groups for legacy apps to prevent unexpected behavior. In particular, 11876 // permissions for one app being granted to someone just because they happen 11877 // to be in a group defined by another app (before this had no implications). 11878 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 11879 p.group = mPermissionGroups.get(p.info.group); 11880 // Warn for a permission in an unknown group. 11881 if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) { 11882 Slog.i(TAG, "Permission " + p.info.name + " from package " 11883 + p.info.packageName + " in an unknown group " + p.info.group); 11884 } 11885 } 11886 11887 ArrayMap<String, BasePermission> permissionMap = 11888 p.tree ? mSettings.mPermissionTrees 11889 : mSettings.mPermissions; 11890 BasePermission bp = permissionMap.get(p.info.name); 11891 11892 // Allow system apps to redefine non-system permissions 11893 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 11894 final boolean currentOwnerIsSystem = (bp.perm != null 11895 && isSystemApp(bp.perm.owner)); 11896 if (isSystemApp(p.owner)) { 11897 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 11898 // It's a built-in permission and no owner, take ownership now 11899 bp.packageSetting = pkgSetting; 11900 bp.perm = p; 11901 bp.uid = pkg.applicationInfo.uid; 11902 bp.sourcePackage = p.info.packageName; 11903 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 11904 } else if (!currentOwnerIsSystem) { 11905 String msg = "New decl " + p.owner + " of permission " 11906 + p.info.name + " is system; overriding " + bp.sourcePackage; 11907 reportSettingsProblem(Log.WARN, msg); 11908 bp = null; 11909 } 11910 } 11911 } 11912 11913 if (bp == null) { 11914 bp = new BasePermission(p.info.name, p.info.packageName, 11915 BasePermission.TYPE_NORMAL); 11916 permissionMap.put(p.info.name, bp); 11917 } 11918 11919 if (bp.perm == null) { 11920 if (bp.sourcePackage == null 11921 || bp.sourcePackage.equals(p.info.packageName)) { 11922 BasePermission tree = findPermissionTreeLP(p.info.name); 11923 if (tree == null 11924 || tree.sourcePackage.equals(p.info.packageName)) { 11925 bp.packageSetting = pkgSetting; 11926 bp.perm = p; 11927 bp.uid = pkg.applicationInfo.uid; 11928 bp.sourcePackage = p.info.packageName; 11929 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 11930 if (chatty) { 11931 if (r == null) { 11932 r = new StringBuilder(256); 11933 } else { 11934 r.append(' '); 11935 } 11936 r.append(p.info.name); 11937 } 11938 } else { 11939 Slog.w(TAG, "Permission " + p.info.name + " from package " 11940 + p.info.packageName + " ignored: base tree " 11941 + tree.name + " is from package " 11942 + tree.sourcePackage); 11943 } 11944 } else { 11945 Slog.w(TAG, "Permission " + p.info.name + " from package " 11946 + p.info.packageName + " ignored: original from " 11947 + bp.sourcePackage); 11948 } 11949 } else if (chatty) { 11950 if (r == null) { 11951 r = new StringBuilder(256); 11952 } else { 11953 r.append(' '); 11954 } 11955 r.append("DUP:"); 11956 r.append(p.info.name); 11957 } 11958 if (bp.perm == p) { 11959 bp.protectionLevel = p.info.protectionLevel; 11960 } 11961 } 11962 11963 if (r != null) { 11964 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 11965 } 11966 11967 N = pkg.instrumentation.size(); 11968 r = null; 11969 for (i=0; i<N; i++) { 11970 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11971 a.info.packageName = pkg.applicationInfo.packageName; 11972 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11973 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11974 a.info.splitNames = pkg.splitNames; 11975 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11976 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11977 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11978 a.info.dataDir = pkg.applicationInfo.dataDir; 11979 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11980 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11981 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11982 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11983 mInstrumentation.put(a.getComponentName(), a); 11984 if (chatty) { 11985 if (r == null) { 11986 r = new StringBuilder(256); 11987 } else { 11988 r.append(' '); 11989 } 11990 r.append(a.info.name); 11991 } 11992 } 11993 if (r != null) { 11994 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11995 } 11996 11997 if (pkg.protectedBroadcasts != null) { 11998 N = pkg.protectedBroadcasts.size(); 11999 synchronized (mProtectedBroadcasts) { 12000 for (i = 0; i < N; i++) { 12001 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 12002 } 12003 } 12004 } 12005 } 12006 12007 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12008 } 12009 12010 /** 12011 * Derive the ABI of a non-system package located at {@code scanFile}. This information 12012 * is derived purely on the basis of the contents of {@code scanFile} and 12013 * {@code cpuAbiOverride}. 12014 * 12015 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 12016 */ 12017 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 12018 String cpuAbiOverride, boolean extractLibs, 12019 File appLib32InstallDir) 12020 throws PackageManagerException { 12021 // Give ourselves some initial paths; we'll come back for another 12022 // pass once we've determined ABI below. 12023 setNativeLibraryPaths(pkg, appLib32InstallDir); 12024 12025 // We would never need to extract libs for forward-locked and external packages, 12026 // since the container service will do it for us. We shouldn't attempt to 12027 // extract libs from system app when it was not updated. 12028 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 12029 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 12030 extractLibs = false; 12031 } 12032 12033 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 12034 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 12035 12036 NativeLibraryHelper.Handle handle = null; 12037 try { 12038 handle = NativeLibraryHelper.Handle.create(pkg); 12039 // TODO(multiArch): This can be null for apps that didn't go through the 12040 // usual installation process. We can calculate it again, like we 12041 // do during install time. 12042 // 12043 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 12044 // unnecessary. 12045 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 12046 12047 // Null out the abis so that they can be recalculated. 12048 pkg.applicationInfo.primaryCpuAbi = null; 12049 pkg.applicationInfo.secondaryCpuAbi = null; 12050 if (isMultiArch(pkg.applicationInfo)) { 12051 // Warn if we've set an abiOverride for multi-lib packages.. 12052 // By definition, we need to copy both 32 and 64 bit libraries for 12053 // such packages. 12054 if (pkg.cpuAbiOverride != null 12055 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 12056 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 12057 } 12058 12059 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 12060 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 12061 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 12062 if (extractLibs) { 12063 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 12064 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 12065 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 12066 useIsaSpecificSubdirs); 12067 } else { 12068 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 12069 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 12070 } 12071 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12072 } 12073 12074 // Shared library native code should be in the APK zip aligned 12075 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 12076 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 12077 "Shared library native lib extraction not supported"); 12078 } 12079 12080 maybeThrowExceptionForMultiArchCopy( 12081 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 12082 12083 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 12084 if (extractLibs) { 12085 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 12086 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 12087 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 12088 useIsaSpecificSubdirs); 12089 } else { 12090 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 12091 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 12092 } 12093 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12094 } 12095 12096 maybeThrowExceptionForMultiArchCopy( 12097 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 12098 12099 if (abi64 >= 0) { 12100 // Shared library native libs should be in the APK zip aligned 12101 if (extractLibs && pkg.isLibrary()) { 12102 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 12103 "Shared library native lib extraction not supported"); 12104 } 12105 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 12106 } 12107 12108 if (abi32 >= 0) { 12109 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 12110 if (abi64 >= 0) { 12111 if (pkg.use32bitAbi) { 12112 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 12113 pkg.applicationInfo.primaryCpuAbi = abi; 12114 } else { 12115 pkg.applicationInfo.secondaryCpuAbi = abi; 12116 } 12117 } else { 12118 pkg.applicationInfo.primaryCpuAbi = abi; 12119 } 12120 } 12121 } else { 12122 String[] abiList = (cpuAbiOverride != null) ? 12123 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 12124 12125 // Enable gross and lame hacks for apps that are built with old 12126 // SDK tools. We must scan their APKs for renderscript bitcode and 12127 // not launch them if it's present. Don't bother checking on devices 12128 // that don't have 64 bit support. 12129 boolean needsRenderScriptOverride = false; 12130 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 12131 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 12132 abiList = Build.SUPPORTED_32_BIT_ABIS; 12133 needsRenderScriptOverride = true; 12134 } 12135 12136 final int copyRet; 12137 if (extractLibs) { 12138 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 12139 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 12140 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 12141 } else { 12142 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 12143 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 12144 } 12145 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12146 12147 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 12148 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 12149 "Error unpackaging native libs for app, errorCode=" + copyRet); 12150 } 12151 12152 if (copyRet >= 0) { 12153 // Shared libraries that have native libs must be multi-architecture 12154 if (pkg.isLibrary()) { 12155 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 12156 "Shared library with native libs must be multiarch"); 12157 } 12158 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 12159 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 12160 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 12161 } else if (needsRenderScriptOverride) { 12162 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 12163 } 12164 } 12165 } catch (IOException ioe) { 12166 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 12167 } finally { 12168 IoUtils.closeQuietly(handle); 12169 } 12170 12171 // Now that we've calculated the ABIs and determined if it's an internal app, 12172 // we will go ahead and populate the nativeLibraryPath. 12173 setNativeLibraryPaths(pkg, appLib32InstallDir); 12174 } 12175 12176 /** 12177 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 12178 * i.e, so that all packages can be run inside a single process if required. 12179 * 12180 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 12181 * this function will either try and make the ABI for all packages in {@code packagesForUser} 12182 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 12183 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 12184 * updating a package that belongs to a shared user. 12185 * 12186 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 12187 * adds unnecessary complexity. 12188 */ 12189 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 12190 PackageParser.Package scannedPackage) { 12191 String requiredInstructionSet = null; 12192 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 12193 requiredInstructionSet = VMRuntime.getInstructionSet( 12194 scannedPackage.applicationInfo.primaryCpuAbi); 12195 } 12196 12197 PackageSetting requirer = null; 12198 for (PackageSetting ps : packagesForUser) { 12199 // If packagesForUser contains scannedPackage, we skip it. This will happen 12200 // when scannedPackage is an update of an existing package. Without this check, 12201 // we will never be able to change the ABI of any package belonging to a shared 12202 // user, even if it's compatible with other packages. 12203 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 12204 if (ps.primaryCpuAbiString == null) { 12205 continue; 12206 } 12207 12208 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 12209 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 12210 // We have a mismatch between instruction sets (say arm vs arm64) warn about 12211 // this but there's not much we can do. 12212 String errorMessage = "Instruction set mismatch, " 12213 + ((requirer == null) ? "[caller]" : requirer) 12214 + " requires " + requiredInstructionSet + " whereas " + ps 12215 + " requires " + instructionSet; 12216 Slog.w(TAG, errorMessage); 12217 } 12218 12219 if (requiredInstructionSet == null) { 12220 requiredInstructionSet = instructionSet; 12221 requirer = ps; 12222 } 12223 } 12224 } 12225 12226 if (requiredInstructionSet != null) { 12227 String adjustedAbi; 12228 if (requirer != null) { 12229 // requirer != null implies that either scannedPackage was null or that scannedPackage 12230 // did not require an ABI, in which case we have to adjust scannedPackage to match 12231 // the ABI of the set (which is the same as requirer's ABI) 12232 adjustedAbi = requirer.primaryCpuAbiString; 12233 if (scannedPackage != null) { 12234 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 12235 } 12236 } else { 12237 // requirer == null implies that we're updating all ABIs in the set to 12238 // match scannedPackage. 12239 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 12240 } 12241 12242 for (PackageSetting ps : packagesForUser) { 12243 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 12244 if (ps.primaryCpuAbiString != null) { 12245 continue; 12246 } 12247 12248 ps.primaryCpuAbiString = adjustedAbi; 12249 if (ps.pkg != null && ps.pkg.applicationInfo != null && 12250 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 12251 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 12252 if (DEBUG_ABI_SELECTION) { 12253 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 12254 + " (requirer=" 12255 + (requirer != null ? requirer.pkg : "null") 12256 + ", scannedPackage=" 12257 + (scannedPackage != null ? scannedPackage : "null") 12258 + ")"); 12259 } 12260 try { 12261 mInstaller.rmdex(ps.codePathString, 12262 getDexCodeInstructionSet(getPreferredInstructionSet())); 12263 } catch (InstallerException ignored) { 12264 } 12265 } 12266 } 12267 } 12268 } 12269 } 12270 12271 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 12272 synchronized (mPackages) { 12273 mResolverReplaced = true; 12274 // Set up information for custom user intent resolution activity. 12275 mResolveActivity.applicationInfo = pkg.applicationInfo; 12276 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 12277 mResolveActivity.packageName = pkg.applicationInfo.packageName; 12278 mResolveActivity.processName = pkg.applicationInfo.packageName; 12279 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 12280 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 12281 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 12282 mResolveActivity.theme = 0; 12283 mResolveActivity.exported = true; 12284 mResolveActivity.enabled = true; 12285 mResolveInfo.activityInfo = mResolveActivity; 12286 mResolveInfo.priority = 0; 12287 mResolveInfo.preferredOrder = 0; 12288 mResolveInfo.match = 0; 12289 mResolveComponentName = mCustomResolverComponentName; 12290 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 12291 mResolveComponentName); 12292 } 12293 } 12294 12295 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 12296 if (installerActivity == null) { 12297 if (DEBUG_EPHEMERAL) { 12298 Slog.d(TAG, "Clear ephemeral installer activity"); 12299 } 12300 mInstantAppInstallerActivity = null; 12301 return; 12302 } 12303 12304 if (DEBUG_EPHEMERAL) { 12305 Slog.d(TAG, "Set ephemeral installer activity: " 12306 + installerActivity.getComponentName()); 12307 } 12308 // Set up information for ephemeral installer activity 12309 mInstantAppInstallerActivity = installerActivity; 12310 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 12311 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 12312 mInstantAppInstallerActivity.exported = true; 12313 mInstantAppInstallerActivity.enabled = true; 12314 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 12315 mInstantAppInstallerInfo.priority = 0; 12316 mInstantAppInstallerInfo.preferredOrder = 1; 12317 mInstantAppInstallerInfo.isDefault = true; 12318 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 12319 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 12320 } 12321 12322 private static String calculateBundledApkRoot(final String codePathString) { 12323 final File codePath = new File(codePathString); 12324 final File codeRoot; 12325 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 12326 codeRoot = Environment.getRootDirectory(); 12327 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 12328 codeRoot = Environment.getOemDirectory(); 12329 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 12330 codeRoot = Environment.getVendorDirectory(); 12331 } else { 12332 // Unrecognized code path; take its top real segment as the apk root: 12333 // e.g. /something/app/blah.apk => /something 12334 try { 12335 File f = codePath.getCanonicalFile(); 12336 File parent = f.getParentFile(); // non-null because codePath is a file 12337 File tmp; 12338 while ((tmp = parent.getParentFile()) != null) { 12339 f = parent; 12340 parent = tmp; 12341 } 12342 codeRoot = f; 12343 Slog.w(TAG, "Unrecognized code path " 12344 + codePath + " - using " + codeRoot); 12345 } catch (IOException e) { 12346 // Can't canonicalize the code path -- shenanigans? 12347 Slog.w(TAG, "Can't canonicalize code path " + codePath); 12348 return Environment.getRootDirectory().getPath(); 12349 } 12350 } 12351 return codeRoot.getPath(); 12352 } 12353 12354 /** 12355 * Derive and set the location of native libraries for the given package, 12356 * which varies depending on where and how the package was installed. 12357 */ 12358 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 12359 final ApplicationInfo info = pkg.applicationInfo; 12360 final String codePath = pkg.codePath; 12361 final File codeFile = new File(codePath); 12362 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 12363 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 12364 12365 info.nativeLibraryRootDir = null; 12366 info.nativeLibraryRootRequiresIsa = false; 12367 info.nativeLibraryDir = null; 12368 info.secondaryNativeLibraryDir = null; 12369 12370 if (isApkFile(codeFile)) { 12371 // Monolithic install 12372 if (bundledApp) { 12373 // If "/system/lib64/apkname" exists, assume that is the per-package 12374 // native library directory to use; otherwise use "/system/lib/apkname". 12375 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 12376 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 12377 getPrimaryInstructionSet(info)); 12378 12379 // This is a bundled system app so choose the path based on the ABI. 12380 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 12381 // is just the default path. 12382 final String apkName = deriveCodePathName(codePath); 12383 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 12384 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 12385 apkName).getAbsolutePath(); 12386 12387 if (info.secondaryCpuAbi != null) { 12388 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 12389 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 12390 secondaryLibDir, apkName).getAbsolutePath(); 12391 } 12392 } else if (asecApp) { 12393 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 12394 .getAbsolutePath(); 12395 } else { 12396 final String apkName = deriveCodePathName(codePath); 12397 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 12398 .getAbsolutePath(); 12399 } 12400 12401 info.nativeLibraryRootRequiresIsa = false; 12402 info.nativeLibraryDir = info.nativeLibraryRootDir; 12403 } else { 12404 // Cluster install 12405 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 12406 info.nativeLibraryRootRequiresIsa = true; 12407 12408 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 12409 getPrimaryInstructionSet(info)).getAbsolutePath(); 12410 12411 if (info.secondaryCpuAbi != null) { 12412 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 12413 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 12414 } 12415 } 12416 } 12417 12418 /** 12419 * Calculate the abis and roots for a bundled app. These can uniquely 12420 * be determined from the contents of the system partition, i.e whether 12421 * it contains 64 or 32 bit shared libraries etc. We do not validate any 12422 * of this information, and instead assume that the system was built 12423 * sensibly. 12424 */ 12425 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 12426 PackageSetting pkgSetting) { 12427 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 12428 12429 // If "/system/lib64/apkname" exists, assume that is the per-package 12430 // native library directory to use; otherwise use "/system/lib/apkname". 12431 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 12432 setBundledAppAbi(pkg, apkRoot, apkName); 12433 // pkgSetting might be null during rescan following uninstall of updates 12434 // to a bundled app, so accommodate that possibility. The settings in 12435 // that case will be established later from the parsed package. 12436 // 12437 // If the settings aren't null, sync them up with what we've just derived. 12438 // note that apkRoot isn't stored in the package settings. 12439 if (pkgSetting != null) { 12440 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 12441 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 12442 } 12443 } 12444 12445 /** 12446 * Deduces the ABI of a bundled app and sets the relevant fields on the 12447 * parsed pkg object. 12448 * 12449 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 12450 * under which system libraries are installed. 12451 * @param apkName the name of the installed package. 12452 */ 12453 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 12454 final File codeFile = new File(pkg.codePath); 12455 12456 final boolean has64BitLibs; 12457 final boolean has32BitLibs; 12458 if (isApkFile(codeFile)) { 12459 // Monolithic install 12460 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 12461 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 12462 } else { 12463 // Cluster install 12464 final File rootDir = new File(codeFile, LIB_DIR_NAME); 12465 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 12466 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 12467 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 12468 has64BitLibs = (new File(rootDir, isa)).exists(); 12469 } else { 12470 has64BitLibs = false; 12471 } 12472 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 12473 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 12474 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 12475 has32BitLibs = (new File(rootDir, isa)).exists(); 12476 } else { 12477 has32BitLibs = false; 12478 } 12479 } 12480 12481 if (has64BitLibs && !has32BitLibs) { 12482 // The package has 64 bit libs, but not 32 bit libs. Its primary 12483 // ABI should be 64 bit. We can safely assume here that the bundled 12484 // native libraries correspond to the most preferred ABI in the list. 12485 12486 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 12487 pkg.applicationInfo.secondaryCpuAbi = null; 12488 } else if (has32BitLibs && !has64BitLibs) { 12489 // The package has 32 bit libs but not 64 bit libs. Its primary 12490 // ABI should be 32 bit. 12491 12492 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 12493 pkg.applicationInfo.secondaryCpuAbi = null; 12494 } else if (has32BitLibs && has64BitLibs) { 12495 // The application has both 64 and 32 bit bundled libraries. We check 12496 // here that the app declares multiArch support, and warn if it doesn't. 12497 // 12498 // We will be lenient here and record both ABIs. The primary will be the 12499 // ABI that's higher on the list, i.e, a device that's configured to prefer 12500 // 64 bit apps will see a 64 bit primary ABI, 12501 12502 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 12503 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 12504 } 12505 12506 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 12507 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 12508 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 12509 } else { 12510 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 12511 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 12512 } 12513 } else { 12514 pkg.applicationInfo.primaryCpuAbi = null; 12515 pkg.applicationInfo.secondaryCpuAbi = null; 12516 } 12517 } 12518 12519 private void killApplication(String pkgName, int appId, String reason) { 12520 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 12521 } 12522 12523 private void killApplication(String pkgName, int appId, int userId, String reason) { 12524 // Request the ActivityManager to kill the process(only for existing packages) 12525 // so that we do not end up in a confused state while the user is still using the older 12526 // version of the application while the new one gets installed. 12527 final long token = Binder.clearCallingIdentity(); 12528 try { 12529 IActivityManager am = ActivityManager.getService(); 12530 if (am != null) { 12531 try { 12532 am.killApplication(pkgName, appId, userId, reason); 12533 } catch (RemoteException e) { 12534 } 12535 } 12536 } finally { 12537 Binder.restoreCallingIdentity(token); 12538 } 12539 } 12540 12541 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 12542 // Remove the parent package setting 12543 PackageSetting ps = (PackageSetting) pkg.mExtras; 12544 if (ps != null) { 12545 removePackageLI(ps, chatty); 12546 } 12547 // Remove the child package setting 12548 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12549 for (int i = 0; i < childCount; i++) { 12550 PackageParser.Package childPkg = pkg.childPackages.get(i); 12551 ps = (PackageSetting) childPkg.mExtras; 12552 if (ps != null) { 12553 removePackageLI(ps, chatty); 12554 } 12555 } 12556 } 12557 12558 void removePackageLI(PackageSetting ps, boolean chatty) { 12559 if (DEBUG_INSTALL) { 12560 if (chatty) 12561 Log.d(TAG, "Removing package " + ps.name); 12562 } 12563 12564 // writer 12565 synchronized (mPackages) { 12566 mPackages.remove(ps.name); 12567 final PackageParser.Package pkg = ps.pkg; 12568 if (pkg != null) { 12569 cleanPackageDataStructuresLILPw(pkg, chatty); 12570 } 12571 } 12572 } 12573 12574 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 12575 if (DEBUG_INSTALL) { 12576 if (chatty) 12577 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 12578 } 12579 12580 // writer 12581 synchronized (mPackages) { 12582 // Remove the parent package 12583 mPackages.remove(pkg.applicationInfo.packageName); 12584 cleanPackageDataStructuresLILPw(pkg, chatty); 12585 12586 // Remove the child packages 12587 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12588 for (int i = 0; i < childCount; i++) { 12589 PackageParser.Package childPkg = pkg.childPackages.get(i); 12590 mPackages.remove(childPkg.applicationInfo.packageName); 12591 cleanPackageDataStructuresLILPw(childPkg, chatty); 12592 } 12593 } 12594 } 12595 12596 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 12597 int N = pkg.providers.size(); 12598 StringBuilder r = null; 12599 int i; 12600 for (i=0; i<N; i++) { 12601 PackageParser.Provider p = pkg.providers.get(i); 12602 mProviders.removeProvider(p); 12603 if (p.info.authority == null) { 12604 12605 /* There was another ContentProvider with this authority when 12606 * this app was installed so this authority is null, 12607 * Ignore it as we don't have to unregister the provider. 12608 */ 12609 continue; 12610 } 12611 String names[] = p.info.authority.split(";"); 12612 for (int j = 0; j < names.length; j++) { 12613 if (mProvidersByAuthority.get(names[j]) == p) { 12614 mProvidersByAuthority.remove(names[j]); 12615 if (DEBUG_REMOVE) { 12616 if (chatty) 12617 Log.d(TAG, "Unregistered content provider: " + names[j] 12618 + ", className = " + p.info.name + ", isSyncable = " 12619 + p.info.isSyncable); 12620 } 12621 } 12622 } 12623 if (DEBUG_REMOVE && chatty) { 12624 if (r == null) { 12625 r = new StringBuilder(256); 12626 } else { 12627 r.append(' '); 12628 } 12629 r.append(p.info.name); 12630 } 12631 } 12632 if (r != null) { 12633 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 12634 } 12635 12636 N = pkg.services.size(); 12637 r = null; 12638 for (i=0; i<N; i++) { 12639 PackageParser.Service s = pkg.services.get(i); 12640 mServices.removeService(s); 12641 if (chatty) { 12642 if (r == null) { 12643 r = new StringBuilder(256); 12644 } else { 12645 r.append(' '); 12646 } 12647 r.append(s.info.name); 12648 } 12649 } 12650 if (r != null) { 12651 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 12652 } 12653 12654 N = pkg.receivers.size(); 12655 r = null; 12656 for (i=0; i<N; i++) { 12657 PackageParser.Activity a = pkg.receivers.get(i); 12658 mReceivers.removeActivity(a, "receiver"); 12659 if (DEBUG_REMOVE && chatty) { 12660 if (r == null) { 12661 r = new StringBuilder(256); 12662 } else { 12663 r.append(' '); 12664 } 12665 r.append(a.info.name); 12666 } 12667 } 12668 if (r != null) { 12669 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 12670 } 12671 12672 N = pkg.activities.size(); 12673 r = null; 12674 for (i=0; i<N; i++) { 12675 PackageParser.Activity a = pkg.activities.get(i); 12676 mActivities.removeActivity(a, "activity"); 12677 if (DEBUG_REMOVE && chatty) { 12678 if (r == null) { 12679 r = new StringBuilder(256); 12680 } else { 12681 r.append(' '); 12682 } 12683 r.append(a.info.name); 12684 } 12685 } 12686 if (r != null) { 12687 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 12688 } 12689 12690 N = pkg.permissions.size(); 12691 r = null; 12692 for (i=0; i<N; i++) { 12693 PackageParser.Permission p = pkg.permissions.get(i); 12694 BasePermission bp = mSettings.mPermissions.get(p.info.name); 12695 if (bp == null) { 12696 bp = mSettings.mPermissionTrees.get(p.info.name); 12697 } 12698 if (bp != null && bp.perm == p) { 12699 bp.perm = null; 12700 if (DEBUG_REMOVE && chatty) { 12701 if (r == null) { 12702 r = new StringBuilder(256); 12703 } else { 12704 r.append(' '); 12705 } 12706 r.append(p.info.name); 12707 } 12708 } 12709 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 12710 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 12711 if (appOpPkgs != null) { 12712 appOpPkgs.remove(pkg.packageName); 12713 } 12714 } 12715 } 12716 if (r != null) { 12717 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 12718 } 12719 12720 N = pkg.requestedPermissions.size(); 12721 r = null; 12722 for (i=0; i<N; i++) { 12723 String perm = pkg.requestedPermissions.get(i); 12724 BasePermission bp = mSettings.mPermissions.get(perm); 12725 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 12726 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 12727 if (appOpPkgs != null) { 12728 appOpPkgs.remove(pkg.packageName); 12729 if (appOpPkgs.isEmpty()) { 12730 mAppOpPermissionPackages.remove(perm); 12731 } 12732 } 12733 } 12734 } 12735 if (r != null) { 12736 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 12737 } 12738 12739 N = pkg.instrumentation.size(); 12740 r = null; 12741 for (i=0; i<N; i++) { 12742 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12743 mInstrumentation.remove(a.getComponentName()); 12744 if (DEBUG_REMOVE && chatty) { 12745 if (r == null) { 12746 r = new StringBuilder(256); 12747 } else { 12748 r.append(' '); 12749 } 12750 r.append(a.info.name); 12751 } 12752 } 12753 if (r != null) { 12754 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 12755 } 12756 12757 r = null; 12758 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 12759 // Only system apps can hold shared libraries. 12760 if (pkg.libraryNames != null) { 12761 for (i = 0; i < pkg.libraryNames.size(); i++) { 12762 String name = pkg.libraryNames.get(i); 12763 if (removeSharedLibraryLPw(name, 0)) { 12764 if (DEBUG_REMOVE && chatty) { 12765 if (r == null) { 12766 r = new StringBuilder(256); 12767 } else { 12768 r.append(' '); 12769 } 12770 r.append(name); 12771 } 12772 } 12773 } 12774 } 12775 } 12776 12777 r = null; 12778 12779 // Any package can hold static shared libraries. 12780 if (pkg.staticSharedLibName != null) { 12781 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 12782 if (DEBUG_REMOVE && chatty) { 12783 if (r == null) { 12784 r = new StringBuilder(256); 12785 } else { 12786 r.append(' '); 12787 } 12788 r.append(pkg.staticSharedLibName); 12789 } 12790 } 12791 } 12792 12793 if (r != null) { 12794 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12795 } 12796 } 12797 12798 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 12799 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 12800 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 12801 return true; 12802 } 12803 } 12804 return false; 12805 } 12806 12807 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 12808 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 12809 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 12810 12811 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 12812 // Update the parent permissions 12813 updatePermissionsLPw(pkg.packageName, pkg, flags); 12814 // Update the child permissions 12815 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12816 for (int i = 0; i < childCount; i++) { 12817 PackageParser.Package childPkg = pkg.childPackages.get(i); 12818 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 12819 } 12820 } 12821 12822 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 12823 int flags) { 12824 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 12825 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 12826 } 12827 12828 private void updatePermissionsLPw(String changingPkg, 12829 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 12830 // Make sure there are no dangling permission trees. 12831 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 12832 while (it.hasNext()) { 12833 final BasePermission bp = it.next(); 12834 if (bp.packageSetting == null) { 12835 // We may not yet have parsed the package, so just see if 12836 // we still know about its settings. 12837 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 12838 } 12839 if (bp.packageSetting == null) { 12840 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 12841 + " from package " + bp.sourcePackage); 12842 it.remove(); 12843 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 12844 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 12845 Slog.i(TAG, "Removing old permission tree: " + bp.name 12846 + " from package " + bp.sourcePackage); 12847 flags |= UPDATE_PERMISSIONS_ALL; 12848 it.remove(); 12849 } 12850 } 12851 } 12852 12853 // Make sure all dynamic permissions have been assigned to a package, 12854 // and make sure there are no dangling permissions. 12855 it = mSettings.mPermissions.values().iterator(); 12856 while (it.hasNext()) { 12857 final BasePermission bp = it.next(); 12858 if (bp.type == BasePermission.TYPE_DYNAMIC) { 12859 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 12860 + bp.name + " pkg=" + bp.sourcePackage 12861 + " info=" + bp.pendingInfo); 12862 if (bp.packageSetting == null && bp.pendingInfo != null) { 12863 final BasePermission tree = findPermissionTreeLP(bp.name); 12864 if (tree != null && tree.perm != null) { 12865 bp.packageSetting = tree.packageSetting; 12866 bp.perm = new PackageParser.Permission(tree.perm.owner, 12867 new PermissionInfo(bp.pendingInfo)); 12868 bp.perm.info.packageName = tree.perm.info.packageName; 12869 bp.perm.info.name = bp.name; 12870 bp.uid = tree.uid; 12871 } 12872 } 12873 } 12874 if (bp.packageSetting == null) { 12875 // We may not yet have parsed the package, so just see if 12876 // we still know about its settings. 12877 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 12878 } 12879 if (bp.packageSetting == null) { 12880 Slog.w(TAG, "Removing dangling permission: " + bp.name 12881 + " from package " + bp.sourcePackage); 12882 it.remove(); 12883 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 12884 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 12885 Slog.i(TAG, "Removing old permission: " + bp.name 12886 + " from package " + bp.sourcePackage); 12887 flags |= UPDATE_PERMISSIONS_ALL; 12888 it.remove(); 12889 } 12890 } 12891 } 12892 12893 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 12894 // Now update the permissions for all packages, in particular 12895 // replace the granted permissions of the system packages. 12896 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 12897 for (PackageParser.Package pkg : mPackages.values()) { 12898 if (pkg != pkgInfo) { 12899 // Only replace for packages on requested volume 12900 final String volumeUuid = getVolumeUuidForPackage(pkg); 12901 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 12902 && Objects.equals(replaceVolumeUuid, volumeUuid); 12903 grantPermissionsLPw(pkg, replace, changingPkg); 12904 } 12905 } 12906 } 12907 12908 if (pkgInfo != null) { 12909 // Only replace for packages on requested volume 12910 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 12911 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 12912 && Objects.equals(replaceVolumeUuid, volumeUuid); 12913 grantPermissionsLPw(pkgInfo, replace, changingPkg); 12914 } 12915 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12916 } 12917 12918 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 12919 String packageOfInterest) { 12920 // IMPORTANT: There are two types of permissions: install and runtime. 12921 // Install time permissions are granted when the app is installed to 12922 // all device users and users added in the future. Runtime permissions 12923 // are granted at runtime explicitly to specific users. Normal and signature 12924 // protected permissions are install time permissions. Dangerous permissions 12925 // are install permissions if the app's target SDK is Lollipop MR1 or older, 12926 // otherwise they are runtime permissions. This function does not manage 12927 // runtime permissions except for the case an app targeting Lollipop MR1 12928 // being upgraded to target a newer SDK, in which case dangerous permissions 12929 // are transformed from install time to runtime ones. 12930 12931 final PackageSetting ps = (PackageSetting) pkg.mExtras; 12932 if (ps == null) { 12933 return; 12934 } 12935 12936 PermissionsState permissionsState = ps.getPermissionsState(); 12937 PermissionsState origPermissions = permissionsState; 12938 12939 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 12940 12941 boolean runtimePermissionsRevoked = false; 12942 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 12943 12944 boolean changedInstallPermission = false; 12945 12946 if (replace) { 12947 ps.installPermissionsFixed = false; 12948 if (!ps.isSharedUser()) { 12949 origPermissions = new PermissionsState(permissionsState); 12950 permissionsState.reset(); 12951 } else { 12952 // We need to know only about runtime permission changes since the 12953 // calling code always writes the install permissions state but 12954 // the runtime ones are written only if changed. The only cases of 12955 // changed runtime permissions here are promotion of an install to 12956 // runtime and revocation of a runtime from a shared user. 12957 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 12958 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 12959 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 12960 runtimePermissionsRevoked = true; 12961 } 12962 } 12963 } 12964 12965 permissionsState.setGlobalGids(mGlobalGids); 12966 12967 final int N = pkg.requestedPermissions.size(); 12968 for (int i=0; i<N; i++) { 12969 final String name = pkg.requestedPermissions.get(i); 12970 final BasePermission bp = mSettings.mPermissions.get(name); 12971 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 12972 >= Build.VERSION_CODES.M; 12973 12974 if (DEBUG_INSTALL) { 12975 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 12976 } 12977 12978 if (bp == null || bp.packageSetting == null) { 12979 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 12980 if (DEBUG_PERMISSIONS) { 12981 Slog.i(TAG, "Unknown permission " + name 12982 + " in package " + pkg.packageName); 12983 } 12984 } 12985 continue; 12986 } 12987 12988 12989 // Limit ephemeral apps to ephemeral allowed permissions. 12990 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 12991 if (DEBUG_PERMISSIONS) { 12992 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 12993 + pkg.packageName); 12994 } 12995 continue; 12996 } 12997 12998 if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) { 12999 if (DEBUG_PERMISSIONS) { 13000 Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package " 13001 + pkg.packageName); 13002 } 13003 continue; 13004 } 13005 13006 final String perm = bp.name; 13007 boolean allowedSig = false; 13008 int grant = GRANT_DENIED; 13009 13010 // Keep track of app op permissions. 13011 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 13012 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 13013 if (pkgs == null) { 13014 pkgs = new ArraySet<>(); 13015 mAppOpPermissionPackages.put(bp.name, pkgs); 13016 } 13017 pkgs.add(pkg.packageName); 13018 } 13019 13020 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 13021 switch (level) { 13022 case PermissionInfo.PROTECTION_NORMAL: { 13023 // For all apps normal permissions are install time ones. 13024 grant = GRANT_INSTALL; 13025 } break; 13026 13027 case PermissionInfo.PROTECTION_DANGEROUS: { 13028 // If a permission review is required for legacy apps we represent 13029 // their permissions as always granted runtime ones since we need 13030 // to keep the review required permission flag per user while an 13031 // install permission's state is shared across all users. 13032 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 13033 // For legacy apps dangerous permissions are install time ones. 13034 grant = GRANT_INSTALL; 13035 } else if (origPermissions.hasInstallPermission(bp.name)) { 13036 // For legacy apps that became modern, install becomes runtime. 13037 grant = GRANT_UPGRADE; 13038 } else if (mPromoteSystemApps 13039 && isSystemApp(ps) 13040 && mExistingSystemPackages.contains(ps.name)) { 13041 // For legacy system apps, install becomes runtime. 13042 // We cannot check hasInstallPermission() for system apps since those 13043 // permissions were granted implicitly and not persisted pre-M. 13044 grant = GRANT_UPGRADE; 13045 } else { 13046 // For modern apps keep runtime permissions unchanged. 13047 grant = GRANT_RUNTIME; 13048 } 13049 } break; 13050 13051 case PermissionInfo.PROTECTION_SIGNATURE: { 13052 // For all apps signature permissions are install time ones. 13053 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 13054 if (allowedSig) { 13055 grant = GRANT_INSTALL; 13056 } 13057 } break; 13058 } 13059 13060 if (DEBUG_PERMISSIONS) { 13061 Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName); 13062 } 13063 13064 if (grant != GRANT_DENIED) { 13065 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 13066 // If this is an existing, non-system package, then 13067 // we can't add any new permissions to it. 13068 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 13069 // Except... if this is a permission that was added 13070 // to the platform (note: need to only do this when 13071 // updating the platform). 13072 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 13073 grant = GRANT_DENIED; 13074 } 13075 } 13076 } 13077 13078 switch (grant) { 13079 case GRANT_INSTALL: { 13080 // Revoke this as runtime permission to handle the case of 13081 // a runtime permission being downgraded to an install one. 13082 // Also in permission review mode we keep dangerous permissions 13083 // for legacy apps 13084 for (int userId : UserManagerService.getInstance().getUserIds()) { 13085 if (origPermissions.getRuntimePermissionState( 13086 bp.name, userId) != null) { 13087 // Revoke the runtime permission and clear the flags. 13088 origPermissions.revokeRuntimePermission(bp, userId); 13089 origPermissions.updatePermissionFlags(bp, userId, 13090 PackageManager.MASK_PERMISSION_FLAGS, 0); 13091 // If we revoked a permission permission, we have to write. 13092 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 13093 changedRuntimePermissionUserIds, userId); 13094 } 13095 } 13096 // Grant an install permission. 13097 if (permissionsState.grantInstallPermission(bp) != 13098 PermissionsState.PERMISSION_OPERATION_FAILURE) { 13099 changedInstallPermission = true; 13100 } 13101 } break; 13102 13103 case GRANT_RUNTIME: { 13104 // Grant previously granted runtime permissions. 13105 for (int userId : UserManagerService.getInstance().getUserIds()) { 13106 PermissionState permissionState = origPermissions 13107 .getRuntimePermissionState(bp.name, userId); 13108 int flags = permissionState != null 13109 ? permissionState.getFlags() : 0; 13110 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 13111 // Don't propagate the permission in a permission review mode if 13112 // the former was revoked, i.e. marked to not propagate on upgrade. 13113 // Note that in a permission review mode install permissions are 13114 // represented as constantly granted runtime ones since we need to 13115 // keep a per user state associated with the permission. Also the 13116 // revoke on upgrade flag is no longer applicable and is reset. 13117 final boolean revokeOnUpgrade = (flags & PackageManager 13118 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 13119 if (revokeOnUpgrade) { 13120 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13121 // Since we changed the flags, we have to write. 13122 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 13123 changedRuntimePermissionUserIds, userId); 13124 } 13125 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 13126 if (permissionsState.grantRuntimePermission(bp, userId) == 13127 PermissionsState.PERMISSION_OPERATION_FAILURE) { 13128 // If we cannot put the permission as it was, 13129 // we have to write. 13130 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 13131 changedRuntimePermissionUserIds, userId); 13132 } 13133 } 13134 13135 // If the app supports runtime permissions no need for a review. 13136 if (mPermissionReviewRequired 13137 && appSupportsRuntimePermissions 13138 && (flags & PackageManager 13139 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 13140 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 13141 // Since we changed the flags, we have to write. 13142 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 13143 changedRuntimePermissionUserIds, userId); 13144 } 13145 } else if (mPermissionReviewRequired 13146 && !appSupportsRuntimePermissions) { 13147 // For legacy apps that need a permission review, every new 13148 // runtime permission is granted but it is pending a review. 13149 // We also need to review only platform defined runtime 13150 // permissions as these are the only ones the platform knows 13151 // how to disable the API to simulate revocation as legacy 13152 // apps don't expect to run with revoked permissions. 13153 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 13154 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 13155 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 13156 // We changed the flags, hence have to write. 13157 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 13158 changedRuntimePermissionUserIds, userId); 13159 } 13160 } 13161 if (permissionsState.grantRuntimePermission(bp, userId) 13162 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 13163 // We changed the permission, hence have to write. 13164 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 13165 changedRuntimePermissionUserIds, userId); 13166 } 13167 } 13168 // Propagate the permission flags. 13169 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 13170 } 13171 } break; 13172 13173 case GRANT_UPGRADE: { 13174 // Grant runtime permissions for a previously held install permission. 13175 PermissionState permissionState = origPermissions 13176 .getInstallPermissionState(bp.name); 13177 final int flags = permissionState != null ? permissionState.getFlags() : 0; 13178 13179 if (origPermissions.revokeInstallPermission(bp) 13180 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 13181 // We will be transferring the permission flags, so clear them. 13182 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 13183 PackageManager.MASK_PERMISSION_FLAGS, 0); 13184 changedInstallPermission = true; 13185 } 13186 13187 // If the permission is not to be promoted to runtime we ignore it and 13188 // also its other flags as they are not applicable to install permissions. 13189 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 13190 for (int userId : currentUserIds) { 13191 if (permissionsState.grantRuntimePermission(bp, userId) != 13192 PermissionsState.PERMISSION_OPERATION_FAILURE) { 13193 // Transfer the permission flags. 13194 permissionsState.updatePermissionFlags(bp, userId, 13195 flags, flags); 13196 // If we granted the permission, we have to write. 13197 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 13198 changedRuntimePermissionUserIds, userId); 13199 } 13200 } 13201 } 13202 } break; 13203 13204 default: { 13205 if (packageOfInterest == null 13206 || packageOfInterest.equals(pkg.packageName)) { 13207 if (DEBUG_PERMISSIONS) { 13208 Slog.i(TAG, "Not granting permission " + perm 13209 + " to package " + pkg.packageName 13210 + " because it was previously installed without"); 13211 } 13212 } 13213 } break; 13214 } 13215 } else { 13216 if (permissionsState.revokeInstallPermission(bp) != 13217 PermissionsState.PERMISSION_OPERATION_FAILURE) { 13218 // Also drop the permission flags. 13219 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13220 PackageManager.MASK_PERMISSION_FLAGS, 0); 13221 changedInstallPermission = true; 13222 Slog.i(TAG, "Un-granting permission " + perm 13223 + " from package " + pkg.packageName 13224 + " (protectionLevel=" + bp.protectionLevel 13225 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 13226 + ")"); 13227 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 13228 // Don't print warning for app op permissions, since it is fine for them 13229 // not to be granted, there is a UI for the user to decide. 13230 if (DEBUG_PERMISSIONS 13231 && (packageOfInterest == null 13232 || packageOfInterest.equals(pkg.packageName))) { 13233 Slog.i(TAG, "Not granting permission " + perm 13234 + " to package " + pkg.packageName 13235 + " (protectionLevel=" + bp.protectionLevel 13236 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 13237 + ")"); 13238 } 13239 } 13240 } 13241 } 13242 13243 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 13244 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 13245 // This is the first that we have heard about this package, so the 13246 // permissions we have now selected are fixed until explicitly 13247 // changed. 13248 ps.installPermissionsFixed = true; 13249 } 13250 13251 // Persist the runtime permissions state for users with changes. If permissions 13252 // were revoked because no app in the shared user declares them we have to 13253 // write synchronously to avoid losing runtime permissions state. 13254 for (int userId : changedRuntimePermissionUserIds) { 13255 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 13256 } 13257 } 13258 13259 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 13260 boolean allowed = false; 13261 final int NP = PackageParser.NEW_PERMISSIONS.length; 13262 for (int ip=0; ip<NP; ip++) { 13263 final PackageParser.NewPermissionInfo npi 13264 = PackageParser.NEW_PERMISSIONS[ip]; 13265 if (npi.name.equals(perm) 13266 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 13267 allowed = true; 13268 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 13269 + pkg.packageName); 13270 break; 13271 } 13272 } 13273 return allowed; 13274 } 13275 13276 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 13277 BasePermission bp, PermissionsState origPermissions) { 13278 boolean privilegedPermission = (bp.protectionLevel 13279 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 13280 boolean privappPermissionsDisable = 13281 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 13282 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 13283 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 13284 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 13285 && !platformPackage && platformPermission) { 13286 final ArraySet<String> allowedPermissions = SystemConfig.getInstance() 13287 .getPrivAppPermissions(pkg.packageName); 13288 final boolean whitelisted = 13289 allowedPermissions != null && allowedPermissions.contains(perm); 13290 if (!whitelisted) { 13291 Slog.w(TAG, "Privileged permission " + perm + " for package " 13292 + pkg.packageName + " - not in privapp-permissions whitelist"); 13293 // Only report violations for apps on system image 13294 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 13295 // it's only a reportable violation if the permission isn't explicitly denied 13296 final ArraySet<String> deniedPermissions = SystemConfig.getInstance() 13297 .getPrivAppDenyPermissions(pkg.packageName); 13298 final boolean permissionViolation = 13299 deniedPermissions == null || !deniedPermissions.contains(perm); 13300 if (permissionViolation) { 13301 if (mPrivappPermissionsViolations == null) { 13302 mPrivappPermissionsViolations = new ArraySet<>(); 13303 } 13304 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 13305 } else { 13306 return false; 13307 } 13308 } 13309 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 13310 return false; 13311 } 13312 } 13313 } 13314 boolean allowed = (compareSignatures( 13315 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 13316 == PackageManager.SIGNATURE_MATCH) 13317 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 13318 == PackageManager.SIGNATURE_MATCH); 13319 if (!allowed && privilegedPermission) { 13320 if (isSystemApp(pkg)) { 13321 // For updated system applications, a system permission 13322 // is granted only if it had been defined by the original application. 13323 if (pkg.isUpdatedSystemApp()) { 13324 final PackageSetting sysPs = mSettings 13325 .getDisabledSystemPkgLPr(pkg.packageName); 13326 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 13327 // If the original was granted this permission, we take 13328 // that grant decision as read and propagate it to the 13329 // update. 13330 if (sysPs.isPrivileged()) { 13331 allowed = true; 13332 } 13333 } else { 13334 // The system apk may have been updated with an older 13335 // version of the one on the data partition, but which 13336 // granted a new system permission that it didn't have 13337 // before. In this case we do want to allow the app to 13338 // now get the new permission if the ancestral apk is 13339 // privileged to get it. 13340 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 13341 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 13342 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 13343 allowed = true; 13344 break; 13345 } 13346 } 13347 } 13348 // Also if a privileged parent package on the system image or any of 13349 // its children requested a privileged permission, the updated child 13350 // packages can also get the permission. 13351 if (pkg.parentPackage != null) { 13352 final PackageSetting disabledSysParentPs = mSettings 13353 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 13354 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 13355 && disabledSysParentPs.isPrivileged()) { 13356 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 13357 allowed = true; 13358 } else if (disabledSysParentPs.pkg.childPackages != null) { 13359 final int count = disabledSysParentPs.pkg.childPackages.size(); 13360 for (int i = 0; i < count; i++) { 13361 PackageParser.Package disabledSysChildPkg = 13362 disabledSysParentPs.pkg.childPackages.get(i); 13363 if (isPackageRequestingPermission(disabledSysChildPkg, 13364 perm)) { 13365 allowed = true; 13366 break; 13367 } 13368 } 13369 } 13370 } 13371 } 13372 } 13373 } else { 13374 allowed = isPrivilegedApp(pkg); 13375 } 13376 } 13377 } 13378 if (!allowed) { 13379 if (!allowed && (bp.protectionLevel 13380 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 13381 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 13382 // If this was a previously normal/dangerous permission that got moved 13383 // to a system permission as part of the runtime permission redesign, then 13384 // we still want to blindly grant it to old apps. 13385 allowed = true; 13386 } 13387 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 13388 && pkg.packageName.equals(mRequiredInstallerPackage)) { 13389 // If this permission is to be granted to the system installer and 13390 // this app is an installer, then it gets the permission. 13391 allowed = true; 13392 } 13393 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 13394 && pkg.packageName.equals(mRequiredVerifierPackage)) { 13395 // If this permission is to be granted to the system verifier and 13396 // this app is a verifier, then it gets the permission. 13397 allowed = true; 13398 } 13399 if (!allowed && (bp.protectionLevel 13400 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 13401 && isSystemApp(pkg)) { 13402 // Any pre-installed system app is allowed to get this permission. 13403 allowed = true; 13404 } 13405 if (!allowed && (bp.protectionLevel 13406 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 13407 // For development permissions, a development permission 13408 // is granted only if it was already granted. 13409 allowed = origPermissions.hasInstallPermission(perm); 13410 } 13411 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 13412 && pkg.packageName.equals(mSetupWizardPackage)) { 13413 // If this permission is to be granted to the system setup wizard and 13414 // this app is a setup wizard, then it gets the permission. 13415 allowed = true; 13416 } 13417 } 13418 return allowed; 13419 } 13420 13421 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 13422 final int permCount = pkg.requestedPermissions.size(); 13423 for (int j = 0; j < permCount; j++) { 13424 String requestedPermission = pkg.requestedPermissions.get(j); 13425 if (permission.equals(requestedPermission)) { 13426 return true; 13427 } 13428 } 13429 return false; 13430 } 13431 13432 final class ActivityIntentResolver 13433 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 13434 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 13435 boolean defaultOnly, int userId) { 13436 if (!sUserManager.exists(userId)) return null; 13437 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 13438 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 13439 } 13440 13441 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 13442 int userId) { 13443 if (!sUserManager.exists(userId)) return null; 13444 mFlags = flags; 13445 return super.queryIntent(intent, resolvedType, 13446 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 13447 userId); 13448 } 13449 13450 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 13451 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 13452 if (!sUserManager.exists(userId)) return null; 13453 if (packageActivities == null) { 13454 return null; 13455 } 13456 mFlags = flags; 13457 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 13458 final int N = packageActivities.size(); 13459 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 13460 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 13461 13462 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 13463 for (int i = 0; i < N; ++i) { 13464 intentFilters = packageActivities.get(i).intents; 13465 if (intentFilters != null && intentFilters.size() > 0) { 13466 PackageParser.ActivityIntentInfo[] array = 13467 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 13468 intentFilters.toArray(array); 13469 listCut.add(array); 13470 } 13471 } 13472 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 13473 } 13474 13475 /** 13476 * Finds a privileged activity that matches the specified activity names. 13477 */ 13478 private PackageParser.Activity findMatchingActivity( 13479 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 13480 for (PackageParser.Activity sysActivity : activityList) { 13481 if (sysActivity.info.name.equals(activityInfo.name)) { 13482 return sysActivity; 13483 } 13484 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 13485 return sysActivity; 13486 } 13487 if (sysActivity.info.targetActivity != null) { 13488 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 13489 return sysActivity; 13490 } 13491 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 13492 return sysActivity; 13493 } 13494 } 13495 } 13496 return null; 13497 } 13498 13499 public class IterGenerator<E> { 13500 public Iterator<E> generate(ActivityIntentInfo info) { 13501 return null; 13502 } 13503 } 13504 13505 public class ActionIterGenerator extends IterGenerator<String> { 13506 @Override 13507 public Iterator<String> generate(ActivityIntentInfo info) { 13508 return info.actionsIterator(); 13509 } 13510 } 13511 13512 public class CategoriesIterGenerator extends IterGenerator<String> { 13513 @Override 13514 public Iterator<String> generate(ActivityIntentInfo info) { 13515 return info.categoriesIterator(); 13516 } 13517 } 13518 13519 public class SchemesIterGenerator extends IterGenerator<String> { 13520 @Override 13521 public Iterator<String> generate(ActivityIntentInfo info) { 13522 return info.schemesIterator(); 13523 } 13524 } 13525 13526 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 13527 @Override 13528 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 13529 return info.authoritiesIterator(); 13530 } 13531 } 13532 13533 /** 13534 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 13535 * MODIFIED. Do not pass in a list that should not be changed. 13536 */ 13537 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 13538 IterGenerator<T> generator, Iterator<T> searchIterator) { 13539 // loop through the set of actions; every one must be found in the intent filter 13540 while (searchIterator.hasNext()) { 13541 // we must have at least one filter in the list to consider a match 13542 if (intentList.size() == 0) { 13543 break; 13544 } 13545 13546 final T searchAction = searchIterator.next(); 13547 13548 // loop through the set of intent filters 13549 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 13550 while (intentIter.hasNext()) { 13551 final ActivityIntentInfo intentInfo = intentIter.next(); 13552 boolean selectionFound = false; 13553 13554 // loop through the intent filter's selection criteria; at least one 13555 // of them must match the searched criteria 13556 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 13557 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 13558 final T intentSelection = intentSelectionIter.next(); 13559 if (intentSelection != null && intentSelection.equals(searchAction)) { 13560 selectionFound = true; 13561 break; 13562 } 13563 } 13564 13565 // the selection criteria wasn't found in this filter's set; this filter 13566 // is not a potential match 13567 if (!selectionFound) { 13568 intentIter.remove(); 13569 } 13570 } 13571 } 13572 } 13573 13574 private boolean isProtectedAction(ActivityIntentInfo filter) { 13575 final Iterator<String> actionsIter = filter.actionsIterator(); 13576 while (actionsIter != null && actionsIter.hasNext()) { 13577 final String filterAction = actionsIter.next(); 13578 if (PROTECTED_ACTIONS.contains(filterAction)) { 13579 return true; 13580 } 13581 } 13582 return false; 13583 } 13584 13585 /** 13586 * Adjusts the priority of the given intent filter according to policy. 13587 * <p> 13588 * <ul> 13589 * <li>The priority for non privileged applications is capped to '0'</li> 13590 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 13591 * <li>The priority for unbundled updates to privileged applications is capped to the 13592 * priority defined on the system partition</li> 13593 * </ul> 13594 * <p> 13595 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 13596 * allowed to obtain any priority on any action. 13597 */ 13598 private void adjustPriority( 13599 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 13600 // nothing to do; priority is fine as-is 13601 if (intent.getPriority() <= 0) { 13602 return; 13603 } 13604 13605 final ActivityInfo activityInfo = intent.activity.info; 13606 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 13607 13608 final boolean privilegedApp = 13609 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 13610 if (!privilegedApp) { 13611 // non-privileged applications can never define a priority >0 13612 if (DEBUG_FILTERS) { 13613 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 13614 + " package: " + applicationInfo.packageName 13615 + " activity: " + intent.activity.className 13616 + " origPrio: " + intent.getPriority()); 13617 } 13618 intent.setPriority(0); 13619 return; 13620 } 13621 13622 if (systemActivities == null) { 13623 // the system package is not disabled; we're parsing the system partition 13624 if (isProtectedAction(intent)) { 13625 if (mDeferProtectedFilters) { 13626 // We can't deal with these just yet. No component should ever obtain a 13627 // >0 priority for a protected actions, with ONE exception -- the setup 13628 // wizard. The setup wizard, however, cannot be known until we're able to 13629 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 13630 // until all intent filters have been processed. Chicken, meet egg. 13631 // Let the filter temporarily have a high priority and rectify the 13632 // priorities after all system packages have been scanned. 13633 mProtectedFilters.add(intent); 13634 if (DEBUG_FILTERS) { 13635 Slog.i(TAG, "Protected action; save for later;" 13636 + " package: " + applicationInfo.packageName 13637 + " activity: " + intent.activity.className 13638 + " origPrio: " + intent.getPriority()); 13639 } 13640 return; 13641 } else { 13642 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 13643 Slog.i(TAG, "No setup wizard;" 13644 + " All protected intents capped to priority 0"); 13645 } 13646 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 13647 if (DEBUG_FILTERS) { 13648 Slog.i(TAG, "Found setup wizard;" 13649 + " allow priority " + intent.getPriority() + ";" 13650 + " package: " + intent.activity.info.packageName 13651 + " activity: " + intent.activity.className 13652 + " priority: " + intent.getPriority()); 13653 } 13654 // setup wizard gets whatever it wants 13655 return; 13656 } 13657 if (DEBUG_FILTERS) { 13658 Slog.i(TAG, "Protected action; cap priority to 0;" 13659 + " package: " + intent.activity.info.packageName 13660 + " activity: " + intent.activity.className 13661 + " origPrio: " + intent.getPriority()); 13662 } 13663 intent.setPriority(0); 13664 return; 13665 } 13666 } 13667 // privileged apps on the system image get whatever priority they request 13668 return; 13669 } 13670 13671 // privileged app unbundled update ... try to find the same activity 13672 final PackageParser.Activity foundActivity = 13673 findMatchingActivity(systemActivities, activityInfo); 13674 if (foundActivity == null) { 13675 // this is a new activity; it cannot obtain >0 priority 13676 if (DEBUG_FILTERS) { 13677 Slog.i(TAG, "New activity; cap priority to 0;" 13678 + " package: " + applicationInfo.packageName 13679 + " activity: " + intent.activity.className 13680 + " origPrio: " + intent.getPriority()); 13681 } 13682 intent.setPriority(0); 13683 return; 13684 } 13685 13686 // found activity, now check for filter equivalence 13687 13688 // a shallow copy is enough; we modify the list, not its contents 13689 final List<ActivityIntentInfo> intentListCopy = 13690 new ArrayList<>(foundActivity.intents); 13691 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 13692 13693 // find matching action subsets 13694 final Iterator<String> actionsIterator = intent.actionsIterator(); 13695 if (actionsIterator != null) { 13696 getIntentListSubset( 13697 intentListCopy, new ActionIterGenerator(), actionsIterator); 13698 if (intentListCopy.size() == 0) { 13699 // no more intents to match; we're not equivalent 13700 if (DEBUG_FILTERS) { 13701 Slog.i(TAG, "Mismatched action; cap priority to 0;" 13702 + " package: " + applicationInfo.packageName 13703 + " activity: " + intent.activity.className 13704 + " origPrio: " + intent.getPriority()); 13705 } 13706 intent.setPriority(0); 13707 return; 13708 } 13709 } 13710 13711 // find matching category subsets 13712 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 13713 if (categoriesIterator != null) { 13714 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 13715 categoriesIterator); 13716 if (intentListCopy.size() == 0) { 13717 // no more intents to match; we're not equivalent 13718 if (DEBUG_FILTERS) { 13719 Slog.i(TAG, "Mismatched category; cap priority to 0;" 13720 + " package: " + applicationInfo.packageName 13721 + " activity: " + intent.activity.className 13722 + " origPrio: " + intent.getPriority()); 13723 } 13724 intent.setPriority(0); 13725 return; 13726 } 13727 } 13728 13729 // find matching schemes subsets 13730 final Iterator<String> schemesIterator = intent.schemesIterator(); 13731 if (schemesIterator != null) { 13732 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 13733 schemesIterator); 13734 if (intentListCopy.size() == 0) { 13735 // no more intents to match; we're not equivalent 13736 if (DEBUG_FILTERS) { 13737 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 13738 + " package: " + applicationInfo.packageName 13739 + " activity: " + intent.activity.className 13740 + " origPrio: " + intent.getPriority()); 13741 } 13742 intent.setPriority(0); 13743 return; 13744 } 13745 } 13746 13747 // find matching authorities subsets 13748 final Iterator<IntentFilter.AuthorityEntry> 13749 authoritiesIterator = intent.authoritiesIterator(); 13750 if (authoritiesIterator != null) { 13751 getIntentListSubset(intentListCopy, 13752 new AuthoritiesIterGenerator(), 13753 authoritiesIterator); 13754 if (intentListCopy.size() == 0) { 13755 // no more intents to match; we're not equivalent 13756 if (DEBUG_FILTERS) { 13757 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 13758 + " package: " + applicationInfo.packageName 13759 + " activity: " + intent.activity.className 13760 + " origPrio: " + intent.getPriority()); 13761 } 13762 intent.setPriority(0); 13763 return; 13764 } 13765 } 13766 13767 // we found matching filter(s); app gets the max priority of all intents 13768 int cappedPriority = 0; 13769 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 13770 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 13771 } 13772 if (intent.getPriority() > cappedPriority) { 13773 if (DEBUG_FILTERS) { 13774 Slog.i(TAG, "Found matching filter(s);" 13775 + " cap priority to " + cappedPriority + ";" 13776 + " package: " + applicationInfo.packageName 13777 + " activity: " + intent.activity.className 13778 + " origPrio: " + intent.getPriority()); 13779 } 13780 intent.setPriority(cappedPriority); 13781 return; 13782 } 13783 // all this for nothing; the requested priority was <= what was on the system 13784 } 13785 13786 public final void addActivity(PackageParser.Activity a, String type) { 13787 mActivities.put(a.getComponentName(), a); 13788 if (DEBUG_SHOW_INFO) 13789 Log.v( 13790 TAG, " " + type + " " + 13791 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 13792 if (DEBUG_SHOW_INFO) 13793 Log.v(TAG, " Class=" + a.info.name); 13794 final int NI = a.intents.size(); 13795 for (int j=0; j<NI; j++) { 13796 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 13797 if ("activity".equals(type)) { 13798 final PackageSetting ps = 13799 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 13800 final List<PackageParser.Activity> systemActivities = 13801 ps != null && ps.pkg != null ? ps.pkg.activities : null; 13802 adjustPriority(systemActivities, intent); 13803 } 13804 if (DEBUG_SHOW_INFO) { 13805 Log.v(TAG, " IntentFilter:"); 13806 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13807 } 13808 if (!intent.debugCheck()) { 13809 Log.w(TAG, "==> For Activity " + a.info.name); 13810 } 13811 addFilter(intent); 13812 } 13813 } 13814 13815 public final void removeActivity(PackageParser.Activity a, String type) { 13816 mActivities.remove(a.getComponentName()); 13817 if (DEBUG_SHOW_INFO) { 13818 Log.v(TAG, " " + type + " " 13819 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 13820 : a.info.name) + ":"); 13821 Log.v(TAG, " Class=" + a.info.name); 13822 } 13823 final int NI = a.intents.size(); 13824 for (int j=0; j<NI; j++) { 13825 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 13826 if (DEBUG_SHOW_INFO) { 13827 Log.v(TAG, " IntentFilter:"); 13828 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13829 } 13830 removeFilter(intent); 13831 } 13832 } 13833 13834 @Override 13835 protected boolean allowFilterResult( 13836 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 13837 ActivityInfo filterAi = filter.activity.info; 13838 for (int i=dest.size()-1; i>=0; i--) { 13839 ActivityInfo destAi = dest.get(i).activityInfo; 13840 if (destAi.name == filterAi.name 13841 && destAi.packageName == filterAi.packageName) { 13842 return false; 13843 } 13844 } 13845 return true; 13846 } 13847 13848 @Override 13849 protected ActivityIntentInfo[] newArray(int size) { 13850 return new ActivityIntentInfo[size]; 13851 } 13852 13853 @Override 13854 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 13855 if (!sUserManager.exists(userId)) return true; 13856 PackageParser.Package p = filter.activity.owner; 13857 if (p != null) { 13858 PackageSetting ps = (PackageSetting)p.mExtras; 13859 if (ps != null) { 13860 // System apps are never considered stopped for purposes of 13861 // filtering, because there may be no way for the user to 13862 // actually re-launch them. 13863 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 13864 && ps.getStopped(userId); 13865 } 13866 } 13867 return false; 13868 } 13869 13870 @Override 13871 protected boolean isPackageForFilter(String packageName, 13872 PackageParser.ActivityIntentInfo info) { 13873 return packageName.equals(info.activity.owner.packageName); 13874 } 13875 13876 @Override 13877 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 13878 int match, int userId) { 13879 if (!sUserManager.exists(userId)) return null; 13880 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 13881 return null; 13882 } 13883 final PackageParser.Activity activity = info.activity; 13884 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 13885 if (ps == null) { 13886 return null; 13887 } 13888 final PackageUserState userState = ps.readUserState(userId); 13889 ActivityInfo ai = 13890 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 13891 if (ai == null) { 13892 return null; 13893 } 13894 final boolean matchExplicitlyVisibleOnly = 13895 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 13896 final boolean matchVisibleToInstantApp = 13897 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13898 final boolean componentVisible = 13899 matchVisibleToInstantApp 13900 && info.isVisibleToInstantApp() 13901 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 13902 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13903 // throw out filters that aren't visible to ephemeral apps 13904 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 13905 return null; 13906 } 13907 // throw out instant app filters if we're not explicitly requesting them 13908 if (!matchInstantApp && userState.instantApp) { 13909 return null; 13910 } 13911 // throw out instant app filters if updates are available; will trigger 13912 // instant app resolution 13913 if (userState.instantApp && ps.isUpdateAvailable()) { 13914 return null; 13915 } 13916 final ResolveInfo res = new ResolveInfo(); 13917 res.activityInfo = ai; 13918 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 13919 res.filter = info; 13920 } 13921 if (info != null) { 13922 res.handleAllWebDataURI = info.handleAllWebDataURI(); 13923 } 13924 res.priority = info.getPriority(); 13925 res.preferredOrder = activity.owner.mPreferredOrder; 13926 //System.out.println("Result: " + res.activityInfo.className + 13927 // " = " + res.priority); 13928 res.match = match; 13929 res.isDefault = info.hasDefault; 13930 res.labelRes = info.labelRes; 13931 res.nonLocalizedLabel = info.nonLocalizedLabel; 13932 if (userNeedsBadging(userId)) { 13933 res.noResourceId = true; 13934 } else { 13935 res.icon = info.icon; 13936 } 13937 res.iconResourceId = info.icon; 13938 res.system = res.activityInfo.applicationInfo.isSystemApp(); 13939 res.isInstantAppAvailable = userState.instantApp; 13940 return res; 13941 } 13942 13943 @Override 13944 protected void sortResults(List<ResolveInfo> results) { 13945 Collections.sort(results, mResolvePrioritySorter); 13946 } 13947 13948 @Override 13949 protected void dumpFilter(PrintWriter out, String prefix, 13950 PackageParser.ActivityIntentInfo filter) { 13951 out.print(prefix); out.print( 13952 Integer.toHexString(System.identityHashCode(filter.activity))); 13953 out.print(' '); 13954 filter.activity.printComponentShortName(out); 13955 out.print(" filter "); 13956 out.println(Integer.toHexString(System.identityHashCode(filter))); 13957 } 13958 13959 @Override 13960 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 13961 return filter.activity; 13962 } 13963 13964 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13965 PackageParser.Activity activity = (PackageParser.Activity)label; 13966 out.print(prefix); out.print( 13967 Integer.toHexString(System.identityHashCode(activity))); 13968 out.print(' '); 13969 activity.printComponentShortName(out); 13970 if (count > 1) { 13971 out.print(" ("); out.print(count); out.print(" filters)"); 13972 } 13973 out.println(); 13974 } 13975 13976 // Keys are String (activity class name), values are Activity. 13977 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 13978 = new ArrayMap<ComponentName, PackageParser.Activity>(); 13979 private int mFlags; 13980 } 13981 13982 private final class ServiceIntentResolver 13983 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 13984 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 13985 boolean defaultOnly, int userId) { 13986 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 13987 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 13988 } 13989 13990 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 13991 int userId) { 13992 if (!sUserManager.exists(userId)) return null; 13993 mFlags = flags; 13994 return super.queryIntent(intent, resolvedType, 13995 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 13996 userId); 13997 } 13998 13999 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 14000 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 14001 if (!sUserManager.exists(userId)) return null; 14002 if (packageServices == null) { 14003 return null; 14004 } 14005 mFlags = flags; 14006 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 14007 final int N = packageServices.size(); 14008 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 14009 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 14010 14011 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 14012 for (int i = 0; i < N; ++i) { 14013 intentFilters = packageServices.get(i).intents; 14014 if (intentFilters != null && intentFilters.size() > 0) { 14015 PackageParser.ServiceIntentInfo[] array = 14016 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 14017 intentFilters.toArray(array); 14018 listCut.add(array); 14019 } 14020 } 14021 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 14022 } 14023 14024 public final void addService(PackageParser.Service s) { 14025 mServices.put(s.getComponentName(), s); 14026 if (DEBUG_SHOW_INFO) { 14027 Log.v(TAG, " " 14028 + (s.info.nonLocalizedLabel != null 14029 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 14030 Log.v(TAG, " Class=" + s.info.name); 14031 } 14032 final int NI = s.intents.size(); 14033 int j; 14034 for (j=0; j<NI; j++) { 14035 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 14036 if (DEBUG_SHOW_INFO) { 14037 Log.v(TAG, " IntentFilter:"); 14038 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 14039 } 14040 if (!intent.debugCheck()) { 14041 Log.w(TAG, "==> For Service " + s.info.name); 14042 } 14043 addFilter(intent); 14044 } 14045 } 14046 14047 public final void removeService(PackageParser.Service s) { 14048 mServices.remove(s.getComponentName()); 14049 if (DEBUG_SHOW_INFO) { 14050 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 14051 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 14052 Log.v(TAG, " Class=" + s.info.name); 14053 } 14054 final int NI = s.intents.size(); 14055 int j; 14056 for (j=0; j<NI; j++) { 14057 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 14058 if (DEBUG_SHOW_INFO) { 14059 Log.v(TAG, " IntentFilter:"); 14060 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 14061 } 14062 removeFilter(intent); 14063 } 14064 } 14065 14066 @Override 14067 protected boolean allowFilterResult( 14068 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 14069 ServiceInfo filterSi = filter.service.info; 14070 for (int i=dest.size()-1; i>=0; i--) { 14071 ServiceInfo destAi = dest.get(i).serviceInfo; 14072 if (destAi.name == filterSi.name 14073 && destAi.packageName == filterSi.packageName) { 14074 return false; 14075 } 14076 } 14077 return true; 14078 } 14079 14080 @Override 14081 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 14082 return new PackageParser.ServiceIntentInfo[size]; 14083 } 14084 14085 @Override 14086 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 14087 if (!sUserManager.exists(userId)) return true; 14088 PackageParser.Package p = filter.service.owner; 14089 if (p != null) { 14090 PackageSetting ps = (PackageSetting)p.mExtras; 14091 if (ps != null) { 14092 // System apps are never considered stopped for purposes of 14093 // filtering, because there may be no way for the user to 14094 // actually re-launch them. 14095 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 14096 && ps.getStopped(userId); 14097 } 14098 } 14099 return false; 14100 } 14101 14102 @Override 14103 protected boolean isPackageForFilter(String packageName, 14104 PackageParser.ServiceIntentInfo info) { 14105 return packageName.equals(info.service.owner.packageName); 14106 } 14107 14108 @Override 14109 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 14110 int match, int userId) { 14111 if (!sUserManager.exists(userId)) return null; 14112 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 14113 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 14114 return null; 14115 } 14116 final PackageParser.Service service = info.service; 14117 PackageSetting ps = (PackageSetting) service.owner.mExtras; 14118 if (ps == null) { 14119 return null; 14120 } 14121 final PackageUserState userState = ps.readUserState(userId); 14122 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 14123 userState, userId); 14124 if (si == null) { 14125 return null; 14126 } 14127 final boolean matchVisibleToInstantApp = 14128 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 14129 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 14130 // throw out filters that aren't visible to ephemeral apps 14131 if (matchVisibleToInstantApp 14132 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 14133 return null; 14134 } 14135 // throw out ephemeral filters if we're not explicitly requesting them 14136 if (!isInstantApp && userState.instantApp) { 14137 return null; 14138 } 14139 // throw out instant app filters if updates are available; will trigger 14140 // instant app resolution 14141 if (userState.instantApp && ps.isUpdateAvailable()) { 14142 return null; 14143 } 14144 final ResolveInfo res = new ResolveInfo(); 14145 res.serviceInfo = si; 14146 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 14147 res.filter = filter; 14148 } 14149 res.priority = info.getPriority(); 14150 res.preferredOrder = service.owner.mPreferredOrder; 14151 res.match = match; 14152 res.isDefault = info.hasDefault; 14153 res.labelRes = info.labelRes; 14154 res.nonLocalizedLabel = info.nonLocalizedLabel; 14155 res.icon = info.icon; 14156 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 14157 return res; 14158 } 14159 14160 @Override 14161 protected void sortResults(List<ResolveInfo> results) { 14162 Collections.sort(results, mResolvePrioritySorter); 14163 } 14164 14165 @Override 14166 protected void dumpFilter(PrintWriter out, String prefix, 14167 PackageParser.ServiceIntentInfo filter) { 14168 out.print(prefix); out.print( 14169 Integer.toHexString(System.identityHashCode(filter.service))); 14170 out.print(' '); 14171 filter.service.printComponentShortName(out); 14172 out.print(" filter "); 14173 out.println(Integer.toHexString(System.identityHashCode(filter))); 14174 } 14175 14176 @Override 14177 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 14178 return filter.service; 14179 } 14180 14181 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 14182 PackageParser.Service service = (PackageParser.Service)label; 14183 out.print(prefix); out.print( 14184 Integer.toHexString(System.identityHashCode(service))); 14185 out.print(' '); 14186 service.printComponentShortName(out); 14187 if (count > 1) { 14188 out.print(" ("); out.print(count); out.print(" filters)"); 14189 } 14190 out.println(); 14191 } 14192 14193 // List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 14194 // final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 14195 // final List<ResolveInfo> retList = Lists.newArrayList(); 14196 // while (i.hasNext()) { 14197 // final ResolveInfo resolveInfo = (ResolveInfo) i; 14198 // if (isEnabledLP(resolveInfo.serviceInfo)) { 14199 // retList.add(resolveInfo); 14200 // } 14201 // } 14202 // return retList; 14203 // } 14204 14205 // Keys are String (activity class name), values are Activity. 14206 private final ArrayMap<ComponentName, PackageParser.Service> mServices 14207 = new ArrayMap<ComponentName, PackageParser.Service>(); 14208 private int mFlags; 14209 } 14210 14211 private final class ProviderIntentResolver 14212 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 14213 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 14214 boolean defaultOnly, int userId) { 14215 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 14216 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 14217 } 14218 14219 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 14220 int userId) { 14221 if (!sUserManager.exists(userId)) 14222 return null; 14223 mFlags = flags; 14224 return super.queryIntent(intent, resolvedType, 14225 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 14226 userId); 14227 } 14228 14229 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 14230 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 14231 if (!sUserManager.exists(userId)) 14232 return null; 14233 if (packageProviders == null) { 14234 return null; 14235 } 14236 mFlags = flags; 14237 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 14238 final int N = packageProviders.size(); 14239 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 14240 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 14241 14242 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 14243 for (int i = 0; i < N; ++i) { 14244 intentFilters = packageProviders.get(i).intents; 14245 if (intentFilters != null && intentFilters.size() > 0) { 14246 PackageParser.ProviderIntentInfo[] array = 14247 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 14248 intentFilters.toArray(array); 14249 listCut.add(array); 14250 } 14251 } 14252 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 14253 } 14254 14255 public final void addProvider(PackageParser.Provider p) { 14256 if (mProviders.containsKey(p.getComponentName())) { 14257 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 14258 return; 14259 } 14260 14261 mProviders.put(p.getComponentName(), p); 14262 if (DEBUG_SHOW_INFO) { 14263 Log.v(TAG, " " 14264 + (p.info.nonLocalizedLabel != null 14265 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 14266 Log.v(TAG, " Class=" + p.info.name); 14267 } 14268 final int NI = p.intents.size(); 14269 int j; 14270 for (j = 0; j < NI; j++) { 14271 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 14272 if (DEBUG_SHOW_INFO) { 14273 Log.v(TAG, " IntentFilter:"); 14274 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 14275 } 14276 if (!intent.debugCheck()) { 14277 Log.w(TAG, "==> For Provider " + p.info.name); 14278 } 14279 addFilter(intent); 14280 } 14281 } 14282 14283 public final void removeProvider(PackageParser.Provider p) { 14284 mProviders.remove(p.getComponentName()); 14285 if (DEBUG_SHOW_INFO) { 14286 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 14287 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 14288 Log.v(TAG, " Class=" + p.info.name); 14289 } 14290 final int NI = p.intents.size(); 14291 int j; 14292 for (j = 0; j < NI; j++) { 14293 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 14294 if (DEBUG_SHOW_INFO) { 14295 Log.v(TAG, " IntentFilter:"); 14296 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 14297 } 14298 removeFilter(intent); 14299 } 14300 } 14301 14302 @Override 14303 protected boolean allowFilterResult( 14304 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 14305 ProviderInfo filterPi = filter.provider.info; 14306 for (int i = dest.size() - 1; i >= 0; i--) { 14307 ProviderInfo destPi = dest.get(i).providerInfo; 14308 if (destPi.name == filterPi.name 14309 && destPi.packageName == filterPi.packageName) { 14310 return false; 14311 } 14312 } 14313 return true; 14314 } 14315 14316 @Override 14317 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 14318 return new PackageParser.ProviderIntentInfo[size]; 14319 } 14320 14321 @Override 14322 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 14323 if (!sUserManager.exists(userId)) 14324 return true; 14325 PackageParser.Package p = filter.provider.owner; 14326 if (p != null) { 14327 PackageSetting ps = (PackageSetting) p.mExtras; 14328 if (ps != null) { 14329 // System apps are never considered stopped for purposes of 14330 // filtering, because there may be no way for the user to 14331 // actually re-launch them. 14332 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 14333 && ps.getStopped(userId); 14334 } 14335 } 14336 return false; 14337 } 14338 14339 @Override 14340 protected boolean isPackageForFilter(String packageName, 14341 PackageParser.ProviderIntentInfo info) { 14342 return packageName.equals(info.provider.owner.packageName); 14343 } 14344 14345 @Override 14346 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 14347 int match, int userId) { 14348 if (!sUserManager.exists(userId)) 14349 return null; 14350 final PackageParser.ProviderIntentInfo info = filter; 14351 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 14352 return null; 14353 } 14354 final PackageParser.Provider provider = info.provider; 14355 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 14356 if (ps == null) { 14357 return null; 14358 } 14359 final PackageUserState userState = ps.readUserState(userId); 14360 final boolean matchVisibleToInstantApp = 14361 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 14362 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 14363 // throw out filters that aren't visible to instant applications 14364 if (matchVisibleToInstantApp 14365 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 14366 return null; 14367 } 14368 // throw out instant application filters if we're not explicitly requesting them 14369 if (!isInstantApp && userState.instantApp) { 14370 return null; 14371 } 14372 // throw out instant application filters if updates are available; will trigger 14373 // instant application resolution 14374 if (userState.instantApp && ps.isUpdateAvailable()) { 14375 return null; 14376 } 14377 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 14378 userState, userId); 14379 if (pi == null) { 14380 return null; 14381 } 14382 final ResolveInfo res = new ResolveInfo(); 14383 res.providerInfo = pi; 14384 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 14385 res.filter = filter; 14386 } 14387 res.priority = info.getPriority(); 14388 res.preferredOrder = provider.owner.mPreferredOrder; 14389 res.match = match; 14390 res.isDefault = info.hasDefault; 14391 res.labelRes = info.labelRes; 14392 res.nonLocalizedLabel = info.nonLocalizedLabel; 14393 res.icon = info.icon; 14394 res.system = res.providerInfo.applicationInfo.isSystemApp(); 14395 return res; 14396 } 14397 14398 @Override 14399 protected void sortResults(List<ResolveInfo> results) { 14400 Collections.sort(results, mResolvePrioritySorter); 14401 } 14402 14403 @Override 14404 protected void dumpFilter(PrintWriter out, String prefix, 14405 PackageParser.ProviderIntentInfo filter) { 14406 out.print(prefix); 14407 out.print( 14408 Integer.toHexString(System.identityHashCode(filter.provider))); 14409 out.print(' '); 14410 filter.provider.printComponentShortName(out); 14411 out.print(" filter "); 14412 out.println(Integer.toHexString(System.identityHashCode(filter))); 14413 } 14414 14415 @Override 14416 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 14417 return filter.provider; 14418 } 14419 14420 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 14421 PackageParser.Provider provider = (PackageParser.Provider)label; 14422 out.print(prefix); out.print( 14423 Integer.toHexString(System.identityHashCode(provider))); 14424 out.print(' '); 14425 provider.printComponentShortName(out); 14426 if (count > 1) { 14427 out.print(" ("); out.print(count); out.print(" filters)"); 14428 } 14429 out.println(); 14430 } 14431 14432 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 14433 = new ArrayMap<ComponentName, PackageParser.Provider>(); 14434 private int mFlags; 14435 } 14436 14437 static final class EphemeralIntentResolver 14438 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 14439 /** 14440 * The result that has the highest defined order. Ordering applies on a 14441 * per-package basis. Mapping is from package name to Pair of order and 14442 * EphemeralResolveInfo. 14443 * <p> 14444 * NOTE: This is implemented as a field variable for convenience and efficiency. 14445 * By having a field variable, we're able to track filter ordering as soon as 14446 * a non-zero order is defined. Otherwise, multiple loops across the result set 14447 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 14448 * this needs to be contained entirely within {@link #filterResults}. 14449 */ 14450 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 14451 14452 @Override 14453 protected AuxiliaryResolveInfo[] newArray(int size) { 14454 return new AuxiliaryResolveInfo[size]; 14455 } 14456 14457 @Override 14458 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 14459 return true; 14460 } 14461 14462 @Override 14463 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 14464 int userId) { 14465 if (!sUserManager.exists(userId)) { 14466 return null; 14467 } 14468 final String packageName = responseObj.resolveInfo.getPackageName(); 14469 final Integer order = responseObj.getOrder(); 14470 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 14471 mOrderResult.get(packageName); 14472 // ordering is enabled and this item's order isn't high enough 14473 if (lastOrderResult != null && lastOrderResult.first >= order) { 14474 return null; 14475 } 14476 final InstantAppResolveInfo res = responseObj.resolveInfo; 14477 if (order > 0) { 14478 // non-zero order, enable ordering 14479 mOrderResult.put(packageName, new Pair<>(order, res)); 14480 } 14481 return responseObj; 14482 } 14483 14484 @Override 14485 protected void filterResults(List<AuxiliaryResolveInfo> results) { 14486 // only do work if ordering is enabled [most of the time it won't be] 14487 if (mOrderResult.size() == 0) { 14488 return; 14489 } 14490 int resultSize = results.size(); 14491 for (int i = 0; i < resultSize; i++) { 14492 final InstantAppResolveInfo info = results.get(i).resolveInfo; 14493 final String packageName = info.getPackageName(); 14494 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 14495 if (savedInfo == null) { 14496 // package doesn't having ordering 14497 continue; 14498 } 14499 if (savedInfo.second == info) { 14500 // circled back to the highest ordered item; remove from order list 14501 mOrderResult.remove(packageName); 14502 if (mOrderResult.size() == 0) { 14503 // no more ordered items 14504 break; 14505 } 14506 continue; 14507 } 14508 // item has a worse order, remove it from the result list 14509 results.remove(i); 14510 resultSize--; 14511 i--; 14512 } 14513 } 14514 } 14515 14516 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 14517 new Comparator<ResolveInfo>() { 14518 public int compare(ResolveInfo r1, ResolveInfo r2) { 14519 int v1 = r1.priority; 14520 int v2 = r2.priority; 14521 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 14522 if (v1 != v2) { 14523 return (v1 > v2) ? -1 : 1; 14524 } 14525 v1 = r1.preferredOrder; 14526 v2 = r2.preferredOrder; 14527 if (v1 != v2) { 14528 return (v1 > v2) ? -1 : 1; 14529 } 14530 if (r1.isDefault != r2.isDefault) { 14531 return r1.isDefault ? -1 : 1; 14532 } 14533 v1 = r1.match; 14534 v2 = r2.match; 14535 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 14536 if (v1 != v2) { 14537 return (v1 > v2) ? -1 : 1; 14538 } 14539 if (r1.system != r2.system) { 14540 return r1.system ? -1 : 1; 14541 } 14542 if (r1.activityInfo != null) { 14543 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 14544 } 14545 if (r1.serviceInfo != null) { 14546 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 14547 } 14548 if (r1.providerInfo != null) { 14549 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 14550 } 14551 return 0; 14552 } 14553 }; 14554 14555 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 14556 new Comparator<ProviderInfo>() { 14557 public int compare(ProviderInfo p1, ProviderInfo p2) { 14558 final int v1 = p1.initOrder; 14559 final int v2 = p2.initOrder; 14560 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 14561 } 14562 }; 14563 14564 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 14565 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 14566 final int[] userIds) { 14567 mHandler.post(new Runnable() { 14568 @Override 14569 public void run() { 14570 try { 14571 final IActivityManager am = ActivityManager.getService(); 14572 if (am == null) return; 14573 final int[] resolvedUserIds; 14574 if (userIds == null) { 14575 resolvedUserIds = am.getRunningUserIds(); 14576 } else { 14577 resolvedUserIds = userIds; 14578 } 14579 for (int id : resolvedUserIds) { 14580 final Intent intent = new Intent(action, 14581 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 14582 if (extras != null) { 14583 intent.putExtras(extras); 14584 } 14585 if (targetPkg != null) { 14586 intent.setPackage(targetPkg); 14587 } 14588 // Modify the UID when posting to other users 14589 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 14590 if (uid > 0 && UserHandle.getUserId(uid) != id) { 14591 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 14592 intent.putExtra(Intent.EXTRA_UID, uid); 14593 } 14594 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 14595 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 14596 if (DEBUG_BROADCASTS) { 14597 RuntimeException here = new RuntimeException("here"); 14598 here.fillInStackTrace(); 14599 Slog.d(TAG, "Sending to user " + id + ": " 14600 + intent.toShortString(false, true, false, false) 14601 + " " + intent.getExtras(), here); 14602 } 14603 am.broadcastIntent(null, intent, null, finishedReceiver, 14604 0, null, null, null, android.app.AppOpsManager.OP_NONE, 14605 null, finishedReceiver != null, false, id); 14606 } 14607 } catch (RemoteException ex) { 14608 } 14609 } 14610 }); 14611 } 14612 14613 /** 14614 * Check if the external storage media is available. This is true if there 14615 * is a mounted external storage medium or if the external storage is 14616 * emulated. 14617 */ 14618 private boolean isExternalMediaAvailable() { 14619 return mMediaMounted || Environment.isExternalStorageEmulated(); 14620 } 14621 14622 @Override 14623 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 14624 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14625 return null; 14626 } 14627 // writer 14628 synchronized (mPackages) { 14629 if (!isExternalMediaAvailable()) { 14630 // If the external storage is no longer mounted at this point, 14631 // the caller may not have been able to delete all of this 14632 // packages files and can not delete any more. Bail. 14633 return null; 14634 } 14635 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 14636 if (lastPackage != null) { 14637 pkgs.remove(lastPackage); 14638 } 14639 if (pkgs.size() > 0) { 14640 return pkgs.get(0); 14641 } 14642 } 14643 return null; 14644 } 14645 14646 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 14647 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 14648 userId, andCode ? 1 : 0, packageName); 14649 if (mSystemReady) { 14650 msg.sendToTarget(); 14651 } else { 14652 if (mPostSystemReadyMessages == null) { 14653 mPostSystemReadyMessages = new ArrayList<>(); 14654 } 14655 mPostSystemReadyMessages.add(msg); 14656 } 14657 } 14658 14659 void startCleaningPackages() { 14660 // reader 14661 if (!isExternalMediaAvailable()) { 14662 return; 14663 } 14664 synchronized (mPackages) { 14665 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 14666 return; 14667 } 14668 } 14669 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 14670 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 14671 IActivityManager am = ActivityManager.getService(); 14672 if (am != null) { 14673 int dcsUid = -1; 14674 synchronized (mPackages) { 14675 if (!mDefaultContainerWhitelisted) { 14676 mDefaultContainerWhitelisted = true; 14677 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 14678 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 14679 } 14680 } 14681 try { 14682 if (dcsUid > 0) { 14683 am.backgroundWhitelistUid(dcsUid); 14684 } 14685 am.startService(null, intent, null, false, mContext.getOpPackageName(), 14686 UserHandle.USER_SYSTEM); 14687 } catch (RemoteException e) { 14688 } 14689 } 14690 } 14691 14692 @Override 14693 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 14694 int installFlags, String installerPackageName, int userId) { 14695 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 14696 14697 final int callingUid = Binder.getCallingUid(); 14698 enforceCrossUserPermission(callingUid, userId, 14699 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 14700 14701 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 14702 try { 14703 if (observer != null) { 14704 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 14705 } 14706 } catch (RemoteException re) { 14707 } 14708 return; 14709 } 14710 14711 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 14712 installFlags |= PackageManager.INSTALL_FROM_ADB; 14713 14714 } else { 14715 // Caller holds INSTALL_PACKAGES permission, so we're less strict 14716 // about installerPackageName. 14717 14718 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 14719 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 14720 } 14721 14722 UserHandle user; 14723 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 14724 user = UserHandle.ALL; 14725 } else { 14726 user = new UserHandle(userId); 14727 } 14728 14729 // Only system components can circumvent runtime permissions when installing. 14730 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 14731 && mContext.checkCallingOrSelfPermission(Manifest.permission 14732 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 14733 throw new SecurityException("You need the " 14734 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 14735 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 14736 } 14737 14738 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 14739 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14740 throw new IllegalArgumentException( 14741 "New installs into ASEC containers no longer supported"); 14742 } 14743 14744 final File originFile = new File(originPath); 14745 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 14746 14747 final Message msg = mHandler.obtainMessage(INIT_COPY); 14748 final VerificationInfo verificationInfo = new VerificationInfo( 14749 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 14750 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 14751 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 14752 null /*packageAbiOverride*/, null /*grantedPermissions*/, 14753 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 14754 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 14755 msg.obj = params; 14756 14757 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 14758 System.identityHashCode(msg.obj)); 14759 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 14760 System.identityHashCode(msg.obj)); 14761 14762 mHandler.sendMessage(msg); 14763 } 14764 14765 14766 /** 14767 * Ensure that the install reason matches what we know about the package installer (e.g. whether 14768 * it is acting on behalf on an enterprise or the user). 14769 * 14770 * Note that the ordering of the conditionals in this method is important. The checks we perform 14771 * are as follows, in this order: 14772 * 14773 * 1) If the install is being performed by a system app, we can trust the app to have set the 14774 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 14775 * what it is. 14776 * 2) If the install is being performed by a device or profile owner app, the install reason 14777 * should be enterprise policy. However, we cannot be sure that the device or profile owner 14778 * set the install reason correctly. If the app targets an older SDK version where install 14779 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 14780 * unset or wrong. Thus, we force the install reason to be enterprise policy. 14781 * 3) In all other cases, the install is being performed by a regular app that is neither part 14782 * of the system nor a device or profile owner. We have no reason to believe that this app is 14783 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 14784 * set to enterprise policy and if so, change it to unknown instead. 14785 */ 14786 private int fixUpInstallReason(String installerPackageName, int installerUid, 14787 int installReason) { 14788 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 14789 == PERMISSION_GRANTED) { 14790 // If the install is being performed by a system app, we trust that app to have set the 14791 // install reason correctly. 14792 return installReason; 14793 } 14794 14795 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14796 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14797 if (dpm != null) { 14798 ComponentName owner = null; 14799 try { 14800 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 14801 if (owner == null) { 14802 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 14803 } 14804 } catch (RemoteException e) { 14805 } 14806 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 14807 // If the install is being performed by a device or profile owner, the install 14808 // reason should be enterprise policy. 14809 return PackageManager.INSTALL_REASON_POLICY; 14810 } 14811 } 14812 14813 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 14814 // If the install is being performed by a regular app (i.e. neither system app nor 14815 // device or profile owner), we have no reason to believe that the app is acting on 14816 // behalf of an enterprise. If the app set the install reason to enterprise policy, 14817 // change it to unknown instead. 14818 return PackageManager.INSTALL_REASON_UNKNOWN; 14819 } 14820 14821 // If the install is being performed by a regular app and the install reason was set to any 14822 // value but enterprise policy, leave the install reason unchanged. 14823 return installReason; 14824 } 14825 14826 void installStage(String packageName, File stagedDir, String stagedCid, 14827 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 14828 String installerPackageName, int installerUid, UserHandle user, 14829 Certificate[][] certificates) { 14830 if (DEBUG_EPHEMERAL) { 14831 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14832 Slog.d(TAG, "Ephemeral install of " + packageName); 14833 } 14834 } 14835 final VerificationInfo verificationInfo = new VerificationInfo( 14836 sessionParams.originatingUri, sessionParams.referrerUri, 14837 sessionParams.originatingUid, installerUid); 14838 14839 final OriginInfo origin; 14840 if (stagedDir != null) { 14841 origin = OriginInfo.fromStagedFile(stagedDir); 14842 } else { 14843 origin = OriginInfo.fromStagedContainer(stagedCid); 14844 } 14845 14846 final Message msg = mHandler.obtainMessage(INIT_COPY); 14847 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 14848 sessionParams.installReason); 14849 final InstallParams params = new InstallParams(origin, null, observer, 14850 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 14851 verificationInfo, user, sessionParams.abiOverride, 14852 sessionParams.grantedRuntimePermissions, certificates, installReason); 14853 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 14854 msg.obj = params; 14855 14856 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 14857 System.identityHashCode(msg.obj)); 14858 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 14859 System.identityHashCode(msg.obj)); 14860 14861 mHandler.sendMessage(msg); 14862 } 14863 14864 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 14865 int userId) { 14866 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 14867 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 14868 false /*startReceiver*/, pkgSetting.appId, userId); 14869 14870 // Send a session commit broadcast 14871 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 14872 info.installReason = pkgSetting.getInstallReason(userId); 14873 info.appPackageName = packageName; 14874 sendSessionCommitBroadcast(info, userId); 14875 } 14876 14877 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 14878 boolean includeStopped, int appId, int... userIds) { 14879 if (ArrayUtils.isEmpty(userIds)) { 14880 return; 14881 } 14882 Bundle extras = new Bundle(1); 14883 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 14884 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 14885 14886 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 14887 packageName, extras, 0, null, null, userIds); 14888 if (sendBootCompleted) { 14889 mHandler.post(() -> { 14890 for (int userId : userIds) { 14891 sendBootCompletedBroadcastToSystemApp( 14892 packageName, includeStopped, userId); 14893 } 14894 } 14895 ); 14896 } 14897 } 14898 14899 /** 14900 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 14901 * automatically without needing an explicit launch. 14902 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 14903 */ 14904 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 14905 int userId) { 14906 // If user is not running, the app didn't miss any broadcast 14907 if (!mUserManagerInternal.isUserRunning(userId)) { 14908 return; 14909 } 14910 final IActivityManager am = ActivityManager.getService(); 14911 try { 14912 // Deliver LOCKED_BOOT_COMPLETED first 14913 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 14914 .setPackage(packageName); 14915 if (includeStopped) { 14916 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 14917 } 14918 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 14919 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 14920 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 14921 14922 // Deliver BOOT_COMPLETED only if user is unlocked 14923 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 14924 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 14925 if (includeStopped) { 14926 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 14927 } 14928 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 14929 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 14930 } 14931 } catch (RemoteException e) { 14932 throw e.rethrowFromSystemServer(); 14933 } 14934 } 14935 14936 @Override 14937 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 14938 int userId) { 14939 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 14940 PackageSetting pkgSetting; 14941 final int callingUid = Binder.getCallingUid(); 14942 enforceCrossUserPermission(callingUid, userId, 14943 true /* requireFullPermission */, true /* checkShell */, 14944 "setApplicationHiddenSetting for user " + userId); 14945 14946 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 14947 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 14948 return false; 14949 } 14950 14951 long callingId = Binder.clearCallingIdentity(); 14952 try { 14953 boolean sendAdded = false; 14954 boolean sendRemoved = false; 14955 // writer 14956 synchronized (mPackages) { 14957 pkgSetting = mSettings.mPackages.get(packageName); 14958 if (pkgSetting == null) { 14959 return false; 14960 } 14961 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 14962 return false; 14963 } 14964 // Do not allow "android" is being disabled 14965 if ("android".equals(packageName)) { 14966 Slog.w(TAG, "Cannot hide package: android"); 14967 return false; 14968 } 14969 // Cannot hide static shared libs as they are considered 14970 // a part of the using app (emulating static linking). Also 14971 // static libs are installed always on internal storage. 14972 PackageParser.Package pkg = mPackages.get(packageName); 14973 if (pkg != null && pkg.staticSharedLibName != null) { 14974 Slog.w(TAG, "Cannot hide package: " + packageName 14975 + " providing static shared library: " 14976 + pkg.staticSharedLibName); 14977 return false; 14978 } 14979 // Only allow protected packages to hide themselves. 14980 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 14981 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14982 Slog.w(TAG, "Not hiding protected package: " + packageName); 14983 return false; 14984 } 14985 14986 if (pkgSetting.getHidden(userId) != hidden) { 14987 pkgSetting.setHidden(hidden, userId); 14988 mSettings.writePackageRestrictionsLPr(userId); 14989 if (hidden) { 14990 sendRemoved = true; 14991 } else { 14992 sendAdded = true; 14993 } 14994 } 14995 } 14996 if (sendAdded) { 14997 sendPackageAddedForUser(packageName, pkgSetting, userId); 14998 return true; 14999 } 15000 if (sendRemoved) { 15001 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 15002 "hiding pkg"); 15003 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 15004 return true; 15005 } 15006 } finally { 15007 Binder.restoreCallingIdentity(callingId); 15008 } 15009 return false; 15010 } 15011 15012 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 15013 int userId) { 15014 final PackageRemovedInfo info = new PackageRemovedInfo(this); 15015 info.removedPackage = packageName; 15016 info.installerPackageName = pkgSetting.installerPackageName; 15017 info.removedUsers = new int[] {userId}; 15018 info.broadcastUsers = new int[] {userId}; 15019 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 15020 info.sendPackageRemovedBroadcasts(true /*killApp*/); 15021 } 15022 15023 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 15024 if (pkgList.length > 0) { 15025 Bundle extras = new Bundle(1); 15026 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15027 15028 sendPackageBroadcast( 15029 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 15030 : Intent.ACTION_PACKAGES_UNSUSPENDED, 15031 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 15032 new int[] {userId}); 15033 } 15034 } 15035 15036 /** 15037 * Returns true if application is not found or there was an error. Otherwise it returns 15038 * the hidden state of the package for the given user. 15039 */ 15040 @Override 15041 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 15042 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 15043 final int callingUid = Binder.getCallingUid(); 15044 enforceCrossUserPermission(callingUid, userId, 15045 true /* requireFullPermission */, false /* checkShell */, 15046 "getApplicationHidden for user " + userId); 15047 PackageSetting ps; 15048 long callingId = Binder.clearCallingIdentity(); 15049 try { 15050 // writer 15051 synchronized (mPackages) { 15052 ps = mSettings.mPackages.get(packageName); 15053 if (ps == null) { 15054 return true; 15055 } 15056 if (filterAppAccessLPr(ps, callingUid, userId)) { 15057 return true; 15058 } 15059 return ps.getHidden(userId); 15060 } 15061 } finally { 15062 Binder.restoreCallingIdentity(callingId); 15063 } 15064 } 15065 15066 /** 15067 * @hide 15068 */ 15069 @Override 15070 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 15071 int installReason) { 15072 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 15073 null); 15074 PackageSetting pkgSetting; 15075 final int callingUid = Binder.getCallingUid(); 15076 enforceCrossUserPermission(callingUid, userId, 15077 true /* requireFullPermission */, true /* checkShell */, 15078 "installExistingPackage for user " + userId); 15079 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 15080 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 15081 } 15082 15083 long callingId = Binder.clearCallingIdentity(); 15084 try { 15085 boolean installed = false; 15086 final boolean instantApp = 15087 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15088 final boolean fullApp = 15089 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 15090 15091 // writer 15092 synchronized (mPackages) { 15093 pkgSetting = mSettings.mPackages.get(packageName); 15094 if (pkgSetting == null) { 15095 return PackageManager.INSTALL_FAILED_INVALID_URI; 15096 } 15097 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 15098 // only allow the existing package to be used if it's installed as a full 15099 // application for at least one user 15100 boolean installAllowed = false; 15101 for (int checkUserId : sUserManager.getUserIds()) { 15102 installAllowed = !pkgSetting.getInstantApp(checkUserId); 15103 if (installAllowed) { 15104 break; 15105 } 15106 } 15107 if (!installAllowed) { 15108 return PackageManager.INSTALL_FAILED_INVALID_URI; 15109 } 15110 } 15111 if (!pkgSetting.getInstalled(userId)) { 15112 pkgSetting.setInstalled(true, userId); 15113 pkgSetting.setHidden(false, userId); 15114 pkgSetting.setInstallReason(installReason, userId); 15115 mSettings.writePackageRestrictionsLPr(userId); 15116 mSettings.writeKernelMappingLPr(pkgSetting); 15117 installed = true; 15118 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 15119 // upgrade app from instant to full; we don't allow app downgrade 15120 installed = true; 15121 } 15122 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 15123 } 15124 15125 if (installed) { 15126 if (pkgSetting.pkg != null) { 15127 synchronized (mInstallLock) { 15128 // We don't need to freeze for a brand new install 15129 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 15130 } 15131 } 15132 sendPackageAddedForUser(packageName, pkgSetting, userId); 15133 synchronized (mPackages) { 15134 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 15135 } 15136 } 15137 } finally { 15138 Binder.restoreCallingIdentity(callingId); 15139 } 15140 15141 return PackageManager.INSTALL_SUCCEEDED; 15142 } 15143 15144 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 15145 boolean instantApp, boolean fullApp) { 15146 // no state specified; do nothing 15147 if (!instantApp && !fullApp) { 15148 return; 15149 } 15150 if (userId != UserHandle.USER_ALL) { 15151 if (instantApp && !pkgSetting.getInstantApp(userId)) { 15152 pkgSetting.setInstantApp(true /*instantApp*/, userId); 15153 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 15154 pkgSetting.setInstantApp(false /*instantApp*/, userId); 15155 } 15156 } else { 15157 for (int currentUserId : sUserManager.getUserIds()) { 15158 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 15159 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 15160 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 15161 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 15162 } 15163 } 15164 } 15165 } 15166 15167 boolean isUserRestricted(int userId, String restrictionKey) { 15168 Bundle restrictions = sUserManager.getUserRestrictions(userId); 15169 if (restrictions.getBoolean(restrictionKey, false)) { 15170 Log.w(TAG, "User is restricted: " + restrictionKey); 15171 return true; 15172 } 15173 return false; 15174 } 15175 15176 @Override 15177 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 15178 int userId) { 15179 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 15180 final int callingUid = Binder.getCallingUid(); 15181 enforceCrossUserPermission(callingUid, userId, 15182 true /* requireFullPermission */, true /* checkShell */, 15183 "setPackagesSuspended for user " + userId); 15184 15185 if (ArrayUtils.isEmpty(packageNames)) { 15186 return packageNames; 15187 } 15188 15189 // List of package names for whom the suspended state has changed. 15190 List<String> changedPackages = new ArrayList<>(packageNames.length); 15191 // List of package names for whom the suspended state is not set as requested in this 15192 // method. 15193 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 15194 long callingId = Binder.clearCallingIdentity(); 15195 try { 15196 for (int i = 0; i < packageNames.length; i++) { 15197 String packageName = packageNames[i]; 15198 boolean changed = false; 15199 final int appId; 15200 synchronized (mPackages) { 15201 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 15202 if (pkgSetting == null 15203 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 15204 Slog.w(TAG, "Could not find package setting for package \"" + packageName 15205 + "\". Skipping suspending/un-suspending."); 15206 unactionedPackages.add(packageName); 15207 continue; 15208 } 15209 appId = pkgSetting.appId; 15210 if (pkgSetting.getSuspended(userId) != suspended) { 15211 if (!canSuspendPackageForUserLocked(packageName, userId)) { 15212 unactionedPackages.add(packageName); 15213 continue; 15214 } 15215 pkgSetting.setSuspended(suspended, userId); 15216 mSettings.writePackageRestrictionsLPr(userId); 15217 changed = true; 15218 changedPackages.add(packageName); 15219 } 15220 } 15221 15222 if (changed && suspended) { 15223 killApplication(packageName, UserHandle.getUid(userId, appId), 15224 "suspending package"); 15225 } 15226 } 15227 } finally { 15228 Binder.restoreCallingIdentity(callingId); 15229 } 15230 15231 if (!changedPackages.isEmpty()) { 15232 sendPackagesSuspendedForUser(changedPackages.toArray( 15233 new String[changedPackages.size()]), userId, suspended); 15234 } 15235 15236 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 15237 } 15238 15239 @Override 15240 public boolean isPackageSuspendedForUser(String packageName, int userId) { 15241 final int callingUid = Binder.getCallingUid(); 15242 enforceCrossUserPermission(callingUid, userId, 15243 true /* requireFullPermission */, false /* checkShell */, 15244 "isPackageSuspendedForUser for user " + userId); 15245 synchronized (mPackages) { 15246 final PackageSetting ps = mSettings.mPackages.get(packageName); 15247 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 15248 throw new IllegalArgumentException("Unknown target package: " + packageName); 15249 } 15250 return ps.getSuspended(userId); 15251 } 15252 } 15253 15254 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 15255 if (isPackageDeviceAdmin(packageName, userId)) { 15256 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 15257 + "\": has an active device admin"); 15258 return false; 15259 } 15260 15261 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 15262 if (packageName.equals(activeLauncherPackageName)) { 15263 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 15264 + "\": contains the active launcher"); 15265 return false; 15266 } 15267 15268 if (packageName.equals(mRequiredInstallerPackage)) { 15269 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 15270 + "\": required for package installation"); 15271 return false; 15272 } 15273 15274 if (packageName.equals(mRequiredUninstallerPackage)) { 15275 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 15276 + "\": required for package uninstallation"); 15277 return false; 15278 } 15279 15280 if (packageName.equals(mRequiredVerifierPackage)) { 15281 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 15282 + "\": required for package verification"); 15283 return false; 15284 } 15285 15286 if (packageName.equals(getDefaultDialerPackageName(userId))) { 15287 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 15288 + "\": is the default dialer"); 15289 return false; 15290 } 15291 15292 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 15293 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 15294 + "\": protected package"); 15295 return false; 15296 } 15297 15298 // Cannot suspend static shared libs as they are considered 15299 // a part of the using app (emulating static linking). Also 15300 // static libs are installed always on internal storage. 15301 PackageParser.Package pkg = mPackages.get(packageName); 15302 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 15303 Slog.w(TAG, "Cannot suspend package: " + packageName 15304 + " providing static shared library: " 15305 + pkg.staticSharedLibName); 15306 return false; 15307 } 15308 15309 return true; 15310 } 15311 15312 private String getActiveLauncherPackageName(int userId) { 15313 Intent intent = new Intent(Intent.ACTION_MAIN); 15314 intent.addCategory(Intent.CATEGORY_HOME); 15315 ResolveInfo resolveInfo = resolveIntent( 15316 intent, 15317 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 15318 PackageManager.MATCH_DEFAULT_ONLY, 15319 userId); 15320 15321 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 15322 } 15323 15324 private String getDefaultDialerPackageName(int userId) { 15325 synchronized (mPackages) { 15326 return mSettings.getDefaultDialerPackageNameLPw(userId); 15327 } 15328 } 15329 15330 @Override 15331 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 15332 mContext.enforceCallingOrSelfPermission( 15333 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15334 "Only package verification agents can verify applications"); 15335 15336 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 15337 final PackageVerificationResponse response = new PackageVerificationResponse( 15338 verificationCode, Binder.getCallingUid()); 15339 msg.arg1 = id; 15340 msg.obj = response; 15341 mHandler.sendMessage(msg); 15342 } 15343 15344 @Override 15345 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 15346 long millisecondsToDelay) { 15347 mContext.enforceCallingOrSelfPermission( 15348 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15349 "Only package verification agents can extend verification timeouts"); 15350 15351 final PackageVerificationState state = mPendingVerification.get(id); 15352 final PackageVerificationResponse response = new PackageVerificationResponse( 15353 verificationCodeAtTimeout, Binder.getCallingUid()); 15354 15355 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 15356 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 15357 } 15358 if (millisecondsToDelay < 0) { 15359 millisecondsToDelay = 0; 15360 } 15361 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 15362 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 15363 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 15364 } 15365 15366 if ((state != null) && !state.timeoutExtended()) { 15367 state.extendTimeout(); 15368 15369 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 15370 msg.arg1 = id; 15371 msg.obj = response; 15372 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 15373 } 15374 } 15375 15376 private void broadcastPackageVerified(int verificationId, Uri packageUri, 15377 int verificationCode, UserHandle user) { 15378 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 15379 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 15380 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15381 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15382 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 15383 15384 mContext.sendBroadcastAsUser(intent, user, 15385 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 15386 } 15387 15388 private ComponentName matchComponentForVerifier(String packageName, 15389 List<ResolveInfo> receivers) { 15390 ActivityInfo targetReceiver = null; 15391 15392 final int NR = receivers.size(); 15393 for (int i = 0; i < NR; i++) { 15394 final ResolveInfo info = receivers.get(i); 15395 if (info.activityInfo == null) { 15396 continue; 15397 } 15398 15399 if (packageName.equals(info.activityInfo.packageName)) { 15400 targetReceiver = info.activityInfo; 15401 break; 15402 } 15403 } 15404 15405 if (targetReceiver == null) { 15406 return null; 15407 } 15408 15409 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 15410 } 15411 15412 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 15413 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 15414 if (pkgInfo.verifiers.length == 0) { 15415 return null; 15416 } 15417 15418 final int N = pkgInfo.verifiers.length; 15419 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 15420 for (int i = 0; i < N; i++) { 15421 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 15422 15423 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 15424 receivers); 15425 if (comp == null) { 15426 continue; 15427 } 15428 15429 final int verifierUid = getUidForVerifier(verifierInfo); 15430 if (verifierUid == -1) { 15431 continue; 15432 } 15433 15434 if (DEBUG_VERIFY) { 15435 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 15436 + " with the correct signature"); 15437 } 15438 sufficientVerifiers.add(comp); 15439 verificationState.addSufficientVerifier(verifierUid); 15440 } 15441 15442 return sufficientVerifiers; 15443 } 15444 15445 private int getUidForVerifier(VerifierInfo verifierInfo) { 15446 synchronized (mPackages) { 15447 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 15448 if (pkg == null) { 15449 return -1; 15450 } else if (pkg.mSignatures.length != 1) { 15451 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 15452 + " has more than one signature; ignoring"); 15453 return -1; 15454 } 15455 15456 /* 15457 * If the public key of the package's signature does not match 15458 * our expected public key, then this is a different package and 15459 * we should skip. 15460 */ 15461 15462 final byte[] expectedPublicKey; 15463 try { 15464 final Signature verifierSig = pkg.mSignatures[0]; 15465 final PublicKey publicKey = verifierSig.getPublicKey(); 15466 expectedPublicKey = publicKey.getEncoded(); 15467 } catch (CertificateException e) { 15468 return -1; 15469 } 15470 15471 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 15472 15473 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 15474 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 15475 + " does not have the expected public key; ignoring"); 15476 return -1; 15477 } 15478 15479 return pkg.applicationInfo.uid; 15480 } 15481 } 15482 15483 @Override 15484 public void finishPackageInstall(int token, boolean didLaunch) { 15485 enforceSystemOrRoot("Only the system is allowed to finish installs"); 15486 15487 if (DEBUG_INSTALL) { 15488 Slog.v(TAG, "BM finishing package install for " + token); 15489 } 15490 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 15491 15492 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 15493 mHandler.sendMessage(msg); 15494 } 15495 15496 /** 15497 * Get the verification agent timeout. Used for both the APK verifier and the 15498 * intent filter verifier. 15499 * 15500 * @return verification timeout in milliseconds 15501 */ 15502 private long getVerificationTimeout() { 15503 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 15504 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 15505 DEFAULT_VERIFICATION_TIMEOUT); 15506 } 15507 15508 /** 15509 * Get the default verification agent response code. 15510 * 15511 * @return default verification response code 15512 */ 15513 private int getDefaultVerificationResponse(UserHandle user) { 15514 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 15515 return PackageManager.VERIFICATION_REJECT; 15516 } 15517 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15518 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 15519 DEFAULT_VERIFICATION_RESPONSE); 15520 } 15521 15522 /** 15523 * Check whether or not package verification has been enabled. 15524 * 15525 * @return true if verification should be performed 15526 */ 15527 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 15528 if (!DEFAULT_VERIFY_ENABLE) { 15529 return false; 15530 } 15531 15532 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 15533 15534 // Check if installing from ADB 15535 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 15536 // Do not run verification in a test harness environment 15537 if (ActivityManager.isRunningInTestHarness()) { 15538 return false; 15539 } 15540 if (ensureVerifyAppsEnabled) { 15541 return true; 15542 } 15543 // Check if the developer does not want package verification for ADB installs 15544 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15545 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 15546 return false; 15547 } 15548 } else { 15549 // only when not installed from ADB, skip verification for instant apps when 15550 // the installer and verifier are the same. 15551 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 15552 if (mInstantAppInstallerActivity != null 15553 && mInstantAppInstallerActivity.packageName.equals( 15554 mRequiredVerifierPackage)) { 15555 try { 15556 mContext.getSystemService(AppOpsManager.class) 15557 .checkPackage(installerUid, mRequiredVerifierPackage); 15558 if (DEBUG_VERIFY) { 15559 Slog.i(TAG, "disable verification for instant app"); 15560 } 15561 return false; 15562 } catch (SecurityException ignore) { } 15563 } 15564 } 15565 } 15566 15567 if (ensureVerifyAppsEnabled) { 15568 return true; 15569 } 15570 15571 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15572 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 15573 } 15574 15575 @Override 15576 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 15577 throws RemoteException { 15578 mContext.enforceCallingOrSelfPermission( 15579 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 15580 "Only intentfilter verification agents can verify applications"); 15581 15582 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 15583 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 15584 Binder.getCallingUid(), verificationCode, failedDomains); 15585 msg.arg1 = id; 15586 msg.obj = response; 15587 mHandler.sendMessage(msg); 15588 } 15589 15590 @Override 15591 public int getIntentVerificationStatus(String packageName, int userId) { 15592 final int callingUid = Binder.getCallingUid(); 15593 if (UserHandle.getUserId(callingUid) != userId) { 15594 mContext.enforceCallingOrSelfPermission( 15595 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15596 "getIntentVerificationStatus" + userId); 15597 } 15598 if (getInstantAppPackageName(callingUid) != null) { 15599 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 15600 } 15601 synchronized (mPackages) { 15602 final PackageSetting ps = mSettings.mPackages.get(packageName); 15603 if (ps == null 15604 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 15605 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 15606 } 15607 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 15608 } 15609 } 15610 15611 @Override 15612 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 15613 mContext.enforceCallingOrSelfPermission( 15614 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15615 15616 boolean result = false; 15617 synchronized (mPackages) { 15618 final PackageSetting ps = mSettings.mPackages.get(packageName); 15619 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 15620 return false; 15621 } 15622 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 15623 } 15624 if (result) { 15625 scheduleWritePackageRestrictionsLocked(userId); 15626 } 15627 return result; 15628 } 15629 15630 @Override 15631 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 15632 String packageName) { 15633 final int callingUid = Binder.getCallingUid(); 15634 if (getInstantAppPackageName(callingUid) != null) { 15635 return ParceledListSlice.emptyList(); 15636 } 15637 synchronized (mPackages) { 15638 final PackageSetting ps = mSettings.mPackages.get(packageName); 15639 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 15640 return ParceledListSlice.emptyList(); 15641 } 15642 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 15643 } 15644 } 15645 15646 @Override 15647 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 15648 if (TextUtils.isEmpty(packageName)) { 15649 return ParceledListSlice.emptyList(); 15650 } 15651 final int callingUid = Binder.getCallingUid(); 15652 final int callingUserId = UserHandle.getUserId(callingUid); 15653 synchronized (mPackages) { 15654 PackageParser.Package pkg = mPackages.get(packageName); 15655 if (pkg == null || pkg.activities == null) { 15656 return ParceledListSlice.emptyList(); 15657 } 15658 if (pkg.mExtras == null) { 15659 return ParceledListSlice.emptyList(); 15660 } 15661 final PackageSetting ps = (PackageSetting) pkg.mExtras; 15662 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 15663 return ParceledListSlice.emptyList(); 15664 } 15665 final int count = pkg.activities.size(); 15666 ArrayList<IntentFilter> result = new ArrayList<>(); 15667 for (int n=0; n<count; n++) { 15668 PackageParser.Activity activity = pkg.activities.get(n); 15669 if (activity.intents != null && activity.intents.size() > 0) { 15670 result.addAll(activity.intents); 15671 } 15672 } 15673 return new ParceledListSlice<>(result); 15674 } 15675 } 15676 15677 @Override 15678 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 15679 mContext.enforceCallingOrSelfPermission( 15680 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15681 if (UserHandle.getCallingUserId() != userId) { 15682 mContext.enforceCallingOrSelfPermission( 15683 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15684 } 15685 15686 synchronized (mPackages) { 15687 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 15688 if (packageName != null) { 15689 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 15690 packageName, userId); 15691 } 15692 return result; 15693 } 15694 } 15695 15696 @Override 15697 public String getDefaultBrowserPackageName(int userId) { 15698 if (UserHandle.getCallingUserId() != userId) { 15699 mContext.enforceCallingOrSelfPermission( 15700 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15701 } 15702 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 15703 return null; 15704 } 15705 synchronized (mPackages) { 15706 return mSettings.getDefaultBrowserPackageNameLPw(userId); 15707 } 15708 } 15709 15710 /** 15711 * Get the "allow unknown sources" setting. 15712 * 15713 * @return the current "allow unknown sources" setting 15714 */ 15715 private int getUnknownSourcesSettings() { 15716 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 15717 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 15718 -1); 15719 } 15720 15721 @Override 15722 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 15723 final int callingUid = Binder.getCallingUid(); 15724 if (getInstantAppPackageName(callingUid) != null) { 15725 return; 15726 } 15727 // writer 15728 synchronized (mPackages) { 15729 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 15730 if (targetPackageSetting == null 15731 || filterAppAccessLPr( 15732 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 15733 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 15734 } 15735 15736 PackageSetting installerPackageSetting; 15737 if (installerPackageName != null) { 15738 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 15739 if (installerPackageSetting == null) { 15740 throw new IllegalArgumentException("Unknown installer package: " 15741 + installerPackageName); 15742 } 15743 } else { 15744 installerPackageSetting = null; 15745 } 15746 15747 Signature[] callerSignature; 15748 Object obj = mSettings.getUserIdLPr(callingUid); 15749 if (obj != null) { 15750 if (obj instanceof SharedUserSetting) { 15751 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 15752 } else if (obj instanceof PackageSetting) { 15753 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 15754 } else { 15755 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 15756 } 15757 } else { 15758 throw new SecurityException("Unknown calling UID: " + callingUid); 15759 } 15760 15761 // Verify: can't set installerPackageName to a package that is 15762 // not signed with the same cert as the caller. 15763 if (installerPackageSetting != null) { 15764 if (compareSignatures(callerSignature, 15765 installerPackageSetting.signatures.mSignatures) 15766 != PackageManager.SIGNATURE_MATCH) { 15767 throw new SecurityException( 15768 "Caller does not have same cert as new installer package " 15769 + installerPackageName); 15770 } 15771 } 15772 15773 // Verify: if target already has an installer package, it must 15774 // be signed with the same cert as the caller. 15775 if (targetPackageSetting.installerPackageName != null) { 15776 PackageSetting setting = mSettings.mPackages.get( 15777 targetPackageSetting.installerPackageName); 15778 // If the currently set package isn't valid, then it's always 15779 // okay to change it. 15780 if (setting != null) { 15781 if (compareSignatures(callerSignature, 15782 setting.signatures.mSignatures) 15783 != PackageManager.SIGNATURE_MATCH) { 15784 throw new SecurityException( 15785 "Caller does not have same cert as old installer package " 15786 + targetPackageSetting.installerPackageName); 15787 } 15788 } 15789 } 15790 15791 // Okay! 15792 targetPackageSetting.installerPackageName = installerPackageName; 15793 if (installerPackageName != null) { 15794 mSettings.mInstallerPackages.add(installerPackageName); 15795 } 15796 scheduleWriteSettingsLocked(); 15797 } 15798 } 15799 15800 @Override 15801 public void setApplicationCategoryHint(String packageName, int categoryHint, 15802 String callerPackageName) { 15803 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 15804 throw new SecurityException("Instant applications don't have access to this method"); 15805 } 15806 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 15807 callerPackageName); 15808 synchronized (mPackages) { 15809 PackageSetting ps = mSettings.mPackages.get(packageName); 15810 if (ps == null) { 15811 throw new IllegalArgumentException("Unknown target package " + packageName); 15812 } 15813 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 15814 throw new IllegalArgumentException("Unknown target package " + packageName); 15815 } 15816 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 15817 throw new IllegalArgumentException("Calling package " + callerPackageName 15818 + " is not installer for " + packageName); 15819 } 15820 15821 if (ps.categoryHint != categoryHint) { 15822 ps.categoryHint = categoryHint; 15823 scheduleWriteSettingsLocked(); 15824 } 15825 } 15826 } 15827 15828 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 15829 // Queue up an async operation since the package installation may take a little while. 15830 mHandler.post(new Runnable() { 15831 public void run() { 15832 mHandler.removeCallbacks(this); 15833 // Result object to be returned 15834 PackageInstalledInfo res = new PackageInstalledInfo(); 15835 res.setReturnCode(currentStatus); 15836 res.uid = -1; 15837 res.pkg = null; 15838 res.removedInfo = null; 15839 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15840 args.doPreInstall(res.returnCode); 15841 synchronized (mInstallLock) { 15842 installPackageTracedLI(args, res); 15843 } 15844 args.doPostInstall(res.returnCode, res.uid); 15845 } 15846 15847 // A restore should be performed at this point if (a) the install 15848 // succeeded, (b) the operation is not an update, and (c) the new 15849 // package has not opted out of backup participation. 15850 final boolean update = res.removedInfo != null 15851 && res.removedInfo.removedPackage != null; 15852 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 15853 boolean doRestore = !update 15854 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 15855 15856 // Set up the post-install work request bookkeeping. This will be used 15857 // and cleaned up by the post-install event handling regardless of whether 15858 // there's a restore pass performed. Token values are >= 1. 15859 int token; 15860 if (mNextInstallToken < 0) mNextInstallToken = 1; 15861 token = mNextInstallToken++; 15862 15863 PostInstallData data = new PostInstallData(args, res); 15864 mRunningInstalls.put(token, data); 15865 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 15866 15867 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 15868 // Pass responsibility to the Backup Manager. It will perform a 15869 // restore if appropriate, then pass responsibility back to the 15870 // Package Manager to run the post-install observer callbacks 15871 // and broadcasts. 15872 IBackupManager bm = IBackupManager.Stub.asInterface( 15873 ServiceManager.getService(Context.BACKUP_SERVICE)); 15874 if (bm != null) { 15875 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 15876 + " to BM for possible restore"); 15877 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 15878 try { 15879 // TODO: http://b/22388012 15880 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 15881 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 15882 } else { 15883 doRestore = false; 15884 } 15885 } catch (RemoteException e) { 15886 // can't happen; the backup manager is local 15887 } catch (Exception e) { 15888 Slog.e(TAG, "Exception trying to enqueue restore", e); 15889 doRestore = false; 15890 } 15891 } else { 15892 Slog.e(TAG, "Backup Manager not found!"); 15893 doRestore = false; 15894 } 15895 } 15896 15897 if (!doRestore) { 15898 // No restore possible, or the Backup Manager was mysteriously not 15899 // available -- just fire the post-install work request directly. 15900 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 15901 15902 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 15903 15904 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 15905 mHandler.sendMessage(msg); 15906 } 15907 } 15908 }); 15909 } 15910 15911 /** 15912 * Callback from PackageSettings whenever an app is first transitioned out of the 15913 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 15914 * the app was "launched" for a restoreAtInstall operation. Therefore we check 15915 * here whether the app is the target of an ongoing install, and only send the 15916 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 15917 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 15918 * handling. 15919 */ 15920 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 15921 // Serialize this with the rest of the install-process message chain. In the 15922 // restore-at-install case, this Runnable will necessarily run before the 15923 // POST_INSTALL message is processed, so the contents of mRunningInstalls 15924 // are coherent. In the non-restore case, the app has already completed install 15925 // and been launched through some other means, so it is not in a problematic 15926 // state for observers to see the FIRST_LAUNCH signal. 15927 mHandler.post(new Runnable() { 15928 @Override 15929 public void run() { 15930 for (int i = 0; i < mRunningInstalls.size(); i++) { 15931 final PostInstallData data = mRunningInstalls.valueAt(i); 15932 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15933 continue; 15934 } 15935 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 15936 // right package; but is it for the right user? 15937 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 15938 if (userId == data.res.newUsers[uIndex]) { 15939 if (DEBUG_BACKUP) { 15940 Slog.i(TAG, "Package " + pkgName 15941 + " being restored so deferring FIRST_LAUNCH"); 15942 } 15943 return; 15944 } 15945 } 15946 } 15947 } 15948 // didn't find it, so not being restored 15949 if (DEBUG_BACKUP) { 15950 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 15951 } 15952 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 15953 } 15954 }); 15955 } 15956 15957 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 15958 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 15959 installerPkg, null, userIds); 15960 } 15961 15962 private abstract class HandlerParams { 15963 private static final int MAX_RETRIES = 4; 15964 15965 /** 15966 * Number of times startCopy() has been attempted and had a non-fatal 15967 * error. 15968 */ 15969 private int mRetries = 0; 15970 15971 /** User handle for the user requesting the information or installation. */ 15972 private final UserHandle mUser; 15973 String traceMethod; 15974 int traceCookie; 15975 15976 HandlerParams(UserHandle user) { 15977 mUser = user; 15978 } 15979 15980 UserHandle getUser() { 15981 return mUser; 15982 } 15983 15984 HandlerParams setTraceMethod(String traceMethod) { 15985 this.traceMethod = traceMethod; 15986 return this; 15987 } 15988 15989 HandlerParams setTraceCookie(int traceCookie) { 15990 this.traceCookie = traceCookie; 15991 return this; 15992 } 15993 15994 final boolean startCopy() { 15995 boolean res; 15996 try { 15997 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 15998 15999 if (++mRetries > MAX_RETRIES) { 16000 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 16001 mHandler.sendEmptyMessage(MCS_GIVE_UP); 16002 handleServiceError(); 16003 return false; 16004 } else { 16005 handleStartCopy(); 16006 res = true; 16007 } 16008 } catch (RemoteException e) { 16009 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 16010 mHandler.sendEmptyMessage(MCS_RECONNECT); 16011 res = false; 16012 } 16013 handleReturnCode(); 16014 return res; 16015 } 16016 16017 final void serviceError() { 16018 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 16019 handleServiceError(); 16020 handleReturnCode(); 16021 } 16022 16023 abstract void handleStartCopy() throws RemoteException; 16024 abstract void handleServiceError(); 16025 abstract void handleReturnCode(); 16026 } 16027 16028 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 16029 for (File path : paths) { 16030 try { 16031 mcs.clearDirectory(path.getAbsolutePath()); 16032 } catch (RemoteException e) { 16033 } 16034 } 16035 } 16036 16037 static class OriginInfo { 16038 /** 16039 * Location where install is coming from, before it has been 16040 * copied/renamed into place. This could be a single monolithic APK 16041 * file, or a cluster directory. This location may be untrusted. 16042 */ 16043 final File file; 16044 final String cid; 16045 16046 /** 16047 * Flag indicating that {@link #file} or {@link #cid} has already been 16048 * staged, meaning downstream users don't need to defensively copy the 16049 * contents. 16050 */ 16051 final boolean staged; 16052 16053 /** 16054 * Flag indicating that {@link #file} or {@link #cid} is an already 16055 * installed app that is being moved. 16056 */ 16057 final boolean existing; 16058 16059 final String resolvedPath; 16060 final File resolvedFile; 16061 16062 static OriginInfo fromNothing() { 16063 return new OriginInfo(null, null, false, false); 16064 } 16065 16066 static OriginInfo fromUntrustedFile(File file) { 16067 return new OriginInfo(file, null, false, false); 16068 } 16069 16070 static OriginInfo fromExistingFile(File file) { 16071 return new OriginInfo(file, null, false, true); 16072 } 16073 16074 static OriginInfo fromStagedFile(File file) { 16075 return new OriginInfo(file, null, true, false); 16076 } 16077 16078 static OriginInfo fromStagedContainer(String cid) { 16079 return new OriginInfo(null, cid, true, false); 16080 } 16081 16082 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 16083 this.file = file; 16084 this.cid = cid; 16085 this.staged = staged; 16086 this.existing = existing; 16087 16088 if (cid != null) { 16089 resolvedPath = PackageHelper.getSdDir(cid); 16090 resolvedFile = new File(resolvedPath); 16091 } else if (file != null) { 16092 resolvedPath = file.getAbsolutePath(); 16093 resolvedFile = file; 16094 } else { 16095 resolvedPath = null; 16096 resolvedFile = null; 16097 } 16098 } 16099 } 16100 16101 static class MoveInfo { 16102 final int moveId; 16103 final String fromUuid; 16104 final String toUuid; 16105 final String packageName; 16106 final String dataAppName; 16107 final int appId; 16108 final String seinfo; 16109 final int targetSdkVersion; 16110 16111 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 16112 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 16113 this.moveId = moveId; 16114 this.fromUuid = fromUuid; 16115 this.toUuid = toUuid; 16116 this.packageName = packageName; 16117 this.dataAppName = dataAppName; 16118 this.appId = appId; 16119 this.seinfo = seinfo; 16120 this.targetSdkVersion = targetSdkVersion; 16121 } 16122 } 16123 16124 static class VerificationInfo { 16125 /** A constant used to indicate that a uid value is not present. */ 16126 public static final int NO_UID = -1; 16127 16128 /** URI referencing where the package was downloaded from. */ 16129 final Uri originatingUri; 16130 16131 /** HTTP referrer URI associated with the originatingURI. */ 16132 final Uri referrer; 16133 16134 /** UID of the application that the install request originated from. */ 16135 final int originatingUid; 16136 16137 /** UID of application requesting the install */ 16138 final int installerUid; 16139 16140 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 16141 this.originatingUri = originatingUri; 16142 this.referrer = referrer; 16143 this.originatingUid = originatingUid; 16144 this.installerUid = installerUid; 16145 } 16146 } 16147 16148 class InstallParams extends HandlerParams { 16149 final OriginInfo origin; 16150 final MoveInfo move; 16151 final IPackageInstallObserver2 observer; 16152 int installFlags; 16153 final String installerPackageName; 16154 final String volumeUuid; 16155 private InstallArgs mArgs; 16156 private int mRet; 16157 final String packageAbiOverride; 16158 final String[] grantedRuntimePermissions; 16159 final VerificationInfo verificationInfo; 16160 final Certificate[][] certificates; 16161 final int installReason; 16162 16163 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 16164 int installFlags, String installerPackageName, String volumeUuid, 16165 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 16166 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 16167 super(user); 16168 this.origin = origin; 16169 this.move = move; 16170 this.observer = observer; 16171 this.installFlags = installFlags; 16172 this.installerPackageName = installerPackageName; 16173 this.volumeUuid = volumeUuid; 16174 this.verificationInfo = verificationInfo; 16175 this.packageAbiOverride = packageAbiOverride; 16176 this.grantedRuntimePermissions = grantedPermissions; 16177 this.certificates = certificates; 16178 this.installReason = installReason; 16179 } 16180 16181 @Override 16182 public String toString() { 16183 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 16184 + " file=" + origin.file + " cid=" + origin.cid + "}"; 16185 } 16186 16187 private int installLocationPolicy(PackageInfoLite pkgLite) { 16188 String packageName = pkgLite.packageName; 16189 int installLocation = pkgLite.installLocation; 16190 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 16191 // reader 16192 synchronized (mPackages) { 16193 // Currently installed package which the new package is attempting to replace or 16194 // null if no such package is installed. 16195 PackageParser.Package installedPkg = mPackages.get(packageName); 16196 // Package which currently owns the data which the new package will own if installed. 16197 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 16198 // will be null whereas dataOwnerPkg will contain information about the package 16199 // which was uninstalled while keeping its data. 16200 PackageParser.Package dataOwnerPkg = installedPkg; 16201 if (dataOwnerPkg == null) { 16202 PackageSetting ps = mSettings.mPackages.get(packageName); 16203 if (ps != null) { 16204 dataOwnerPkg = ps.pkg; 16205 } 16206 } 16207 16208 if (dataOwnerPkg != null) { 16209 // If installed, the package will get access to data left on the device by its 16210 // predecessor. As a security measure, this is permited only if this is not a 16211 // version downgrade or if the predecessor package is marked as debuggable and 16212 // a downgrade is explicitly requested. 16213 // 16214 // On debuggable platform builds, downgrades are permitted even for 16215 // non-debuggable packages to make testing easier. Debuggable platform builds do 16216 // not offer security guarantees and thus it's OK to disable some security 16217 // mechanisms to make debugging/testing easier on those builds. However, even on 16218 // debuggable builds downgrades of packages are permitted only if requested via 16219 // installFlags. This is because we aim to keep the behavior of debuggable 16220 // platform builds as close as possible to the behavior of non-debuggable 16221 // platform builds. 16222 final boolean downgradeRequested = 16223 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 16224 final boolean packageDebuggable = 16225 (dataOwnerPkg.applicationInfo.flags 16226 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 16227 final boolean downgradePermitted = 16228 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 16229 if (!downgradePermitted) { 16230 try { 16231 checkDowngrade(dataOwnerPkg, pkgLite); 16232 } catch (PackageManagerException e) { 16233 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 16234 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 16235 } 16236 } 16237 } 16238 16239 if (installedPkg != null) { 16240 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16241 // Check for updated system application. 16242 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16243 if (onSd) { 16244 Slog.w(TAG, "Cannot install update to system app on sdcard"); 16245 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 16246 } 16247 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 16248 } else { 16249 if (onSd) { 16250 // Install flag overrides everything. 16251 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 16252 } 16253 // If current upgrade specifies particular preference 16254 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 16255 // Application explicitly specified internal. 16256 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 16257 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 16258 // App explictly prefers external. Let policy decide 16259 } else { 16260 // Prefer previous location 16261 if (isExternal(installedPkg)) { 16262 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 16263 } 16264 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 16265 } 16266 } 16267 } else { 16268 // Invalid install. Return error code 16269 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 16270 } 16271 } 16272 } 16273 // All the special cases have been taken care of. 16274 // Return result based on recommended install location. 16275 if (onSd) { 16276 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 16277 } 16278 return pkgLite.recommendedInstallLocation; 16279 } 16280 16281 /* 16282 * Invoke remote method to get package information and install 16283 * location values. Override install location based on default 16284 * policy if needed and then create install arguments based 16285 * on the install location. 16286 */ 16287 public void handleStartCopy() throws RemoteException { 16288 int ret = PackageManager.INSTALL_SUCCEEDED; 16289 16290 // If we're already staged, we've firmly committed to an install location 16291 if (origin.staged) { 16292 if (origin.file != null) { 16293 installFlags |= PackageManager.INSTALL_INTERNAL; 16294 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 16295 } else if (origin.cid != null) { 16296 installFlags |= PackageManager.INSTALL_EXTERNAL; 16297 installFlags &= ~PackageManager.INSTALL_INTERNAL; 16298 } else { 16299 throw new IllegalStateException("Invalid stage location"); 16300 } 16301 } 16302 16303 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 16304 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 16305 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 16306 PackageInfoLite pkgLite = null; 16307 16308 if (onInt && onSd) { 16309 // Check if both bits are set. 16310 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 16311 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 16312 } else if (onSd && ephemeral) { 16313 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 16314 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 16315 } else { 16316 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 16317 packageAbiOverride); 16318 16319 if (DEBUG_EPHEMERAL && ephemeral) { 16320 Slog.v(TAG, "pkgLite for install: " + pkgLite); 16321 } 16322 16323 /* 16324 * If we have too little free space, try to free cache 16325 * before giving up. 16326 */ 16327 if (!origin.staged && pkgLite.recommendedInstallLocation 16328 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 16329 // TODO: focus freeing disk space on the target device 16330 final StorageManager storage = StorageManager.from(mContext); 16331 final long lowThreshold = storage.getStorageLowBytes( 16332 Environment.getDataDirectory()); 16333 16334 final long sizeBytes = mContainerService.calculateInstalledSize( 16335 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 16336 16337 try { 16338 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 16339 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 16340 installFlags, packageAbiOverride); 16341 } catch (InstallerException e) { 16342 Slog.w(TAG, "Failed to free cache", e); 16343 } 16344 16345 /* 16346 * The cache free must have deleted the file we 16347 * downloaded to install. 16348 * 16349 * TODO: fix the "freeCache" call to not delete 16350 * the file we care about. 16351 */ 16352 if (pkgLite.recommendedInstallLocation 16353 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 16354 pkgLite.recommendedInstallLocation 16355 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 16356 } 16357 } 16358 } 16359 16360 if (ret == PackageManager.INSTALL_SUCCEEDED) { 16361 int loc = pkgLite.recommendedInstallLocation; 16362 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 16363 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 16364 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 16365 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 16366 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 16367 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 16368 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 16369 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 16370 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 16371 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 16372 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 16373 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 16374 } else { 16375 // Override with defaults if needed. 16376 loc = installLocationPolicy(pkgLite); 16377 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 16378 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 16379 } else if (!onSd && !onInt) { 16380 // Override install location with flags 16381 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 16382 // Set the flag to install on external media. 16383 installFlags |= PackageManager.INSTALL_EXTERNAL; 16384 installFlags &= ~PackageManager.INSTALL_INTERNAL; 16385 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 16386 if (DEBUG_EPHEMERAL) { 16387 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 16388 } 16389 installFlags |= PackageManager.INSTALL_INSTANT_APP; 16390 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 16391 |PackageManager.INSTALL_INTERNAL); 16392 } else { 16393 // Make sure the flag for installing on external 16394 // media is unset 16395 installFlags |= PackageManager.INSTALL_INTERNAL; 16396 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 16397 } 16398 } 16399 } 16400 } 16401 16402 final InstallArgs args = createInstallArgs(this); 16403 mArgs = args; 16404 16405 if (ret == PackageManager.INSTALL_SUCCEEDED) { 16406 // TODO: http://b/22976637 16407 // Apps installed for "all" users use the device owner to verify the app 16408 UserHandle verifierUser = getUser(); 16409 if (verifierUser == UserHandle.ALL) { 16410 verifierUser = UserHandle.SYSTEM; 16411 } 16412 16413 /* 16414 * Determine if we have any installed package verifiers. If we 16415 * do, then we'll defer to them to verify the packages. 16416 */ 16417 final int requiredUid = mRequiredVerifierPackage == null ? -1 16418 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16419 verifierUser.getIdentifier()); 16420 final int installerUid = 16421 verificationInfo == null ? -1 : verificationInfo.installerUid; 16422 if (!origin.existing && requiredUid != -1 16423 && isVerificationEnabled( 16424 verifierUser.getIdentifier(), installFlags, installerUid)) { 16425 final Intent verification = new Intent( 16426 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 16427 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 16428 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 16429 PACKAGE_MIME_TYPE); 16430 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 16431 16432 // Query all live verifiers based on current user state 16433 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 16434 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 16435 false /*allowDynamicSplits*/); 16436 16437 if (DEBUG_VERIFY) { 16438 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 16439 + verification.toString() + " with " + pkgLite.verifiers.length 16440 + " optional verifiers"); 16441 } 16442 16443 final int verificationId = mPendingVerificationToken++; 16444 16445 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 16446 16447 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 16448 installerPackageName); 16449 16450 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 16451 installFlags); 16452 16453 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 16454 pkgLite.packageName); 16455 16456 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 16457 pkgLite.versionCode); 16458 16459 if (verificationInfo != null) { 16460 if (verificationInfo.originatingUri != null) { 16461 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 16462 verificationInfo.originatingUri); 16463 } 16464 if (verificationInfo.referrer != null) { 16465 verification.putExtra(Intent.EXTRA_REFERRER, 16466 verificationInfo.referrer); 16467 } 16468 if (verificationInfo.originatingUid >= 0) { 16469 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 16470 verificationInfo.originatingUid); 16471 } 16472 if (verificationInfo.installerUid >= 0) { 16473 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 16474 verificationInfo.installerUid); 16475 } 16476 } 16477 16478 final PackageVerificationState verificationState = new PackageVerificationState( 16479 requiredUid, args); 16480 16481 mPendingVerification.append(verificationId, verificationState); 16482 16483 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 16484 receivers, verificationState); 16485 16486 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 16487 final long idleDuration = getVerificationTimeout(); 16488 16489 /* 16490 * If any sufficient verifiers were listed in the package 16491 * manifest, attempt to ask them. 16492 */ 16493 if (sufficientVerifiers != null) { 16494 final int N = sufficientVerifiers.size(); 16495 if (N == 0) { 16496 Slog.i(TAG, "Additional verifiers required, but none installed."); 16497 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 16498 } else { 16499 for (int i = 0; i < N; i++) { 16500 final ComponentName verifierComponent = sufficientVerifiers.get(i); 16501 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 16502 verifierComponent.getPackageName(), idleDuration, 16503 verifierUser.getIdentifier(), false, "package verifier"); 16504 16505 final Intent sufficientIntent = new Intent(verification); 16506 sufficientIntent.setComponent(verifierComponent); 16507 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 16508 } 16509 } 16510 } 16511 16512 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 16513 mRequiredVerifierPackage, receivers); 16514 if (ret == PackageManager.INSTALL_SUCCEEDED 16515 && mRequiredVerifierPackage != null) { 16516 Trace.asyncTraceBegin( 16517 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 16518 /* 16519 * Send the intent to the required verification agent, 16520 * but only start the verification timeout after the 16521 * target BroadcastReceivers have run. 16522 */ 16523 verification.setComponent(requiredVerifierComponent); 16524 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 16525 mRequiredVerifierPackage, idleDuration, 16526 verifierUser.getIdentifier(), false, "package verifier"); 16527 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 16528 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16529 new BroadcastReceiver() { 16530 @Override 16531 public void onReceive(Context context, Intent intent) { 16532 final Message msg = mHandler 16533 .obtainMessage(CHECK_PENDING_VERIFICATION); 16534 msg.arg1 = verificationId; 16535 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 16536 } 16537 }, null, 0, null, null); 16538 16539 /* 16540 * We don't want the copy to proceed until verification 16541 * succeeds, so null out this field. 16542 */ 16543 mArgs = null; 16544 } 16545 } else { 16546 /* 16547 * No package verification is enabled, so immediately start 16548 * the remote call to initiate copy using temporary file. 16549 */ 16550 ret = args.copyApk(mContainerService, true); 16551 } 16552 } 16553 16554 mRet = ret; 16555 } 16556 16557 @Override 16558 void handleReturnCode() { 16559 // If mArgs is null, then MCS couldn't be reached. When it 16560 // reconnects, it will try again to install. At that point, this 16561 // will succeed. 16562 if (mArgs != null) { 16563 processPendingInstall(mArgs, mRet); 16564 } 16565 } 16566 16567 @Override 16568 void handleServiceError() { 16569 mArgs = createInstallArgs(this); 16570 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 16571 } 16572 16573 public boolean isForwardLocked() { 16574 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 16575 } 16576 } 16577 16578 /** 16579 * Used during creation of InstallArgs 16580 * 16581 * @param installFlags package installation flags 16582 * @return true if should be installed on external storage 16583 */ 16584 private static boolean installOnExternalAsec(int installFlags) { 16585 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 16586 return false; 16587 } 16588 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 16589 return true; 16590 } 16591 return false; 16592 } 16593 16594 /** 16595 * Used during creation of InstallArgs 16596 * 16597 * @param installFlags package installation flags 16598 * @return true if should be installed as forward locked 16599 */ 16600 private static boolean installForwardLocked(int installFlags) { 16601 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 16602 } 16603 16604 private InstallArgs createInstallArgs(InstallParams params) { 16605 if (params.move != null) { 16606 return new MoveInstallArgs(params); 16607 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 16608 return new AsecInstallArgs(params); 16609 } else { 16610 return new FileInstallArgs(params); 16611 } 16612 } 16613 16614 /** 16615 * Create args that describe an existing installed package. Typically used 16616 * when cleaning up old installs, or used as a move source. 16617 */ 16618 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 16619 String resourcePath, String[] instructionSets) { 16620 final boolean isInAsec; 16621 if (installOnExternalAsec(installFlags)) { 16622 /* Apps on SD card are always in ASEC containers. */ 16623 isInAsec = true; 16624 } else if (installForwardLocked(installFlags) 16625 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 16626 /* 16627 * Forward-locked apps are only in ASEC containers if they're the 16628 * new style 16629 */ 16630 isInAsec = true; 16631 } else { 16632 isInAsec = false; 16633 } 16634 16635 if (isInAsec) { 16636 return new AsecInstallArgs(codePath, instructionSets, 16637 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 16638 } else { 16639 return new FileInstallArgs(codePath, resourcePath, instructionSets); 16640 } 16641 } 16642 16643 static abstract class InstallArgs { 16644 /** @see InstallParams#origin */ 16645 final OriginInfo origin; 16646 /** @see InstallParams#move */ 16647 final MoveInfo move; 16648 16649 final IPackageInstallObserver2 observer; 16650 // Always refers to PackageManager flags only 16651 final int installFlags; 16652 final String installerPackageName; 16653 final String volumeUuid; 16654 final UserHandle user; 16655 final String abiOverride; 16656 final String[] installGrantPermissions; 16657 /** If non-null, drop an async trace when the install completes */ 16658 final String traceMethod; 16659 final int traceCookie; 16660 final Certificate[][] certificates; 16661 final int installReason; 16662 16663 // The list of instruction sets supported by this app. This is currently 16664 // only used during the rmdex() phase to clean up resources. We can get rid of this 16665 // if we move dex files under the common app path. 16666 /* nullable */ String[] instructionSets; 16667 16668 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 16669 int installFlags, String installerPackageName, String volumeUuid, 16670 UserHandle user, String[] instructionSets, 16671 String abiOverride, String[] installGrantPermissions, 16672 String traceMethod, int traceCookie, Certificate[][] certificates, 16673 int installReason) { 16674 this.origin = origin; 16675 this.move = move; 16676 this.installFlags = installFlags; 16677 this.observer = observer; 16678 this.installerPackageName = installerPackageName; 16679 this.volumeUuid = volumeUuid; 16680 this.user = user; 16681 this.instructionSets = instructionSets; 16682 this.abiOverride = abiOverride; 16683 this.installGrantPermissions = installGrantPermissions; 16684 this.traceMethod = traceMethod; 16685 this.traceCookie = traceCookie; 16686 this.certificates = certificates; 16687 this.installReason = installReason; 16688 } 16689 16690 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 16691 abstract int doPreInstall(int status); 16692 16693 /** 16694 * Rename package into final resting place. All paths on the given 16695 * scanned package should be updated to reflect the rename. 16696 */ 16697 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 16698 abstract int doPostInstall(int status, int uid); 16699 16700 /** @see PackageSettingBase#codePathString */ 16701 abstract String getCodePath(); 16702 /** @see PackageSettingBase#resourcePathString */ 16703 abstract String getResourcePath(); 16704 16705 // Need installer lock especially for dex file removal. 16706 abstract void cleanUpResourcesLI(); 16707 abstract boolean doPostDeleteLI(boolean delete); 16708 16709 /** 16710 * Called before the source arguments are copied. This is used mostly 16711 * for MoveParams when it needs to read the source file to put it in the 16712 * destination. 16713 */ 16714 int doPreCopy() { 16715 return PackageManager.INSTALL_SUCCEEDED; 16716 } 16717 16718 /** 16719 * Called after the source arguments are copied. This is used mostly for 16720 * MoveParams when it needs to read the source file to put it in the 16721 * destination. 16722 */ 16723 int doPostCopy(int uid) { 16724 return PackageManager.INSTALL_SUCCEEDED; 16725 } 16726 16727 protected boolean isFwdLocked() { 16728 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 16729 } 16730 16731 protected boolean isExternalAsec() { 16732 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 16733 } 16734 16735 protected boolean isEphemeral() { 16736 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 16737 } 16738 16739 UserHandle getUser() { 16740 return user; 16741 } 16742 } 16743 16744 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 16745 if (!allCodePaths.isEmpty()) { 16746 if (instructionSets == null) { 16747 throw new IllegalStateException("instructionSet == null"); 16748 } 16749 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 16750 for (String codePath : allCodePaths) { 16751 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 16752 try { 16753 mInstaller.rmdex(codePath, dexCodeInstructionSet); 16754 } catch (InstallerException ignored) { 16755 } 16756 } 16757 } 16758 } 16759 } 16760 16761 /** 16762 * Logic to handle installation of non-ASEC applications, including copying 16763 * and renaming logic. 16764 */ 16765 class FileInstallArgs extends InstallArgs { 16766 private File codeFile; 16767 private File resourceFile; 16768 16769 // Example topology: 16770 // /data/app/com.example/base.apk 16771 // /data/app/com.example/split_foo.apk 16772 // /data/app/com.example/lib/arm/libfoo.so 16773 // /data/app/com.example/lib/arm64/libfoo.so 16774 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 16775 16776 /** New install */ 16777 FileInstallArgs(InstallParams params) { 16778 super(params.origin, params.move, params.observer, params.installFlags, 16779 params.installerPackageName, params.volumeUuid, 16780 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 16781 params.grantedRuntimePermissions, 16782 params.traceMethod, params.traceCookie, params.certificates, 16783 params.installReason); 16784 if (isFwdLocked()) { 16785 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 16786 } 16787 } 16788 16789 /** Existing install */ 16790 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 16791 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 16792 null, null, null, 0, null /*certificates*/, 16793 PackageManager.INSTALL_REASON_UNKNOWN); 16794 this.codeFile = (codePath != null) ? new File(codePath) : null; 16795 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 16796 } 16797 16798 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 16799 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 16800 try { 16801 return doCopyApk(imcs, temp); 16802 } finally { 16803 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16804 } 16805 } 16806 16807 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 16808 if (origin.staged) { 16809 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 16810 codeFile = origin.file; 16811 resourceFile = origin.file; 16812 return PackageManager.INSTALL_SUCCEEDED; 16813 } 16814 16815 try { 16816 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 16817 final File tempDir = 16818 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 16819 codeFile = tempDir; 16820 resourceFile = tempDir; 16821 } catch (IOException e) { 16822 Slog.w(TAG, "Failed to create copy file: " + e); 16823 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 16824 } 16825 16826 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 16827 @Override 16828 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 16829 if (!FileUtils.isValidExtFilename(name)) { 16830 throw new IllegalArgumentException("Invalid filename: " + name); 16831 } 16832 try { 16833 final File file = new File(codeFile, name); 16834 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 16835 O_RDWR | O_CREAT, 0644); 16836 Os.chmod(file.getAbsolutePath(), 0644); 16837 return new ParcelFileDescriptor(fd); 16838 } catch (ErrnoException e) { 16839 throw new RemoteException("Failed to open: " + e.getMessage()); 16840 } 16841 } 16842 }; 16843 16844 int ret = PackageManager.INSTALL_SUCCEEDED; 16845 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 16846 if (ret != PackageManager.INSTALL_SUCCEEDED) { 16847 Slog.e(TAG, "Failed to copy package"); 16848 return ret; 16849 } 16850 16851 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 16852 NativeLibraryHelper.Handle handle = null; 16853 try { 16854 handle = NativeLibraryHelper.Handle.create(codeFile); 16855 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 16856 abiOverride); 16857 } catch (IOException e) { 16858 Slog.e(TAG, "Copying native libraries failed", e); 16859 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 16860 } finally { 16861 IoUtils.closeQuietly(handle); 16862 } 16863 16864 return ret; 16865 } 16866 16867 int doPreInstall(int status) { 16868 if (status != PackageManager.INSTALL_SUCCEEDED) { 16869 cleanUp(); 16870 } 16871 return status; 16872 } 16873 16874 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 16875 if (status != PackageManager.INSTALL_SUCCEEDED) { 16876 cleanUp(); 16877 return false; 16878 } 16879 16880 final File targetDir = codeFile.getParentFile(); 16881 final File beforeCodeFile = codeFile; 16882 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 16883 16884 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 16885 try { 16886 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 16887 } catch (ErrnoException e) { 16888 Slog.w(TAG, "Failed to rename", e); 16889 return false; 16890 } 16891 16892 if (!SELinux.restoreconRecursive(afterCodeFile)) { 16893 Slog.w(TAG, "Failed to restorecon"); 16894 return false; 16895 } 16896 16897 // Reflect the rename internally 16898 codeFile = afterCodeFile; 16899 resourceFile = afterCodeFile; 16900 16901 // Reflect the rename in scanned details 16902 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 16903 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 16904 afterCodeFile, pkg.baseCodePath)); 16905 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 16906 afterCodeFile, pkg.splitCodePaths)); 16907 16908 // Reflect the rename in app info 16909 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 16910 pkg.setApplicationInfoCodePath(pkg.codePath); 16911 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 16912 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 16913 pkg.setApplicationInfoResourcePath(pkg.codePath); 16914 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 16915 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 16916 16917 return true; 16918 } 16919 16920 int doPostInstall(int status, int uid) { 16921 if (status != PackageManager.INSTALL_SUCCEEDED) { 16922 cleanUp(); 16923 } 16924 return status; 16925 } 16926 16927 @Override 16928 String getCodePath() { 16929 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 16930 } 16931 16932 @Override 16933 String getResourcePath() { 16934 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 16935 } 16936 16937 private boolean cleanUp() { 16938 if (codeFile == null || !codeFile.exists()) { 16939 return false; 16940 } 16941 16942 removeCodePathLI(codeFile); 16943 16944 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 16945 resourceFile.delete(); 16946 } 16947 16948 return true; 16949 } 16950 16951 void cleanUpResourcesLI() { 16952 // Try enumerating all code paths before deleting 16953 List<String> allCodePaths = Collections.EMPTY_LIST; 16954 if (codeFile != null && codeFile.exists()) { 16955 try { 16956 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 16957 allCodePaths = pkg.getAllCodePaths(); 16958 } catch (PackageParserException e) { 16959 // Ignored; we tried our best 16960 } 16961 } 16962 16963 cleanUp(); 16964 removeDexFiles(allCodePaths, instructionSets); 16965 } 16966 16967 boolean doPostDeleteLI(boolean delete) { 16968 // XXX err, shouldn't we respect the delete flag? 16969 cleanUpResourcesLI(); 16970 return true; 16971 } 16972 } 16973 16974 private boolean isAsecExternal(String cid) { 16975 final String asecPath = PackageHelper.getSdFilesystem(cid); 16976 return !asecPath.startsWith(mAsecInternalPath); 16977 } 16978 16979 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 16980 PackageManagerException { 16981 if (copyRet < 0) { 16982 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 16983 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 16984 throw new PackageManagerException(copyRet, message); 16985 } 16986 } 16987 } 16988 16989 /** 16990 * Extract the StorageManagerService "container ID" from the full code path of an 16991 * .apk. 16992 */ 16993 static String cidFromCodePath(String fullCodePath) { 16994 int eidx = fullCodePath.lastIndexOf("/"); 16995 String subStr1 = fullCodePath.substring(0, eidx); 16996 int sidx = subStr1.lastIndexOf("/"); 16997 return subStr1.substring(sidx+1, eidx); 16998 } 16999 17000 /** 17001 * Logic to handle installation of ASEC applications, including copying and 17002 * renaming logic. 17003 */ 17004 class AsecInstallArgs extends InstallArgs { 17005 static final String RES_FILE_NAME = "pkg.apk"; 17006 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 17007 17008 String cid; 17009 String packagePath; 17010 String resourcePath; 17011 17012 /** New install */ 17013 AsecInstallArgs(InstallParams params) { 17014 super(params.origin, params.move, params.observer, params.installFlags, 17015 params.installerPackageName, params.volumeUuid, 17016 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 17017 params.grantedRuntimePermissions, 17018 params.traceMethod, params.traceCookie, params.certificates, 17019 params.installReason); 17020 } 17021 17022 /** Existing install */ 17023 AsecInstallArgs(String fullCodePath, String[] instructionSets, 17024 boolean isExternal, boolean isForwardLocked) { 17025 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 17026 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 17027 instructionSets, null, null, null, 0, null /*certificates*/, 17028 PackageManager.INSTALL_REASON_UNKNOWN); 17029 // Hackily pretend we're still looking at a full code path 17030 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 17031 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 17032 } 17033 17034 // Extract cid from fullCodePath 17035 int eidx = fullCodePath.lastIndexOf("/"); 17036 String subStr1 = fullCodePath.substring(0, eidx); 17037 int sidx = subStr1.lastIndexOf("/"); 17038 cid = subStr1.substring(sidx+1, eidx); 17039 setMountPath(subStr1); 17040 } 17041 17042 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 17043 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 17044 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 17045 instructionSets, null, null, null, 0, null /*certificates*/, 17046 PackageManager.INSTALL_REASON_UNKNOWN); 17047 this.cid = cid; 17048 setMountPath(PackageHelper.getSdDir(cid)); 17049 } 17050 17051 void createCopyFile() { 17052 cid = mInstallerService.allocateExternalStageCidLegacy(); 17053 } 17054 17055 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 17056 if (origin.staged && origin.cid != null) { 17057 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 17058 cid = origin.cid; 17059 setMountPath(PackageHelper.getSdDir(cid)); 17060 return PackageManager.INSTALL_SUCCEEDED; 17061 } 17062 17063 if (temp) { 17064 createCopyFile(); 17065 } else { 17066 /* 17067 * Pre-emptively destroy the container since it's destroyed if 17068 * copying fails due to it existing anyway. 17069 */ 17070 PackageHelper.destroySdDir(cid); 17071 } 17072 17073 final String newMountPath = imcs.copyPackageToContainer( 17074 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 17075 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 17076 17077 if (newMountPath != null) { 17078 setMountPath(newMountPath); 17079 return PackageManager.INSTALL_SUCCEEDED; 17080 } else { 17081 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17082 } 17083 } 17084 17085 @Override 17086 String getCodePath() { 17087 return packagePath; 17088 } 17089 17090 @Override 17091 String getResourcePath() { 17092 return resourcePath; 17093 } 17094 17095 int doPreInstall(int status) { 17096 if (status != PackageManager.INSTALL_SUCCEEDED) { 17097 // Destroy container 17098 PackageHelper.destroySdDir(cid); 17099 } else { 17100 boolean mounted = PackageHelper.isContainerMounted(cid); 17101 if (!mounted) { 17102 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 17103 Process.SYSTEM_UID); 17104 if (newMountPath != null) { 17105 setMountPath(newMountPath); 17106 } else { 17107 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17108 } 17109 } 17110 } 17111 return status; 17112 } 17113 17114 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 17115 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 17116 String newMountPath = null; 17117 if (PackageHelper.isContainerMounted(cid)) { 17118 // Unmount the container 17119 if (!PackageHelper.unMountSdDir(cid)) { 17120 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 17121 return false; 17122 } 17123 } 17124 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 17125 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 17126 " which might be stale. Will try to clean up."); 17127 // Clean up the stale container and proceed to recreate. 17128 if (!PackageHelper.destroySdDir(newCacheId)) { 17129 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 17130 return false; 17131 } 17132 // Successfully cleaned up stale container. Try to rename again. 17133 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 17134 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 17135 + " inspite of cleaning it up."); 17136 return false; 17137 } 17138 } 17139 if (!PackageHelper.isContainerMounted(newCacheId)) { 17140 Slog.w(TAG, "Mounting container " + newCacheId); 17141 newMountPath = PackageHelper.mountSdDir(newCacheId, 17142 getEncryptKey(), Process.SYSTEM_UID); 17143 } else { 17144 newMountPath = PackageHelper.getSdDir(newCacheId); 17145 } 17146 if (newMountPath == null) { 17147 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 17148 return false; 17149 } 17150 Log.i(TAG, "Succesfully renamed " + cid + 17151 " to " + newCacheId + 17152 " at new path: " + newMountPath); 17153 cid = newCacheId; 17154 17155 final File beforeCodeFile = new File(packagePath); 17156 setMountPath(newMountPath); 17157 final File afterCodeFile = new File(packagePath); 17158 17159 // Reflect the rename in scanned details 17160 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 17161 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 17162 afterCodeFile, pkg.baseCodePath)); 17163 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 17164 afterCodeFile, pkg.splitCodePaths)); 17165 17166 // Reflect the rename in app info 17167 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 17168 pkg.setApplicationInfoCodePath(pkg.codePath); 17169 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 17170 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 17171 pkg.setApplicationInfoResourcePath(pkg.codePath); 17172 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 17173 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 17174 17175 return true; 17176 } 17177 17178 private void setMountPath(String mountPath) { 17179 final File mountFile = new File(mountPath); 17180 17181 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 17182 if (monolithicFile.exists()) { 17183 packagePath = monolithicFile.getAbsolutePath(); 17184 if (isFwdLocked()) { 17185 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 17186 } else { 17187 resourcePath = packagePath; 17188 } 17189 } else { 17190 packagePath = mountFile.getAbsolutePath(); 17191 resourcePath = packagePath; 17192 } 17193 } 17194 17195 int doPostInstall(int status, int uid) { 17196 if (status != PackageManager.INSTALL_SUCCEEDED) { 17197 cleanUp(); 17198 } else { 17199 final int groupOwner; 17200 final String protectedFile; 17201 if (isFwdLocked()) { 17202 groupOwner = UserHandle.getSharedAppGid(uid); 17203 protectedFile = RES_FILE_NAME; 17204 } else { 17205 groupOwner = -1; 17206 protectedFile = null; 17207 } 17208 17209 if (uid < Process.FIRST_APPLICATION_UID 17210 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 17211 Slog.e(TAG, "Failed to finalize " + cid); 17212 PackageHelper.destroySdDir(cid); 17213 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17214 } 17215 17216 boolean mounted = PackageHelper.isContainerMounted(cid); 17217 if (!mounted) { 17218 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 17219 } 17220 } 17221 return status; 17222 } 17223 17224 private void cleanUp() { 17225 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 17226 17227 // Destroy secure container 17228 PackageHelper.destroySdDir(cid); 17229 } 17230 17231 private List<String> getAllCodePaths() { 17232 final File codeFile = new File(getCodePath()); 17233 if (codeFile != null && codeFile.exists()) { 17234 try { 17235 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 17236 return pkg.getAllCodePaths(); 17237 } catch (PackageParserException e) { 17238 // Ignored; we tried our best 17239 } 17240 } 17241 return Collections.EMPTY_LIST; 17242 } 17243 17244 void cleanUpResourcesLI() { 17245 // Enumerate all code paths before deleting 17246 cleanUpResourcesLI(getAllCodePaths()); 17247 } 17248 17249 private void cleanUpResourcesLI(List<String> allCodePaths) { 17250 cleanUp(); 17251 removeDexFiles(allCodePaths, instructionSets); 17252 } 17253 17254 String getPackageName() { 17255 return getAsecPackageName(cid); 17256 } 17257 17258 boolean doPostDeleteLI(boolean delete) { 17259 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 17260 final List<String> allCodePaths = getAllCodePaths(); 17261 boolean mounted = PackageHelper.isContainerMounted(cid); 17262 if (mounted) { 17263 // Unmount first 17264 if (PackageHelper.unMountSdDir(cid)) { 17265 mounted = false; 17266 } 17267 } 17268 if (!mounted && delete) { 17269 cleanUpResourcesLI(allCodePaths); 17270 } 17271 return !mounted; 17272 } 17273 17274 @Override 17275 int doPreCopy() { 17276 if (isFwdLocked()) { 17277 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 17278 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 17279 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17280 } 17281 } 17282 17283 return PackageManager.INSTALL_SUCCEEDED; 17284 } 17285 17286 @Override 17287 int doPostCopy(int uid) { 17288 if (isFwdLocked()) { 17289 if (uid < Process.FIRST_APPLICATION_UID 17290 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 17291 RES_FILE_NAME)) { 17292 Slog.e(TAG, "Failed to finalize " + cid); 17293 PackageHelper.destroySdDir(cid); 17294 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17295 } 17296 } 17297 17298 return PackageManager.INSTALL_SUCCEEDED; 17299 } 17300 } 17301 17302 /** 17303 * Logic to handle movement of existing installed applications. 17304 */ 17305 class MoveInstallArgs extends InstallArgs { 17306 private File codeFile; 17307 private File resourceFile; 17308 17309 /** New install */ 17310 MoveInstallArgs(InstallParams params) { 17311 super(params.origin, params.move, params.observer, params.installFlags, 17312 params.installerPackageName, params.volumeUuid, 17313 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 17314 params.grantedRuntimePermissions, 17315 params.traceMethod, params.traceCookie, params.certificates, 17316 params.installReason); 17317 } 17318 17319 int copyApk(IMediaContainerService imcs, boolean temp) { 17320 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 17321 + move.fromUuid + " to " + move.toUuid); 17322 synchronized (mInstaller) { 17323 try { 17324 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 17325 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 17326 } catch (InstallerException e) { 17327 Slog.w(TAG, "Failed to move app", e); 17328 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 17329 } 17330 } 17331 17332 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 17333 resourceFile = codeFile; 17334 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 17335 17336 return PackageManager.INSTALL_SUCCEEDED; 17337 } 17338 17339 int doPreInstall(int status) { 17340 if (status != PackageManager.INSTALL_SUCCEEDED) { 17341 cleanUp(move.toUuid); 17342 } 17343 return status; 17344 } 17345 17346 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 17347 if (status != PackageManager.INSTALL_SUCCEEDED) { 17348 cleanUp(move.toUuid); 17349 return false; 17350 } 17351 17352 // Reflect the move in app info 17353 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 17354 pkg.setApplicationInfoCodePath(pkg.codePath); 17355 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 17356 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 17357 pkg.setApplicationInfoResourcePath(pkg.codePath); 17358 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 17359 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 17360 17361 return true; 17362 } 17363 17364 int doPostInstall(int status, int uid) { 17365 if (status == PackageManager.INSTALL_SUCCEEDED) { 17366 cleanUp(move.fromUuid); 17367 } else { 17368 cleanUp(move.toUuid); 17369 } 17370 return status; 17371 } 17372 17373 @Override 17374 String getCodePath() { 17375 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 17376 } 17377 17378 @Override 17379 String getResourcePath() { 17380 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 17381 } 17382 17383 private boolean cleanUp(String volumeUuid) { 17384 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 17385 move.dataAppName); 17386 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 17387 final int[] userIds = sUserManager.getUserIds(); 17388 synchronized (mInstallLock) { 17389 // Clean up both app data and code 17390 // All package moves are frozen until finished 17391 for (int userId : userIds) { 17392 try { 17393 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 17394 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 17395 } catch (InstallerException e) { 17396 Slog.w(TAG, String.valueOf(e)); 17397 } 17398 } 17399 removeCodePathLI(codeFile); 17400 } 17401 return true; 17402 } 17403 17404 void cleanUpResourcesLI() { 17405 throw new UnsupportedOperationException(); 17406 } 17407 17408 boolean doPostDeleteLI(boolean delete) { 17409 throw new UnsupportedOperationException(); 17410 } 17411 } 17412 17413 static String getAsecPackageName(String packageCid) { 17414 int idx = packageCid.lastIndexOf("-"); 17415 if (idx == -1) { 17416 return packageCid; 17417 } 17418 return packageCid.substring(0, idx); 17419 } 17420 17421 // Utility method used to create code paths based on package name and available index. 17422 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 17423 String idxStr = ""; 17424 int idx = 1; 17425 // Fall back to default value of idx=1 if prefix is not 17426 // part of oldCodePath 17427 if (oldCodePath != null) { 17428 String subStr = oldCodePath; 17429 // Drop the suffix right away 17430 if (suffix != null && subStr.endsWith(suffix)) { 17431 subStr = subStr.substring(0, subStr.length() - suffix.length()); 17432 } 17433 // If oldCodePath already contains prefix find out the 17434 // ending index to either increment or decrement. 17435 int sidx = subStr.lastIndexOf(prefix); 17436 if (sidx != -1) { 17437 subStr = subStr.substring(sidx + prefix.length()); 17438 if (subStr != null) { 17439 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 17440 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 17441 } 17442 try { 17443 idx = Integer.parseInt(subStr); 17444 if (idx <= 1) { 17445 idx++; 17446 } else { 17447 idx--; 17448 } 17449 } catch(NumberFormatException e) { 17450 } 17451 } 17452 } 17453 } 17454 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 17455 return prefix + idxStr; 17456 } 17457 17458 private File getNextCodePath(File targetDir, String packageName) { 17459 File result; 17460 SecureRandom random = new SecureRandom(); 17461 byte[] bytes = new byte[16]; 17462 do { 17463 random.nextBytes(bytes); 17464 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 17465 result = new File(targetDir, packageName + "-" + suffix); 17466 } while (result.exists()); 17467 return result; 17468 } 17469 17470 // Utility method that returns the relative package path with respect 17471 // to the installation directory. Like say for /data/data/com.test-1.apk 17472 // string com.test-1 is returned. 17473 static String deriveCodePathName(String codePath) { 17474 if (codePath == null) { 17475 return null; 17476 } 17477 final File codeFile = new File(codePath); 17478 final String name = codeFile.getName(); 17479 if (codeFile.isDirectory()) { 17480 return name; 17481 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 17482 final int lastDot = name.lastIndexOf('.'); 17483 return name.substring(0, lastDot); 17484 } else { 17485 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 17486 return null; 17487 } 17488 } 17489 17490 static class PackageInstalledInfo { 17491 String name; 17492 int uid; 17493 // The set of users that originally had this package installed. 17494 int[] origUsers; 17495 // The set of users that now have this package installed. 17496 int[] newUsers; 17497 PackageParser.Package pkg; 17498 int returnCode; 17499 String returnMsg; 17500 String installerPackageName; 17501 PackageRemovedInfo removedInfo; 17502 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 17503 17504 public void setError(int code, String msg) { 17505 setReturnCode(code); 17506 setReturnMessage(msg); 17507 Slog.w(TAG, msg); 17508 } 17509 17510 public void setError(String msg, PackageParserException e) { 17511 setReturnCode(e.error); 17512 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 17513 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 17514 for (int i = 0; i < childCount; i++) { 17515 addedChildPackages.valueAt(i).setError(msg, e); 17516 } 17517 Slog.w(TAG, msg, e); 17518 } 17519 17520 public void setError(String msg, PackageManagerException e) { 17521 returnCode = e.error; 17522 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 17523 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 17524 for (int i = 0; i < childCount; i++) { 17525 addedChildPackages.valueAt(i).setError(msg, e); 17526 } 17527 Slog.w(TAG, msg, e); 17528 } 17529 17530 public void setReturnCode(int returnCode) { 17531 this.returnCode = returnCode; 17532 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 17533 for (int i = 0; i < childCount; i++) { 17534 addedChildPackages.valueAt(i).returnCode = returnCode; 17535 } 17536 } 17537 17538 private void setReturnMessage(String returnMsg) { 17539 this.returnMsg = returnMsg; 17540 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 17541 for (int i = 0; i < childCount; i++) { 17542 addedChildPackages.valueAt(i).returnMsg = returnMsg; 17543 } 17544 } 17545 17546 // In some error cases we want to convey more info back to the observer 17547 String origPackage; 17548 String origPermission; 17549 } 17550 17551 /* 17552 * Install a non-existing package. 17553 */ 17554 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 17555 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 17556 PackageInstalledInfo res, int installReason) { 17557 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 17558 17559 // Remember this for later, in case we need to rollback this install 17560 String pkgName = pkg.packageName; 17561 17562 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 17563 17564 synchronized(mPackages) { 17565 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 17566 if (renamedPackage != null) { 17567 // A package with the same name is already installed, though 17568 // it has been renamed to an older name. The package we 17569 // are trying to install should be installed as an update to 17570 // the existing one, but that has not been requested, so bail. 17571 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 17572 + " without first uninstalling package running as " 17573 + renamedPackage); 17574 return; 17575 } 17576 if (mPackages.containsKey(pkgName)) { 17577 // Don't allow installation over an existing package with the same name. 17578 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 17579 + " without first uninstalling."); 17580 return; 17581 } 17582 } 17583 17584 try { 17585 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 17586 System.currentTimeMillis(), user); 17587 17588 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 17589 17590 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17591 prepareAppDataAfterInstallLIF(newPackage); 17592 17593 } else { 17594 // Remove package from internal structures, but keep around any 17595 // data that might have already existed 17596 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 17597 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 17598 } 17599 } catch (PackageManagerException e) { 17600 res.setError("Package couldn't be installed in " + pkg.codePath, e); 17601 } 17602 17603 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17604 } 17605 17606 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 17607 // Can't rotate keys during boot or if sharedUser. 17608 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 17609 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 17610 return false; 17611 } 17612 // app is using upgradeKeySets; make sure all are valid 17613 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17614 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 17615 for (int i = 0; i < upgradeKeySets.length; i++) { 17616 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 17617 Slog.wtf(TAG, "Package " 17618 + (oldPs.name != null ? oldPs.name : "<null>") 17619 + " contains upgrade-key-set reference to unknown key-set: " 17620 + upgradeKeySets[i] 17621 + " reverting to signatures check."); 17622 return false; 17623 } 17624 } 17625 return true; 17626 } 17627 17628 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 17629 // Upgrade keysets are being used. Determine if new package has a superset of the 17630 // required keys. 17631 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 17632 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17633 for (int i = 0; i < upgradeKeySets.length; i++) { 17634 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 17635 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 17636 return true; 17637 } 17638 } 17639 return false; 17640 } 17641 17642 private static void updateDigest(MessageDigest digest, File file) throws IOException { 17643 try (DigestInputStream digestStream = 17644 new DigestInputStream(new FileInputStream(file), digest)) { 17645 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 17646 } 17647 } 17648 17649 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 17650 UserHandle user, String installerPackageName, PackageInstalledInfo res, 17651 int installReason) { 17652 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 17653 17654 final PackageParser.Package oldPackage; 17655 final PackageSetting ps; 17656 final String pkgName = pkg.packageName; 17657 final int[] allUsers; 17658 final int[] installedUsers; 17659 17660 synchronized(mPackages) { 17661 oldPackage = mPackages.get(pkgName); 17662 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 17663 17664 // don't allow upgrade to target a release SDK from a pre-release SDK 17665 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 17666 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 17667 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 17668 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 17669 if (oldTargetsPreRelease 17670 && !newTargetsPreRelease 17671 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 17672 Slog.w(TAG, "Can't install package targeting released sdk"); 17673 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 17674 return; 17675 } 17676 17677 ps = mSettings.mPackages.get(pkgName); 17678 17679 // verify signatures are valid 17680 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 17681 if (!checkUpgradeKeySetLP(ps, pkg)) { 17682 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 17683 "New package not signed by keys specified by upgrade-keysets: " 17684 + pkgName); 17685 return; 17686 } 17687 } else { 17688 // default to original signature matching 17689 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 17690 != PackageManager.SIGNATURE_MATCH) { 17691 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 17692 "New package has a different signature: " + pkgName); 17693 return; 17694 } 17695 } 17696 17697 // don't allow a system upgrade unless the upgrade hash matches 17698 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 17699 byte[] digestBytes = null; 17700 try { 17701 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 17702 updateDigest(digest, new File(pkg.baseCodePath)); 17703 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 17704 for (String path : pkg.splitCodePaths) { 17705 updateDigest(digest, new File(path)); 17706 } 17707 } 17708 digestBytes = digest.digest(); 17709 } catch (NoSuchAlgorithmException | IOException e) { 17710 res.setError(INSTALL_FAILED_INVALID_APK, 17711 "Could not compute hash: " + pkgName); 17712 return; 17713 } 17714 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 17715 res.setError(INSTALL_FAILED_INVALID_APK, 17716 "New package fails restrict-update check: " + pkgName); 17717 return; 17718 } 17719 // retain upgrade restriction 17720 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 17721 } 17722 17723 // Check for shared user id changes 17724 String invalidPackageName = 17725 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 17726 if (invalidPackageName != null) { 17727 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 17728 "Package " + invalidPackageName + " tried to change user " 17729 + oldPackage.mSharedUserId); 17730 return; 17731 } 17732 17733 // In case of rollback, remember per-user/profile install state 17734 allUsers = sUserManager.getUserIds(); 17735 installedUsers = ps.queryInstalledUsers(allUsers, true); 17736 17737 // don't allow an upgrade from full to ephemeral 17738 if (isInstantApp) { 17739 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 17740 for (int currentUser : allUsers) { 17741 if (!ps.getInstantApp(currentUser)) { 17742 // can't downgrade from full to instant 17743 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 17744 + " for user: " + currentUser); 17745 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17746 return; 17747 } 17748 } 17749 } else if (!ps.getInstantApp(user.getIdentifier())) { 17750 // can't downgrade from full to instant 17751 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 17752 + " for user: " + user.getIdentifier()); 17753 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17754 return; 17755 } 17756 } 17757 } 17758 17759 // Update what is removed 17760 res.removedInfo = new PackageRemovedInfo(this); 17761 res.removedInfo.uid = oldPackage.applicationInfo.uid; 17762 res.removedInfo.removedPackage = oldPackage.packageName; 17763 res.removedInfo.installerPackageName = ps.installerPackageName; 17764 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 17765 res.removedInfo.isUpdate = true; 17766 res.removedInfo.origUsers = installedUsers; 17767 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 17768 for (int i = 0; i < installedUsers.length; i++) { 17769 final int userId = installedUsers[i]; 17770 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 17771 } 17772 17773 final int childCount = (oldPackage.childPackages != null) 17774 ? oldPackage.childPackages.size() : 0; 17775 for (int i = 0; i < childCount; i++) { 17776 boolean childPackageUpdated = false; 17777 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 17778 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17779 if (res.addedChildPackages != null) { 17780 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17781 if (childRes != null) { 17782 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 17783 childRes.removedInfo.removedPackage = childPkg.packageName; 17784 if (childPs != null) { 17785 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 17786 } 17787 childRes.removedInfo.isUpdate = true; 17788 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 17789 childPackageUpdated = true; 17790 } 17791 } 17792 if (!childPackageUpdated) { 17793 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 17794 childRemovedRes.removedPackage = childPkg.packageName; 17795 if (childPs != null) { 17796 childRemovedRes.installerPackageName = childPs.installerPackageName; 17797 } 17798 childRemovedRes.isUpdate = false; 17799 childRemovedRes.dataRemoved = true; 17800 synchronized (mPackages) { 17801 if (childPs != null) { 17802 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 17803 } 17804 } 17805 if (res.removedInfo.removedChildPackages == null) { 17806 res.removedInfo.removedChildPackages = new ArrayMap<>(); 17807 } 17808 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 17809 } 17810 } 17811 17812 boolean sysPkg = (isSystemApp(oldPackage)); 17813 if (sysPkg) { 17814 // Set the system/privileged flags as needed 17815 final boolean privileged = 17816 (oldPackage.applicationInfo.privateFlags 17817 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17818 final int systemPolicyFlags = policyFlags 17819 | PackageParser.PARSE_IS_SYSTEM 17820 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 17821 17822 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 17823 user, allUsers, installerPackageName, res, installReason); 17824 } else { 17825 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 17826 user, allUsers, installerPackageName, res, installReason); 17827 } 17828 } 17829 17830 @Override 17831 public List<String> getPreviousCodePaths(String packageName) { 17832 final int callingUid = Binder.getCallingUid(); 17833 final List<String> result = new ArrayList<>(); 17834 if (getInstantAppPackageName(callingUid) != null) { 17835 return result; 17836 } 17837 final PackageSetting ps = mSettings.mPackages.get(packageName); 17838 if (ps != null 17839 && ps.oldCodePaths != null 17840 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 17841 result.addAll(ps.oldCodePaths); 17842 } 17843 return result; 17844 } 17845 17846 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 17847 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 17848 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 17849 int installReason) { 17850 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 17851 + deletedPackage); 17852 17853 String pkgName = deletedPackage.packageName; 17854 boolean deletedPkg = true; 17855 boolean addedPkg = false; 17856 boolean updatedSettings = false; 17857 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 17858 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 17859 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 17860 17861 final long origUpdateTime = (pkg.mExtras != null) 17862 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 17863 17864 // First delete the existing package while retaining the data directory 17865 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 17866 res.removedInfo, true, pkg)) { 17867 // If the existing package wasn't successfully deleted 17868 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 17869 deletedPkg = false; 17870 } else { 17871 // Successfully deleted the old package; proceed with replace. 17872 17873 // If deleted package lived in a container, give users a chance to 17874 // relinquish resources before killing. 17875 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 17876 if (DEBUG_INSTALL) { 17877 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 17878 } 17879 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 17880 final ArrayList<String> pkgList = new ArrayList<String>(1); 17881 pkgList.add(deletedPackage.applicationInfo.packageName); 17882 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 17883 } 17884 17885 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 17886 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17887 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 17888 17889 try { 17890 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 17891 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 17892 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 17893 installReason); 17894 17895 // Update the in-memory copy of the previous code paths. 17896 PackageSetting ps = mSettings.mPackages.get(pkgName); 17897 if (!killApp) { 17898 if (ps.oldCodePaths == null) { 17899 ps.oldCodePaths = new ArraySet<>(); 17900 } 17901 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 17902 if (deletedPackage.splitCodePaths != null) { 17903 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 17904 } 17905 } else { 17906 ps.oldCodePaths = null; 17907 } 17908 if (ps.childPackageNames != null) { 17909 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 17910 final String childPkgName = ps.childPackageNames.get(i); 17911 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 17912 childPs.oldCodePaths = ps.oldCodePaths; 17913 } 17914 } 17915 // set instant app status, but, only if it's explicitly specified 17916 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 17917 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 17918 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 17919 prepareAppDataAfterInstallLIF(newPackage); 17920 addedPkg = true; 17921 mDexManager.notifyPackageUpdated(newPackage.packageName, 17922 newPackage.baseCodePath, newPackage.splitCodePaths); 17923 } catch (PackageManagerException e) { 17924 res.setError("Package couldn't be installed in " + pkg.codePath, e); 17925 } 17926 } 17927 17928 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 17929 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 17930 17931 // Revert all internal state mutations and added folders for the failed install 17932 if (addedPkg) { 17933 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 17934 res.removedInfo, true, null); 17935 } 17936 17937 // Restore the old package 17938 if (deletedPkg) { 17939 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 17940 File restoreFile = new File(deletedPackage.codePath); 17941 // Parse old package 17942 boolean oldExternal = isExternal(deletedPackage); 17943 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 17944 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 17945 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 17946 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 17947 try { 17948 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 17949 null); 17950 } catch (PackageManagerException e) { 17951 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 17952 + e.getMessage()); 17953 return; 17954 } 17955 17956 synchronized (mPackages) { 17957 // Ensure the installer package name up to date 17958 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 17959 17960 // Update permissions for restored package 17961 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 17962 17963 mSettings.writeLPr(); 17964 } 17965 17966 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 17967 } 17968 } else { 17969 synchronized (mPackages) { 17970 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 17971 if (ps != null) { 17972 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 17973 if (res.removedInfo.removedChildPackages != null) { 17974 final int childCount = res.removedInfo.removedChildPackages.size(); 17975 // Iterate in reverse as we may modify the collection 17976 for (int i = childCount - 1; i >= 0; i--) { 17977 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 17978 if (res.addedChildPackages.containsKey(childPackageName)) { 17979 res.removedInfo.removedChildPackages.removeAt(i); 17980 } else { 17981 PackageRemovedInfo childInfo = res.removedInfo 17982 .removedChildPackages.valueAt(i); 17983 childInfo.removedForAllUsers = mPackages.get( 17984 childInfo.removedPackage) == null; 17985 } 17986 } 17987 } 17988 } 17989 } 17990 } 17991 } 17992 17993 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 17994 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 17995 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 17996 int installReason) { 17997 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 17998 + ", old=" + deletedPackage); 17999 18000 final boolean disabledSystem; 18001 18002 // Remove existing system package 18003 removePackageLI(deletedPackage, true); 18004 18005 synchronized (mPackages) { 18006 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 18007 } 18008 if (!disabledSystem) { 18009 // We didn't need to disable the .apk as a current system package, 18010 // which means we are replacing another update that is already 18011 // installed. We need to make sure to delete the older one's .apk. 18012 res.removedInfo.args = createInstallArgsForExisting(0, 18013 deletedPackage.applicationInfo.getCodePath(), 18014 deletedPackage.applicationInfo.getResourcePath(), 18015 getAppDexInstructionSets(deletedPackage.applicationInfo)); 18016 } else { 18017 res.removedInfo.args = null; 18018 } 18019 18020 // Successfully disabled the old package. Now proceed with re-installation 18021 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 18022 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18023 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 18024 18025 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 18026 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 18027 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 18028 18029 PackageParser.Package newPackage = null; 18030 try { 18031 // Add the package to the internal data structures 18032 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 18033 18034 // Set the update and install times 18035 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 18036 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 18037 System.currentTimeMillis()); 18038 18039 // Update the package dynamic state if succeeded 18040 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 18041 // Now that the install succeeded make sure we remove data 18042 // directories for any child package the update removed. 18043 final int deletedChildCount = (deletedPackage.childPackages != null) 18044 ? deletedPackage.childPackages.size() : 0; 18045 final int newChildCount = (newPackage.childPackages != null) 18046 ? newPackage.childPackages.size() : 0; 18047 for (int i = 0; i < deletedChildCount; i++) { 18048 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 18049 boolean childPackageDeleted = true; 18050 for (int j = 0; j < newChildCount; j++) { 18051 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 18052 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 18053 childPackageDeleted = false; 18054 break; 18055 } 18056 } 18057 if (childPackageDeleted) { 18058 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 18059 deletedChildPkg.packageName); 18060 if (ps != null && res.removedInfo.removedChildPackages != null) { 18061 PackageRemovedInfo removedChildRes = res.removedInfo 18062 .removedChildPackages.get(deletedChildPkg.packageName); 18063 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 18064 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 18065 } 18066 } 18067 } 18068 18069 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 18070 installReason); 18071 prepareAppDataAfterInstallLIF(newPackage); 18072 18073 mDexManager.notifyPackageUpdated(newPackage.packageName, 18074 newPackage.baseCodePath, newPackage.splitCodePaths); 18075 } 18076 } catch (PackageManagerException e) { 18077 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 18078 res.setError("Package couldn't be installed in " + pkg.codePath, e); 18079 } 18080 18081 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 18082 // Re installation failed. Restore old information 18083 // Remove new pkg information 18084 if (newPackage != null) { 18085 removeInstalledPackageLI(newPackage, true); 18086 } 18087 // Add back the old system package 18088 try { 18089 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 18090 } catch (PackageManagerException e) { 18091 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 18092 } 18093 18094 synchronized (mPackages) { 18095 if (disabledSystem) { 18096 enableSystemPackageLPw(deletedPackage); 18097 } 18098 18099 // Ensure the installer package name up to date 18100 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 18101 18102 // Update permissions for restored package 18103 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 18104 18105 mSettings.writeLPr(); 18106 } 18107 18108 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 18109 + " after failed upgrade"); 18110 } 18111 } 18112 18113 /** 18114 * Checks whether the parent or any of the child packages have a change shared 18115 * user. For a package to be a valid update the shred users of the parent and 18116 * the children should match. We may later support changing child shared users. 18117 * @param oldPkg The updated package. 18118 * @param newPkg The update package. 18119 * @return The shared user that change between the versions. 18120 */ 18121 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 18122 PackageParser.Package newPkg) { 18123 // Check parent shared user 18124 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 18125 return newPkg.packageName; 18126 } 18127 // Check child shared users 18128 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 18129 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 18130 for (int i = 0; i < newChildCount; i++) { 18131 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 18132 // If this child was present, did it have the same shared user? 18133 for (int j = 0; j < oldChildCount; j++) { 18134 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 18135 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 18136 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 18137 return newChildPkg.packageName; 18138 } 18139 } 18140 } 18141 return null; 18142 } 18143 18144 private void removeNativeBinariesLI(PackageSetting ps) { 18145 // Remove the lib path for the parent package 18146 if (ps != null) { 18147 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 18148 // Remove the lib path for the child packages 18149 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18150 for (int i = 0; i < childCount; i++) { 18151 PackageSetting childPs = null; 18152 synchronized (mPackages) { 18153 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18154 } 18155 if (childPs != null) { 18156 NativeLibraryHelper.removeNativeBinariesLI(childPs 18157 .legacyNativeLibraryPathString); 18158 } 18159 } 18160 } 18161 } 18162 18163 private void enableSystemPackageLPw(PackageParser.Package pkg) { 18164 // Enable the parent package 18165 mSettings.enableSystemPackageLPw(pkg.packageName); 18166 // Enable the child packages 18167 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18168 for (int i = 0; i < childCount; i++) { 18169 PackageParser.Package childPkg = pkg.childPackages.get(i); 18170 mSettings.enableSystemPackageLPw(childPkg.packageName); 18171 } 18172 } 18173 18174 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 18175 PackageParser.Package newPkg) { 18176 // Disable the parent package (parent always replaced) 18177 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 18178 // Disable the child packages 18179 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 18180 for (int i = 0; i < childCount; i++) { 18181 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 18182 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 18183 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 18184 } 18185 return disabled; 18186 } 18187 18188 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 18189 String installerPackageName) { 18190 // Enable the parent package 18191 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 18192 // Enable the child packages 18193 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18194 for (int i = 0; i < childCount; i++) { 18195 PackageParser.Package childPkg = pkg.childPackages.get(i); 18196 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 18197 } 18198 } 18199 18200 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 18201 // Collect all used permissions in the UID 18202 ArraySet<String> usedPermissions = new ArraySet<>(); 18203 final int packageCount = su.packages.size(); 18204 for (int i = 0; i < packageCount; i++) { 18205 PackageSetting ps = su.packages.valueAt(i); 18206 if (ps.pkg == null) { 18207 continue; 18208 } 18209 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 18210 for (int j = 0; j < requestedPermCount; j++) { 18211 String permission = ps.pkg.requestedPermissions.get(j); 18212 BasePermission bp = mSettings.mPermissions.get(permission); 18213 if (bp != null) { 18214 usedPermissions.add(permission); 18215 } 18216 } 18217 } 18218 18219 PermissionsState permissionsState = su.getPermissionsState(); 18220 // Prune install permissions 18221 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 18222 final int installPermCount = installPermStates.size(); 18223 for (int i = installPermCount - 1; i >= 0; i--) { 18224 PermissionState permissionState = installPermStates.get(i); 18225 if (!usedPermissions.contains(permissionState.getName())) { 18226 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 18227 if (bp != null) { 18228 permissionsState.revokeInstallPermission(bp); 18229 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 18230 PackageManager.MASK_PERMISSION_FLAGS, 0); 18231 } 18232 } 18233 } 18234 18235 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 18236 18237 // Prune runtime permissions 18238 for (int userId : allUserIds) { 18239 List<PermissionState> runtimePermStates = permissionsState 18240 .getRuntimePermissionStates(userId); 18241 final int runtimePermCount = runtimePermStates.size(); 18242 for (int i = runtimePermCount - 1; i >= 0; i--) { 18243 PermissionState permissionState = runtimePermStates.get(i); 18244 if (!usedPermissions.contains(permissionState.getName())) { 18245 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 18246 if (bp != null) { 18247 permissionsState.revokeRuntimePermission(bp, userId); 18248 permissionsState.updatePermissionFlags(bp, userId, 18249 PackageManager.MASK_PERMISSION_FLAGS, 0); 18250 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 18251 runtimePermissionChangedUserIds, userId); 18252 } 18253 } 18254 } 18255 } 18256 18257 return runtimePermissionChangedUserIds; 18258 } 18259 18260 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 18261 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 18262 // Update the parent package setting 18263 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 18264 res, user, installReason); 18265 // Update the child packages setting 18266 final int childCount = (newPackage.childPackages != null) 18267 ? newPackage.childPackages.size() : 0; 18268 for (int i = 0; i < childCount; i++) { 18269 PackageParser.Package childPackage = newPackage.childPackages.get(i); 18270 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 18271 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 18272 childRes.origUsers, childRes, user, installReason); 18273 } 18274 } 18275 18276 private void updateSettingsInternalLI(PackageParser.Package newPackage, 18277 String installerPackageName, int[] allUsers, int[] installedForUsers, 18278 PackageInstalledInfo res, UserHandle user, int installReason) { 18279 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 18280 18281 String pkgName = newPackage.packageName; 18282 synchronized (mPackages) { 18283 //write settings. the installStatus will be incomplete at this stage. 18284 //note that the new package setting would have already been 18285 //added to mPackages. It hasn't been persisted yet. 18286 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 18287 // TODO: Remove this write? It's also written at the end of this method 18288 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 18289 mSettings.writeLPr(); 18290 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 18291 } 18292 18293 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 18294 synchronized (mPackages) { 18295 updatePermissionsLPw(newPackage.packageName, newPackage, 18296 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 18297 ? UPDATE_PERMISSIONS_ALL : 0)); 18298 // For system-bundled packages, we assume that installing an upgraded version 18299 // of the package implies that the user actually wants to run that new code, 18300 // so we enable the package. 18301 PackageSetting ps = mSettings.mPackages.get(pkgName); 18302 final int userId = user.getIdentifier(); 18303 if (ps != null) { 18304 if (isSystemApp(newPackage)) { 18305 if (DEBUG_INSTALL) { 18306 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 18307 } 18308 // Enable system package for requested users 18309 if (res.origUsers != null) { 18310 for (int origUserId : res.origUsers) { 18311 if (userId == UserHandle.USER_ALL || userId == origUserId) { 18312 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 18313 origUserId, installerPackageName); 18314 } 18315 } 18316 } 18317 // Also convey the prior install/uninstall state 18318 if (allUsers != null && installedForUsers != null) { 18319 for (int currentUserId : allUsers) { 18320 final boolean installed = ArrayUtils.contains( 18321 installedForUsers, currentUserId); 18322 if (DEBUG_INSTALL) { 18323 Slog.d(TAG, " user " + currentUserId + " => " + installed); 18324 } 18325 ps.setInstalled(installed, currentUserId); 18326 } 18327 // these install state changes will be persisted in the 18328 // upcoming call to mSettings.writeLPr(). 18329 } 18330 } 18331 // It's implied that when a user requests installation, they want the app to be 18332 // installed and enabled. 18333 if (userId != UserHandle.USER_ALL) { 18334 ps.setInstalled(true, userId); 18335 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 18336 } 18337 18338 // When replacing an existing package, preserve the original install reason for all 18339 // users that had the package installed before. 18340 final Set<Integer> previousUserIds = new ArraySet<>(); 18341 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 18342 final int installReasonCount = res.removedInfo.installReasons.size(); 18343 for (int i = 0; i < installReasonCount; i++) { 18344 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 18345 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 18346 ps.setInstallReason(previousInstallReason, previousUserId); 18347 previousUserIds.add(previousUserId); 18348 } 18349 } 18350 18351 // Set install reason for users that are having the package newly installed. 18352 if (userId == UserHandle.USER_ALL) { 18353 for (int currentUserId : sUserManager.getUserIds()) { 18354 if (!previousUserIds.contains(currentUserId)) { 18355 ps.setInstallReason(installReason, currentUserId); 18356 } 18357 } 18358 } else if (!previousUserIds.contains(userId)) { 18359 ps.setInstallReason(installReason, userId); 18360 } 18361 mSettings.writeKernelMappingLPr(ps); 18362 } 18363 res.name = pkgName; 18364 res.uid = newPackage.applicationInfo.uid; 18365 res.pkg = newPackage; 18366 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 18367 mSettings.setInstallerPackageName(pkgName, installerPackageName); 18368 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 18369 //to update install status 18370 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 18371 mSettings.writeLPr(); 18372 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 18373 } 18374 18375 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 18376 } 18377 18378 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 18379 try { 18380 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 18381 installPackageLI(args, res); 18382 } finally { 18383 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 18384 } 18385 } 18386 18387 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 18388 final int installFlags = args.installFlags; 18389 final String installerPackageName = args.installerPackageName; 18390 final String volumeUuid = args.volumeUuid; 18391 final File tmpPackageFile = new File(args.getCodePath()); 18392 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 18393 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 18394 || (args.volumeUuid != null)); 18395 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 18396 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 18397 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 18398 final boolean virtualPreload = 18399 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 18400 boolean replace = false; 18401 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 18402 if (args.move != null) { 18403 // moving a complete application; perform an initial scan on the new install location 18404 scanFlags |= SCAN_INITIAL; 18405 } 18406 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 18407 scanFlags |= SCAN_DONT_KILL_APP; 18408 } 18409 if (instantApp) { 18410 scanFlags |= SCAN_AS_INSTANT_APP; 18411 } 18412 if (fullApp) { 18413 scanFlags |= SCAN_AS_FULL_APP; 18414 } 18415 if (virtualPreload) { 18416 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 18417 } 18418 18419 // Result object to be returned 18420 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 18421 res.installerPackageName = installerPackageName; 18422 18423 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 18424 18425 // Sanity check 18426 if (instantApp && (forwardLocked || onExternal)) { 18427 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 18428 + " external=" + onExternal); 18429 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 18430 return; 18431 } 18432 18433 // Retrieve PackageSettings and parse package 18434 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 18435 | PackageParser.PARSE_ENFORCE_CODE 18436 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 18437 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 18438 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 18439 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 18440 PackageParser pp = new PackageParser(); 18441 pp.setSeparateProcesses(mSeparateProcesses); 18442 pp.setDisplayMetrics(mMetrics); 18443 pp.setCallback(mPackageParserCallback); 18444 18445 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 18446 final PackageParser.Package pkg; 18447 try { 18448 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 18449 } catch (PackageParserException e) { 18450 res.setError("Failed parse during installPackageLI", e); 18451 return; 18452 } finally { 18453 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 18454 } 18455 18456 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 18457 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 18458 Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O"); 18459 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 18460 "Instant app package must target O"); 18461 return; 18462 } 18463 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 18464 Slog.w(TAG, "Instant app package " + pkg.packageName 18465 + " does not target targetSandboxVersion 2"); 18466 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 18467 "Instant app package must use targetSanboxVersion 2"); 18468 return; 18469 } 18470 18471 if (pkg.applicationInfo.isStaticSharedLibrary()) { 18472 // Static shared libraries have synthetic package names 18473 renameStaticSharedLibraryPackage(pkg); 18474 18475 // No static shared libs on external storage 18476 if (onExternal) { 18477 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 18478 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 18479 "Packages declaring static-shared libs cannot be updated"); 18480 return; 18481 } 18482 } 18483 18484 // If we are installing a clustered package add results for the children 18485 if (pkg.childPackages != null) { 18486 synchronized (mPackages) { 18487 final int childCount = pkg.childPackages.size(); 18488 for (int i = 0; i < childCount; i++) { 18489 PackageParser.Package childPkg = pkg.childPackages.get(i); 18490 PackageInstalledInfo childRes = new PackageInstalledInfo(); 18491 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 18492 childRes.pkg = childPkg; 18493 childRes.name = childPkg.packageName; 18494 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 18495 if (childPs != null) { 18496 childRes.origUsers = childPs.queryInstalledUsers( 18497 sUserManager.getUserIds(), true); 18498 } 18499 if ((mPackages.containsKey(childPkg.packageName))) { 18500 childRes.removedInfo = new PackageRemovedInfo(this); 18501 childRes.removedInfo.removedPackage = childPkg.packageName; 18502 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 18503 } 18504 if (res.addedChildPackages == null) { 18505 res.addedChildPackages = new ArrayMap<>(); 18506 } 18507 res.addedChildPackages.put(childPkg.packageName, childRes); 18508 } 18509 } 18510 } 18511 18512 // If package doesn't declare API override, mark that we have an install 18513 // time CPU ABI override. 18514 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 18515 pkg.cpuAbiOverride = args.abiOverride; 18516 } 18517 18518 String pkgName = res.name = pkg.packageName; 18519 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 18520 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 18521 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 18522 return; 18523 } 18524 } 18525 18526 try { 18527 // either use what we've been given or parse directly from the APK 18528 if (args.certificates != null) { 18529 try { 18530 PackageParser.populateCertificates(pkg, args.certificates); 18531 } catch (PackageParserException e) { 18532 // there was something wrong with the certificates we were given; 18533 // try to pull them from the APK 18534 PackageParser.collectCertificates(pkg, parseFlags); 18535 } 18536 } else { 18537 PackageParser.collectCertificates(pkg, parseFlags); 18538 } 18539 } catch (PackageParserException e) { 18540 res.setError("Failed collect during installPackageLI", e); 18541 return; 18542 } 18543 18544 // Get rid of all references to package scan path via parser. 18545 pp = null; 18546 String oldCodePath = null; 18547 boolean systemApp = false; 18548 synchronized (mPackages) { 18549 // Check if installing already existing package 18550 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 18551 String oldName = mSettings.getRenamedPackageLPr(pkgName); 18552 if (pkg.mOriginalPackages != null 18553 && pkg.mOriginalPackages.contains(oldName) 18554 && mPackages.containsKey(oldName)) { 18555 // This package is derived from an original package, 18556 // and this device has been updating from that original 18557 // name. We must continue using the original name, so 18558 // rename the new package here. 18559 pkg.setPackageName(oldName); 18560 pkgName = pkg.packageName; 18561 replace = true; 18562 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 18563 + oldName + " pkgName=" + pkgName); 18564 } else if (mPackages.containsKey(pkgName)) { 18565 // This package, under its official name, already exists 18566 // on the device; we should replace it. 18567 replace = true; 18568 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 18569 } 18570 18571 // Child packages are installed through the parent package 18572 if (pkg.parentPackage != null) { 18573 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 18574 "Package " + pkg.packageName + " is child of package " 18575 + pkg.parentPackage.parentPackage + ". Child packages " 18576 + "can be updated only through the parent package."); 18577 return; 18578 } 18579 18580 if (replace) { 18581 // Prevent apps opting out from runtime permissions 18582 PackageParser.Package oldPackage = mPackages.get(pkgName); 18583 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 18584 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 18585 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 18586 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 18587 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 18588 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 18589 + " doesn't support runtime permissions but the old" 18590 + " target SDK " + oldTargetSdk + " does."); 18591 return; 18592 } 18593 // Prevent apps from downgrading their targetSandbox. 18594 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 18595 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 18596 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 18597 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 18598 "Package " + pkg.packageName + " new target sandbox " 18599 + newTargetSandbox + " is incompatible with the previous value of" 18600 + oldTargetSandbox + "."); 18601 return; 18602 } 18603 18604 // Prevent installing of child packages 18605 if (oldPackage.parentPackage != null) { 18606 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 18607 "Package " + pkg.packageName + " is child of package " 18608 + oldPackage.parentPackage + ". Child packages " 18609 + "can be updated only through the parent package."); 18610 return; 18611 } 18612 } 18613 } 18614 18615 PackageSetting ps = mSettings.mPackages.get(pkgName); 18616 if (ps != null) { 18617 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 18618 18619 // Static shared libs have same package with different versions where 18620 // we internally use a synthetic package name to allow multiple versions 18621 // of the same package, therefore we need to compare signatures against 18622 // the package setting for the latest library version. 18623 PackageSetting signatureCheckPs = ps; 18624 if (pkg.applicationInfo.isStaticSharedLibrary()) { 18625 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 18626 if (libraryEntry != null) { 18627 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 18628 } 18629 } 18630 18631 // Quick sanity check that we're signed correctly if updating; 18632 // we'll check this again later when scanning, but we want to 18633 // bail early here before tripping over redefined permissions. 18634 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 18635 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 18636 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 18637 + pkg.packageName + " upgrade keys do not match the " 18638 + "previously installed version"); 18639 return; 18640 } 18641 } else { 18642 try { 18643 verifySignaturesLP(signatureCheckPs, pkg); 18644 } catch (PackageManagerException e) { 18645 res.setError(e.error, e.getMessage()); 18646 return; 18647 } 18648 } 18649 18650 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 18651 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 18652 systemApp = (ps.pkg.applicationInfo.flags & 18653 ApplicationInfo.FLAG_SYSTEM) != 0; 18654 } 18655 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 18656 } 18657 18658 int N = pkg.permissions.size(); 18659 for (int i = N-1; i >= 0; i--) { 18660 PackageParser.Permission perm = pkg.permissions.get(i); 18661 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 18662 18663 // Don't allow anyone but the system to define ephemeral permissions. 18664 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 18665 && !systemApp) { 18666 Slog.w(TAG, "Non-System package " + pkg.packageName 18667 + " attempting to delcare ephemeral permission " 18668 + perm.info.name + "; Removing ephemeral."); 18669 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 18670 } 18671 // Check whether the newly-scanned package wants to define an already-defined perm 18672 if (bp != null) { 18673 // If the defining package is signed with our cert, it's okay. This 18674 // also includes the "updating the same package" case, of course. 18675 // "updating same package" could also involve key-rotation. 18676 final boolean sigsOk; 18677 if (bp.sourcePackage.equals(pkg.packageName) 18678 && (bp.packageSetting instanceof PackageSetting) 18679 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 18680 scanFlags))) { 18681 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 18682 } else { 18683 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 18684 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 18685 } 18686 if (!sigsOk) { 18687 // If the owning package is the system itself, we log but allow 18688 // install to proceed; we fail the install on all other permission 18689 // redefinitions. 18690 if (!bp.sourcePackage.equals("android")) { 18691 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 18692 + pkg.packageName + " attempting to redeclare permission " 18693 + perm.info.name + " already owned by " + bp.sourcePackage); 18694 res.origPermission = perm.info.name; 18695 res.origPackage = bp.sourcePackage; 18696 return; 18697 } else { 18698 Slog.w(TAG, "Package " + pkg.packageName 18699 + " attempting to redeclare system permission " 18700 + perm.info.name + "; ignoring new declaration"); 18701 pkg.permissions.remove(i); 18702 } 18703 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 18704 // Prevent apps to change protection level to dangerous from any other 18705 // type as this would allow a privilege escalation where an app adds a 18706 // normal/signature permission in other app's group and later redefines 18707 // it as dangerous leading to the group auto-grant. 18708 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 18709 == PermissionInfo.PROTECTION_DANGEROUS) { 18710 if (bp != null && !bp.isRuntime()) { 18711 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 18712 + "non-runtime permission " + perm.info.name 18713 + " to runtime; keeping old protection level"); 18714 perm.info.protectionLevel = bp.protectionLevel; 18715 } 18716 } 18717 } 18718 } 18719 } 18720 } 18721 18722 if (systemApp) { 18723 if (onExternal) { 18724 // Abort update; system app can't be replaced with app on sdcard 18725 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 18726 "Cannot install updates to system apps on sdcard"); 18727 return; 18728 } else if (instantApp) { 18729 // Abort update; system app can't be replaced with an instant app 18730 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 18731 "Cannot update a system app with an instant app"); 18732 return; 18733 } 18734 } 18735 18736 if (args.move != null) { 18737 // We did an in-place move, so dex is ready to roll 18738 scanFlags |= SCAN_NO_DEX; 18739 scanFlags |= SCAN_MOVE; 18740 18741 synchronized (mPackages) { 18742 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18743 if (ps == null) { 18744 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 18745 "Missing settings for moved package " + pkgName); 18746 } 18747 18748 // We moved the entire application as-is, so bring over the 18749 // previously derived ABI information. 18750 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 18751 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 18752 } 18753 18754 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 18755 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 18756 scanFlags |= SCAN_NO_DEX; 18757 18758 try { 18759 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 18760 args.abiOverride : pkg.cpuAbiOverride); 18761 final boolean extractNativeLibs = !pkg.isLibrary(); 18762 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 18763 extractNativeLibs, mAppLib32InstallDir); 18764 } catch (PackageManagerException pme) { 18765 Slog.e(TAG, "Error deriving application ABI", pme); 18766 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 18767 return; 18768 } 18769 18770 // Shared libraries for the package need to be updated. 18771 synchronized (mPackages) { 18772 try { 18773 updateSharedLibrariesLPr(pkg, null); 18774 } catch (PackageManagerException e) { 18775 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18776 } 18777 } 18778 } 18779 18780 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 18781 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 18782 return; 18783 } 18784 18785 // Verify if we need to dexopt the app. 18786 // 18787 // NOTE: it is *important* to call dexopt after doRename which will sync the 18788 // package data from PackageParser.Package and its corresponding ApplicationInfo. 18789 // 18790 // We only need to dexopt if the package meets ALL of the following conditions: 18791 // 1) it is not forward locked. 18792 // 2) it is not on on an external ASEC container. 18793 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 18794 // 18795 // Note that we do not dexopt instant apps by default. dexopt can take some time to 18796 // complete, so we skip this step during installation. Instead, we'll take extra time 18797 // the first time the instant app starts. It's preferred to do it this way to provide 18798 // continuous progress to the useur instead of mysteriously blocking somewhere in the 18799 // middle of running an instant app. The default behaviour can be overridden 18800 // via gservices. 18801 final boolean performDexopt = !forwardLocked 18802 && !pkg.applicationInfo.isExternalAsec() 18803 && (!instantApp || Global.getInt(mContext.getContentResolver(), 18804 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 18805 18806 if (performDexopt) { 18807 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 18808 // Do not run PackageDexOptimizer through the local performDexOpt 18809 // method because `pkg` may not be in `mPackages` yet. 18810 // 18811 // Also, don't fail application installs if the dexopt step fails. 18812 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 18813 REASON_INSTALL, 18814 DexoptOptions.DEXOPT_BOOT_COMPLETE); 18815 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 18816 null /* instructionSets */, 18817 getOrCreateCompilerPackageStats(pkg), 18818 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 18819 dexoptOptions); 18820 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 18821 } 18822 18823 // Notify BackgroundDexOptService that the package has been changed. 18824 // If this is an update of a package which used to fail to compile, 18825 // BackgroundDexOptService will remove it from its blacklist. 18826 // TODO: Layering violation 18827 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 18828 18829 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 18830 18831 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 18832 "installPackageLI")) { 18833 if (replace) { 18834 if (pkg.applicationInfo.isStaticSharedLibrary()) { 18835 // Static libs have a synthetic package name containing the version 18836 // and cannot be updated as an update would get a new package name, 18837 // unless this is the exact same version code which is useful for 18838 // development. 18839 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 18840 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 18841 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 18842 + "static-shared libs cannot be updated"); 18843 return; 18844 } 18845 } 18846 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 18847 installerPackageName, res, args.installReason); 18848 } else { 18849 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 18850 args.user, installerPackageName, volumeUuid, res, args.installReason); 18851 } 18852 } 18853 18854 synchronized (mPackages) { 18855 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18856 if (ps != null) { 18857 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 18858 ps.setUpdateAvailable(false /*updateAvailable*/); 18859 } 18860 18861 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18862 for (int i = 0; i < childCount; i++) { 18863 PackageParser.Package childPkg = pkg.childPackages.get(i); 18864 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 18865 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 18866 if (childPs != null) { 18867 childRes.newUsers = childPs.queryInstalledUsers( 18868 sUserManager.getUserIds(), true); 18869 } 18870 } 18871 18872 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 18873 updateSequenceNumberLP(ps, res.newUsers); 18874 updateInstantAppInstallerLocked(pkgName); 18875 } 18876 } 18877 } 18878 18879 private void startIntentFilterVerifications(int userId, boolean replacing, 18880 PackageParser.Package pkg) { 18881 if (mIntentFilterVerifierComponent == null) { 18882 Slog.w(TAG, "No IntentFilter verification will not be done as " 18883 + "there is no IntentFilterVerifier available!"); 18884 return; 18885 } 18886 18887 final int verifierUid = getPackageUid( 18888 mIntentFilterVerifierComponent.getPackageName(), 18889 MATCH_DEBUG_TRIAGED_MISSING, 18890 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 18891 18892 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 18893 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 18894 mHandler.sendMessage(msg); 18895 18896 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18897 for (int i = 0; i < childCount; i++) { 18898 PackageParser.Package childPkg = pkg.childPackages.get(i); 18899 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 18900 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 18901 mHandler.sendMessage(msg); 18902 } 18903 } 18904 18905 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 18906 PackageParser.Package pkg) { 18907 int size = pkg.activities.size(); 18908 if (size == 0) { 18909 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 18910 "No activity, so no need to verify any IntentFilter!"); 18911 return; 18912 } 18913 18914 final boolean hasDomainURLs = hasDomainURLs(pkg); 18915 if (!hasDomainURLs) { 18916 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 18917 "No domain URLs, so no need to verify any IntentFilter!"); 18918 return; 18919 } 18920 18921 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 18922 + " if any IntentFilter from the " + size 18923 + " Activities needs verification ..."); 18924 18925 int count = 0; 18926 final String packageName = pkg.packageName; 18927 18928 synchronized (mPackages) { 18929 // If this is a new install and we see that we've already run verification for this 18930 // package, we have nothing to do: it means the state was restored from backup. 18931 if (!replacing) { 18932 IntentFilterVerificationInfo ivi = 18933 mSettings.getIntentFilterVerificationLPr(packageName); 18934 if (ivi != null) { 18935 if (DEBUG_DOMAIN_VERIFICATION) { 18936 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 18937 + ivi.getStatusString()); 18938 } 18939 return; 18940 } 18941 } 18942 18943 // If any filters need to be verified, then all need to be. 18944 boolean needToVerify = false; 18945 for (PackageParser.Activity a : pkg.activities) { 18946 for (ActivityIntentInfo filter : a.intents) { 18947 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 18948 if (DEBUG_DOMAIN_VERIFICATION) { 18949 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 18950 } 18951 needToVerify = true; 18952 break; 18953 } 18954 } 18955 } 18956 18957 if (needToVerify) { 18958 final int verificationId = mIntentFilterVerificationToken++; 18959 for (PackageParser.Activity a : pkg.activities) { 18960 for (ActivityIntentInfo filter : a.intents) { 18961 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 18962 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 18963 "Verification needed for IntentFilter:" + filter.toString()); 18964 mIntentFilterVerifier.addOneIntentFilterVerification( 18965 verifierUid, userId, verificationId, filter, packageName); 18966 count++; 18967 } 18968 } 18969 } 18970 } 18971 } 18972 18973 if (count > 0) { 18974 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 18975 + " IntentFilter verification" + (count > 1 ? "s" : "") 18976 + " for userId:" + userId); 18977 mIntentFilterVerifier.startVerifications(userId); 18978 } else { 18979 if (DEBUG_DOMAIN_VERIFICATION) { 18980 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 18981 } 18982 } 18983 } 18984 18985 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 18986 final ComponentName cn = filter.activity.getComponentName(); 18987 final String packageName = cn.getPackageName(); 18988 18989 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 18990 packageName); 18991 if (ivi == null) { 18992 return true; 18993 } 18994 int status = ivi.getStatus(); 18995 switch (status) { 18996 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 18997 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 18998 return true; 18999 19000 default: 19001 // Nothing to do 19002 return false; 19003 } 19004 } 19005 19006 private static boolean isMultiArch(ApplicationInfo info) { 19007 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 19008 } 19009 19010 private static boolean isExternal(PackageParser.Package pkg) { 19011 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 19012 } 19013 19014 private static boolean isExternal(PackageSetting ps) { 19015 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 19016 } 19017 19018 private static boolean isSystemApp(PackageParser.Package pkg) { 19019 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 19020 } 19021 19022 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 19023 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 19024 } 19025 19026 private static boolean hasDomainURLs(PackageParser.Package pkg) { 19027 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 19028 } 19029 19030 private static boolean isSystemApp(PackageSetting ps) { 19031 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 19032 } 19033 19034 private static boolean isUpdatedSystemApp(PackageSetting ps) { 19035 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 19036 } 19037 19038 private int packageFlagsToInstallFlags(PackageSetting ps) { 19039 int installFlags = 0; 19040 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 19041 // This existing package was an external ASEC install when we have 19042 // the external flag without a UUID 19043 installFlags |= PackageManager.INSTALL_EXTERNAL; 19044 } 19045 if (ps.isForwardLocked()) { 19046 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 19047 } 19048 return installFlags; 19049 } 19050 19051 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 19052 if (isExternal(pkg)) { 19053 if (TextUtils.isEmpty(pkg.volumeUuid)) { 19054 return StorageManager.UUID_PRIMARY_PHYSICAL; 19055 } else { 19056 return pkg.volumeUuid; 19057 } 19058 } else { 19059 return StorageManager.UUID_PRIVATE_INTERNAL; 19060 } 19061 } 19062 19063 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 19064 if (isExternal(pkg)) { 19065 if (TextUtils.isEmpty(pkg.volumeUuid)) { 19066 return mSettings.getExternalVersion(); 19067 } else { 19068 return mSettings.findOrCreateVersion(pkg.volumeUuid); 19069 } 19070 } else { 19071 return mSettings.getInternalVersion(); 19072 } 19073 } 19074 19075 private void deleteTempPackageFiles() { 19076 final FilenameFilter filter = new FilenameFilter() { 19077 public boolean accept(File dir, String name) { 19078 return name.startsWith("vmdl") && name.endsWith(".tmp"); 19079 } 19080 }; 19081 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 19082 file.delete(); 19083 } 19084 } 19085 19086 @Override 19087 public void deletePackageAsUser(String packageName, int versionCode, 19088 IPackageDeleteObserver observer, int userId, int flags) { 19089 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 19090 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 19091 } 19092 19093 @Override 19094 public void deletePackageVersioned(VersionedPackage versionedPackage, 19095 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 19096 final int callingUid = Binder.getCallingUid(); 19097 mContext.enforceCallingOrSelfPermission( 19098 android.Manifest.permission.DELETE_PACKAGES, null); 19099 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 19100 Preconditions.checkNotNull(versionedPackage); 19101 Preconditions.checkNotNull(observer); 19102 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 19103 PackageManager.VERSION_CODE_HIGHEST, 19104 Integer.MAX_VALUE, "versionCode must be >= -1"); 19105 19106 final String packageName = versionedPackage.getPackageName(); 19107 final int versionCode = versionedPackage.getVersionCode(); 19108 final String internalPackageName; 19109 synchronized (mPackages) { 19110 // Normalize package name to handle renamed packages and static libs 19111 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 19112 versionedPackage.getVersionCode()); 19113 } 19114 19115 final int uid = Binder.getCallingUid(); 19116 if (!isOrphaned(internalPackageName) 19117 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 19118 try { 19119 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 19120 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 19121 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 19122 observer.onUserActionRequired(intent); 19123 } catch (RemoteException re) { 19124 } 19125 return; 19126 } 19127 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 19128 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 19129 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 19130 mContext.enforceCallingOrSelfPermission( 19131 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 19132 "deletePackage for user " + userId); 19133 } 19134 19135 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 19136 try { 19137 observer.onPackageDeleted(packageName, 19138 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 19139 } catch (RemoteException re) { 19140 } 19141 return; 19142 } 19143 19144 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 19145 try { 19146 observer.onPackageDeleted(packageName, 19147 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 19148 } catch (RemoteException re) { 19149 } 19150 return; 19151 } 19152 19153 if (DEBUG_REMOVE) { 19154 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 19155 + " deleteAllUsers: " + deleteAllUsers + " version=" 19156 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 19157 ? "VERSION_CODE_HIGHEST" : versionCode)); 19158 } 19159 // Queue up an async operation since the package deletion may take a little while. 19160 mHandler.post(new Runnable() { 19161 public void run() { 19162 mHandler.removeCallbacks(this); 19163 int returnCode; 19164 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 19165 boolean doDeletePackage = true; 19166 if (ps != null) { 19167 final boolean targetIsInstantApp = 19168 ps.getInstantApp(UserHandle.getUserId(callingUid)); 19169 doDeletePackage = !targetIsInstantApp 19170 || canViewInstantApps; 19171 } 19172 if (doDeletePackage) { 19173 if (!deleteAllUsers) { 19174 returnCode = deletePackageX(internalPackageName, versionCode, 19175 userId, deleteFlags); 19176 } else { 19177 int[] blockUninstallUserIds = getBlockUninstallForUsers( 19178 internalPackageName, users); 19179 // If nobody is blocking uninstall, proceed with delete for all users 19180 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 19181 returnCode = deletePackageX(internalPackageName, versionCode, 19182 userId, deleteFlags); 19183 } else { 19184 // Otherwise uninstall individually for users with blockUninstalls=false 19185 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 19186 for (int userId : users) { 19187 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 19188 returnCode = deletePackageX(internalPackageName, versionCode, 19189 userId, userFlags); 19190 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 19191 Slog.w(TAG, "Package delete failed for user " + userId 19192 + ", returnCode " + returnCode); 19193 } 19194 } 19195 } 19196 // The app has only been marked uninstalled for certain users. 19197 // We still need to report that delete was blocked 19198 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 19199 } 19200 } 19201 } else { 19202 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 19203 } 19204 try { 19205 observer.onPackageDeleted(packageName, returnCode, null); 19206 } catch (RemoteException e) { 19207 Log.i(TAG, "Observer no longer exists."); 19208 } //end catch 19209 } //end run 19210 }); 19211 } 19212 19213 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 19214 if (pkg.staticSharedLibName != null) { 19215 return pkg.manifestPackageName; 19216 } 19217 return pkg.packageName; 19218 } 19219 19220 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 19221 // Handle renamed packages 19222 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 19223 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 19224 19225 // Is this a static library? 19226 SparseArray<SharedLibraryEntry> versionedLib = 19227 mStaticLibsByDeclaringPackage.get(packageName); 19228 if (versionedLib == null || versionedLib.size() <= 0) { 19229 return packageName; 19230 } 19231 19232 // Figure out which lib versions the caller can see 19233 SparseIntArray versionsCallerCanSee = null; 19234 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 19235 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 19236 && callingAppId != Process.ROOT_UID) { 19237 versionsCallerCanSee = new SparseIntArray(); 19238 String libName = versionedLib.valueAt(0).info.getName(); 19239 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 19240 if (uidPackages != null) { 19241 for (String uidPackage : uidPackages) { 19242 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 19243 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 19244 if (libIdx >= 0) { 19245 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 19246 versionsCallerCanSee.append(libVersion, libVersion); 19247 } 19248 } 19249 } 19250 } 19251 19252 // Caller can see nothing - done 19253 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 19254 return packageName; 19255 } 19256 19257 // Find the version the caller can see and the app version code 19258 SharedLibraryEntry highestVersion = null; 19259 final int versionCount = versionedLib.size(); 19260 for (int i = 0; i < versionCount; i++) { 19261 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 19262 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 19263 libEntry.info.getVersion()) < 0) { 19264 continue; 19265 } 19266 final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode(); 19267 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 19268 if (libVersionCode == versionCode) { 19269 return libEntry.apk; 19270 } 19271 } else if (highestVersion == null) { 19272 highestVersion = libEntry; 19273 } else if (libVersionCode > highestVersion.info 19274 .getDeclaringPackage().getVersionCode()) { 19275 highestVersion = libEntry; 19276 } 19277 } 19278 19279 if (highestVersion != null) { 19280 return highestVersion.apk; 19281 } 19282 19283 return packageName; 19284 } 19285 19286 boolean isCallerVerifier(int callingUid) { 19287 final int callingUserId = UserHandle.getUserId(callingUid); 19288 return mRequiredVerifierPackage != null && 19289 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 19290 } 19291 19292 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 19293 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 19294 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19295 return true; 19296 } 19297 final int callingUserId = UserHandle.getUserId(callingUid); 19298 // If the caller installed the pkgName, then allow it to silently uninstall. 19299 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 19300 return true; 19301 } 19302 19303 // Allow package verifier to silently uninstall. 19304 if (mRequiredVerifierPackage != null && 19305 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 19306 return true; 19307 } 19308 19309 // Allow package uninstaller to silently uninstall. 19310 if (mRequiredUninstallerPackage != null && 19311 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 19312 return true; 19313 } 19314 19315 // Allow storage manager to silently uninstall. 19316 if (mStorageManagerPackage != null && 19317 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 19318 return true; 19319 } 19320 19321 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 19322 // uninstall for device owner provisioning. 19323 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 19324 == PERMISSION_GRANTED) { 19325 return true; 19326 } 19327 19328 return false; 19329 } 19330 19331 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 19332 int[] result = EMPTY_INT_ARRAY; 19333 for (int userId : userIds) { 19334 if (getBlockUninstallForUser(packageName, userId)) { 19335 result = ArrayUtils.appendInt(result, userId); 19336 } 19337 } 19338 return result; 19339 } 19340 19341 @Override 19342 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 19343 final int callingUid = Binder.getCallingUid(); 19344 if (getInstantAppPackageName(callingUid) != null 19345 && !isCallerSameApp(packageName, callingUid)) { 19346 return false; 19347 } 19348 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 19349 } 19350 19351 private boolean isPackageDeviceAdmin(String packageName, int userId) { 19352 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 19353 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 19354 try { 19355 if (dpm != null) { 19356 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 19357 /* callingUserOnly =*/ false); 19358 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 19359 : deviceOwnerComponentName.getPackageName(); 19360 // Does the package contains the device owner? 19361 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 19362 // this check is probably not needed, since DO should be registered as a device 19363 // admin on some user too. (Original bug for this: b/17657954) 19364 if (packageName.equals(deviceOwnerPackageName)) { 19365 return true; 19366 } 19367 // Does it contain a device admin for any user? 19368 int[] users; 19369 if (userId == UserHandle.USER_ALL) { 19370 users = sUserManager.getUserIds(); 19371 } else { 19372 users = new int[]{userId}; 19373 } 19374 for (int i = 0; i < users.length; ++i) { 19375 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 19376 return true; 19377 } 19378 } 19379 } 19380 } catch (RemoteException e) { 19381 } 19382 return false; 19383 } 19384 19385 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 19386 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 19387 } 19388 19389 /** 19390 * This method is an internal method that could be get invoked either 19391 * to delete an installed package or to clean up a failed installation. 19392 * After deleting an installed package, a broadcast is sent to notify any 19393 * listeners that the package has been removed. For cleaning up a failed 19394 * installation, the broadcast is not necessary since the package's 19395 * installation wouldn't have sent the initial broadcast either 19396 * The key steps in deleting a package are 19397 * deleting the package information in internal structures like mPackages, 19398 * deleting the packages base directories through installd 19399 * updating mSettings to reflect current status 19400 * persisting settings for later use 19401 * sending a broadcast if necessary 19402 */ 19403 int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 19404 final PackageRemovedInfo info = new PackageRemovedInfo(this); 19405 final boolean res; 19406 19407 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 19408 ? UserHandle.USER_ALL : userId; 19409 19410 if (isPackageDeviceAdmin(packageName, removeUser)) { 19411 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 19412 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 19413 } 19414 19415 PackageSetting uninstalledPs = null; 19416 PackageParser.Package pkg = null; 19417 19418 // for the uninstall-updates case and restricted profiles, remember the per- 19419 // user handle installed state 19420 int[] allUsers; 19421 synchronized (mPackages) { 19422 uninstalledPs = mSettings.mPackages.get(packageName); 19423 if (uninstalledPs == null) { 19424 Slog.w(TAG, "Not removing non-existent package " + packageName); 19425 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 19426 } 19427 19428 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 19429 && uninstalledPs.versionCode != versionCode) { 19430 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 19431 + uninstalledPs.versionCode + " != " + versionCode); 19432 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 19433 } 19434 19435 // Static shared libs can be declared by any package, so let us not 19436 // allow removing a package if it provides a lib others depend on. 19437 pkg = mPackages.get(packageName); 19438 19439 allUsers = sUserManager.getUserIds(); 19440 19441 if (pkg != null && pkg.staticSharedLibName != null) { 19442 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 19443 pkg.staticSharedLibVersion); 19444 if (libEntry != null) { 19445 for (int currUserId : allUsers) { 19446 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 19447 continue; 19448 } 19449 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 19450 libEntry.info, 0, currUserId); 19451 if (!ArrayUtils.isEmpty(libClientPackages)) { 19452 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 19453 + " hosting lib " + libEntry.info.getName() + " version " 19454 + libEntry.info.getVersion() + " used by " + libClientPackages 19455 + " for user " + currUserId); 19456 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 19457 } 19458 } 19459 } 19460 } 19461 19462 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 19463 } 19464 19465 final int freezeUser; 19466 if (isUpdatedSystemApp(uninstalledPs) 19467 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 19468 // We're downgrading a system app, which will apply to all users, so 19469 // freeze them all during the downgrade 19470 freezeUser = UserHandle.USER_ALL; 19471 } else { 19472 freezeUser = removeUser; 19473 } 19474 19475 synchronized (mInstallLock) { 19476 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 19477 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 19478 deleteFlags, "deletePackageX")) { 19479 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 19480 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 19481 } 19482 synchronized (mPackages) { 19483 if (res) { 19484 if (pkg != null) { 19485 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 19486 } 19487 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 19488 updateInstantAppInstallerLocked(packageName); 19489 } 19490 } 19491 } 19492 19493 if (res) { 19494 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 19495 info.sendPackageRemovedBroadcasts(killApp); 19496 info.sendSystemPackageUpdatedBroadcasts(); 19497 info.sendSystemPackageAppearedBroadcasts(); 19498 } 19499 // Force a gc here. 19500 Runtime.getRuntime().gc(); 19501 // Delete the resources here after sending the broadcast to let 19502 // other processes clean up before deleting resources. 19503 if (info.args != null) { 19504 synchronized (mInstallLock) { 19505 info.args.doPostDeleteLI(true); 19506 } 19507 } 19508 19509 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 19510 } 19511 19512 static class PackageRemovedInfo { 19513 final PackageSender packageSender; 19514 String removedPackage; 19515 String installerPackageName; 19516 int uid = -1; 19517 int removedAppId = -1; 19518 int[] origUsers; 19519 int[] removedUsers = null; 19520 int[] broadcastUsers = null; 19521 SparseArray<Integer> installReasons; 19522 boolean isRemovedPackageSystemUpdate = false; 19523 boolean isUpdate; 19524 boolean dataRemoved; 19525 boolean removedForAllUsers; 19526 boolean isStaticSharedLib; 19527 // Clean up resources deleted packages. 19528 InstallArgs args = null; 19529 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 19530 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 19531 19532 PackageRemovedInfo(PackageSender packageSender) { 19533 this.packageSender = packageSender; 19534 } 19535 19536 void sendPackageRemovedBroadcasts(boolean killApp) { 19537 sendPackageRemovedBroadcastInternal(killApp); 19538 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 19539 for (int i = 0; i < childCount; i++) { 19540 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 19541 childInfo.sendPackageRemovedBroadcastInternal(killApp); 19542 } 19543 } 19544 19545 void sendSystemPackageUpdatedBroadcasts() { 19546 if (isRemovedPackageSystemUpdate) { 19547 sendSystemPackageUpdatedBroadcastsInternal(); 19548 final int childCount = (removedChildPackages != null) 19549 ? removedChildPackages.size() : 0; 19550 for (int i = 0; i < childCount; i++) { 19551 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 19552 if (childInfo.isRemovedPackageSystemUpdate) { 19553 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 19554 } 19555 } 19556 } 19557 } 19558 19559 void sendSystemPackageAppearedBroadcasts() { 19560 final int packageCount = (appearedChildPackages != null) 19561 ? appearedChildPackages.size() : 0; 19562 for (int i = 0; i < packageCount; i++) { 19563 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 19564 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 19565 true /*sendBootCompleted*/, false /*startReceiver*/, 19566 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 19567 } 19568 } 19569 19570 private void sendSystemPackageUpdatedBroadcastsInternal() { 19571 Bundle extras = new Bundle(2); 19572 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 19573 extras.putBoolean(Intent.EXTRA_REPLACING, true); 19574 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 19575 removedPackage, extras, 0, null /*targetPackage*/, null, null); 19576 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 19577 removedPackage, extras, 0, null /*targetPackage*/, null, null); 19578 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 19579 null, null, 0, removedPackage, null, null); 19580 if (installerPackageName != null) { 19581 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 19582 removedPackage, extras, 0 /*flags*/, 19583 installerPackageName, null, null); 19584 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 19585 removedPackage, extras, 0 /*flags*/, 19586 installerPackageName, null, null); 19587 } 19588 } 19589 19590 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 19591 // Don't send static shared library removal broadcasts as these 19592 // libs are visible only the the apps that depend on them an one 19593 // cannot remove the library if it has a dependency. 19594 if (isStaticSharedLib) { 19595 return; 19596 } 19597 Bundle extras = new Bundle(2); 19598 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 19599 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 19600 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 19601 if (isUpdate || isRemovedPackageSystemUpdate) { 19602 extras.putBoolean(Intent.EXTRA_REPLACING, true); 19603 } 19604 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 19605 if (removedPackage != null) { 19606 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 19607 removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers); 19608 if (installerPackageName != null) { 19609 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 19610 removedPackage, extras, 0 /*flags*/, 19611 installerPackageName, null, broadcastUsers); 19612 } 19613 if (dataRemoved && !isRemovedPackageSystemUpdate) { 19614 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 19615 removedPackage, extras, 19616 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 19617 null, null, broadcastUsers); 19618 } 19619 } 19620 if (removedAppId >= 0) { 19621 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 19622 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 19623 null, null, broadcastUsers); 19624 } 19625 } 19626 19627 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 19628 removedUsers = userIds; 19629 if (removedUsers == null) { 19630 broadcastUsers = null; 19631 return; 19632 } 19633 19634 broadcastUsers = EMPTY_INT_ARRAY; 19635 for (int i = userIds.length - 1; i >= 0; --i) { 19636 final int userId = userIds[i]; 19637 if (deletedPackageSetting.getInstantApp(userId)) { 19638 continue; 19639 } 19640 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 19641 } 19642 } 19643 } 19644 19645 /* 19646 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 19647 * flag is not set, the data directory is removed as well. 19648 * make sure this flag is set for partially installed apps. If not its meaningless to 19649 * delete a partially installed application. 19650 */ 19651 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 19652 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 19653 String packageName = ps.name; 19654 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 19655 // Retrieve object to delete permissions for shared user later on 19656 final PackageParser.Package deletedPkg; 19657 final PackageSetting deletedPs; 19658 // reader 19659 synchronized (mPackages) { 19660 deletedPkg = mPackages.get(packageName); 19661 deletedPs = mSettings.mPackages.get(packageName); 19662 if (outInfo != null) { 19663 outInfo.removedPackage = packageName; 19664 outInfo.installerPackageName = ps.installerPackageName; 19665 outInfo.isStaticSharedLib = deletedPkg != null 19666 && deletedPkg.staticSharedLibName != null; 19667 outInfo.populateUsers(deletedPs == null ? null 19668 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 19669 } 19670 } 19671 19672 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 19673 19674 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 19675 final PackageParser.Package resolvedPkg; 19676 if (deletedPkg != null) { 19677 resolvedPkg = deletedPkg; 19678 } else { 19679 // We don't have a parsed package when it lives on an ejected 19680 // adopted storage device, so fake something together 19681 resolvedPkg = new PackageParser.Package(ps.name); 19682 resolvedPkg.setVolumeUuid(ps.volumeUuid); 19683 } 19684 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 19685 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19686 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 19687 if (outInfo != null) { 19688 outInfo.dataRemoved = true; 19689 } 19690 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 19691 } 19692 19693 int removedAppId = -1; 19694 19695 // writer 19696 synchronized (mPackages) { 19697 boolean installedStateChanged = false; 19698 if (deletedPs != null) { 19699 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 19700 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 19701 clearDefaultBrowserIfNeeded(packageName); 19702 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 19703 removedAppId = mSettings.removePackageLPw(packageName); 19704 if (outInfo != null) { 19705 outInfo.removedAppId = removedAppId; 19706 } 19707 updatePermissionsLPw(deletedPs.name, null, 0); 19708 if (deletedPs.sharedUser != null) { 19709 // Remove permissions associated with package. Since runtime 19710 // permissions are per user we have to kill the removed package 19711 // or packages running under the shared user of the removed 19712 // package if revoking the permissions requested only by the removed 19713 // package is successful and this causes a change in gids. 19714 for (int userId : UserManagerService.getInstance().getUserIds()) { 19715 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 19716 userId); 19717 if (userIdToKill == UserHandle.USER_ALL 19718 || userIdToKill >= UserHandle.USER_SYSTEM) { 19719 // If gids changed for this user, kill all affected packages. 19720 mHandler.post(new Runnable() { 19721 @Override 19722 public void run() { 19723 // This has to happen with no lock held. 19724 killApplication(deletedPs.name, deletedPs.appId, 19725 KILL_APP_REASON_GIDS_CHANGED); 19726 } 19727 }); 19728 break; 19729 } 19730 } 19731 } 19732 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 19733 } 19734 // make sure to preserve per-user disabled state if this removal was just 19735 // a downgrade of a system app to the factory package 19736 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 19737 if (DEBUG_REMOVE) { 19738 Slog.d(TAG, "Propagating install state across downgrade"); 19739 } 19740 for (int userId : allUserHandles) { 19741 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 19742 if (DEBUG_REMOVE) { 19743 Slog.d(TAG, " user " + userId + " => " + installed); 19744 } 19745 if (installed != ps.getInstalled(userId)) { 19746 installedStateChanged = true; 19747 } 19748 ps.setInstalled(installed, userId); 19749 } 19750 } 19751 } 19752 // can downgrade to reader 19753 if (writeSettings) { 19754 // Save settings now 19755 mSettings.writeLPr(); 19756 } 19757 if (installedStateChanged) { 19758 mSettings.writeKernelMappingLPr(ps); 19759 } 19760 } 19761 if (removedAppId != -1) { 19762 // A user ID was deleted here. Go through all users and remove it 19763 // from KeyStore. 19764 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 19765 } 19766 } 19767 19768 static boolean locationIsPrivileged(File path) { 19769 try { 19770 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 19771 .getCanonicalPath(); 19772 return path.getCanonicalPath().startsWith(privilegedAppDir); 19773 } catch (IOException e) { 19774 Slog.e(TAG, "Unable to access code path " + path); 19775 } 19776 return false; 19777 } 19778 19779 /* 19780 * Tries to delete system package. 19781 */ 19782 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 19783 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 19784 boolean writeSettings) { 19785 if (deletedPs.parentPackageName != null) { 19786 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 19787 return false; 19788 } 19789 19790 final boolean applyUserRestrictions 19791 = (allUserHandles != null) && (outInfo.origUsers != null); 19792 final PackageSetting disabledPs; 19793 // Confirm if the system package has been updated 19794 // An updated system app can be deleted. This will also have to restore 19795 // the system pkg from system partition 19796 // reader 19797 synchronized (mPackages) { 19798 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 19799 } 19800 19801 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 19802 + " disabledPs=" + disabledPs); 19803 19804 if (disabledPs == null) { 19805 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 19806 return false; 19807 } else if (DEBUG_REMOVE) { 19808 Slog.d(TAG, "Deleting system pkg from data partition"); 19809 } 19810 19811 if (DEBUG_REMOVE) { 19812 if (applyUserRestrictions) { 19813 Slog.d(TAG, "Remembering install states:"); 19814 for (int userId : allUserHandles) { 19815 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 19816 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 19817 } 19818 } 19819 } 19820 19821 // Delete the updated package 19822 outInfo.isRemovedPackageSystemUpdate = true; 19823 if (outInfo.removedChildPackages != null) { 19824 final int childCount = (deletedPs.childPackageNames != null) 19825 ? deletedPs.childPackageNames.size() : 0; 19826 for (int i = 0; i < childCount; i++) { 19827 String childPackageName = deletedPs.childPackageNames.get(i); 19828 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 19829 .contains(childPackageName)) { 19830 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 19831 childPackageName); 19832 if (childInfo != null) { 19833 childInfo.isRemovedPackageSystemUpdate = true; 19834 } 19835 } 19836 } 19837 } 19838 19839 if (disabledPs.versionCode < deletedPs.versionCode) { 19840 // Delete data for downgrades 19841 flags &= ~PackageManager.DELETE_KEEP_DATA; 19842 } else { 19843 // Preserve data by setting flag 19844 flags |= PackageManager.DELETE_KEEP_DATA; 19845 } 19846 19847 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 19848 outInfo, writeSettings, disabledPs.pkg); 19849 if (!ret) { 19850 return false; 19851 } 19852 19853 // writer 19854 synchronized (mPackages) { 19855 // NOTE: The system package always needs to be enabled; even if it's for 19856 // a compressed stub. If we don't, installing the system package fails 19857 // during scan [scanning checks the disabled packages]. We will reverse 19858 // this later, after we've "installed" the stub. 19859 // Reinstate the old system package 19860 enableSystemPackageLPw(disabledPs.pkg); 19861 // Remove any native libraries from the upgraded package. 19862 removeNativeBinariesLI(deletedPs); 19863 } 19864 19865 // Install the system package 19866 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 19867 try { 19868 installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles, 19869 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 19870 } catch (PackageManagerException e) { 19871 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 19872 + e.getMessage()); 19873 return false; 19874 } finally { 19875 if (disabledPs.pkg.isStub) { 19876 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 19877 } 19878 } 19879 return true; 19880 } 19881 19882 /** 19883 * Installs a package that's already on the system partition. 19884 */ 19885 private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath, 19886 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 19887 @Nullable PermissionsState origPermissionState, boolean writeSettings) 19888 throws PackageManagerException { 19889 int parseFlags = mDefParseFlags 19890 | PackageParser.PARSE_MUST_BE_APK 19891 | PackageParser.PARSE_IS_SYSTEM 19892 | PackageParser.PARSE_IS_SYSTEM_DIR; 19893 if (isPrivileged || locationIsPrivileged(codePath)) { 19894 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 19895 } 19896 19897 final PackageParser.Package newPkg = 19898 scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null); 19899 19900 try { 19901 // update shared libraries for the newly re-installed system package 19902 updateSharedLibrariesLPr(newPkg, null); 19903 } catch (PackageManagerException e) { 19904 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 19905 } 19906 19907 prepareAppDataAfterInstallLIF(newPkg); 19908 19909 // writer 19910 synchronized (mPackages) { 19911 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 19912 19913 // Propagate the permissions state as we do not want to drop on the floor 19914 // runtime permissions. The update permissions method below will take 19915 // care of removing obsolete permissions and grant install permissions. 19916 if (origPermissionState != null) { 19917 ps.getPermissionsState().copyFrom(origPermissionState); 19918 } 19919 updatePermissionsLPw(newPkg.packageName, newPkg, 19920 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 19921 19922 final boolean applyUserRestrictions 19923 = (allUserHandles != null) && (origUserHandles != null); 19924 if (applyUserRestrictions) { 19925 boolean installedStateChanged = false; 19926 if (DEBUG_REMOVE) { 19927 Slog.d(TAG, "Propagating install state across reinstall"); 19928 } 19929 for (int userId : allUserHandles) { 19930 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 19931 if (DEBUG_REMOVE) { 19932 Slog.d(TAG, " user " + userId + " => " + installed); 19933 } 19934 if (installed != ps.getInstalled(userId)) { 19935 installedStateChanged = true; 19936 } 19937 ps.setInstalled(installed, userId); 19938 19939 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19940 } 19941 // Regardless of writeSettings we need to ensure that this restriction 19942 // state propagation is persisted 19943 mSettings.writeAllUsersPackageRestrictionsLPr(); 19944 if (installedStateChanged) { 19945 mSettings.writeKernelMappingLPr(ps); 19946 } 19947 } 19948 // can downgrade to reader here 19949 if (writeSettings) { 19950 mSettings.writeLPr(); 19951 } 19952 } 19953 return newPkg; 19954 } 19955 19956 private boolean deleteInstalledPackageLIF(PackageSetting ps, 19957 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 19958 PackageRemovedInfo outInfo, boolean writeSettings, 19959 PackageParser.Package replacingPackage) { 19960 synchronized (mPackages) { 19961 if (outInfo != null) { 19962 outInfo.uid = ps.appId; 19963 } 19964 19965 if (outInfo != null && outInfo.removedChildPackages != null) { 19966 final int childCount = (ps.childPackageNames != null) 19967 ? ps.childPackageNames.size() : 0; 19968 for (int i = 0; i < childCount; i++) { 19969 String childPackageName = ps.childPackageNames.get(i); 19970 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 19971 if (childPs == null) { 19972 return false; 19973 } 19974 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 19975 childPackageName); 19976 if (childInfo != null) { 19977 childInfo.uid = childPs.appId; 19978 } 19979 } 19980 } 19981 } 19982 19983 // Delete package data from internal structures and also remove data if flag is set 19984 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 19985 19986 // Delete the child packages data 19987 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 19988 for (int i = 0; i < childCount; i++) { 19989 PackageSetting childPs; 19990 synchronized (mPackages) { 19991 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 19992 } 19993 if (childPs != null) { 19994 PackageRemovedInfo childOutInfo = (outInfo != null 19995 && outInfo.removedChildPackages != null) 19996 ? outInfo.removedChildPackages.get(childPs.name) : null; 19997 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 19998 && (replacingPackage != null 19999 && !replacingPackage.hasChildPackage(childPs.name)) 20000 ? flags & ~DELETE_KEEP_DATA : flags; 20001 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 20002 deleteFlags, writeSettings); 20003 } 20004 } 20005 20006 // Delete application code and resources only for parent packages 20007 if (ps.parentPackageName == null) { 20008 if (deleteCodeAndResources && (outInfo != null)) { 20009 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 20010 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 20011 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 20012 } 20013 } 20014 20015 return true; 20016 } 20017 20018 @Override 20019 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 20020 int userId) { 20021 mContext.enforceCallingOrSelfPermission( 20022 android.Manifest.permission.DELETE_PACKAGES, null); 20023 synchronized (mPackages) { 20024 // Cannot block uninstall of static shared libs as they are 20025 // considered a part of the using app (emulating static linking). 20026 // Also static libs are installed always on internal storage. 20027 PackageParser.Package pkg = mPackages.get(packageName); 20028 if (pkg != null && pkg.staticSharedLibName != null) { 20029 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 20030 + " providing static shared library: " + pkg.staticSharedLibName); 20031 return false; 20032 } 20033 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 20034 mSettings.writePackageRestrictionsLPr(userId); 20035 } 20036 return true; 20037 } 20038 20039 @Override 20040 public boolean getBlockUninstallForUser(String packageName, int userId) { 20041 synchronized (mPackages) { 20042 final PackageSetting ps = mSettings.mPackages.get(packageName); 20043 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 20044 return false; 20045 } 20046 return mSettings.getBlockUninstallLPr(userId, packageName); 20047 } 20048 } 20049 20050 @Override 20051 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 20052 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 20053 synchronized (mPackages) { 20054 PackageSetting ps = mSettings.mPackages.get(packageName); 20055 if (ps == null) { 20056 Log.w(TAG, "Package doesn't exist: " + packageName); 20057 return false; 20058 } 20059 if (systemUserApp) { 20060 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 20061 } else { 20062 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 20063 } 20064 mSettings.writeLPr(); 20065 } 20066 return true; 20067 } 20068 20069 /* 20070 * This method handles package deletion in general 20071 */ 20072 private boolean deletePackageLIF(String packageName, UserHandle user, 20073 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 20074 PackageRemovedInfo outInfo, boolean writeSettings, 20075 PackageParser.Package replacingPackage) { 20076 if (packageName == null) { 20077 Slog.w(TAG, "Attempt to delete null packageName."); 20078 return false; 20079 } 20080 20081 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 20082 20083 PackageSetting ps; 20084 synchronized (mPackages) { 20085 ps = mSettings.mPackages.get(packageName); 20086 if (ps == null) { 20087 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 20088 return false; 20089 } 20090 20091 if (ps.parentPackageName != null && (!isSystemApp(ps) 20092 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 20093 if (DEBUG_REMOVE) { 20094 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 20095 + ((user == null) ? UserHandle.USER_ALL : user)); 20096 } 20097 final int removedUserId = (user != null) ? user.getIdentifier() 20098 : UserHandle.USER_ALL; 20099 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 20100 return false; 20101 } 20102 markPackageUninstalledForUserLPw(ps, user); 20103 scheduleWritePackageRestrictionsLocked(user); 20104 return true; 20105 } 20106 } 20107 20108 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 20109 && user.getIdentifier() != UserHandle.USER_ALL)) { 20110 // The caller is asking that the package only be deleted for a single 20111 // user. To do this, we just mark its uninstalled state and delete 20112 // its data. If this is a system app, we only allow this to happen if 20113 // they have set the special DELETE_SYSTEM_APP which requests different 20114 // semantics than normal for uninstalling system apps. 20115 markPackageUninstalledForUserLPw(ps, user); 20116 20117 if (!isSystemApp(ps)) { 20118 // Do not uninstall the APK if an app should be cached 20119 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 20120 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 20121 // Other user still have this package installed, so all 20122 // we need to do is clear this user's data and save that 20123 // it is uninstalled. 20124 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 20125 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 20126 return false; 20127 } 20128 scheduleWritePackageRestrictionsLocked(user); 20129 return true; 20130 } else { 20131 // We need to set it back to 'installed' so the uninstall 20132 // broadcasts will be sent correctly. 20133 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 20134 ps.setInstalled(true, user.getIdentifier()); 20135 mSettings.writeKernelMappingLPr(ps); 20136 } 20137 } else { 20138 // This is a system app, so we assume that the 20139 // other users still have this package installed, so all 20140 // we need to do is clear this user's data and save that 20141 // it is uninstalled. 20142 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 20143 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 20144 return false; 20145 } 20146 scheduleWritePackageRestrictionsLocked(user); 20147 return true; 20148 } 20149 } 20150 20151 // If we are deleting a composite package for all users, keep track 20152 // of result for each child. 20153 if (ps.childPackageNames != null && outInfo != null) { 20154 synchronized (mPackages) { 20155 final int childCount = ps.childPackageNames.size(); 20156 outInfo.removedChildPackages = new ArrayMap<>(childCount); 20157 for (int i = 0; i < childCount; i++) { 20158 String childPackageName = ps.childPackageNames.get(i); 20159 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 20160 childInfo.removedPackage = childPackageName; 20161 childInfo.installerPackageName = ps.installerPackageName; 20162 outInfo.removedChildPackages.put(childPackageName, childInfo); 20163 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 20164 if (childPs != null) { 20165 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 20166 } 20167 } 20168 } 20169 } 20170 20171 boolean ret = false; 20172 if (isSystemApp(ps)) { 20173 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 20174 // When an updated system application is deleted we delete the existing resources 20175 // as well and fall back to existing code in system partition 20176 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 20177 } else { 20178 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 20179 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 20180 outInfo, writeSettings, replacingPackage); 20181 } 20182 20183 // Take a note whether we deleted the package for all users 20184 if (outInfo != null) { 20185 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 20186 if (outInfo.removedChildPackages != null) { 20187 synchronized (mPackages) { 20188 final int childCount = outInfo.removedChildPackages.size(); 20189 for (int i = 0; i < childCount; i++) { 20190 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 20191 if (childInfo != null) { 20192 childInfo.removedForAllUsers = mPackages.get( 20193 childInfo.removedPackage) == null; 20194 } 20195 } 20196 } 20197 } 20198 // If we uninstalled an update to a system app there may be some 20199 // child packages that appeared as they are declared in the system 20200 // app but were not declared in the update. 20201 if (isSystemApp(ps)) { 20202 synchronized (mPackages) { 20203 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 20204 final int childCount = (updatedPs.childPackageNames != null) 20205 ? updatedPs.childPackageNames.size() : 0; 20206 for (int i = 0; i < childCount; i++) { 20207 String childPackageName = updatedPs.childPackageNames.get(i); 20208 if (outInfo.removedChildPackages == null 20209 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 20210 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 20211 if (childPs == null) { 20212 continue; 20213 } 20214 PackageInstalledInfo installRes = new PackageInstalledInfo(); 20215 installRes.name = childPackageName; 20216 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 20217 installRes.pkg = mPackages.get(childPackageName); 20218 installRes.uid = childPs.pkg.applicationInfo.uid; 20219 if (outInfo.appearedChildPackages == null) { 20220 outInfo.appearedChildPackages = new ArrayMap<>(); 20221 } 20222 outInfo.appearedChildPackages.put(childPackageName, installRes); 20223 } 20224 } 20225 } 20226 } 20227 } 20228 20229 return ret; 20230 } 20231 20232 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 20233 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 20234 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 20235 for (int nextUserId : userIds) { 20236 if (DEBUG_REMOVE) { 20237 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 20238 } 20239 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 20240 false /*installed*/, 20241 true /*stopped*/, 20242 true /*notLaunched*/, 20243 false /*hidden*/, 20244 false /*suspended*/, 20245 false /*instantApp*/, 20246 false /*virtualPreload*/, 20247 null /*lastDisableAppCaller*/, 20248 null /*enabledComponents*/, 20249 null /*disabledComponents*/, 20250 ps.readUserState(nextUserId).domainVerificationStatus, 20251 0, PackageManager.INSTALL_REASON_UNKNOWN); 20252 } 20253 mSettings.writeKernelMappingLPr(ps); 20254 } 20255 20256 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 20257 PackageRemovedInfo outInfo) { 20258 final PackageParser.Package pkg; 20259 synchronized (mPackages) { 20260 pkg = mPackages.get(ps.name); 20261 } 20262 20263 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 20264 : new int[] {userId}; 20265 for (int nextUserId : userIds) { 20266 if (DEBUG_REMOVE) { 20267 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 20268 + nextUserId); 20269 } 20270 20271 destroyAppDataLIF(pkg, userId, 20272 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20273 destroyAppProfilesLIF(pkg, userId); 20274 clearDefaultBrowserIfNeededForUser(ps.name, userId); 20275 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 20276 schedulePackageCleaning(ps.name, nextUserId, false); 20277 synchronized (mPackages) { 20278 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 20279 scheduleWritePackageRestrictionsLocked(nextUserId); 20280 } 20281 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 20282 } 20283 } 20284 20285 if (outInfo != null) { 20286 outInfo.removedPackage = ps.name; 20287 outInfo.installerPackageName = ps.installerPackageName; 20288 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 20289 outInfo.removedAppId = ps.appId; 20290 outInfo.removedUsers = userIds; 20291 outInfo.broadcastUsers = userIds; 20292 } 20293 20294 return true; 20295 } 20296 20297 private final class ClearStorageConnection implements ServiceConnection { 20298 IMediaContainerService mContainerService; 20299 20300 @Override 20301 public void onServiceConnected(ComponentName name, IBinder service) { 20302 synchronized (this) { 20303 mContainerService = IMediaContainerService.Stub 20304 .asInterface(Binder.allowBlocking(service)); 20305 notifyAll(); 20306 } 20307 } 20308 20309 @Override 20310 public void onServiceDisconnected(ComponentName name) { 20311 } 20312 } 20313 20314 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 20315 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 20316 20317 final boolean mounted; 20318 if (Environment.isExternalStorageEmulated()) { 20319 mounted = true; 20320 } else { 20321 final String status = Environment.getExternalStorageState(); 20322 20323 mounted = status.equals(Environment.MEDIA_MOUNTED) 20324 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 20325 } 20326 20327 if (!mounted) { 20328 return; 20329 } 20330 20331 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 20332 int[] users; 20333 if (userId == UserHandle.USER_ALL) { 20334 users = sUserManager.getUserIds(); 20335 } else { 20336 users = new int[] { userId }; 20337 } 20338 final ClearStorageConnection conn = new ClearStorageConnection(); 20339 if (mContext.bindServiceAsUser( 20340 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 20341 try { 20342 for (int curUser : users) { 20343 long timeout = SystemClock.uptimeMillis() + 5000; 20344 synchronized (conn) { 20345 long now; 20346 while (conn.mContainerService == null && 20347 (now = SystemClock.uptimeMillis()) < timeout) { 20348 try { 20349 conn.wait(timeout - now); 20350 } catch (InterruptedException e) { 20351 } 20352 } 20353 } 20354 if (conn.mContainerService == null) { 20355 return; 20356 } 20357 20358 final UserEnvironment userEnv = new UserEnvironment(curUser); 20359 clearDirectory(conn.mContainerService, 20360 userEnv.buildExternalStorageAppCacheDirs(packageName)); 20361 if (allData) { 20362 clearDirectory(conn.mContainerService, 20363 userEnv.buildExternalStorageAppDataDirs(packageName)); 20364 clearDirectory(conn.mContainerService, 20365 userEnv.buildExternalStorageAppMediaDirs(packageName)); 20366 } 20367 } 20368 } finally { 20369 mContext.unbindService(conn); 20370 } 20371 } 20372 } 20373 20374 @Override 20375 public void clearApplicationProfileData(String packageName) { 20376 enforceSystemOrRoot("Only the system can clear all profile data"); 20377 20378 final PackageParser.Package pkg; 20379 synchronized (mPackages) { 20380 pkg = mPackages.get(packageName); 20381 } 20382 20383 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 20384 synchronized (mInstallLock) { 20385 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 20386 } 20387 } 20388 } 20389 20390 @Override 20391 public void clearApplicationUserData(final String packageName, 20392 final IPackageDataObserver observer, final int userId) { 20393 mContext.enforceCallingOrSelfPermission( 20394 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 20395 20396 final int callingUid = Binder.getCallingUid(); 20397 enforceCrossUserPermission(callingUid, userId, 20398 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 20399 20400 final PackageSetting ps = mSettings.getPackageLPr(packageName); 20401 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 20402 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 20403 throw new SecurityException("Cannot clear data for a protected package: " 20404 + packageName); 20405 } 20406 // Queue up an async operation since the package deletion may take a little while. 20407 mHandler.post(new Runnable() { 20408 public void run() { 20409 mHandler.removeCallbacks(this); 20410 final boolean succeeded; 20411 if (!filterApp) { 20412 try (PackageFreezer freezer = freezePackage(packageName, 20413 "clearApplicationUserData")) { 20414 synchronized (mInstallLock) { 20415 succeeded = clearApplicationUserDataLIF(packageName, userId); 20416 } 20417 clearExternalStorageDataSync(packageName, userId, true); 20418 synchronized (mPackages) { 20419 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 20420 packageName, userId); 20421 } 20422 } 20423 if (succeeded) { 20424 // invoke DeviceStorageMonitor's update method to clear any notifications 20425 DeviceStorageMonitorInternal dsm = LocalServices 20426 .getService(DeviceStorageMonitorInternal.class); 20427 if (dsm != null) { 20428 dsm.checkMemory(); 20429 } 20430 } 20431 } else { 20432 succeeded = false; 20433 } 20434 if (observer != null) { 20435 try { 20436 observer.onRemoveCompleted(packageName, succeeded); 20437 } catch (RemoteException e) { 20438 Log.i(TAG, "Observer no longer exists."); 20439 } 20440 } //end if observer 20441 } //end run 20442 }); 20443 } 20444 20445 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 20446 if (packageName == null) { 20447 Slog.w(TAG, "Attempt to delete null packageName."); 20448 return false; 20449 } 20450 20451 // Try finding details about the requested package 20452 PackageParser.Package pkg; 20453 synchronized (mPackages) { 20454 pkg = mPackages.get(packageName); 20455 if (pkg == null) { 20456 final PackageSetting ps = mSettings.mPackages.get(packageName); 20457 if (ps != null) { 20458 pkg = ps.pkg; 20459 } 20460 } 20461 20462 if (pkg == null) { 20463 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 20464 return false; 20465 } 20466 20467 PackageSetting ps = (PackageSetting) pkg.mExtras; 20468 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 20469 } 20470 20471 clearAppDataLIF(pkg, userId, 20472 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20473 20474 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20475 removeKeystoreDataIfNeeded(userId, appId); 20476 20477 UserManagerInternal umInternal = getUserManagerInternal(); 20478 final int flags; 20479 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 20480 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20481 } else if (umInternal.isUserRunning(userId)) { 20482 flags = StorageManager.FLAG_STORAGE_DE; 20483 } else { 20484 flags = 0; 20485 } 20486 prepareAppDataContentsLIF(pkg, userId, flags); 20487 20488 return true; 20489 } 20490 20491 /** 20492 * Reverts user permission state changes (permissions and flags) in 20493 * all packages for a given user. 20494 * 20495 * @param userId The device user for which to do a reset. 20496 */ 20497 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 20498 final int packageCount = mPackages.size(); 20499 for (int i = 0; i < packageCount; i++) { 20500 PackageParser.Package pkg = mPackages.valueAt(i); 20501 PackageSetting ps = (PackageSetting) pkg.mExtras; 20502 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 20503 } 20504 } 20505 20506 private void resetNetworkPolicies(int userId) { 20507 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 20508 } 20509 20510 /** 20511 * Reverts user permission state changes (permissions and flags). 20512 * 20513 * @param ps The package for which to reset. 20514 * @param userId The device user for which to do a reset. 20515 */ 20516 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 20517 final PackageSetting ps, final int userId) { 20518 if (ps.pkg == null) { 20519 return; 20520 } 20521 20522 // These are flags that can change base on user actions. 20523 final int userSettableMask = FLAG_PERMISSION_USER_SET 20524 | FLAG_PERMISSION_USER_FIXED 20525 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 20526 | FLAG_PERMISSION_REVIEW_REQUIRED; 20527 20528 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 20529 | FLAG_PERMISSION_POLICY_FIXED; 20530 20531 boolean writeInstallPermissions = false; 20532 boolean writeRuntimePermissions = false; 20533 20534 final int permissionCount = ps.pkg.requestedPermissions.size(); 20535 for (int i = 0; i < permissionCount; i++) { 20536 String permission = ps.pkg.requestedPermissions.get(i); 20537 20538 BasePermission bp = mSettings.mPermissions.get(permission); 20539 if (bp == null) { 20540 continue; 20541 } 20542 20543 // If shared user we just reset the state to which only this app contributed. 20544 if (ps.sharedUser != null) { 20545 boolean used = false; 20546 final int packageCount = ps.sharedUser.packages.size(); 20547 for (int j = 0; j < packageCount; j++) { 20548 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 20549 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 20550 && pkg.pkg.requestedPermissions.contains(permission)) { 20551 used = true; 20552 break; 20553 } 20554 } 20555 if (used) { 20556 continue; 20557 } 20558 } 20559 20560 PermissionsState permissionsState = ps.getPermissionsState(); 20561 20562 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 20563 20564 // Always clear the user settable flags. 20565 final boolean hasInstallState = permissionsState.getInstallPermissionState( 20566 bp.name) != null; 20567 // If permission review is enabled and this is a legacy app, mark the 20568 // permission as requiring a review as this is the initial state. 20569 int flags = 0; 20570 if (mPermissionReviewRequired 20571 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 20572 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 20573 } 20574 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 20575 if (hasInstallState) { 20576 writeInstallPermissions = true; 20577 } else { 20578 writeRuntimePermissions = true; 20579 } 20580 } 20581 20582 // Below is only runtime permission handling. 20583 if (!bp.isRuntime()) { 20584 continue; 20585 } 20586 20587 // Never clobber system or policy. 20588 if ((oldFlags & policyOrSystemFlags) != 0) { 20589 continue; 20590 } 20591 20592 // If this permission was granted by default, make sure it is. 20593 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 20594 if (permissionsState.grantRuntimePermission(bp, userId) 20595 != PERMISSION_OPERATION_FAILURE) { 20596 writeRuntimePermissions = true; 20597 } 20598 // If permission review is enabled the permissions for a legacy apps 20599 // are represented as constantly granted runtime ones, so don't revoke. 20600 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 20601 // Otherwise, reset the permission. 20602 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 20603 switch (revokeResult) { 20604 case PERMISSION_OPERATION_SUCCESS: 20605 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 20606 writeRuntimePermissions = true; 20607 final int appId = ps.appId; 20608 mHandler.post(new Runnable() { 20609 @Override 20610 public void run() { 20611 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 20612 } 20613 }); 20614 } break; 20615 } 20616 } 20617 } 20618 20619 // Synchronously write as we are taking permissions away. 20620 if (writeRuntimePermissions) { 20621 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 20622 } 20623 20624 // Synchronously write as we are taking permissions away. 20625 if (writeInstallPermissions) { 20626 mSettings.writeLPr(); 20627 } 20628 } 20629 20630 /** 20631 * Remove entries from the keystore daemon. Will only remove it if the 20632 * {@code appId} is valid. 20633 */ 20634 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 20635 if (appId < 0) { 20636 return; 20637 } 20638 20639 final KeyStore keyStore = KeyStore.getInstance(); 20640 if (keyStore != null) { 20641 if (userId == UserHandle.USER_ALL) { 20642 for (final int individual : sUserManager.getUserIds()) { 20643 keyStore.clearUid(UserHandle.getUid(individual, appId)); 20644 } 20645 } else { 20646 keyStore.clearUid(UserHandle.getUid(userId, appId)); 20647 } 20648 } else { 20649 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 20650 } 20651 } 20652 20653 @Override 20654 public void deleteApplicationCacheFiles(final String packageName, 20655 final IPackageDataObserver observer) { 20656 final int userId = UserHandle.getCallingUserId(); 20657 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 20658 } 20659 20660 @Override 20661 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 20662 final IPackageDataObserver observer) { 20663 final int callingUid = Binder.getCallingUid(); 20664 mContext.enforceCallingOrSelfPermission( 20665 android.Manifest.permission.DELETE_CACHE_FILES, null); 20666 enforceCrossUserPermission(callingUid, userId, 20667 /* requireFullPermission= */ true, /* checkShell= */ false, 20668 "delete application cache files"); 20669 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 20670 android.Manifest.permission.ACCESS_INSTANT_APPS); 20671 20672 final PackageParser.Package pkg; 20673 synchronized (mPackages) { 20674 pkg = mPackages.get(packageName); 20675 } 20676 20677 // Queue up an async operation since the package deletion may take a little while. 20678 mHandler.post(new Runnable() { 20679 public void run() { 20680 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 20681 boolean doClearData = true; 20682 if (ps != null) { 20683 final boolean targetIsInstantApp = 20684 ps.getInstantApp(UserHandle.getUserId(callingUid)); 20685 doClearData = !targetIsInstantApp 20686 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 20687 } 20688 if (doClearData) { 20689 synchronized (mInstallLock) { 20690 final int flags = StorageManager.FLAG_STORAGE_DE 20691 | StorageManager.FLAG_STORAGE_CE; 20692 // We're only clearing cache files, so we don't care if the 20693 // app is unfrozen and still able to run 20694 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 20695 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20696 } 20697 clearExternalStorageDataSync(packageName, userId, false); 20698 } 20699 if (observer != null) { 20700 try { 20701 observer.onRemoveCompleted(packageName, true); 20702 } catch (RemoteException e) { 20703 Log.i(TAG, "Observer no longer exists."); 20704 } 20705 } 20706 } 20707 }); 20708 } 20709 20710 @Override 20711 public void getPackageSizeInfo(final String packageName, int userHandle, 20712 final IPackageStatsObserver observer) { 20713 throw new UnsupportedOperationException( 20714 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 20715 } 20716 20717 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 20718 final PackageSetting ps; 20719 synchronized (mPackages) { 20720 ps = mSettings.mPackages.get(packageName); 20721 if (ps == null) { 20722 Slog.w(TAG, "Failed to find settings for " + packageName); 20723 return false; 20724 } 20725 } 20726 20727 final String[] packageNames = { packageName }; 20728 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 20729 final String[] codePaths = { ps.codePathString }; 20730 20731 try { 20732 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 20733 ps.appId, ceDataInodes, codePaths, stats); 20734 20735 // For now, ignore code size of packages on system partition 20736 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 20737 stats.codeSize = 0; 20738 } 20739 20740 // External clients expect these to be tracked separately 20741 stats.dataSize -= stats.cacheSize; 20742 20743 } catch (InstallerException e) { 20744 Slog.w(TAG, String.valueOf(e)); 20745 return false; 20746 } 20747 20748 return true; 20749 } 20750 20751 private int getUidTargetSdkVersionLockedLPr(int uid) { 20752 Object obj = mSettings.getUserIdLPr(uid); 20753 if (obj instanceof SharedUserSetting) { 20754 final SharedUserSetting sus = (SharedUserSetting) obj; 20755 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 20756 final Iterator<PackageSetting> it = sus.packages.iterator(); 20757 while (it.hasNext()) { 20758 final PackageSetting ps = it.next(); 20759 if (ps.pkg != null) { 20760 int v = ps.pkg.applicationInfo.targetSdkVersion; 20761 if (v < vers) vers = v; 20762 } 20763 } 20764 return vers; 20765 } else if (obj instanceof PackageSetting) { 20766 final PackageSetting ps = (PackageSetting) obj; 20767 if (ps.pkg != null) { 20768 return ps.pkg.applicationInfo.targetSdkVersion; 20769 } 20770 } 20771 return Build.VERSION_CODES.CUR_DEVELOPMENT; 20772 } 20773 20774 @Override 20775 public void addPreferredActivity(IntentFilter filter, int match, 20776 ComponentName[] set, ComponentName activity, int userId) { 20777 addPreferredActivityInternal(filter, match, set, activity, true, userId, 20778 "Adding preferred"); 20779 } 20780 20781 private void addPreferredActivityInternal(IntentFilter filter, int match, 20782 ComponentName[] set, ComponentName activity, boolean always, int userId, 20783 String opname) { 20784 // writer 20785 int callingUid = Binder.getCallingUid(); 20786 enforceCrossUserPermission(callingUid, userId, 20787 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 20788 if (filter.countActions() == 0) { 20789 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 20790 return; 20791 } 20792 synchronized (mPackages) { 20793 if (mContext.checkCallingOrSelfPermission( 20794 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 20795 != PackageManager.PERMISSION_GRANTED) { 20796 if (getUidTargetSdkVersionLockedLPr(callingUid) 20797 < Build.VERSION_CODES.FROYO) { 20798 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 20799 + callingUid); 20800 return; 20801 } 20802 mContext.enforceCallingOrSelfPermission( 20803 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20804 } 20805 20806 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 20807 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 20808 + userId + ":"); 20809 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20810 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 20811 scheduleWritePackageRestrictionsLocked(userId); 20812 postPreferredActivityChangedBroadcast(userId); 20813 } 20814 } 20815 20816 private void postPreferredActivityChangedBroadcast(int userId) { 20817 mHandler.post(() -> { 20818 final IActivityManager am = ActivityManager.getService(); 20819 if (am == null) { 20820 return; 20821 } 20822 20823 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 20824 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 20825 try { 20826 am.broadcastIntent(null, intent, null, null, 20827 0, null, null, null, android.app.AppOpsManager.OP_NONE, 20828 null, false, false, userId); 20829 } catch (RemoteException e) { 20830 } 20831 }); 20832 } 20833 20834 @Override 20835 public void replacePreferredActivity(IntentFilter filter, int match, 20836 ComponentName[] set, ComponentName activity, int userId) { 20837 if (filter.countActions() != 1) { 20838 throw new IllegalArgumentException( 20839 "replacePreferredActivity expects filter to have only 1 action."); 20840 } 20841 if (filter.countDataAuthorities() != 0 20842 || filter.countDataPaths() != 0 20843 || filter.countDataSchemes() > 1 20844 || filter.countDataTypes() != 0) { 20845 throw new IllegalArgumentException( 20846 "replacePreferredActivity expects filter to have no data authorities, " + 20847 "paths, or types; and at most one scheme."); 20848 } 20849 20850 final int callingUid = Binder.getCallingUid(); 20851 enforceCrossUserPermission(callingUid, userId, 20852 true /* requireFullPermission */, false /* checkShell */, 20853 "replace preferred activity"); 20854 synchronized (mPackages) { 20855 if (mContext.checkCallingOrSelfPermission( 20856 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 20857 != PackageManager.PERMISSION_GRANTED) { 20858 if (getUidTargetSdkVersionLockedLPr(callingUid) 20859 < Build.VERSION_CODES.FROYO) { 20860 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 20861 + Binder.getCallingUid()); 20862 return; 20863 } 20864 mContext.enforceCallingOrSelfPermission( 20865 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20866 } 20867 20868 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 20869 if (pir != null) { 20870 // Get all of the existing entries that exactly match this filter. 20871 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 20872 if (existing != null && existing.size() == 1) { 20873 PreferredActivity cur = existing.get(0); 20874 if (DEBUG_PREFERRED) { 20875 Slog.i(TAG, "Checking replace of preferred:"); 20876 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20877 if (!cur.mPref.mAlways) { 20878 Slog.i(TAG, " -- CUR; not mAlways!"); 20879 } else { 20880 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 20881 Slog.i(TAG, " -- CUR: mSet=" 20882 + Arrays.toString(cur.mPref.mSetComponents)); 20883 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 20884 Slog.i(TAG, " -- NEW: mMatch=" 20885 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 20886 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 20887 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 20888 } 20889 } 20890 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 20891 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 20892 && cur.mPref.sameSet(set)) { 20893 // Setting the preferred activity to what it happens to be already 20894 if (DEBUG_PREFERRED) { 20895 Slog.i(TAG, "Replacing with same preferred activity " 20896 + cur.mPref.mShortComponent + " for user " 20897 + userId + ":"); 20898 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20899 } 20900 return; 20901 } 20902 } 20903 20904 if (existing != null) { 20905 if (DEBUG_PREFERRED) { 20906 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 20907 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20908 } 20909 for (int i = 0; i < existing.size(); i++) { 20910 PreferredActivity pa = existing.get(i); 20911 if (DEBUG_PREFERRED) { 20912 Slog.i(TAG, "Removing existing preferred activity " 20913 + pa.mPref.mComponent + ":"); 20914 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 20915 } 20916 pir.removeFilter(pa); 20917 } 20918 } 20919 } 20920 addPreferredActivityInternal(filter, match, set, activity, true, userId, 20921 "Replacing preferred"); 20922 } 20923 } 20924 20925 @Override 20926 public void clearPackagePreferredActivities(String packageName) { 20927 final int callingUid = Binder.getCallingUid(); 20928 if (getInstantAppPackageName(callingUid) != null) { 20929 return; 20930 } 20931 // writer 20932 synchronized (mPackages) { 20933 PackageParser.Package pkg = mPackages.get(packageName); 20934 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 20935 if (mContext.checkCallingOrSelfPermission( 20936 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 20937 != PackageManager.PERMISSION_GRANTED) { 20938 if (getUidTargetSdkVersionLockedLPr(callingUid) 20939 < Build.VERSION_CODES.FROYO) { 20940 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 20941 + callingUid); 20942 return; 20943 } 20944 mContext.enforceCallingOrSelfPermission( 20945 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20946 } 20947 } 20948 final PackageSetting ps = mSettings.getPackageLPr(packageName); 20949 if (ps != null 20950 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20951 return; 20952 } 20953 int user = UserHandle.getCallingUserId(); 20954 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 20955 scheduleWritePackageRestrictionsLocked(user); 20956 } 20957 } 20958 } 20959 20960 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 20961 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 20962 ArrayList<PreferredActivity> removed = null; 20963 boolean changed = false; 20964 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20965 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 20966 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20967 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 20968 continue; 20969 } 20970 Iterator<PreferredActivity> it = pir.filterIterator(); 20971 while (it.hasNext()) { 20972 PreferredActivity pa = it.next(); 20973 // Mark entry for removal only if it matches the package name 20974 // and the entry is of type "always". 20975 if (packageName == null || 20976 (pa.mPref.mComponent.getPackageName().equals(packageName) 20977 && pa.mPref.mAlways)) { 20978 if (removed == null) { 20979 removed = new ArrayList<PreferredActivity>(); 20980 } 20981 removed.add(pa); 20982 } 20983 } 20984 if (removed != null) { 20985 for (int j=0; j<removed.size(); j++) { 20986 PreferredActivity pa = removed.get(j); 20987 pir.removeFilter(pa); 20988 } 20989 changed = true; 20990 } 20991 } 20992 if (changed) { 20993 postPreferredActivityChangedBroadcast(userId); 20994 } 20995 return changed; 20996 } 20997 20998 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 20999 private void clearIntentFilterVerificationsLPw(int userId) { 21000 final int packageCount = mPackages.size(); 21001 for (int i = 0; i < packageCount; i++) { 21002 PackageParser.Package pkg = mPackages.valueAt(i); 21003 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 21004 } 21005 } 21006 21007 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 21008 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 21009 if (userId == UserHandle.USER_ALL) { 21010 if (mSettings.removeIntentFilterVerificationLPw(packageName, 21011 sUserManager.getUserIds())) { 21012 for (int oneUserId : sUserManager.getUserIds()) { 21013 scheduleWritePackageRestrictionsLocked(oneUserId); 21014 } 21015 } 21016 } else { 21017 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 21018 scheduleWritePackageRestrictionsLocked(userId); 21019 } 21020 } 21021 } 21022 21023 /** Clears state for all users, and touches intent filter verification policy */ 21024 void clearDefaultBrowserIfNeeded(String packageName) { 21025 for (int oneUserId : sUserManager.getUserIds()) { 21026 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 21027 } 21028 } 21029 21030 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 21031 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 21032 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 21033 if (packageName.equals(defaultBrowserPackageName)) { 21034 setDefaultBrowserPackageName(null, userId); 21035 } 21036 } 21037 } 21038 21039 @Override 21040 public void resetApplicationPreferences(int userId) { 21041 mContext.enforceCallingOrSelfPermission( 21042 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 21043 final long identity = Binder.clearCallingIdentity(); 21044 // writer 21045 try { 21046 synchronized (mPackages) { 21047 clearPackagePreferredActivitiesLPw(null, userId); 21048 mSettings.applyDefaultPreferredAppsLPw(this, userId); 21049 // TODO: We have to reset the default SMS and Phone. This requires 21050 // significant refactoring to keep all default apps in the package 21051 // manager (cleaner but more work) or have the services provide 21052 // callbacks to the package manager to request a default app reset. 21053 applyFactoryDefaultBrowserLPw(userId); 21054 clearIntentFilterVerificationsLPw(userId); 21055 primeDomainVerificationsLPw(userId); 21056 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 21057 scheduleWritePackageRestrictionsLocked(userId); 21058 } 21059 resetNetworkPolicies(userId); 21060 } finally { 21061 Binder.restoreCallingIdentity(identity); 21062 } 21063 } 21064 21065 @Override 21066 public int getPreferredActivities(List<IntentFilter> outFilters, 21067 List<ComponentName> outActivities, String packageName) { 21068 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 21069 return 0; 21070 } 21071 int num = 0; 21072 final int userId = UserHandle.getCallingUserId(); 21073 // reader 21074 synchronized (mPackages) { 21075 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 21076 if (pir != null) { 21077 final Iterator<PreferredActivity> it = pir.filterIterator(); 21078 while (it.hasNext()) { 21079 final PreferredActivity pa = it.next(); 21080 if (packageName == null 21081 || (pa.mPref.mComponent.getPackageName().equals(packageName) 21082 && pa.mPref.mAlways)) { 21083 if (outFilters != null) { 21084 outFilters.add(new IntentFilter(pa)); 21085 } 21086 if (outActivities != null) { 21087 outActivities.add(pa.mPref.mComponent); 21088 } 21089 } 21090 } 21091 } 21092 } 21093 21094 return num; 21095 } 21096 21097 @Override 21098 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 21099 int userId) { 21100 int callingUid = Binder.getCallingUid(); 21101 if (callingUid != Process.SYSTEM_UID) { 21102 throw new SecurityException( 21103 "addPersistentPreferredActivity can only be run by the system"); 21104 } 21105 if (filter.countActions() == 0) { 21106 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 21107 return; 21108 } 21109 synchronized (mPackages) { 21110 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 21111 ":"); 21112 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 21113 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 21114 new PersistentPreferredActivity(filter, activity)); 21115 scheduleWritePackageRestrictionsLocked(userId); 21116 postPreferredActivityChangedBroadcast(userId); 21117 } 21118 } 21119 21120 @Override 21121 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 21122 int callingUid = Binder.getCallingUid(); 21123 if (callingUid != Process.SYSTEM_UID) { 21124 throw new SecurityException( 21125 "clearPackagePersistentPreferredActivities can only be run by the system"); 21126 } 21127 ArrayList<PersistentPreferredActivity> removed = null; 21128 boolean changed = false; 21129 synchronized (mPackages) { 21130 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 21131 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 21132 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 21133 .valueAt(i); 21134 if (userId != thisUserId) { 21135 continue; 21136 } 21137 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 21138 while (it.hasNext()) { 21139 PersistentPreferredActivity ppa = it.next(); 21140 // Mark entry for removal only if it matches the package name. 21141 if (ppa.mComponent.getPackageName().equals(packageName)) { 21142 if (removed == null) { 21143 removed = new ArrayList<PersistentPreferredActivity>(); 21144 } 21145 removed.add(ppa); 21146 } 21147 } 21148 if (removed != null) { 21149 for (int j=0; j<removed.size(); j++) { 21150 PersistentPreferredActivity ppa = removed.get(j); 21151 ppir.removeFilter(ppa); 21152 } 21153 changed = true; 21154 } 21155 } 21156 21157 if (changed) { 21158 scheduleWritePackageRestrictionsLocked(userId); 21159 postPreferredActivityChangedBroadcast(userId); 21160 } 21161 } 21162 } 21163 21164 /** 21165 * Common machinery for picking apart a restored XML blob and passing 21166 * it to a caller-supplied functor to be applied to the running system. 21167 */ 21168 private void restoreFromXml(XmlPullParser parser, int userId, 21169 String expectedStartTag, BlobXmlRestorer functor) 21170 throws IOException, XmlPullParserException { 21171 int type; 21172 while ((type = parser.next()) != XmlPullParser.START_TAG 21173 && type != XmlPullParser.END_DOCUMENT) { 21174 } 21175 if (type != XmlPullParser.START_TAG) { 21176 // oops didn't find a start tag?! 21177 if (DEBUG_BACKUP) { 21178 Slog.e(TAG, "Didn't find start tag during restore"); 21179 } 21180 return; 21181 } 21182 Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 21183 // this is supposed to be TAG_PREFERRED_BACKUP 21184 if (!expectedStartTag.equals(parser.getName())) { 21185 if (DEBUG_BACKUP) { 21186 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 21187 } 21188 return; 21189 } 21190 21191 // skip interfering stuff, then we're aligned with the backing implementation 21192 while ((type = parser.next()) == XmlPullParser.TEXT) { } 21193 Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 21194 functor.apply(parser, userId); 21195 } 21196 21197 private interface BlobXmlRestorer { 21198 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 21199 } 21200 21201 /** 21202 * Non-Binder method, support for the backup/restore mechanism: write the 21203 * full set of preferred activities in its canonical XML format. Returns the 21204 * XML output as a byte array, or null if there is none. 21205 */ 21206 @Override 21207 public byte[] getPreferredActivityBackup(int userId) { 21208 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 21209 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 21210 } 21211 21212 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 21213 try { 21214 final XmlSerializer serializer = new FastXmlSerializer(); 21215 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 21216 serializer.startDocument(null, true); 21217 serializer.startTag(null, TAG_PREFERRED_BACKUP); 21218 21219 synchronized (mPackages) { 21220 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 21221 } 21222 21223 serializer.endTag(null, TAG_PREFERRED_BACKUP); 21224 serializer.endDocument(); 21225 serializer.flush(); 21226 } catch (Exception e) { 21227 if (DEBUG_BACKUP) { 21228 Slog.e(TAG, "Unable to write preferred activities for backup", e); 21229 } 21230 return null; 21231 } 21232 21233 return dataStream.toByteArray(); 21234 } 21235 21236 @Override 21237 public void restorePreferredActivities(byte[] backup, int userId) { 21238 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 21239 throw new SecurityException("Only the system may call restorePreferredActivities()"); 21240 } 21241 21242 try { 21243 final XmlPullParser parser = Xml.newPullParser(); 21244 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 21245 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 21246 new BlobXmlRestorer() { 21247 @Override 21248 public void apply(XmlPullParser parser, int userId) 21249 throws XmlPullParserException, IOException { 21250 synchronized (mPackages) { 21251 mSettings.readPreferredActivitiesLPw(parser, userId); 21252 } 21253 } 21254 } ); 21255 } catch (Exception e) { 21256 if (DEBUG_BACKUP) { 21257 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 21258 } 21259 } 21260 } 21261 21262 /** 21263 * Non-Binder method, support for the backup/restore mechanism: write the 21264 * default browser (etc) settings in its canonical XML format. Returns the default 21265 * browser XML representation as a byte array, or null if there is none. 21266 */ 21267 @Override 21268 public byte[] getDefaultAppsBackup(int userId) { 21269 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 21270 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 21271 } 21272 21273 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 21274 try { 21275 final XmlSerializer serializer = new FastXmlSerializer(); 21276 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 21277 serializer.startDocument(null, true); 21278 serializer.startTag(null, TAG_DEFAULT_APPS); 21279 21280 synchronized (mPackages) { 21281 mSettings.writeDefaultAppsLPr(serializer, userId); 21282 } 21283 21284 serializer.endTag(null, TAG_DEFAULT_APPS); 21285 serializer.endDocument(); 21286 serializer.flush(); 21287 } catch (Exception e) { 21288 if (DEBUG_BACKUP) { 21289 Slog.e(TAG, "Unable to write default apps for backup", e); 21290 } 21291 return null; 21292 } 21293 21294 return dataStream.toByteArray(); 21295 } 21296 21297 @Override 21298 public void restoreDefaultApps(byte[] backup, int userId) { 21299 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 21300 throw new SecurityException("Only the system may call restoreDefaultApps()"); 21301 } 21302 21303 try { 21304 final XmlPullParser parser = Xml.newPullParser(); 21305 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 21306 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 21307 new BlobXmlRestorer() { 21308 @Override 21309 public void apply(XmlPullParser parser, int userId) 21310 throws XmlPullParserException, IOException { 21311 synchronized (mPackages) { 21312 mSettings.readDefaultAppsLPw(parser, userId); 21313 } 21314 } 21315 } ); 21316 } catch (Exception e) { 21317 if (DEBUG_BACKUP) { 21318 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 21319 } 21320 } 21321 } 21322 21323 @Override 21324 public byte[] getIntentFilterVerificationBackup(int userId) { 21325 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 21326 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 21327 } 21328 21329 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 21330 try { 21331 final XmlSerializer serializer = new FastXmlSerializer(); 21332 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 21333 serializer.startDocument(null, true); 21334 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 21335 21336 synchronized (mPackages) { 21337 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 21338 } 21339 21340 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 21341 serializer.endDocument(); 21342 serializer.flush(); 21343 } catch (Exception e) { 21344 if (DEBUG_BACKUP) { 21345 Slog.e(TAG, "Unable to write default apps for backup", e); 21346 } 21347 return null; 21348 } 21349 21350 return dataStream.toByteArray(); 21351 } 21352 21353 @Override 21354 public void restoreIntentFilterVerification(byte[] backup, int userId) { 21355 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 21356 throw new SecurityException("Only the system may call restorePreferredActivities()"); 21357 } 21358 21359 try { 21360 final XmlPullParser parser = Xml.newPullParser(); 21361 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 21362 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 21363 new BlobXmlRestorer() { 21364 @Override 21365 public void apply(XmlPullParser parser, int userId) 21366 throws XmlPullParserException, IOException { 21367 synchronized (mPackages) { 21368 mSettings.readAllDomainVerificationsLPr(parser, userId); 21369 mSettings.writeLPr(); 21370 } 21371 } 21372 } ); 21373 } catch (Exception e) { 21374 if (DEBUG_BACKUP) { 21375 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 21376 } 21377 } 21378 } 21379 21380 @Override 21381 public byte[] getPermissionGrantBackup(int userId) { 21382 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 21383 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 21384 } 21385 21386 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 21387 try { 21388 final XmlSerializer serializer = new FastXmlSerializer(); 21389 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 21390 serializer.startDocument(null, true); 21391 serializer.startTag(null, TAG_PERMISSION_BACKUP); 21392 21393 synchronized (mPackages) { 21394 serializeRuntimePermissionGrantsLPr(serializer, userId); 21395 } 21396 21397 serializer.endTag(null, TAG_PERMISSION_BACKUP); 21398 serializer.endDocument(); 21399 serializer.flush(); 21400 } catch (Exception e) { 21401 if (DEBUG_BACKUP) { 21402 Slog.e(TAG, "Unable to write default apps for backup", e); 21403 } 21404 return null; 21405 } 21406 21407 return dataStream.toByteArray(); 21408 } 21409 21410 @Override 21411 public void restorePermissionGrants(byte[] backup, int userId) { 21412 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 21413 throw new SecurityException("Only the system may call restorePermissionGrants()"); 21414 } 21415 21416 try { 21417 final XmlPullParser parser = Xml.newPullParser(); 21418 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 21419 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 21420 new BlobXmlRestorer() { 21421 @Override 21422 public void apply(XmlPullParser parser, int userId) 21423 throws XmlPullParserException, IOException { 21424 synchronized (mPackages) { 21425 processRestoredPermissionGrantsLPr(parser, userId); 21426 } 21427 } 21428 } ); 21429 } catch (Exception e) { 21430 if (DEBUG_BACKUP) { 21431 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 21432 } 21433 } 21434 } 21435 21436 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 21437 throws IOException { 21438 serializer.startTag(null, TAG_ALL_GRANTS); 21439 21440 final int N = mSettings.mPackages.size(); 21441 for (int i = 0; i < N; i++) { 21442 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21443 boolean pkgGrantsKnown = false; 21444 21445 PermissionsState packagePerms = ps.getPermissionsState(); 21446 21447 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 21448 final int grantFlags = state.getFlags(); 21449 // only look at grants that are not system/policy fixed 21450 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 21451 final boolean isGranted = state.isGranted(); 21452 // And only back up the user-twiddled state bits 21453 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 21454 final String packageName = mSettings.mPackages.keyAt(i); 21455 if (!pkgGrantsKnown) { 21456 serializer.startTag(null, TAG_GRANT); 21457 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 21458 pkgGrantsKnown = true; 21459 } 21460 21461 final boolean userSet = 21462 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 21463 final boolean userFixed = 21464 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 21465 final boolean revoke = 21466 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 21467 21468 serializer.startTag(null, TAG_PERMISSION); 21469 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 21470 if (isGranted) { 21471 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 21472 } 21473 if (userSet) { 21474 serializer.attribute(null, ATTR_USER_SET, "true"); 21475 } 21476 if (userFixed) { 21477 serializer.attribute(null, ATTR_USER_FIXED, "true"); 21478 } 21479 if (revoke) { 21480 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 21481 } 21482 serializer.endTag(null, TAG_PERMISSION); 21483 } 21484 } 21485 } 21486 21487 if (pkgGrantsKnown) { 21488 serializer.endTag(null, TAG_GRANT); 21489 } 21490 } 21491 21492 serializer.endTag(null, TAG_ALL_GRANTS); 21493 } 21494 21495 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 21496 throws XmlPullParserException, IOException { 21497 String pkgName = null; 21498 int outerDepth = parser.getDepth(); 21499 int type; 21500 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 21501 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 21502 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 21503 continue; 21504 } 21505 21506 final String tagName = parser.getName(); 21507 if (tagName.equals(TAG_GRANT)) { 21508 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 21509 if (DEBUG_BACKUP) { 21510 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 21511 } 21512 } else if (tagName.equals(TAG_PERMISSION)) { 21513 21514 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 21515 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 21516 21517 int newFlagSet = 0; 21518 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 21519 newFlagSet |= FLAG_PERMISSION_USER_SET; 21520 } 21521 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 21522 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 21523 } 21524 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 21525 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 21526 } 21527 if (DEBUG_BACKUP) { 21528 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 21529 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 21530 } 21531 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21532 if (ps != null) { 21533 // Already installed so we apply the grant immediately 21534 if (DEBUG_BACKUP) { 21535 Slog.v(TAG, " + already installed; applying"); 21536 } 21537 PermissionsState perms = ps.getPermissionsState(); 21538 BasePermission bp = mSettings.mPermissions.get(permName); 21539 if (bp != null) { 21540 if (isGranted) { 21541 perms.grantRuntimePermission(bp, userId); 21542 } 21543 if (newFlagSet != 0) { 21544 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 21545 } 21546 } 21547 } else { 21548 // Need to wait for post-restore install to apply the grant 21549 if (DEBUG_BACKUP) { 21550 Slog.v(TAG, " - not yet installed; saving for later"); 21551 } 21552 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 21553 isGranted, newFlagSet, userId); 21554 } 21555 } else { 21556 PackageManagerService.reportSettingsProblem(Log.WARN, 21557 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 21558 XmlUtils.skipCurrentTag(parser); 21559 } 21560 } 21561 21562 scheduleWriteSettingsLocked(); 21563 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 21564 } 21565 21566 @Override 21567 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 21568 int sourceUserId, int targetUserId, int flags) { 21569 mContext.enforceCallingOrSelfPermission( 21570 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 21571 int callingUid = Binder.getCallingUid(); 21572 enforceOwnerRights(ownerPackage, callingUid); 21573 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 21574 if (intentFilter.countActions() == 0) { 21575 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 21576 return; 21577 } 21578 synchronized (mPackages) { 21579 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 21580 ownerPackage, targetUserId, flags); 21581 CrossProfileIntentResolver resolver = 21582 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 21583 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 21584 // We have all those whose filter is equal. Now checking if the rest is equal as well. 21585 if (existing != null) { 21586 int size = existing.size(); 21587 for (int i = 0; i < size; i++) { 21588 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 21589 return; 21590 } 21591 } 21592 } 21593 resolver.addFilter(newFilter); 21594 scheduleWritePackageRestrictionsLocked(sourceUserId); 21595 } 21596 } 21597 21598 @Override 21599 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 21600 mContext.enforceCallingOrSelfPermission( 21601 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 21602 final int callingUid = Binder.getCallingUid(); 21603 enforceOwnerRights(ownerPackage, callingUid); 21604 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 21605 synchronized (mPackages) { 21606 CrossProfileIntentResolver resolver = 21607 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 21608 ArraySet<CrossProfileIntentFilter> set = 21609 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 21610 for (CrossProfileIntentFilter filter : set) { 21611 if (filter.getOwnerPackage().equals(ownerPackage)) { 21612 resolver.removeFilter(filter); 21613 } 21614 } 21615 scheduleWritePackageRestrictionsLocked(sourceUserId); 21616 } 21617 } 21618 21619 // Enforcing that callingUid is owning pkg on userId 21620 private void enforceOwnerRights(String pkg, int callingUid) { 21621 // The system owns everything. 21622 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 21623 return; 21624 } 21625 final int callingUserId = UserHandle.getUserId(callingUid); 21626 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 21627 if (pi == null) { 21628 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 21629 + callingUserId); 21630 } 21631 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 21632 throw new SecurityException("Calling uid " + callingUid 21633 + " does not own package " + pkg); 21634 } 21635 } 21636 21637 @Override 21638 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 21639 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 21640 return null; 21641 } 21642 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 21643 } 21644 21645 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 21646 UserManagerService ums = UserManagerService.getInstance(); 21647 if (ums != null) { 21648 final UserInfo parent = ums.getProfileParent(userId); 21649 final int launcherUid = (parent != null) ? parent.id : userId; 21650 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 21651 if (launcherComponent != null) { 21652 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 21653 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 21654 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 21655 .setPackage(launcherComponent.getPackageName()); 21656 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 21657 } 21658 } 21659 } 21660 21661 /** 21662 * Report the 'Home' activity which is currently set as "always use this one". If non is set 21663 * then reports the most likely home activity or null if there are more than one. 21664 */ 21665 private ComponentName getDefaultHomeActivity(int userId) { 21666 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 21667 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 21668 if (cn != null) { 21669 return cn; 21670 } 21671 21672 // Find the launcher with the highest priority and return that component if there are no 21673 // other home activity with the same priority. 21674 int lastPriority = Integer.MIN_VALUE; 21675 ComponentName lastComponent = null; 21676 final int size = allHomeCandidates.size(); 21677 for (int i = 0; i < size; i++) { 21678 final ResolveInfo ri = allHomeCandidates.get(i); 21679 if (ri.priority > lastPriority) { 21680 lastComponent = ri.activityInfo.getComponentName(); 21681 lastPriority = ri.priority; 21682 } else if (ri.priority == lastPriority) { 21683 // Two components found with same priority. 21684 lastComponent = null; 21685 } 21686 } 21687 return lastComponent; 21688 } 21689 21690 private Intent getHomeIntent() { 21691 Intent intent = new Intent(Intent.ACTION_MAIN); 21692 intent.addCategory(Intent.CATEGORY_HOME); 21693 intent.addCategory(Intent.CATEGORY_DEFAULT); 21694 return intent; 21695 } 21696 21697 private IntentFilter getHomeFilter() { 21698 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 21699 filter.addCategory(Intent.CATEGORY_HOME); 21700 filter.addCategory(Intent.CATEGORY_DEFAULT); 21701 return filter; 21702 } 21703 21704 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21705 int userId) { 21706 Intent intent = getHomeIntent(); 21707 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 21708 PackageManager.GET_META_DATA, userId); 21709 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 21710 true, false, false, userId); 21711 21712 allHomeCandidates.clear(); 21713 if (list != null) { 21714 for (ResolveInfo ri : list) { 21715 allHomeCandidates.add(ri); 21716 } 21717 } 21718 return (preferred == null || preferred.activityInfo == null) 21719 ? null 21720 : new ComponentName(preferred.activityInfo.packageName, 21721 preferred.activityInfo.name); 21722 } 21723 21724 @Override 21725 public void setHomeActivity(ComponentName comp, int userId) { 21726 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 21727 return; 21728 } 21729 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 21730 getHomeActivitiesAsUser(homeActivities, userId); 21731 21732 boolean found = false; 21733 21734 final int size = homeActivities.size(); 21735 final ComponentName[] set = new ComponentName[size]; 21736 for (int i = 0; i < size; i++) { 21737 final ResolveInfo candidate = homeActivities.get(i); 21738 final ActivityInfo info = candidate.activityInfo; 21739 final ComponentName activityName = new ComponentName(info.packageName, info.name); 21740 set[i] = activityName; 21741 if (!found && activityName.equals(comp)) { 21742 found = true; 21743 } 21744 } 21745 if (!found) { 21746 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 21747 + userId); 21748 } 21749 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 21750 set, comp, userId); 21751 } 21752 21753 private @Nullable String getSetupWizardPackageName() { 21754 final Intent intent = new Intent(Intent.ACTION_MAIN); 21755 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 21756 21757 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 21758 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 21759 | MATCH_DISABLED_COMPONENTS, 21760 UserHandle.myUserId()); 21761 if (matches.size() == 1) { 21762 return matches.get(0).getComponentInfo().packageName; 21763 } else { 21764 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 21765 + ": matches=" + matches); 21766 return null; 21767 } 21768 } 21769 21770 private @Nullable String getStorageManagerPackageName() { 21771 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 21772 21773 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 21774 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 21775 | MATCH_DISABLED_COMPONENTS, 21776 UserHandle.myUserId()); 21777 if (matches.size() == 1) { 21778 return matches.get(0).getComponentInfo().packageName; 21779 } else { 21780 Slog.e(TAG, "There should probably be exactly one storage manager; found " 21781 + matches.size() + ": matches=" + matches); 21782 return null; 21783 } 21784 } 21785 21786 @Override 21787 public void setApplicationEnabledSetting(String appPackageName, 21788 int newState, int flags, int userId, String callingPackage) { 21789 if (!sUserManager.exists(userId)) return; 21790 if (callingPackage == null) { 21791 callingPackage = Integer.toString(Binder.getCallingUid()); 21792 } 21793 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 21794 } 21795 21796 @Override 21797 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 21798 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 21799 synchronized (mPackages) { 21800 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 21801 if (pkgSetting != null) { 21802 pkgSetting.setUpdateAvailable(updateAvailable); 21803 } 21804 } 21805 } 21806 21807 @Override 21808 public void setComponentEnabledSetting(ComponentName componentName, 21809 int newState, int flags, int userId) { 21810 if (!sUserManager.exists(userId)) return; 21811 setEnabledSetting(componentName.getPackageName(), 21812 componentName.getClassName(), newState, flags, userId, null); 21813 } 21814 21815 private void setEnabledSetting(final String packageName, String className, int newState, 21816 final int flags, int userId, String callingPackage) { 21817 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 21818 || newState == COMPONENT_ENABLED_STATE_ENABLED 21819 || newState == COMPONENT_ENABLED_STATE_DISABLED 21820 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 21821 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 21822 throw new IllegalArgumentException("Invalid new component state: " 21823 + newState); 21824 } 21825 PackageSetting pkgSetting; 21826 final int callingUid = Binder.getCallingUid(); 21827 final int permission; 21828 if (callingUid == Process.SYSTEM_UID) { 21829 permission = PackageManager.PERMISSION_GRANTED; 21830 } else { 21831 permission = mContext.checkCallingOrSelfPermission( 21832 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 21833 } 21834 enforceCrossUserPermission(callingUid, userId, 21835 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 21836 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 21837 boolean sendNow = false; 21838 boolean isApp = (className == null); 21839 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 21840 String componentName = isApp ? packageName : className; 21841 int packageUid = -1; 21842 ArrayList<String> components; 21843 21844 // reader 21845 synchronized (mPackages) { 21846 pkgSetting = mSettings.mPackages.get(packageName); 21847 if (pkgSetting == null) { 21848 if (!isCallerInstantApp) { 21849 if (className == null) { 21850 throw new IllegalArgumentException("Unknown package: " + packageName); 21851 } 21852 throw new IllegalArgumentException( 21853 "Unknown component: " + packageName + "/" + className); 21854 } else { 21855 // throw SecurityException to prevent leaking package information 21856 throw new SecurityException( 21857 "Attempt to change component state; " 21858 + "pid=" + Binder.getCallingPid() 21859 + ", uid=" + callingUid 21860 + (className == null 21861 ? ", package=" + packageName 21862 : ", component=" + packageName + "/" + className)); 21863 } 21864 } 21865 } 21866 21867 // Limit who can change which apps 21868 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 21869 // Don't allow apps that don't have permission to modify other apps 21870 if (!allowedByPermission 21871 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 21872 throw new SecurityException( 21873 "Attempt to change component state; " 21874 + "pid=" + Binder.getCallingPid() 21875 + ", uid=" + callingUid 21876 + (className == null 21877 ? ", package=" + packageName 21878 : ", component=" + packageName + "/" + className)); 21879 } 21880 // Don't allow changing protected packages. 21881 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 21882 throw new SecurityException("Cannot disable a protected package: " + packageName); 21883 } 21884 } 21885 21886 synchronized (mPackages) { 21887 if (callingUid == Process.SHELL_UID 21888 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 21889 // Shell can only change whole packages between ENABLED and DISABLED_USER states 21890 // unless it is a test package. 21891 int oldState = pkgSetting.getEnabled(userId); 21892 if (className == null 21893 && 21894 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 21895 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 21896 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 21897 && 21898 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 21899 || newState == COMPONENT_ENABLED_STATE_DEFAULT 21900 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 21901 // ok 21902 } else { 21903 throw new SecurityException( 21904 "Shell cannot change component state for " + packageName + "/" 21905 + className + " to " + newState); 21906 } 21907 } 21908 } 21909 if (className == null) { 21910 // We're dealing with an application/package level state change 21911 synchronized (mPackages) { 21912 if (pkgSetting.getEnabled(userId) == newState) { 21913 // Nothing to do 21914 return; 21915 } 21916 } 21917 // If we're enabling a system stub, there's a little more work to do. 21918 // Prior to enabling the package, we need to decompress the APK(s) to the 21919 // data partition and then replace the version on the system partition. 21920 final PackageParser.Package deletedPkg = pkgSetting.pkg; 21921 final boolean isSystemStub = deletedPkg.isStub 21922 && deletedPkg.isSystemApp(); 21923 if (isSystemStub 21924 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 21925 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 21926 final File codePath = decompressPackage(deletedPkg); 21927 if (codePath == null) { 21928 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 21929 return; 21930 } 21931 // TODO remove direct parsing of the package object during internal cleanup 21932 // of scan package 21933 // We need to call parse directly here for no other reason than we need 21934 // the new package in order to disable the old one [we use the information 21935 // for some internal optimization to optionally create a new package setting 21936 // object on replace]. However, we can't get the package from the scan 21937 // because the scan modifies live structures and we need to remove the 21938 // old [system] package from the system before a scan can be attempted. 21939 // Once scan is indempotent we can remove this parse and use the package 21940 // object we scanned, prior to adding it to package settings. 21941 final PackageParser pp = new PackageParser(); 21942 pp.setSeparateProcesses(mSeparateProcesses); 21943 pp.setDisplayMetrics(mMetrics); 21944 pp.setCallback(mPackageParserCallback); 21945 final PackageParser.Package tmpPkg; 21946 try { 21947 final int parseFlags = mDefParseFlags 21948 | PackageParser.PARSE_MUST_BE_APK 21949 | PackageParser.PARSE_IS_SYSTEM 21950 | PackageParser.PARSE_IS_SYSTEM_DIR; 21951 tmpPkg = pp.parsePackage(codePath, parseFlags); 21952 } catch (PackageParserException e) { 21953 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 21954 return; 21955 } 21956 synchronized (mInstallLock) { 21957 // Disable the stub and remove any package entries 21958 removePackageLI(deletedPkg, true); 21959 synchronized (mPackages) { 21960 disableSystemPackageLPw(deletedPkg, tmpPkg); 21961 } 21962 final PackageParser.Package newPkg; 21963 try (PackageFreezer freezer = 21964 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 21965 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 21966 | PackageParser.PARSE_ENFORCE_CODE; 21967 newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 21968 0 /*currentTime*/, null /*user*/); 21969 prepareAppDataAfterInstallLIF(newPkg); 21970 synchronized (mPackages) { 21971 try { 21972 updateSharedLibrariesLPr(newPkg, null); 21973 } catch (PackageManagerException e) { 21974 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 21975 } 21976 updatePermissionsLPw(newPkg.packageName, newPkg, 21977 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 21978 mSettings.writeLPr(); 21979 } 21980 } catch (PackageManagerException e) { 21981 // Whoops! Something went wrong; try to roll back to the stub 21982 Slog.w(TAG, "Failed to install compressed system package:" 21983 + pkgSetting.name, e); 21984 // Remove the failed install 21985 removeCodePathLI(codePath); 21986 21987 // Install the system package 21988 try (PackageFreezer freezer = 21989 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 21990 synchronized (mPackages) { 21991 // NOTE: The system package always needs to be enabled; even 21992 // if it's for a compressed stub. If we don't, installing the 21993 // system package fails during scan [scanning checks the disabled 21994 // packages]. We will reverse this later, after we've "installed" 21995 // the stub. 21996 // This leaves us in a fragile state; the stub should never be 21997 // enabled, so, cross your fingers and hope nothing goes wrong 21998 // until we can disable the package later. 21999 enableSystemPackageLPw(deletedPkg); 22000 } 22001 installPackageFromSystemLIF(new File(deletedPkg.codePath), 22002 false /*isPrivileged*/, null /*allUserHandles*/, 22003 null /*origUserHandles*/, null /*origPermissionsState*/, 22004 true /*writeSettings*/); 22005 } catch (PackageManagerException pme) { 22006 Slog.w(TAG, "Failed to restore system package:" 22007 + deletedPkg.packageName, pme); 22008 } finally { 22009 synchronized (mPackages) { 22010 mSettings.disableSystemPackageLPw( 22011 deletedPkg.packageName, true /*replaced*/); 22012 mSettings.writeLPr(); 22013 } 22014 } 22015 return; 22016 } 22017 clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 22018 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 22019 clearAppProfilesLIF(newPkg, UserHandle.USER_ALL); 22020 mDexManager.notifyPackageUpdated(newPkg.packageName, 22021 newPkg.baseCodePath, newPkg.splitCodePaths); 22022 } 22023 } 22024 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 22025 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 22026 // Don't care about who enables an app. 22027 callingPackage = null; 22028 } 22029 synchronized (mPackages) { 22030 pkgSetting.setEnabled(newState, userId, callingPackage); 22031 } 22032 } else { 22033 synchronized (mPackages) { 22034 // We're dealing with a component level state change 22035 // First, verify that this is a valid class name. 22036 PackageParser.Package pkg = pkgSetting.pkg; 22037 if (pkg == null || !pkg.hasComponentClassName(className)) { 22038 if (pkg != null && 22039 pkg.applicationInfo.targetSdkVersion >= 22040 Build.VERSION_CODES.JELLY_BEAN) { 22041 throw new IllegalArgumentException("Component class " + className 22042 + " does not exist in " + packageName); 22043 } else { 22044 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 22045 + className + " does not exist in " + packageName); 22046 } 22047 } 22048 switch (newState) { 22049 case COMPONENT_ENABLED_STATE_ENABLED: 22050 if (!pkgSetting.enableComponentLPw(className, userId)) { 22051 return; 22052 } 22053 break; 22054 case COMPONENT_ENABLED_STATE_DISABLED: 22055 if (!pkgSetting.disableComponentLPw(className, userId)) { 22056 return; 22057 } 22058 break; 22059 case COMPONENT_ENABLED_STATE_DEFAULT: 22060 if (!pkgSetting.restoreComponentLPw(className, userId)) { 22061 return; 22062 } 22063 break; 22064 default: 22065 Slog.e(TAG, "Invalid new component state: " + newState); 22066 return; 22067 } 22068 } 22069 } 22070 synchronized (mPackages) { 22071 scheduleWritePackageRestrictionsLocked(userId); 22072 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 22073 final long callingId = Binder.clearCallingIdentity(); 22074 try { 22075 updateInstantAppInstallerLocked(packageName); 22076 } finally { 22077 Binder.restoreCallingIdentity(callingId); 22078 } 22079 components = mPendingBroadcasts.get(userId, packageName); 22080 final boolean newPackage = components == null; 22081 if (newPackage) { 22082 components = new ArrayList<String>(); 22083 } 22084 if (!components.contains(componentName)) { 22085 components.add(componentName); 22086 } 22087 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 22088 sendNow = true; 22089 // Purge entry from pending broadcast list if another one exists already 22090 // since we are sending one right away. 22091 mPendingBroadcasts.remove(userId, packageName); 22092 } else { 22093 if (newPackage) { 22094 mPendingBroadcasts.put(userId, packageName, components); 22095 } 22096 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 22097 // Schedule a message 22098 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 22099 } 22100 } 22101 } 22102 22103 long callingId = Binder.clearCallingIdentity(); 22104 try { 22105 if (sendNow) { 22106 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 22107 sendPackageChangedBroadcast(packageName, 22108 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 22109 } 22110 } finally { 22111 Binder.restoreCallingIdentity(callingId); 22112 } 22113 } 22114 22115 @Override 22116 public void flushPackageRestrictionsAsUser(int userId) { 22117 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 22118 return; 22119 } 22120 if (!sUserManager.exists(userId)) { 22121 return; 22122 } 22123 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 22124 false /* checkShell */, "flushPackageRestrictions"); 22125 synchronized (mPackages) { 22126 mSettings.writePackageRestrictionsLPr(userId); 22127 mDirtyUsers.remove(userId); 22128 if (mDirtyUsers.isEmpty()) { 22129 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 22130 } 22131 } 22132 } 22133 22134 private void sendPackageChangedBroadcast(String packageName, 22135 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 22136 if (DEBUG_INSTALL) 22137 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 22138 + componentNames); 22139 Bundle extras = new Bundle(4); 22140 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 22141 String nameList[] = new String[componentNames.size()]; 22142 componentNames.toArray(nameList); 22143 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 22144 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 22145 extras.putInt(Intent.EXTRA_UID, packageUid); 22146 // If this is not reporting a change of the overall package, then only send it 22147 // to registered receivers. We don't want to launch a swath of apps for every 22148 // little component state change. 22149 final int flags = !componentNames.contains(packageName) 22150 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 22151 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 22152 new int[] {UserHandle.getUserId(packageUid)}); 22153 } 22154 22155 @Override 22156 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 22157 if (!sUserManager.exists(userId)) return; 22158 final int callingUid = Binder.getCallingUid(); 22159 if (getInstantAppPackageName(callingUid) != null) { 22160 return; 22161 } 22162 final int permission = mContext.checkCallingOrSelfPermission( 22163 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 22164 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 22165 enforceCrossUserPermission(callingUid, userId, 22166 true /* requireFullPermission */, true /* checkShell */, "stop package"); 22167 // writer 22168 synchronized (mPackages) { 22169 final PackageSetting ps = mSettings.mPackages.get(packageName); 22170 if (!filterAppAccessLPr(ps, callingUid, userId) 22171 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 22172 allowedByPermission, callingUid, userId)) { 22173 scheduleWritePackageRestrictionsLocked(userId); 22174 } 22175 } 22176 } 22177 22178 @Override 22179 public String getInstallerPackageName(String packageName) { 22180 final int callingUid = Binder.getCallingUid(); 22181 if (getInstantAppPackageName(callingUid) != null) { 22182 return null; 22183 } 22184 // reader 22185 synchronized (mPackages) { 22186 final PackageSetting ps = mSettings.mPackages.get(packageName); 22187 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 22188 return null; 22189 } 22190 return mSettings.getInstallerPackageNameLPr(packageName); 22191 } 22192 } 22193 22194 public boolean isOrphaned(String packageName) { 22195 // reader 22196 synchronized (mPackages) { 22197 return mSettings.isOrphaned(packageName); 22198 } 22199 } 22200 22201 @Override 22202 public int getApplicationEnabledSetting(String packageName, int userId) { 22203 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 22204 int callingUid = Binder.getCallingUid(); 22205 enforceCrossUserPermission(callingUid, userId, 22206 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 22207 // reader 22208 synchronized (mPackages) { 22209 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 22210 return COMPONENT_ENABLED_STATE_DISABLED; 22211 } 22212 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 22213 } 22214 } 22215 22216 @Override 22217 public int getComponentEnabledSetting(ComponentName component, int userId) { 22218 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 22219 int callingUid = Binder.getCallingUid(); 22220 enforceCrossUserPermission(callingUid, userId, 22221 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 22222 synchronized (mPackages) { 22223 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 22224 component, TYPE_UNKNOWN, userId)) { 22225 return COMPONENT_ENABLED_STATE_DISABLED; 22226 } 22227 return mSettings.getComponentEnabledSettingLPr(component, userId); 22228 } 22229 } 22230 22231 @Override 22232 public void enterSafeMode() { 22233 enforceSystemOrRoot("Only the system can request entering safe mode"); 22234 22235 if (!mSystemReady) { 22236 mSafeMode = true; 22237 } 22238 } 22239 22240 @Override 22241 public void systemReady() { 22242 enforceSystemOrRoot("Only the system can claim the system is ready"); 22243 22244 mSystemReady = true; 22245 final ContentResolver resolver = mContext.getContentResolver(); 22246 ContentObserver co = new ContentObserver(mHandler) { 22247 @Override 22248 public void onChange(boolean selfChange) { 22249 mEphemeralAppsDisabled = 22250 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 22251 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 22252 } 22253 }; 22254 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 22255 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 22256 false, co, UserHandle.USER_SYSTEM); 22257 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 22258 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 22259 co.onChange(true); 22260 22261 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 22262 // disabled after already being started. 22263 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 22264 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 22265 22266 // Read the compatibilty setting when the system is ready. 22267 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 22268 mContext.getContentResolver(), 22269 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 22270 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 22271 if (DEBUG_SETTINGS) { 22272 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 22273 } 22274 22275 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 22276 22277 synchronized (mPackages) { 22278 // Verify that all of the preferred activity components actually 22279 // exist. It is possible for applications to be updated and at 22280 // that point remove a previously declared activity component that 22281 // had been set as a preferred activity. We try to clean this up 22282 // the next time we encounter that preferred activity, but it is 22283 // possible for the user flow to never be able to return to that 22284 // situation so here we do a sanity check to make sure we haven't 22285 // left any junk around. 22286 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 22287 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 22288 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 22289 removed.clear(); 22290 for (PreferredActivity pa : pir.filterSet()) { 22291 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 22292 removed.add(pa); 22293 } 22294 } 22295 if (removed.size() > 0) { 22296 for (int r=0; r<removed.size(); r++) { 22297 PreferredActivity pa = removed.get(r); 22298 Slog.w(TAG, "Removing dangling preferred activity: " 22299 + pa.mPref.mComponent); 22300 pir.removeFilter(pa); 22301 } 22302 mSettings.writePackageRestrictionsLPr( 22303 mSettings.mPreferredActivities.keyAt(i)); 22304 } 22305 } 22306 22307 for (int userId : UserManagerService.getInstance().getUserIds()) { 22308 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 22309 grantPermissionsUserIds = ArrayUtils.appendInt( 22310 grantPermissionsUserIds, userId); 22311 } 22312 } 22313 } 22314 sUserManager.systemReady(); 22315 22316 // If we upgraded grant all default permissions before kicking off. 22317 for (int userId : grantPermissionsUserIds) { 22318 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22319 } 22320 22321 // If we did not grant default permissions, we preload from this the 22322 // default permission exceptions lazily to ensure we don't hit the 22323 // disk on a new user creation. 22324 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 22325 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 22326 } 22327 22328 // Kick off any messages waiting for system ready 22329 if (mPostSystemReadyMessages != null) { 22330 for (Message msg : mPostSystemReadyMessages) { 22331 msg.sendToTarget(); 22332 } 22333 mPostSystemReadyMessages = null; 22334 } 22335 22336 // Watch for external volumes that come and go over time 22337 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22338 storage.registerListener(mStorageListener); 22339 22340 mInstallerService.systemReady(); 22341 mPackageDexOptimizer.systemReady(); 22342 22343 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 22344 StorageManagerInternal.class); 22345 StorageManagerInternal.addExternalStoragePolicy( 22346 new StorageManagerInternal.ExternalStorageMountPolicy() { 22347 @Override 22348 public int getMountMode(int uid, String packageName) { 22349 if (Process.isIsolated(uid)) { 22350 return Zygote.MOUNT_EXTERNAL_NONE; 22351 } 22352 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 22353 return Zygote.MOUNT_EXTERNAL_DEFAULT; 22354 } 22355 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 22356 return Zygote.MOUNT_EXTERNAL_DEFAULT; 22357 } 22358 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 22359 return Zygote.MOUNT_EXTERNAL_READ; 22360 } 22361 return Zygote.MOUNT_EXTERNAL_WRITE; 22362 } 22363 22364 @Override 22365 public boolean hasExternalStorage(int uid, String packageName) { 22366 return true; 22367 } 22368 }); 22369 22370 // Now that we're mostly running, clean up stale users and apps 22371 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 22372 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 22373 22374 if (mPrivappPermissionsViolations != null) { 22375 Slog.wtf(TAG,"Signature|privileged permissions not in " 22376 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 22377 mPrivappPermissionsViolations = null; 22378 } 22379 } 22380 22381 public void waitForAppDataPrepared() { 22382 if (mPrepareAppDataFuture == null) { 22383 return; 22384 } 22385 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 22386 mPrepareAppDataFuture = null; 22387 } 22388 22389 @Override 22390 public boolean isSafeMode() { 22391 // allow instant applications 22392 return mSafeMode; 22393 } 22394 22395 @Override 22396 public boolean hasSystemUidErrors() { 22397 // allow instant applications 22398 return mHasSystemUidErrors; 22399 } 22400 22401 static String arrayToString(int[] array) { 22402 StringBuffer buf = new StringBuffer(128); 22403 buf.append('['); 22404 if (array != null) { 22405 for (int i=0; i<array.length; i++) { 22406 if (i > 0) buf.append(", "); 22407 buf.append(array[i]); 22408 } 22409 } 22410 buf.append(']'); 22411 return buf.toString(); 22412 } 22413 22414 static class DumpState { 22415 public static final int DUMP_LIBS = 1 << 0; 22416 public static final int DUMP_FEATURES = 1 << 1; 22417 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 22418 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 22419 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 22420 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 22421 public static final int DUMP_PERMISSIONS = 1 << 6; 22422 public static final int DUMP_PACKAGES = 1 << 7; 22423 public static final int DUMP_SHARED_USERS = 1 << 8; 22424 public static final int DUMP_MESSAGES = 1 << 9; 22425 public static final int DUMP_PROVIDERS = 1 << 10; 22426 public static final int DUMP_VERIFIERS = 1 << 11; 22427 public static final int DUMP_PREFERRED = 1 << 12; 22428 public static final int DUMP_PREFERRED_XML = 1 << 13; 22429 public static final int DUMP_KEYSETS = 1 << 14; 22430 public static final int DUMP_VERSION = 1 << 15; 22431 public static final int DUMP_INSTALLS = 1 << 16; 22432 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 22433 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 22434 public static final int DUMP_FROZEN = 1 << 19; 22435 public static final int DUMP_DEXOPT = 1 << 20; 22436 public static final int DUMP_COMPILER_STATS = 1 << 21; 22437 public static final int DUMP_CHANGES = 1 << 22; 22438 public static final int DUMP_VOLUMES = 1 << 23; 22439 22440 public static final int OPTION_SHOW_FILTERS = 1 << 0; 22441 22442 private int mTypes; 22443 22444 private int mOptions; 22445 22446 private boolean mTitlePrinted; 22447 22448 private SharedUserSetting mSharedUser; 22449 22450 public boolean isDumping(int type) { 22451 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 22452 return true; 22453 } 22454 22455 return (mTypes & type) != 0; 22456 } 22457 22458 public void setDump(int type) { 22459 mTypes |= type; 22460 } 22461 22462 public boolean isOptionEnabled(int option) { 22463 return (mOptions & option) != 0; 22464 } 22465 22466 public void setOptionEnabled(int option) { 22467 mOptions |= option; 22468 } 22469 22470 public boolean onTitlePrinted() { 22471 final boolean printed = mTitlePrinted; 22472 mTitlePrinted = true; 22473 return printed; 22474 } 22475 22476 public boolean getTitlePrinted() { 22477 return mTitlePrinted; 22478 } 22479 22480 public void setTitlePrinted(boolean enabled) { 22481 mTitlePrinted = enabled; 22482 } 22483 22484 public SharedUserSetting getSharedUser() { 22485 return mSharedUser; 22486 } 22487 22488 public void setSharedUser(SharedUserSetting user) { 22489 mSharedUser = user; 22490 } 22491 } 22492 22493 @Override 22494 public void onShellCommand(FileDescriptor in, FileDescriptor out, 22495 FileDescriptor err, String[] args, ShellCallback callback, 22496 ResultReceiver resultReceiver) { 22497 (new PackageManagerShellCommand(this)).exec( 22498 this, in, out, err, args, callback, resultReceiver); 22499 } 22500 22501 @Override 22502 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 22503 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 22504 22505 DumpState dumpState = new DumpState(); 22506 boolean fullPreferred = false; 22507 boolean checkin = false; 22508 22509 String packageName = null; 22510 ArraySet<String> permissionNames = null; 22511 22512 int opti = 0; 22513 while (opti < args.length) { 22514 String opt = args[opti]; 22515 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 22516 break; 22517 } 22518 opti++; 22519 22520 if ("-a".equals(opt)) { 22521 // Right now we only know how to print all. 22522 } else if ("-h".equals(opt)) { 22523 pw.println("Package manager dump options:"); 22524 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 22525 pw.println(" --checkin: dump for a checkin"); 22526 pw.println(" -f: print details of intent filters"); 22527 pw.println(" -h: print this help"); 22528 pw.println(" cmd may be one of:"); 22529 pw.println(" l[ibraries]: list known shared libraries"); 22530 pw.println(" f[eatures]: list device features"); 22531 pw.println(" k[eysets]: print known keysets"); 22532 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 22533 pw.println(" perm[issions]: dump permissions"); 22534 pw.println(" permission [name ...]: dump declaration and use of given permission"); 22535 pw.println(" pref[erred]: print preferred package settings"); 22536 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 22537 pw.println(" prov[iders]: dump content providers"); 22538 pw.println(" p[ackages]: dump installed packages"); 22539 pw.println(" s[hared-users]: dump shared user IDs"); 22540 pw.println(" m[essages]: print collected runtime messages"); 22541 pw.println(" v[erifiers]: print package verifier info"); 22542 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 22543 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 22544 pw.println(" version: print database version info"); 22545 pw.println(" write: write current settings now"); 22546 pw.println(" installs: details about install sessions"); 22547 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 22548 pw.println(" dexopt: dump dexopt state"); 22549 pw.println(" compiler-stats: dump compiler statistics"); 22550 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 22551 pw.println(" <package.name>: info about given package"); 22552 return; 22553 } else if ("--checkin".equals(opt)) { 22554 checkin = true; 22555 } else if ("-f".equals(opt)) { 22556 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 22557 } else if ("--proto".equals(opt)) { 22558 dumpProto(fd); 22559 return; 22560 } else { 22561 pw.println("Unknown argument: " + opt + "; use -h for help"); 22562 } 22563 } 22564 22565 // Is the caller requesting to dump a particular piece of data? 22566 if (opti < args.length) { 22567 String cmd = args[opti]; 22568 opti++; 22569 // Is this a package name? 22570 if ("android".equals(cmd) || cmd.contains(".")) { 22571 packageName = cmd; 22572 // When dumping a single package, we always dump all of its 22573 // filter information since the amount of data will be reasonable. 22574 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 22575 } else if ("check-permission".equals(cmd)) { 22576 if (opti >= args.length) { 22577 pw.println("Error: check-permission missing permission argument"); 22578 return; 22579 } 22580 String perm = args[opti]; 22581 opti++; 22582 if (opti >= args.length) { 22583 pw.println("Error: check-permission missing package argument"); 22584 return; 22585 } 22586 22587 String pkg = args[opti]; 22588 opti++; 22589 int user = UserHandle.getUserId(Binder.getCallingUid()); 22590 if (opti < args.length) { 22591 try { 22592 user = Integer.parseInt(args[opti]); 22593 } catch (NumberFormatException e) { 22594 pw.println("Error: check-permission user argument is not a number: " 22595 + args[opti]); 22596 return; 22597 } 22598 } 22599 22600 // Normalize package name to handle renamed packages and static libs 22601 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 22602 22603 pw.println(checkPermission(perm, pkg, user)); 22604 return; 22605 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 22606 dumpState.setDump(DumpState.DUMP_LIBS); 22607 } else if ("f".equals(cmd) || "features".equals(cmd)) { 22608 dumpState.setDump(DumpState.DUMP_FEATURES); 22609 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 22610 if (opti >= args.length) { 22611 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 22612 | DumpState.DUMP_SERVICE_RESOLVERS 22613 | DumpState.DUMP_RECEIVER_RESOLVERS 22614 | DumpState.DUMP_CONTENT_RESOLVERS); 22615 } else { 22616 while (opti < args.length) { 22617 String name = args[opti]; 22618 if ("a".equals(name) || "activity".equals(name)) { 22619 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 22620 } else if ("s".equals(name) || "service".equals(name)) { 22621 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 22622 } else if ("r".equals(name) || "receiver".equals(name)) { 22623 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 22624 } else if ("c".equals(name) || "content".equals(name)) { 22625 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 22626 } else { 22627 pw.println("Error: unknown resolver table type: " + name); 22628 return; 22629 } 22630 opti++; 22631 } 22632 } 22633 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 22634 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 22635 } else if ("permission".equals(cmd)) { 22636 if (opti >= args.length) { 22637 pw.println("Error: permission requires permission name"); 22638 return; 22639 } 22640 permissionNames = new ArraySet<>(); 22641 while (opti < args.length) { 22642 permissionNames.add(args[opti]); 22643 opti++; 22644 } 22645 dumpState.setDump(DumpState.DUMP_PERMISSIONS 22646 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 22647 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 22648 dumpState.setDump(DumpState.DUMP_PREFERRED); 22649 } else if ("preferred-xml".equals(cmd)) { 22650 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 22651 if (opti < args.length && "--full".equals(args[opti])) { 22652 fullPreferred = true; 22653 opti++; 22654 } 22655 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 22656 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 22657 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 22658 dumpState.setDump(DumpState.DUMP_PACKAGES); 22659 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 22660 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 22661 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 22662 dumpState.setDump(DumpState.DUMP_PROVIDERS); 22663 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 22664 dumpState.setDump(DumpState.DUMP_MESSAGES); 22665 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 22666 dumpState.setDump(DumpState.DUMP_VERIFIERS); 22667 } else if ("i".equals(cmd) || "ifv".equals(cmd) 22668 || "intent-filter-verifiers".equals(cmd)) { 22669 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 22670 } else if ("version".equals(cmd)) { 22671 dumpState.setDump(DumpState.DUMP_VERSION); 22672 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 22673 dumpState.setDump(DumpState.DUMP_KEYSETS); 22674 } else if ("installs".equals(cmd)) { 22675 dumpState.setDump(DumpState.DUMP_INSTALLS); 22676 } else if ("frozen".equals(cmd)) { 22677 dumpState.setDump(DumpState.DUMP_FROZEN); 22678 } else if ("volumes".equals(cmd)) { 22679 dumpState.setDump(DumpState.DUMP_VOLUMES); 22680 } else if ("dexopt".equals(cmd)) { 22681 dumpState.setDump(DumpState.DUMP_DEXOPT); 22682 } else if ("compiler-stats".equals(cmd)) { 22683 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 22684 } else if ("changes".equals(cmd)) { 22685 dumpState.setDump(DumpState.DUMP_CHANGES); 22686 } else if ("write".equals(cmd)) { 22687 synchronized (mPackages) { 22688 mSettings.writeLPr(); 22689 pw.println("Settings written."); 22690 return; 22691 } 22692 } 22693 } 22694 22695 if (checkin) { 22696 pw.println("vers,1"); 22697 } 22698 22699 // reader 22700 synchronized (mPackages) { 22701 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 22702 if (!checkin) { 22703 if (dumpState.onTitlePrinted()) 22704 pw.println(); 22705 pw.println("Database versions:"); 22706 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 22707 } 22708 } 22709 22710 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 22711 if (!checkin) { 22712 if (dumpState.onTitlePrinted()) 22713 pw.println(); 22714 pw.println("Verifiers:"); 22715 pw.print(" Required: "); 22716 pw.print(mRequiredVerifierPackage); 22717 pw.print(" (uid="); 22718 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 22719 UserHandle.USER_SYSTEM)); 22720 pw.println(")"); 22721 } else if (mRequiredVerifierPackage != null) { 22722 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 22723 pw.print(","); 22724 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 22725 UserHandle.USER_SYSTEM)); 22726 } 22727 } 22728 22729 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 22730 packageName == null) { 22731 if (mIntentFilterVerifierComponent != null) { 22732 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 22733 if (!checkin) { 22734 if (dumpState.onTitlePrinted()) 22735 pw.println(); 22736 pw.println("Intent Filter Verifier:"); 22737 pw.print(" Using: "); 22738 pw.print(verifierPackageName); 22739 pw.print(" (uid="); 22740 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 22741 UserHandle.USER_SYSTEM)); 22742 pw.println(")"); 22743 } else if (verifierPackageName != null) { 22744 pw.print("ifv,"); pw.print(verifierPackageName); 22745 pw.print(","); 22746 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 22747 UserHandle.USER_SYSTEM)); 22748 } 22749 } else { 22750 pw.println(); 22751 pw.println("No Intent Filter Verifier available!"); 22752 } 22753 } 22754 22755 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 22756 boolean printedHeader = false; 22757 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 22758 while (it.hasNext()) { 22759 String libName = it.next(); 22760 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 22761 if (versionedLib == null) { 22762 continue; 22763 } 22764 final int versionCount = versionedLib.size(); 22765 for (int i = 0; i < versionCount; i++) { 22766 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 22767 if (!checkin) { 22768 if (!printedHeader) { 22769 if (dumpState.onTitlePrinted()) 22770 pw.println(); 22771 pw.println("Libraries:"); 22772 printedHeader = true; 22773 } 22774 pw.print(" "); 22775 } else { 22776 pw.print("lib,"); 22777 } 22778 pw.print(libEntry.info.getName()); 22779 if (libEntry.info.isStatic()) { 22780 pw.print(" version=" + libEntry.info.getVersion()); 22781 } 22782 if (!checkin) { 22783 pw.print(" -> "); 22784 } 22785 if (libEntry.path != null) { 22786 pw.print(" (jar) "); 22787 pw.print(libEntry.path); 22788 } else { 22789 pw.print(" (apk) "); 22790 pw.print(libEntry.apk); 22791 } 22792 pw.println(); 22793 } 22794 } 22795 } 22796 22797 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 22798 if (dumpState.onTitlePrinted()) 22799 pw.println(); 22800 if (!checkin) { 22801 pw.println("Features:"); 22802 } 22803 22804 synchronized (mAvailableFeatures) { 22805 for (FeatureInfo feat : mAvailableFeatures.values()) { 22806 if (checkin) { 22807 pw.print("feat,"); 22808 pw.print(feat.name); 22809 pw.print(","); 22810 pw.println(feat.version); 22811 } else { 22812 pw.print(" "); 22813 pw.print(feat.name); 22814 if (feat.version > 0) { 22815 pw.print(" version="); 22816 pw.print(feat.version); 22817 } 22818 pw.println(); 22819 } 22820 } 22821 } 22822 } 22823 22824 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 22825 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 22826 : "Activity Resolver Table:", " ", packageName, 22827 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 22828 dumpState.setTitlePrinted(true); 22829 } 22830 } 22831 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 22832 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 22833 : "Receiver Resolver Table:", " ", packageName, 22834 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 22835 dumpState.setTitlePrinted(true); 22836 } 22837 } 22838 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 22839 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 22840 : "Service Resolver Table:", " ", packageName, 22841 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 22842 dumpState.setTitlePrinted(true); 22843 } 22844 } 22845 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 22846 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 22847 : "Provider Resolver Table:", " ", packageName, 22848 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 22849 dumpState.setTitlePrinted(true); 22850 } 22851 } 22852 22853 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 22854 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 22855 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 22856 int user = mSettings.mPreferredActivities.keyAt(i); 22857 if (pir.dump(pw, 22858 dumpState.getTitlePrinted() 22859 ? "\nPreferred Activities User " + user + ":" 22860 : "Preferred Activities User " + user + ":", " ", 22861 packageName, true, false)) { 22862 dumpState.setTitlePrinted(true); 22863 } 22864 } 22865 } 22866 22867 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 22868 pw.flush(); 22869 FileOutputStream fout = new FileOutputStream(fd); 22870 BufferedOutputStream str = new BufferedOutputStream(fout); 22871 XmlSerializer serializer = new FastXmlSerializer(); 22872 try { 22873 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 22874 serializer.startDocument(null, true); 22875 serializer.setFeature( 22876 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 22877 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 22878 serializer.endDocument(); 22879 serializer.flush(); 22880 } catch (IllegalArgumentException e) { 22881 pw.println("Failed writing: " + e); 22882 } catch (IllegalStateException e) { 22883 pw.println("Failed writing: " + e); 22884 } catch (IOException e) { 22885 pw.println("Failed writing: " + e); 22886 } 22887 } 22888 22889 if (!checkin 22890 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 22891 && packageName == null) { 22892 pw.println(); 22893 int count = mSettings.mPackages.size(); 22894 if (count == 0) { 22895 pw.println("No applications!"); 22896 pw.println(); 22897 } else { 22898 final String prefix = " "; 22899 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 22900 if (allPackageSettings.size() == 0) { 22901 pw.println("No domain preferred apps!"); 22902 pw.println(); 22903 } else { 22904 pw.println("App verification status:"); 22905 pw.println(); 22906 count = 0; 22907 for (PackageSetting ps : allPackageSettings) { 22908 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 22909 if (ivi == null || ivi.getPackageName() == null) continue; 22910 pw.println(prefix + "Package: " + ivi.getPackageName()); 22911 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 22912 pw.println(prefix + "Status: " + ivi.getStatusString()); 22913 pw.println(); 22914 count++; 22915 } 22916 if (count == 0) { 22917 pw.println(prefix + "No app verification established."); 22918 pw.println(); 22919 } 22920 for (int userId : sUserManager.getUserIds()) { 22921 pw.println("App linkages for user " + userId + ":"); 22922 pw.println(); 22923 count = 0; 22924 for (PackageSetting ps : allPackageSettings) { 22925 final long status = ps.getDomainVerificationStatusForUser(userId); 22926 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 22927 && !DEBUG_DOMAIN_VERIFICATION) { 22928 continue; 22929 } 22930 pw.println(prefix + "Package: " + ps.name); 22931 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 22932 String statusStr = IntentFilterVerificationInfo. 22933 getStatusStringFromValue(status); 22934 pw.println(prefix + "Status: " + statusStr); 22935 pw.println(); 22936 count++; 22937 } 22938 if (count == 0) { 22939 pw.println(prefix + "No configured app linkages."); 22940 pw.println(); 22941 } 22942 } 22943 } 22944 } 22945 } 22946 22947 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 22948 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 22949 if (packageName == null && permissionNames == null) { 22950 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 22951 if (iperm == 0) { 22952 if (dumpState.onTitlePrinted()) 22953 pw.println(); 22954 pw.println("AppOp Permissions:"); 22955 } 22956 pw.print(" AppOp Permission "); 22957 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 22958 pw.println(":"); 22959 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 22960 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 22961 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 22962 } 22963 } 22964 } 22965 } 22966 22967 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 22968 boolean printedSomething = false; 22969 for (PackageParser.Provider p : mProviders.mProviders.values()) { 22970 if (packageName != null && !packageName.equals(p.info.packageName)) { 22971 continue; 22972 } 22973 if (!printedSomething) { 22974 if (dumpState.onTitlePrinted()) 22975 pw.println(); 22976 pw.println("Registered ContentProviders:"); 22977 printedSomething = true; 22978 } 22979 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 22980 pw.print(" "); pw.println(p.toString()); 22981 } 22982 printedSomething = false; 22983 for (Map.Entry<String, PackageParser.Provider> entry : 22984 mProvidersByAuthority.entrySet()) { 22985 PackageParser.Provider p = entry.getValue(); 22986 if (packageName != null && !packageName.equals(p.info.packageName)) { 22987 continue; 22988 } 22989 if (!printedSomething) { 22990 if (dumpState.onTitlePrinted()) 22991 pw.println(); 22992 pw.println("ContentProvider Authorities:"); 22993 printedSomething = true; 22994 } 22995 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 22996 pw.print(" "); pw.println(p.toString()); 22997 if (p.info != null && p.info.applicationInfo != null) { 22998 final String appInfo = p.info.applicationInfo.toString(); 22999 pw.print(" applicationInfo="); pw.println(appInfo); 23000 } 23001 } 23002 } 23003 23004 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 23005 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 23006 } 23007 23008 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 23009 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 23010 } 23011 23012 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 23013 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 23014 } 23015 23016 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 23017 if (dumpState.onTitlePrinted()) pw.println(); 23018 pw.println("Package Changes:"); 23019 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 23020 final int K = mChangedPackages.size(); 23021 for (int i = 0; i < K; i++) { 23022 final SparseArray<String> changes = mChangedPackages.valueAt(i); 23023 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 23024 final int N = changes.size(); 23025 if (N == 0) { 23026 pw.print(" "); pw.println("No packages changed"); 23027 } else { 23028 for (int j = 0; j < N; j++) { 23029 final String pkgName = changes.valueAt(j); 23030 final int sequenceNumber = changes.keyAt(j); 23031 pw.print(" "); 23032 pw.print("seq="); 23033 pw.print(sequenceNumber); 23034 pw.print(", package="); 23035 pw.println(pkgName); 23036 } 23037 } 23038 } 23039 } 23040 23041 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 23042 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 23043 } 23044 23045 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 23046 // XXX should handle packageName != null by dumping only install data that 23047 // the given package is involved with. 23048 if (dumpState.onTitlePrinted()) pw.println(); 23049 23050 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 23051 ipw.println(); 23052 ipw.println("Frozen packages:"); 23053 ipw.increaseIndent(); 23054 if (mFrozenPackages.size() == 0) { 23055 ipw.println("(none)"); 23056 } else { 23057 for (int i = 0; i < mFrozenPackages.size(); i++) { 23058 ipw.println(mFrozenPackages.valueAt(i)); 23059 } 23060 } 23061 ipw.decreaseIndent(); 23062 } 23063 23064 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 23065 if (dumpState.onTitlePrinted()) pw.println(); 23066 23067 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 23068 ipw.println(); 23069 ipw.println("Loaded volumes:"); 23070 ipw.increaseIndent(); 23071 if (mLoadedVolumes.size() == 0) { 23072 ipw.println("(none)"); 23073 } else { 23074 for (int i = 0; i < mLoadedVolumes.size(); i++) { 23075 ipw.println(mLoadedVolumes.valueAt(i)); 23076 } 23077 } 23078 ipw.decreaseIndent(); 23079 } 23080 23081 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 23082 if (dumpState.onTitlePrinted()) pw.println(); 23083 dumpDexoptStateLPr(pw, packageName); 23084 } 23085 23086 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 23087 if (dumpState.onTitlePrinted()) pw.println(); 23088 dumpCompilerStatsLPr(pw, packageName); 23089 } 23090 23091 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 23092 if (dumpState.onTitlePrinted()) pw.println(); 23093 mSettings.dumpReadMessagesLPr(pw, dumpState); 23094 23095 pw.println(); 23096 pw.println("Package warning messages:"); 23097 BufferedReader in = null; 23098 String line = null; 23099 try { 23100 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 23101 while ((line = in.readLine()) != null) { 23102 if (line.contains("ignored: updated version")) continue; 23103 pw.println(line); 23104 } 23105 } catch (IOException ignored) { 23106 } finally { 23107 IoUtils.closeQuietly(in); 23108 } 23109 } 23110 23111 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 23112 BufferedReader in = null; 23113 String line = null; 23114 try { 23115 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 23116 while ((line = in.readLine()) != null) { 23117 if (line.contains("ignored: updated version")) continue; 23118 pw.print("msg,"); 23119 pw.println(line); 23120 } 23121 } catch (IOException ignored) { 23122 } finally { 23123 IoUtils.closeQuietly(in); 23124 } 23125 } 23126 } 23127 23128 // PackageInstaller should be called outside of mPackages lock 23129 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 23130 // XXX should handle packageName != null by dumping only install data that 23131 // the given package is involved with. 23132 if (dumpState.onTitlePrinted()) pw.println(); 23133 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 23134 } 23135 } 23136 23137 private void dumpProto(FileDescriptor fd) { 23138 final ProtoOutputStream proto = new ProtoOutputStream(fd); 23139 23140 synchronized (mPackages) { 23141 final long requiredVerifierPackageToken = 23142 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 23143 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 23144 proto.write( 23145 PackageServiceDumpProto.PackageShortProto.UID, 23146 getPackageUid( 23147 mRequiredVerifierPackage, 23148 MATCH_DEBUG_TRIAGED_MISSING, 23149 UserHandle.USER_SYSTEM)); 23150 proto.end(requiredVerifierPackageToken); 23151 23152 if (mIntentFilterVerifierComponent != null) { 23153 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 23154 final long verifierPackageToken = 23155 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 23156 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 23157 proto.write( 23158 PackageServiceDumpProto.PackageShortProto.UID, 23159 getPackageUid( 23160 verifierPackageName, 23161 MATCH_DEBUG_TRIAGED_MISSING, 23162 UserHandle.USER_SYSTEM)); 23163 proto.end(verifierPackageToken); 23164 } 23165 23166 dumpSharedLibrariesProto(proto); 23167 dumpFeaturesProto(proto); 23168 mSettings.dumpPackagesProto(proto); 23169 mSettings.dumpSharedUsersProto(proto); 23170 dumpMessagesProto(proto); 23171 } 23172 proto.flush(); 23173 } 23174 23175 private void dumpMessagesProto(ProtoOutputStream proto) { 23176 BufferedReader in = null; 23177 String line = null; 23178 try { 23179 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 23180 while ((line = in.readLine()) != null) { 23181 if (line.contains("ignored: updated version")) continue; 23182 proto.write(PackageServiceDumpProto.MESSAGES, line); 23183 } 23184 } catch (IOException ignored) { 23185 } finally { 23186 IoUtils.closeQuietly(in); 23187 } 23188 } 23189 23190 private void dumpFeaturesProto(ProtoOutputStream proto) { 23191 synchronized (mAvailableFeatures) { 23192 final int count = mAvailableFeatures.size(); 23193 for (int i = 0; i < count; i++) { 23194 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 23195 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 23196 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 23197 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 23198 proto.end(featureToken); 23199 } 23200 } 23201 } 23202 23203 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 23204 final int count = mSharedLibraries.size(); 23205 for (int i = 0; i < count; i++) { 23206 final String libName = mSharedLibraries.keyAt(i); 23207 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 23208 if (versionedLib == null) { 23209 continue; 23210 } 23211 final int versionCount = versionedLib.size(); 23212 for (int j = 0; j < versionCount; j++) { 23213 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 23214 final long sharedLibraryToken = 23215 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 23216 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 23217 final boolean isJar = (libEntry.path != null); 23218 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 23219 if (isJar) { 23220 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 23221 } else { 23222 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 23223 } 23224 proto.end(sharedLibraryToken); 23225 } 23226 } 23227 } 23228 23229 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 23230 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 23231 ipw.println(); 23232 ipw.println("Dexopt state:"); 23233 ipw.increaseIndent(); 23234 Collection<PackageParser.Package> packages = null; 23235 if (packageName != null) { 23236 PackageParser.Package targetPackage = mPackages.get(packageName); 23237 if (targetPackage != null) { 23238 packages = Collections.singletonList(targetPackage); 23239 } else { 23240 ipw.println("Unable to find package: " + packageName); 23241 return; 23242 } 23243 } else { 23244 packages = mPackages.values(); 23245 } 23246 23247 for (PackageParser.Package pkg : packages) { 23248 ipw.println("[" + pkg.packageName + "]"); 23249 ipw.increaseIndent(); 23250 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 23251 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 23252 ipw.decreaseIndent(); 23253 } 23254 } 23255 23256 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 23257 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 23258 ipw.println(); 23259 ipw.println("Compiler stats:"); 23260 ipw.increaseIndent(); 23261 Collection<PackageParser.Package> packages = null; 23262 if (packageName != null) { 23263 PackageParser.Package targetPackage = mPackages.get(packageName); 23264 if (targetPackage != null) { 23265 packages = Collections.singletonList(targetPackage); 23266 } else { 23267 ipw.println("Unable to find package: " + packageName); 23268 return; 23269 } 23270 } else { 23271 packages = mPackages.values(); 23272 } 23273 23274 for (PackageParser.Package pkg : packages) { 23275 ipw.println("[" + pkg.packageName + "]"); 23276 ipw.increaseIndent(); 23277 23278 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 23279 if (stats == null) { 23280 ipw.println("(No recorded stats)"); 23281 } else { 23282 stats.dump(ipw); 23283 } 23284 ipw.decreaseIndent(); 23285 } 23286 } 23287 23288 private String dumpDomainString(String packageName) { 23289 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 23290 .getList(); 23291 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 23292 23293 ArraySet<String> result = new ArraySet<>(); 23294 if (iviList.size() > 0) { 23295 for (IntentFilterVerificationInfo ivi : iviList) { 23296 for (String host : ivi.getDomains()) { 23297 result.add(host); 23298 } 23299 } 23300 } 23301 if (filters != null && filters.size() > 0) { 23302 for (IntentFilter filter : filters) { 23303 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 23304 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 23305 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 23306 result.addAll(filter.getHostsList()); 23307 } 23308 } 23309 } 23310 23311 StringBuilder sb = new StringBuilder(result.size() * 16); 23312 for (String domain : result) { 23313 if (sb.length() > 0) sb.append(" "); 23314 sb.append(domain); 23315 } 23316 return sb.toString(); 23317 } 23318 23319 // ------- apps on sdcard specific code ------- 23320 static final boolean DEBUG_SD_INSTALL = false; 23321 23322 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 23323 23324 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 23325 23326 private boolean mMediaMounted = false; 23327 23328 static String getEncryptKey() { 23329 try { 23330 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 23331 SD_ENCRYPTION_KEYSTORE_NAME); 23332 if (sdEncKey == null) { 23333 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 23334 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 23335 if (sdEncKey == null) { 23336 Slog.e(TAG, "Failed to create encryption keys"); 23337 return null; 23338 } 23339 } 23340 return sdEncKey; 23341 } catch (NoSuchAlgorithmException nsae) { 23342 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 23343 return null; 23344 } catch (IOException ioe) { 23345 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 23346 return null; 23347 } 23348 } 23349 23350 /* 23351 * Update media status on PackageManager. 23352 */ 23353 @Override 23354 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 23355 enforceSystemOrRoot("Media status can only be updated by the system"); 23356 // reader; this apparently protects mMediaMounted, but should probably 23357 // be a different lock in that case. 23358 synchronized (mPackages) { 23359 Log.i(TAG, "Updating external media status from " 23360 + (mMediaMounted ? "mounted" : "unmounted") + " to " 23361 + (mediaStatus ? "mounted" : "unmounted")); 23362 if (DEBUG_SD_INSTALL) 23363 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 23364 + ", mMediaMounted=" + mMediaMounted); 23365 if (mediaStatus == mMediaMounted) { 23366 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 23367 : 0, -1); 23368 mHandler.sendMessage(msg); 23369 return; 23370 } 23371 mMediaMounted = mediaStatus; 23372 } 23373 // Queue up an async operation since the package installation may take a 23374 // little while. 23375 mHandler.post(new Runnable() { 23376 public void run() { 23377 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 23378 } 23379 }); 23380 } 23381 23382 /** 23383 * Called by StorageManagerService when the initial ASECs to scan are available. 23384 * Should block until all the ASEC containers are finished being scanned. 23385 */ 23386 public void scanAvailableAsecs() { 23387 updateExternalMediaStatusInner(true, false, false); 23388 } 23389 23390 /* 23391 * Collect information of applications on external media, map them against 23392 * existing containers and update information based on current mount status. 23393 * Please note that we always have to report status if reportStatus has been 23394 * set to true especially when unloading packages. 23395 */ 23396 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 23397 boolean externalStorage) { 23398 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 23399 int[] uidArr = EmptyArray.INT; 23400 23401 final String[] list = PackageHelper.getSecureContainerList(); 23402 if (ArrayUtils.isEmpty(list)) { 23403 Log.i(TAG, "No secure containers found"); 23404 } else { 23405 // Process list of secure containers and categorize them 23406 // as active or stale based on their package internal state. 23407 23408 // reader 23409 synchronized (mPackages) { 23410 for (String cid : list) { 23411 // Leave stages untouched for now; installer service owns them 23412 if (PackageInstallerService.isStageName(cid)) continue; 23413 23414 if (DEBUG_SD_INSTALL) 23415 Log.i(TAG, "Processing container " + cid); 23416 String pkgName = getAsecPackageName(cid); 23417 if (pkgName == null) { 23418 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 23419 continue; 23420 } 23421 if (DEBUG_SD_INSTALL) 23422 Log.i(TAG, "Looking for pkg : " + pkgName); 23423 23424 final PackageSetting ps = mSettings.mPackages.get(pkgName); 23425 if (ps == null) { 23426 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 23427 continue; 23428 } 23429 23430 /* 23431 * Skip packages that are not external if we're unmounting 23432 * external storage. 23433 */ 23434 if (externalStorage && !isMounted && !isExternal(ps)) { 23435 continue; 23436 } 23437 23438 final AsecInstallArgs args = new AsecInstallArgs(cid, 23439 getAppDexInstructionSets(ps), ps.isForwardLocked()); 23440 // The package status is changed only if the code path 23441 // matches between settings and the container id. 23442 if (ps.codePathString != null 23443 && ps.codePathString.startsWith(args.getCodePath())) { 23444 if (DEBUG_SD_INSTALL) { 23445 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 23446 + " at code path: " + ps.codePathString); 23447 } 23448 23449 // We do have a valid package installed on sdcard 23450 processCids.put(args, ps.codePathString); 23451 final int uid = ps.appId; 23452 if (uid != -1) { 23453 uidArr = ArrayUtils.appendInt(uidArr, uid); 23454 } 23455 } else { 23456 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 23457 + ps.codePathString); 23458 } 23459 } 23460 } 23461 23462 Arrays.sort(uidArr); 23463 } 23464 23465 // Process packages with valid entries. 23466 if (isMounted) { 23467 if (DEBUG_SD_INSTALL) 23468 Log.i(TAG, "Loading packages"); 23469 loadMediaPackages(processCids, uidArr, externalStorage); 23470 startCleaningPackages(); 23471 mInstallerService.onSecureContainersAvailable(); 23472 } else { 23473 if (DEBUG_SD_INSTALL) 23474 Log.i(TAG, "Unloading packages"); 23475 unloadMediaPackages(processCids, uidArr, reportStatus); 23476 } 23477 } 23478 23479 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 23480 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 23481 final int size = infos.size(); 23482 final String[] packageNames = new String[size]; 23483 final int[] packageUids = new int[size]; 23484 for (int i = 0; i < size; i++) { 23485 final ApplicationInfo info = infos.get(i); 23486 packageNames[i] = info.packageName; 23487 packageUids[i] = info.uid; 23488 } 23489 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 23490 finishedReceiver); 23491 } 23492 23493 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 23494 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 23495 sendResourcesChangedBroadcast(mediaStatus, replacing, 23496 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 23497 } 23498 23499 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 23500 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 23501 int size = pkgList.length; 23502 if (size > 0) { 23503 // Send broadcasts here 23504 Bundle extras = new Bundle(); 23505 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 23506 if (uidArr != null) { 23507 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 23508 } 23509 if (replacing) { 23510 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 23511 } 23512 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 23513 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 23514 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 23515 } 23516 } 23517 23518 /* 23519 * Look at potentially valid container ids from processCids If package 23520 * information doesn't match the one on record or package scanning fails, 23521 * the cid is added to list of removeCids. We currently don't delete stale 23522 * containers. 23523 */ 23524 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 23525 boolean externalStorage) { 23526 ArrayList<String> pkgList = new ArrayList<String>(); 23527 Set<AsecInstallArgs> keys = processCids.keySet(); 23528 23529 for (AsecInstallArgs args : keys) { 23530 String codePath = processCids.get(args); 23531 if (DEBUG_SD_INSTALL) 23532 Log.i(TAG, "Loading container : " + args.cid); 23533 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 23534 try { 23535 // Make sure there are no container errors first. 23536 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 23537 Slog.e(TAG, "Failed to mount cid : " + args.cid 23538 + " when installing from sdcard"); 23539 continue; 23540 } 23541 // Check code path here. 23542 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 23543 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 23544 + " does not match one in settings " + codePath); 23545 continue; 23546 } 23547 // Parse package 23548 int parseFlags = mDefParseFlags; 23549 if (args.isExternalAsec()) { 23550 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 23551 } 23552 if (args.isFwdLocked()) { 23553 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 23554 } 23555 23556 synchronized (mInstallLock) { 23557 PackageParser.Package pkg = null; 23558 try { 23559 // Sadly we don't know the package name yet to freeze it 23560 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 23561 SCAN_IGNORE_FROZEN, 0, null); 23562 } catch (PackageManagerException e) { 23563 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 23564 } 23565 // Scan the package 23566 if (pkg != null) { 23567 /* 23568 * TODO why is the lock being held? doPostInstall is 23569 * called in other places without the lock. This needs 23570 * to be straightened out. 23571 */ 23572 // writer 23573 synchronized (mPackages) { 23574 retCode = PackageManager.INSTALL_SUCCEEDED; 23575 pkgList.add(pkg.packageName); 23576 // Post process args 23577 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 23578 pkg.applicationInfo.uid); 23579 } 23580 } else { 23581 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 23582 } 23583 } 23584 23585 } finally { 23586 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 23587 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 23588 } 23589 } 23590 } 23591 // writer 23592 synchronized (mPackages) { 23593 // If the platform SDK has changed since the last time we booted, 23594 // we need to re-grant app permission to catch any new ones that 23595 // appear. This is really a hack, and means that apps can in some 23596 // cases get permissions that the user didn't initially explicitly 23597 // allow... it would be nice to have some better way to handle 23598 // this situation. 23599 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 23600 : mSettings.getInternalVersion(); 23601 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 23602 : StorageManager.UUID_PRIVATE_INTERNAL; 23603 23604 int updateFlags = UPDATE_PERMISSIONS_ALL; 23605 if (ver.sdkVersion != mSdkVersion) { 23606 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 23607 + mSdkVersion + "; regranting permissions for external"); 23608 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 23609 } 23610 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 23611 23612 // Yay, everything is now upgraded 23613 ver.forceCurrent(); 23614 23615 // can downgrade to reader 23616 // Persist settings 23617 mSettings.writeLPr(); 23618 } 23619 // Send a broadcast to let everyone know we are done processing 23620 if (pkgList.size() > 0) { 23621 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 23622 } 23623 } 23624 23625 /* 23626 * Utility method to unload a list of specified containers 23627 */ 23628 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 23629 // Just unmount all valid containers. 23630 for (AsecInstallArgs arg : cidArgs) { 23631 synchronized (mInstallLock) { 23632 arg.doPostDeleteLI(false); 23633 } 23634 } 23635 } 23636 23637 /* 23638 * Unload packages mounted on external media. This involves deleting package 23639 * data from internal structures, sending broadcasts about disabled packages, 23640 * gc'ing to free up references, unmounting all secure containers 23641 * corresponding to packages on external media, and posting a 23642 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 23643 * that we always have to post this message if status has been requested no 23644 * matter what. 23645 */ 23646 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 23647 final boolean reportStatus) { 23648 if (DEBUG_SD_INSTALL) 23649 Log.i(TAG, "unloading media packages"); 23650 ArrayList<String> pkgList = new ArrayList<String>(); 23651 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 23652 final Set<AsecInstallArgs> keys = processCids.keySet(); 23653 for (AsecInstallArgs args : keys) { 23654 String pkgName = args.getPackageName(); 23655 if (DEBUG_SD_INSTALL) 23656 Log.i(TAG, "Trying to unload pkg : " + pkgName); 23657 // Delete package internally 23658 PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 23659 synchronized (mInstallLock) { 23660 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 23661 final boolean res; 23662 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 23663 "unloadMediaPackages")) { 23664 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 23665 null); 23666 } 23667 if (res) { 23668 pkgList.add(pkgName); 23669 } else { 23670 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 23671 failedList.add(args); 23672 } 23673 } 23674 } 23675 23676 // reader 23677 synchronized (mPackages) { 23678 // We didn't update the settings after removing each package; 23679 // write them now for all packages. 23680 mSettings.writeLPr(); 23681 } 23682 23683 // We have to absolutely send UPDATED_MEDIA_STATUS only 23684 // after confirming that all the receivers processed the ordered 23685 // broadcast when packages get disabled, force a gc to clean things up. 23686 // and unload all the containers. 23687 if (pkgList.size() > 0) { 23688 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 23689 new IIntentReceiver.Stub() { 23690 public void performReceive(Intent intent, int resultCode, String data, 23691 Bundle extras, boolean ordered, boolean sticky, 23692 int sendingUser) throws RemoteException { 23693 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 23694 reportStatus ? 1 : 0, 1, keys); 23695 mHandler.sendMessage(msg); 23696 } 23697 }); 23698 } else { 23699 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 23700 keys); 23701 mHandler.sendMessage(msg); 23702 } 23703 } 23704 23705 private void loadPrivatePackages(final VolumeInfo vol) { 23706 mHandler.post(new Runnable() { 23707 @Override 23708 public void run() { 23709 loadPrivatePackagesInner(vol); 23710 } 23711 }); 23712 } 23713 23714 private void loadPrivatePackagesInner(VolumeInfo vol) { 23715 final String volumeUuid = vol.fsUuid; 23716 if (TextUtils.isEmpty(volumeUuid)) { 23717 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 23718 return; 23719 } 23720 23721 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 23722 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 23723 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 23724 23725 final VersionInfo ver; 23726 final List<PackageSetting> packages; 23727 synchronized (mPackages) { 23728 ver = mSettings.findOrCreateVersion(volumeUuid); 23729 packages = mSettings.getVolumePackagesLPr(volumeUuid); 23730 } 23731 23732 for (PackageSetting ps : packages) { 23733 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 23734 synchronized (mInstallLock) { 23735 final PackageParser.Package pkg; 23736 try { 23737 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 23738 loaded.add(pkg.applicationInfo); 23739 23740 } catch (PackageManagerException e) { 23741 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 23742 } 23743 23744 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 23745 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 23746 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 23747 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 23748 } 23749 } 23750 } 23751 23752 // Reconcile app data for all started/unlocked users 23753 final StorageManager sm = mContext.getSystemService(StorageManager.class); 23754 final UserManager um = mContext.getSystemService(UserManager.class); 23755 UserManagerInternal umInternal = getUserManagerInternal(); 23756 for (UserInfo user : um.getUsers()) { 23757 final int flags; 23758 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 23759 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 23760 } else if (umInternal.isUserRunning(user.id)) { 23761 flags = StorageManager.FLAG_STORAGE_DE; 23762 } else { 23763 continue; 23764 } 23765 23766 try { 23767 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 23768 synchronized (mInstallLock) { 23769 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 23770 } 23771 } catch (IllegalStateException e) { 23772 // Device was probably ejected, and we'll process that event momentarily 23773 Slog.w(TAG, "Failed to prepare storage: " + e); 23774 } 23775 } 23776 23777 synchronized (mPackages) { 23778 int updateFlags = UPDATE_PERMISSIONS_ALL; 23779 if (ver.sdkVersion != mSdkVersion) { 23780 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 23781 + mSdkVersion + "; regranting permissions for " + volumeUuid); 23782 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 23783 } 23784 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 23785 23786 // Yay, everything is now upgraded 23787 ver.forceCurrent(); 23788 23789 mSettings.writeLPr(); 23790 } 23791 23792 for (PackageFreezer freezer : freezers) { 23793 freezer.close(); 23794 } 23795 23796 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 23797 sendResourcesChangedBroadcast(true, false, loaded, null); 23798 mLoadedVolumes.add(vol.getId()); 23799 } 23800 23801 private void unloadPrivatePackages(final VolumeInfo vol) { 23802 mHandler.post(new Runnable() { 23803 @Override 23804 public void run() { 23805 unloadPrivatePackagesInner(vol); 23806 } 23807 }); 23808 } 23809 23810 private void unloadPrivatePackagesInner(VolumeInfo vol) { 23811 final String volumeUuid = vol.fsUuid; 23812 if (TextUtils.isEmpty(volumeUuid)) { 23813 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 23814 return; 23815 } 23816 23817 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 23818 synchronized (mInstallLock) { 23819 synchronized (mPackages) { 23820 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 23821 for (PackageSetting ps : packages) { 23822 if (ps.pkg == null) continue; 23823 23824 final ApplicationInfo info = ps.pkg.applicationInfo; 23825 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 23826 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 23827 23828 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 23829 "unloadPrivatePackagesInner")) { 23830 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 23831 false, null)) { 23832 unloaded.add(info); 23833 } else { 23834 Slog.w(TAG, "Failed to unload " + ps.codePath); 23835 } 23836 } 23837 23838 // Try very hard to release any references to this package 23839 // so we don't risk the system server being killed due to 23840 // open FDs 23841 AttributeCache.instance().removePackage(ps.name); 23842 } 23843 23844 mSettings.writeLPr(); 23845 } 23846 } 23847 23848 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 23849 sendResourcesChangedBroadcast(false, false, unloaded, null); 23850 mLoadedVolumes.remove(vol.getId()); 23851 23852 // Try very hard to release any references to this path so we don't risk 23853 // the system server being killed due to open FDs 23854 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 23855 23856 for (int i = 0; i < 3; i++) { 23857 System.gc(); 23858 System.runFinalization(); 23859 } 23860 } 23861 23862 private void assertPackageKnown(String volumeUuid, String packageName) 23863 throws PackageManagerException { 23864 synchronized (mPackages) { 23865 // Normalize package name to handle renamed packages 23866 packageName = normalizePackageNameLPr(packageName); 23867 23868 final PackageSetting ps = mSettings.mPackages.get(packageName); 23869 if (ps == null) { 23870 throw new PackageManagerException("Package " + packageName + " is unknown"); 23871 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 23872 throw new PackageManagerException( 23873 "Package " + packageName + " found on unknown volume " + volumeUuid 23874 + "; expected volume " + ps.volumeUuid); 23875 } 23876 } 23877 } 23878 23879 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 23880 throws PackageManagerException { 23881 synchronized (mPackages) { 23882 // Normalize package name to handle renamed packages 23883 packageName = normalizePackageNameLPr(packageName); 23884 23885 final PackageSetting ps = mSettings.mPackages.get(packageName); 23886 if (ps == null) { 23887 throw new PackageManagerException("Package " + packageName + " is unknown"); 23888 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 23889 throw new PackageManagerException( 23890 "Package " + packageName + " found on unknown volume " + volumeUuid 23891 + "; expected volume " + ps.volumeUuid); 23892 } else if (!ps.getInstalled(userId)) { 23893 throw new PackageManagerException( 23894 "Package " + packageName + " not installed for user " + userId); 23895 } 23896 } 23897 } 23898 23899 private List<String> collectAbsoluteCodePaths() { 23900 synchronized (mPackages) { 23901 List<String> codePaths = new ArrayList<>(); 23902 final int packageCount = mSettings.mPackages.size(); 23903 for (int i = 0; i < packageCount; i++) { 23904 final PackageSetting ps = mSettings.mPackages.valueAt(i); 23905 codePaths.add(ps.codePath.getAbsolutePath()); 23906 } 23907 return codePaths; 23908 } 23909 } 23910 23911 /** 23912 * Examine all apps present on given mounted volume, and destroy apps that 23913 * aren't expected, either due to uninstallation or reinstallation on 23914 * another volume. 23915 */ 23916 private void reconcileApps(String volumeUuid) { 23917 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 23918 List<File> filesToDelete = null; 23919 23920 final File[] files = FileUtils.listFilesOrEmpty( 23921 Environment.getDataAppDirectory(volumeUuid)); 23922 for (File file : files) { 23923 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 23924 && !PackageInstallerService.isStageName(file.getName()); 23925 if (!isPackage) { 23926 // Ignore entries which are not packages 23927 continue; 23928 } 23929 23930 String absolutePath = file.getAbsolutePath(); 23931 23932 boolean pathValid = false; 23933 final int absoluteCodePathCount = absoluteCodePaths.size(); 23934 for (int i = 0; i < absoluteCodePathCount; i++) { 23935 String absoluteCodePath = absoluteCodePaths.get(i); 23936 if (absolutePath.startsWith(absoluteCodePath)) { 23937 pathValid = true; 23938 break; 23939 } 23940 } 23941 23942 if (!pathValid) { 23943 if (filesToDelete == null) { 23944 filesToDelete = new ArrayList<>(); 23945 } 23946 filesToDelete.add(file); 23947 } 23948 } 23949 23950 if (filesToDelete != null) { 23951 final int fileToDeleteCount = filesToDelete.size(); 23952 for (int i = 0; i < fileToDeleteCount; i++) { 23953 File fileToDelete = filesToDelete.get(i); 23954 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 23955 synchronized (mInstallLock) { 23956 removeCodePathLI(fileToDelete); 23957 } 23958 } 23959 } 23960 } 23961 23962 /** 23963 * Reconcile all app data for the given user. 23964 * <p> 23965 * Verifies that directories exist and that ownership and labeling is 23966 * correct for all installed apps on all mounted volumes. 23967 */ 23968 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 23969 final StorageManager storage = mContext.getSystemService(StorageManager.class); 23970 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 23971 final String volumeUuid = vol.getFsUuid(); 23972 synchronized (mInstallLock) { 23973 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 23974 } 23975 } 23976 } 23977 23978 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 23979 boolean migrateAppData) { 23980 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 23981 } 23982 23983 /** 23984 * Reconcile all app data on given mounted volume. 23985 * <p> 23986 * Destroys app data that isn't expected, either due to uninstallation or 23987 * reinstallation on another volume. 23988 * <p> 23989 * Verifies that directories exist and that ownership and labeling is 23990 * correct for all installed apps. 23991 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 23992 */ 23993 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 23994 boolean migrateAppData, boolean onlyCoreApps) { 23995 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 23996 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 23997 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 23998 23999 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 24000 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 24001 24002 // First look for stale data that doesn't belong, and check if things 24003 // have changed since we did our last restorecon 24004 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 24005 if (StorageManager.isFileEncryptedNativeOrEmulated() 24006 && !StorageManager.isUserKeyUnlocked(userId)) { 24007 throw new RuntimeException( 24008 "Yikes, someone asked us to reconcile CE storage while " + userId 24009 + " was still locked; this would have caused massive data loss!"); 24010 } 24011 24012 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 24013 for (File file : files) { 24014 final String packageName = file.getName(); 24015 try { 24016 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 24017 } catch (PackageManagerException e) { 24018 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 24019 try { 24020 mInstaller.destroyAppData(volumeUuid, packageName, userId, 24021 StorageManager.FLAG_STORAGE_CE, 0); 24022 } catch (InstallerException e2) { 24023 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 24024 } 24025 } 24026 } 24027 } 24028 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 24029 final File[] files = FileUtils.listFilesOrEmpty(deDir); 24030 for (File file : files) { 24031 final String packageName = file.getName(); 24032 try { 24033 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 24034 } catch (PackageManagerException e) { 24035 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 24036 try { 24037 mInstaller.destroyAppData(volumeUuid, packageName, userId, 24038 StorageManager.FLAG_STORAGE_DE, 0); 24039 } catch (InstallerException e2) { 24040 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 24041 } 24042 } 24043 } 24044 } 24045 24046 // Ensure that data directories are ready to roll for all packages 24047 // installed for this volume and user 24048 final List<PackageSetting> packages; 24049 synchronized (mPackages) { 24050 packages = mSettings.getVolumePackagesLPr(volumeUuid); 24051 } 24052 int preparedCount = 0; 24053 for (PackageSetting ps : packages) { 24054 final String packageName = ps.name; 24055 if (ps.pkg == null) { 24056 Slog.w(TAG, "Odd, missing scanned package " + packageName); 24057 // TODO: might be due to legacy ASEC apps; we should circle back 24058 // and reconcile again once they're scanned 24059 continue; 24060 } 24061 // Skip non-core apps if requested 24062 if (onlyCoreApps && !ps.pkg.coreApp) { 24063 result.add(packageName); 24064 continue; 24065 } 24066 24067 if (ps.getInstalled(userId)) { 24068 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 24069 preparedCount++; 24070 } 24071 } 24072 24073 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 24074 return result; 24075 } 24076 24077 /** 24078 * Prepare app data for the given app just after it was installed or 24079 * upgraded. This method carefully only touches users that it's installed 24080 * for, and it forces a restorecon to handle any seinfo changes. 24081 * <p> 24082 * Verifies that directories exist and that ownership and labeling is 24083 * correct for all installed apps. If there is an ownership mismatch, it 24084 * will try recovering system apps by wiping data; third-party app data is 24085 * left intact. 24086 * <p> 24087 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 24088 */ 24089 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 24090 final PackageSetting ps; 24091 synchronized (mPackages) { 24092 ps = mSettings.mPackages.get(pkg.packageName); 24093 mSettings.writeKernelMappingLPr(ps); 24094 } 24095 24096 final UserManager um = mContext.getSystemService(UserManager.class); 24097 UserManagerInternal umInternal = getUserManagerInternal(); 24098 for (UserInfo user : um.getUsers()) { 24099 final int flags; 24100 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 24101 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 24102 } else if (umInternal.isUserRunning(user.id)) { 24103 flags = StorageManager.FLAG_STORAGE_DE; 24104 } else { 24105 continue; 24106 } 24107 24108 if (ps.getInstalled(user.id)) { 24109 // TODO: when user data is locked, mark that we're still dirty 24110 prepareAppDataLIF(pkg, user.id, flags); 24111 } 24112 } 24113 } 24114 24115 /** 24116 * Prepare app data for the given app. 24117 * <p> 24118 * Verifies that directories exist and that ownership and labeling is 24119 * correct for all installed apps. If there is an ownership mismatch, this 24120 * will try recovering system apps by wiping data; third-party app data is 24121 * left intact. 24122 */ 24123 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 24124 if (pkg == null) { 24125 Slog.wtf(TAG, "Package was null!", new Throwable()); 24126 return; 24127 } 24128 prepareAppDataLeafLIF(pkg, userId, flags); 24129 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 24130 for (int i = 0; i < childCount; i++) { 24131 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 24132 } 24133 } 24134 24135 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 24136 boolean maybeMigrateAppData) { 24137 prepareAppDataLIF(pkg, userId, flags); 24138 24139 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 24140 // We may have just shuffled around app data directories, so 24141 // prepare them one more time 24142 prepareAppDataLIF(pkg, userId, flags); 24143 } 24144 } 24145 24146 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 24147 if (DEBUG_APP_DATA) { 24148 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 24149 + Integer.toHexString(flags)); 24150 } 24151 24152 final String volumeUuid = pkg.volumeUuid; 24153 final String packageName = pkg.packageName; 24154 final ApplicationInfo app = pkg.applicationInfo; 24155 final int appId = UserHandle.getAppId(app.uid); 24156 24157 Preconditions.checkNotNull(app.seInfo); 24158 24159 long ceDataInode = -1; 24160 try { 24161 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 24162 appId, app.seInfo, app.targetSdkVersion); 24163 } catch (InstallerException e) { 24164 if (app.isSystemApp()) { 24165 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 24166 + ", but trying to recover: " + e); 24167 destroyAppDataLeafLIF(pkg, userId, flags); 24168 try { 24169 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 24170 appId, app.seInfo, app.targetSdkVersion); 24171 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 24172 } catch (InstallerException e2) { 24173 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 24174 } 24175 } else { 24176 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 24177 } 24178 } 24179 24180 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 24181 // TODO: mark this structure as dirty so we persist it! 24182 synchronized (mPackages) { 24183 final PackageSetting ps = mSettings.mPackages.get(packageName); 24184 if (ps != null) { 24185 ps.setCeDataInode(ceDataInode, userId); 24186 } 24187 } 24188 } 24189 24190 prepareAppDataContentsLeafLIF(pkg, userId, flags); 24191 } 24192 24193 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 24194 if (pkg == null) { 24195 Slog.wtf(TAG, "Package was null!", new Throwable()); 24196 return; 24197 } 24198 prepareAppDataContentsLeafLIF(pkg, userId, flags); 24199 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 24200 for (int i = 0; i < childCount; i++) { 24201 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 24202 } 24203 } 24204 24205 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 24206 final String volumeUuid = pkg.volumeUuid; 24207 final String packageName = pkg.packageName; 24208 final ApplicationInfo app = pkg.applicationInfo; 24209 24210 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 24211 // Create a native library symlink only if we have native libraries 24212 // and if the native libraries are 32 bit libraries. We do not provide 24213 // this symlink for 64 bit libraries. 24214 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 24215 final String nativeLibPath = app.nativeLibraryDir; 24216 try { 24217 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 24218 nativeLibPath, userId); 24219 } catch (InstallerException e) { 24220 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 24221 } 24222 } 24223 } 24224 } 24225 24226 /** 24227 * For system apps on non-FBE devices, this method migrates any existing 24228 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 24229 * requested by the app. 24230 */ 24231 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 24232 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 24233 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 24234 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 24235 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 24236 try { 24237 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 24238 storageTarget); 24239 } catch (InstallerException e) { 24240 logCriticalInfo(Log.WARN, 24241 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 24242 } 24243 return true; 24244 } else { 24245 return false; 24246 } 24247 } 24248 24249 public PackageFreezer freezePackage(String packageName, String killReason) { 24250 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 24251 } 24252 24253 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 24254 return new PackageFreezer(packageName, userId, killReason); 24255 } 24256 24257 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 24258 String killReason) { 24259 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 24260 } 24261 24262 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 24263 String killReason) { 24264 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 24265 return new PackageFreezer(); 24266 } else { 24267 return freezePackage(packageName, userId, killReason); 24268 } 24269 } 24270 24271 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 24272 String killReason) { 24273 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 24274 } 24275 24276 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 24277 String killReason) { 24278 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 24279 return new PackageFreezer(); 24280 } else { 24281 return freezePackage(packageName, userId, killReason); 24282 } 24283 } 24284 24285 /** 24286 * Class that freezes and kills the given package upon creation, and 24287 * unfreezes it upon closing. This is typically used when doing surgery on 24288 * app code/data to prevent the app from running while you're working. 24289 */ 24290 private class PackageFreezer implements AutoCloseable { 24291 private final String mPackageName; 24292 private final PackageFreezer[] mChildren; 24293 24294 private final boolean mWeFroze; 24295 24296 private final AtomicBoolean mClosed = new AtomicBoolean(); 24297 private final CloseGuard mCloseGuard = CloseGuard.get(); 24298 24299 /** 24300 * Create and return a stub freezer that doesn't actually do anything, 24301 * typically used when someone requested 24302 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 24303 * {@link PackageManager#DELETE_DONT_KILL_APP}. 24304 */ 24305 public PackageFreezer() { 24306 mPackageName = null; 24307 mChildren = null; 24308 mWeFroze = false; 24309 mCloseGuard.open("close"); 24310 } 24311 24312 public PackageFreezer(String packageName, int userId, String killReason) { 24313 synchronized (mPackages) { 24314 mPackageName = packageName; 24315 mWeFroze = mFrozenPackages.add(mPackageName); 24316 24317 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 24318 if (ps != null) { 24319 killApplication(ps.name, ps.appId, userId, killReason); 24320 } 24321 24322 final PackageParser.Package p = mPackages.get(packageName); 24323 if (p != null && p.childPackages != null) { 24324 final int N = p.childPackages.size(); 24325 mChildren = new PackageFreezer[N]; 24326 for (int i = 0; i < N; i++) { 24327 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 24328 userId, killReason); 24329 } 24330 } else { 24331 mChildren = null; 24332 } 24333 } 24334 mCloseGuard.open("close"); 24335 } 24336 24337 @Override 24338 protected void finalize() throws Throwable { 24339 try { 24340 if (mCloseGuard != null) { 24341 mCloseGuard.warnIfOpen(); 24342 } 24343 24344 close(); 24345 } finally { 24346 super.finalize(); 24347 } 24348 } 24349 24350 @Override 24351 public void close() { 24352 mCloseGuard.close(); 24353 if (mClosed.compareAndSet(false, true)) { 24354 synchronized (mPackages) { 24355 if (mWeFroze) { 24356 mFrozenPackages.remove(mPackageName); 24357 } 24358 24359 if (mChildren != null) { 24360 for (PackageFreezer freezer : mChildren) { 24361 freezer.close(); 24362 } 24363 } 24364 } 24365 } 24366 } 24367 } 24368 24369 /** 24370 * Verify that given package is currently frozen. 24371 */ 24372 private void checkPackageFrozen(String packageName) { 24373 synchronized (mPackages) { 24374 if (!mFrozenPackages.contains(packageName)) { 24375 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 24376 } 24377 } 24378 } 24379 24380 @Override 24381 public int movePackage(final String packageName, final String volumeUuid) { 24382 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 24383 24384 final int callingUid = Binder.getCallingUid(); 24385 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 24386 final int moveId = mNextMoveId.getAndIncrement(); 24387 mHandler.post(new Runnable() { 24388 @Override 24389 public void run() { 24390 try { 24391 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 24392 } catch (PackageManagerException e) { 24393 Slog.w(TAG, "Failed to move " + packageName, e); 24394 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 24395 } 24396 } 24397 }); 24398 return moveId; 24399 } 24400 24401 private void movePackageInternal(final String packageName, final String volumeUuid, 24402 final int moveId, final int callingUid, UserHandle user) 24403 throws PackageManagerException { 24404 final StorageManager storage = mContext.getSystemService(StorageManager.class); 24405 final PackageManager pm = mContext.getPackageManager(); 24406 24407 final boolean currentAsec; 24408 final String currentVolumeUuid; 24409 final File codeFile; 24410 final String installerPackageName; 24411 final String packageAbiOverride; 24412 final int appId; 24413 final String seinfo; 24414 final String label; 24415 final int targetSdkVersion; 24416 final PackageFreezer freezer; 24417 final int[] installedUserIds; 24418 24419 // reader 24420 synchronized (mPackages) { 24421 final PackageParser.Package pkg = mPackages.get(packageName); 24422 final PackageSetting ps = mSettings.mPackages.get(packageName); 24423 if (pkg == null 24424 || ps == null 24425 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 24426 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 24427 } 24428 if (pkg.applicationInfo.isSystemApp()) { 24429 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 24430 "Cannot move system application"); 24431 } 24432 24433 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 24434 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 24435 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 24436 if (isInternalStorage && !allow3rdPartyOnInternal) { 24437 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 24438 "3rd party apps are not allowed on internal storage"); 24439 } 24440 24441 if (pkg.applicationInfo.isExternalAsec()) { 24442 currentAsec = true; 24443 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 24444 } else if (pkg.applicationInfo.isForwardLocked()) { 24445 currentAsec = true; 24446 currentVolumeUuid = "forward_locked"; 24447 } else { 24448 currentAsec = false; 24449 currentVolumeUuid = ps.volumeUuid; 24450 24451 final File probe = new File(pkg.codePath); 24452 final File probeOat = new File(probe, "oat"); 24453 if (!probe.isDirectory() || !probeOat.isDirectory()) { 24454 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 24455 "Move only supported for modern cluster style installs"); 24456 } 24457 } 24458 24459 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 24460 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 24461 "Package already moved to " + volumeUuid); 24462 } 24463 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 24464 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 24465 "Device admin cannot be moved"); 24466 } 24467 24468 if (mFrozenPackages.contains(packageName)) { 24469 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 24470 "Failed to move already frozen package"); 24471 } 24472 24473 codeFile = new File(pkg.codePath); 24474 installerPackageName = ps.installerPackageName; 24475 packageAbiOverride = ps.cpuAbiOverrideString; 24476 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 24477 seinfo = pkg.applicationInfo.seInfo; 24478 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 24479 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 24480 freezer = freezePackage(packageName, "movePackageInternal"); 24481 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 24482 } 24483 24484 final Bundle extras = new Bundle(); 24485 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 24486 extras.putString(Intent.EXTRA_TITLE, label); 24487 mMoveCallbacks.notifyCreated(moveId, extras); 24488 24489 int installFlags; 24490 final boolean moveCompleteApp; 24491 final File measurePath; 24492 24493 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 24494 installFlags = INSTALL_INTERNAL; 24495 moveCompleteApp = !currentAsec; 24496 measurePath = Environment.getDataAppDirectory(volumeUuid); 24497 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 24498 installFlags = INSTALL_EXTERNAL; 24499 moveCompleteApp = false; 24500 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 24501 } else { 24502 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 24503 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 24504 || !volume.isMountedWritable()) { 24505 freezer.close(); 24506 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 24507 "Move location not mounted private volume"); 24508 } 24509 24510 Preconditions.checkState(!currentAsec); 24511 24512 installFlags = INSTALL_INTERNAL; 24513 moveCompleteApp = true; 24514 measurePath = Environment.getDataAppDirectory(volumeUuid); 24515 } 24516 24517 // If we're moving app data around, we need all the users unlocked 24518 if (moveCompleteApp) { 24519 for (int userId : installedUserIds) { 24520 if (StorageManager.isFileEncryptedNativeOrEmulated() 24521 && !StorageManager.isUserKeyUnlocked(userId)) { 24522 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 24523 "User " + userId + " must be unlocked"); 24524 } 24525 } 24526 } 24527 24528 final PackageStats stats = new PackageStats(null, -1); 24529 synchronized (mInstaller) { 24530 for (int userId : installedUserIds) { 24531 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 24532 freezer.close(); 24533 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 24534 "Failed to measure package size"); 24535 } 24536 } 24537 } 24538 24539 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 24540 + stats.dataSize); 24541 24542 final long startFreeBytes = measurePath.getUsableSpace(); 24543 final long sizeBytes; 24544 if (moveCompleteApp) { 24545 sizeBytes = stats.codeSize + stats.dataSize; 24546 } else { 24547 sizeBytes = stats.codeSize; 24548 } 24549 24550 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 24551 freezer.close(); 24552 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 24553 "Not enough free space to move"); 24554 } 24555 24556 mMoveCallbacks.notifyStatusChanged(moveId, 10); 24557 24558 final CountDownLatch installedLatch = new CountDownLatch(1); 24559 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 24560 @Override 24561 public void onUserActionRequired(Intent intent) throws RemoteException { 24562 throw new IllegalStateException(); 24563 } 24564 24565 @Override 24566 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 24567 Bundle extras) throws RemoteException { 24568 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 24569 + PackageManager.installStatusToString(returnCode, msg)); 24570 24571 installedLatch.countDown(); 24572 freezer.close(); 24573 24574 final int status = PackageManager.installStatusToPublicStatus(returnCode); 24575 switch (status) { 24576 case PackageInstaller.STATUS_SUCCESS: 24577 mMoveCallbacks.notifyStatusChanged(moveId, 24578 PackageManager.MOVE_SUCCEEDED); 24579 break; 24580 case PackageInstaller.STATUS_FAILURE_STORAGE: 24581 mMoveCallbacks.notifyStatusChanged(moveId, 24582 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 24583 break; 24584 default: 24585 mMoveCallbacks.notifyStatusChanged(moveId, 24586 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 24587 break; 24588 } 24589 } 24590 }; 24591 24592 final MoveInfo move; 24593 if (moveCompleteApp) { 24594 // Kick off a thread to report progress estimates 24595 new Thread() { 24596 @Override 24597 public void run() { 24598 while (true) { 24599 try { 24600 if (installedLatch.await(1, TimeUnit.SECONDS)) { 24601 break; 24602 } 24603 } catch (InterruptedException ignored) { 24604 } 24605 24606 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 24607 final int progress = 10 + (int) MathUtils.constrain( 24608 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 24609 mMoveCallbacks.notifyStatusChanged(moveId, progress); 24610 } 24611 } 24612 }.start(); 24613 24614 final String dataAppName = codeFile.getName(); 24615 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 24616 dataAppName, appId, seinfo, targetSdkVersion); 24617 } else { 24618 move = null; 24619 } 24620 24621 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 24622 24623 final Message msg = mHandler.obtainMessage(INIT_COPY); 24624 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 24625 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 24626 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 24627 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 24628 PackageManager.INSTALL_REASON_UNKNOWN); 24629 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 24630 msg.obj = params; 24631 24632 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 24633 System.identityHashCode(msg.obj)); 24634 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 24635 System.identityHashCode(msg.obj)); 24636 24637 mHandler.sendMessage(msg); 24638 } 24639 24640 @Override 24641 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 24642 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 24643 24644 final int realMoveId = mNextMoveId.getAndIncrement(); 24645 final Bundle extras = new Bundle(); 24646 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 24647 mMoveCallbacks.notifyCreated(realMoveId, extras); 24648 24649 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 24650 @Override 24651 public void onCreated(int moveId, Bundle extras) { 24652 // Ignored 24653 } 24654 24655 @Override 24656 public void onStatusChanged(int moveId, int status, long estMillis) { 24657 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 24658 } 24659 }; 24660 24661 final StorageManager storage = mContext.getSystemService(StorageManager.class); 24662 storage.setPrimaryStorageUuid(volumeUuid, callback); 24663 return realMoveId; 24664 } 24665 24666 @Override 24667 public int getMoveStatus(int moveId) { 24668 mContext.enforceCallingOrSelfPermission( 24669 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 24670 return mMoveCallbacks.mLastStatus.get(moveId); 24671 } 24672 24673 @Override 24674 public void registerMoveCallback(IPackageMoveObserver callback) { 24675 mContext.enforceCallingOrSelfPermission( 24676 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 24677 mMoveCallbacks.register(callback); 24678 } 24679 24680 @Override 24681 public void unregisterMoveCallback(IPackageMoveObserver callback) { 24682 mContext.enforceCallingOrSelfPermission( 24683 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 24684 mMoveCallbacks.unregister(callback); 24685 } 24686 24687 @Override 24688 public boolean setInstallLocation(int loc) { 24689 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 24690 null); 24691 if (getInstallLocation() == loc) { 24692 return true; 24693 } 24694 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 24695 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 24696 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 24697 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 24698 return true; 24699 } 24700 return false; 24701 } 24702 24703 @Override 24704 public int getInstallLocation() { 24705 // allow instant app access 24706 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 24707 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 24708 PackageHelper.APP_INSTALL_AUTO); 24709 } 24710 24711 /** Called by UserManagerService */ 24712 void cleanUpUser(UserManagerService userManager, int userHandle) { 24713 synchronized (mPackages) { 24714 mDirtyUsers.remove(userHandle); 24715 mUserNeedsBadging.delete(userHandle); 24716 mSettings.removeUserLPw(userHandle); 24717 mPendingBroadcasts.remove(userHandle); 24718 mInstantAppRegistry.onUserRemovedLPw(userHandle); 24719 removeUnusedPackagesLPw(userManager, userHandle); 24720 } 24721 } 24722 24723 /** 24724 * We're removing userHandle and would like to remove any downloaded packages 24725 * that are no longer in use by any other user. 24726 * @param userHandle the user being removed 24727 */ 24728 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 24729 final boolean DEBUG_CLEAN_APKS = false; 24730 int [] users = userManager.getUserIds(); 24731 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 24732 while (psit.hasNext()) { 24733 PackageSetting ps = psit.next(); 24734 if (ps.pkg == null) { 24735 continue; 24736 } 24737 final String packageName = ps.pkg.packageName; 24738 // Skip over if system app 24739 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 24740 continue; 24741 } 24742 if (DEBUG_CLEAN_APKS) { 24743 Slog.i(TAG, "Checking package " + packageName); 24744 } 24745 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 24746 if (keep) { 24747 if (DEBUG_CLEAN_APKS) { 24748 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 24749 } 24750 } else { 24751 for (int i = 0; i < users.length; i++) { 24752 if (users[i] != userHandle && ps.getInstalled(users[i])) { 24753 keep = true; 24754 if (DEBUG_CLEAN_APKS) { 24755 Slog.i(TAG, " Keeping package " + packageName + " for user " 24756 + users[i]); 24757 } 24758 break; 24759 } 24760 } 24761 } 24762 if (!keep) { 24763 if (DEBUG_CLEAN_APKS) { 24764 Slog.i(TAG, " Removing package " + packageName); 24765 } 24766 mHandler.post(new Runnable() { 24767 public void run() { 24768 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 24769 userHandle, 0); 24770 } //end run 24771 }); 24772 } 24773 } 24774 } 24775 24776 /** Called by UserManagerService */ 24777 void createNewUser(int userId, String[] disallowedPackages) { 24778 synchronized (mInstallLock) { 24779 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 24780 } 24781 synchronized (mPackages) { 24782 scheduleWritePackageRestrictionsLocked(userId); 24783 scheduleWritePackageListLocked(userId); 24784 applyFactoryDefaultBrowserLPw(userId); 24785 primeDomainVerificationsLPw(userId); 24786 } 24787 } 24788 24789 void onNewUserCreated(final int userId) { 24790 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 24791 // If permission review for legacy apps is required, we represent 24792 // dagerous permissions for such apps as always granted runtime 24793 // permissions to keep per user flag state whether review is needed. 24794 // Hence, if a new user is added we have to propagate dangerous 24795 // permission grants for these legacy apps. 24796 if (mPermissionReviewRequired) { 24797 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 24798 | UPDATE_PERMISSIONS_REPLACE_ALL); 24799 } 24800 } 24801 24802 @Override 24803 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 24804 mContext.enforceCallingOrSelfPermission( 24805 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 24806 "Only package verification agents can read the verifier device identity"); 24807 24808 synchronized (mPackages) { 24809 return mSettings.getVerifierDeviceIdentityLPw(); 24810 } 24811 } 24812 24813 @Override 24814 public void setPermissionEnforced(String permission, boolean enforced) { 24815 // TODO: Now that we no longer change GID for storage, this should to away. 24816 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 24817 "setPermissionEnforced"); 24818 if (READ_EXTERNAL_STORAGE.equals(permission)) { 24819 synchronized (mPackages) { 24820 if (mSettings.mReadExternalStorageEnforced == null 24821 || mSettings.mReadExternalStorageEnforced != enforced) { 24822 mSettings.mReadExternalStorageEnforced = enforced; 24823 mSettings.writeLPr(); 24824 } 24825 } 24826 // kill any non-foreground processes so we restart them and 24827 // grant/revoke the GID. 24828 final IActivityManager am = ActivityManager.getService(); 24829 if (am != null) { 24830 final long token = Binder.clearCallingIdentity(); 24831 try { 24832 am.killProcessesBelowForeground("setPermissionEnforcement"); 24833 } catch (RemoteException e) { 24834 } finally { 24835 Binder.restoreCallingIdentity(token); 24836 } 24837 } 24838 } else { 24839 throw new IllegalArgumentException("No selective enforcement for " + permission); 24840 } 24841 } 24842 24843 @Override 24844 @Deprecated 24845 public boolean isPermissionEnforced(String permission) { 24846 // allow instant applications 24847 return true; 24848 } 24849 24850 @Override 24851 public boolean isStorageLow() { 24852 // allow instant applications 24853 final long token = Binder.clearCallingIdentity(); 24854 try { 24855 final DeviceStorageMonitorInternal 24856 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 24857 if (dsm != null) { 24858 return dsm.isMemoryLow(); 24859 } else { 24860 return false; 24861 } 24862 } finally { 24863 Binder.restoreCallingIdentity(token); 24864 } 24865 } 24866 24867 @Override 24868 public IPackageInstaller getPackageInstaller() { 24869 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24870 return null; 24871 } 24872 return mInstallerService; 24873 } 24874 24875 private boolean userNeedsBadging(int userId) { 24876 int index = mUserNeedsBadging.indexOfKey(userId); 24877 if (index < 0) { 24878 final UserInfo userInfo; 24879 final long token = Binder.clearCallingIdentity(); 24880 try { 24881 userInfo = sUserManager.getUserInfo(userId); 24882 } finally { 24883 Binder.restoreCallingIdentity(token); 24884 } 24885 final boolean b; 24886 if (userInfo != null && userInfo.isManagedProfile()) { 24887 b = true; 24888 } else { 24889 b = false; 24890 } 24891 mUserNeedsBadging.put(userId, b); 24892 return b; 24893 } 24894 return mUserNeedsBadging.valueAt(index); 24895 } 24896 24897 @Override 24898 public KeySet getKeySetByAlias(String packageName, String alias) { 24899 if (packageName == null || alias == null) { 24900 return null; 24901 } 24902 synchronized(mPackages) { 24903 final PackageParser.Package pkg = mPackages.get(packageName); 24904 if (pkg == null) { 24905 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 24906 throw new IllegalArgumentException("Unknown package: " + packageName); 24907 } 24908 final PackageSetting ps = (PackageSetting) pkg.mExtras; 24909 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 24910 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 24911 throw new IllegalArgumentException("Unknown package: " + packageName); 24912 } 24913 KeySetManagerService ksms = mSettings.mKeySetManagerService; 24914 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 24915 } 24916 } 24917 24918 @Override 24919 public KeySet getSigningKeySet(String packageName) { 24920 if (packageName == null) { 24921 return null; 24922 } 24923 synchronized(mPackages) { 24924 final int callingUid = Binder.getCallingUid(); 24925 final int callingUserId = UserHandle.getUserId(callingUid); 24926 final PackageParser.Package pkg = mPackages.get(packageName); 24927 if (pkg == null) { 24928 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 24929 throw new IllegalArgumentException("Unknown package: " + packageName); 24930 } 24931 final PackageSetting ps = (PackageSetting) pkg.mExtras; 24932 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 24933 // filter and pretend the package doesn't exist 24934 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 24935 + ", uid:" + callingUid); 24936 throw new IllegalArgumentException("Unknown package: " + packageName); 24937 } 24938 if (pkg.applicationInfo.uid != callingUid 24939 && Process.SYSTEM_UID != callingUid) { 24940 throw new SecurityException("May not access signing KeySet of other apps."); 24941 } 24942 KeySetManagerService ksms = mSettings.mKeySetManagerService; 24943 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 24944 } 24945 } 24946 24947 @Override 24948 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 24949 final int callingUid = Binder.getCallingUid(); 24950 if (getInstantAppPackageName(callingUid) != null) { 24951 return false; 24952 } 24953 if (packageName == null || ks == null) { 24954 return false; 24955 } 24956 synchronized(mPackages) { 24957 final PackageParser.Package pkg = mPackages.get(packageName); 24958 if (pkg == null 24959 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 24960 UserHandle.getUserId(callingUid))) { 24961 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 24962 throw new IllegalArgumentException("Unknown package: " + packageName); 24963 } 24964 IBinder ksh = ks.getToken(); 24965 if (ksh instanceof KeySetHandle) { 24966 KeySetManagerService ksms = mSettings.mKeySetManagerService; 24967 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 24968 } 24969 return false; 24970 } 24971 } 24972 24973 @Override 24974 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 24975 final int callingUid = Binder.getCallingUid(); 24976 if (getInstantAppPackageName(callingUid) != null) { 24977 return false; 24978 } 24979 if (packageName == null || ks == null) { 24980 return false; 24981 } 24982 synchronized(mPackages) { 24983 final PackageParser.Package pkg = mPackages.get(packageName); 24984 if (pkg == null 24985 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 24986 UserHandle.getUserId(callingUid))) { 24987 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 24988 throw new IllegalArgumentException("Unknown package: " + packageName); 24989 } 24990 IBinder ksh = ks.getToken(); 24991 if (ksh instanceof KeySetHandle) { 24992 KeySetManagerService ksms = mSettings.mKeySetManagerService; 24993 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 24994 } 24995 return false; 24996 } 24997 } 24998 24999 private void deletePackageIfUnusedLPr(final String packageName) { 25000 PackageSetting ps = mSettings.mPackages.get(packageName); 25001 if (ps == null) { 25002 return; 25003 } 25004 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 25005 // TODO Implement atomic delete if package is unused 25006 // It is currently possible that the package will be deleted even if it is installed 25007 // after this method returns. 25008 mHandler.post(new Runnable() { 25009 public void run() { 25010 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 25011 0, PackageManager.DELETE_ALL_USERS); 25012 } 25013 }); 25014 } 25015 } 25016 25017 /** 25018 * Check and throw if the given before/after packages would be considered a 25019 * downgrade. 25020 */ 25021 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 25022 throws PackageManagerException { 25023 if (after.versionCode < before.mVersionCode) { 25024 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 25025 "Update version code " + after.versionCode + " is older than current " 25026 + before.mVersionCode); 25027 } else if (after.versionCode == before.mVersionCode) { 25028 if (after.baseRevisionCode < before.baseRevisionCode) { 25029 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 25030 "Update base revision code " + after.baseRevisionCode 25031 + " is older than current " + before.baseRevisionCode); 25032 } 25033 25034 if (!ArrayUtils.isEmpty(after.splitNames)) { 25035 for (int i = 0; i < after.splitNames.length; i++) { 25036 final String splitName = after.splitNames[i]; 25037 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 25038 if (j != -1) { 25039 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 25040 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 25041 "Update split " + splitName + " revision code " 25042 + after.splitRevisionCodes[i] + " is older than current " 25043 + before.splitRevisionCodes[j]); 25044 } 25045 } 25046 } 25047 } 25048 } 25049 } 25050 25051 private static class MoveCallbacks extends Handler { 25052 private static final int MSG_CREATED = 1; 25053 private static final int MSG_STATUS_CHANGED = 2; 25054 25055 private final RemoteCallbackList<IPackageMoveObserver> 25056 mCallbacks = new RemoteCallbackList<>(); 25057 25058 private final SparseIntArray mLastStatus = new SparseIntArray(); 25059 25060 public MoveCallbacks(Looper looper) { 25061 super(looper); 25062 } 25063 25064 public void register(IPackageMoveObserver callback) { 25065 mCallbacks.register(callback); 25066 } 25067 25068 public void unregister(IPackageMoveObserver callback) { 25069 mCallbacks.unregister(callback); 25070 } 25071 25072 @Override 25073 public void handleMessage(Message msg) { 25074 final SomeArgs args = (SomeArgs) msg.obj; 25075 final int n = mCallbacks.beginBroadcast(); 25076 for (int i = 0; i < n; i++) { 25077 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 25078 try { 25079 invokeCallback(callback, msg.what, args); 25080 } catch (RemoteException ignored) { 25081 } 25082 } 25083 mCallbacks.finishBroadcast(); 25084 args.recycle(); 25085 } 25086 25087 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 25088 throws RemoteException { 25089 switch (what) { 25090 case MSG_CREATED: { 25091 callback.onCreated(args.argi1, (Bundle) args.arg2); 25092 break; 25093 } 25094 case MSG_STATUS_CHANGED: { 25095 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 25096 break; 25097 } 25098 } 25099 } 25100 25101 private void notifyCreated(int moveId, Bundle extras) { 25102 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 25103 25104 final SomeArgs args = SomeArgs.obtain(); 25105 args.argi1 = moveId; 25106 args.arg2 = extras; 25107 obtainMessage(MSG_CREATED, args).sendToTarget(); 25108 } 25109 25110 private void notifyStatusChanged(int moveId, int status) { 25111 notifyStatusChanged(moveId, status, -1); 25112 } 25113 25114 private void notifyStatusChanged(int moveId, int status, long estMillis) { 25115 Slog.v(TAG, "Move " + moveId + " status " + status); 25116 25117 final SomeArgs args = SomeArgs.obtain(); 25118 args.argi1 = moveId; 25119 args.argi2 = status; 25120 args.arg3 = estMillis; 25121 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 25122 25123 synchronized (mLastStatus) { 25124 mLastStatus.put(moveId, status); 25125 } 25126 } 25127 } 25128 25129 private final static class OnPermissionChangeListeners extends Handler { 25130 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 25131 25132 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 25133 new RemoteCallbackList<>(); 25134 25135 public OnPermissionChangeListeners(Looper looper) { 25136 super(looper); 25137 } 25138 25139 @Override 25140 public void handleMessage(Message msg) { 25141 switch (msg.what) { 25142 case MSG_ON_PERMISSIONS_CHANGED: { 25143 final int uid = msg.arg1; 25144 handleOnPermissionsChanged(uid); 25145 } break; 25146 } 25147 } 25148 25149 public void addListenerLocked(IOnPermissionsChangeListener listener) { 25150 mPermissionListeners.register(listener); 25151 25152 } 25153 25154 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 25155 mPermissionListeners.unregister(listener); 25156 } 25157 25158 public void onPermissionsChanged(int uid) { 25159 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 25160 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 25161 } 25162 } 25163 25164 private void handleOnPermissionsChanged(int uid) { 25165 final int count = mPermissionListeners.beginBroadcast(); 25166 try { 25167 for (int i = 0; i < count; i++) { 25168 IOnPermissionsChangeListener callback = mPermissionListeners 25169 .getBroadcastItem(i); 25170 try { 25171 callback.onPermissionsChanged(uid); 25172 } catch (RemoteException e) { 25173 Log.e(TAG, "Permission listener is dead", e); 25174 } 25175 } 25176 } finally { 25177 mPermissionListeners.finishBroadcast(); 25178 } 25179 } 25180 } 25181 25182 private class PackageManagerNative extends IPackageManagerNative.Stub { 25183 @Override 25184 public String[] getNamesForUids(int[] uids) throws RemoteException { 25185 final String[] results = PackageManagerService.this.getNamesForUids(uids); 25186 // massage results so they can be parsed by the native binder 25187 for (int i = results.length - 1; i >= 0; --i) { 25188 if (results[i] == null) { 25189 results[i] = ""; 25190 } 25191 } 25192 return results; 25193 } 25194 25195 // NB: this differentiates between preloads and sideloads 25196 @Override 25197 public String getInstallerForPackage(String packageName) throws RemoteException { 25198 final String installerName = getInstallerPackageName(packageName); 25199 if (!TextUtils.isEmpty(installerName)) { 25200 return installerName; 25201 } 25202 // differentiate between preload and sideload 25203 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 25204 ApplicationInfo appInfo = getApplicationInfo(packageName, 25205 /*flags*/ 0, 25206 /*userId*/ callingUser); 25207 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 25208 return "preload"; 25209 } 25210 return ""; 25211 } 25212 25213 @Override 25214 public int getVersionCodeForPackage(String packageName) throws RemoteException { 25215 try { 25216 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 25217 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 25218 if (pInfo != null) { 25219 return pInfo.versionCode; 25220 } 25221 } catch (Exception e) { 25222 } 25223 return 0; 25224 } 25225 } 25226 25227 private class PackageManagerInternalImpl extends PackageManagerInternal { 25228 @Override 25229 public void setLocationPackagesProvider(PackagesProvider provider) { 25230 synchronized (mPackages) { 25231 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 25232 } 25233 } 25234 25235 @Override 25236 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 25237 synchronized (mPackages) { 25238 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 25239 } 25240 } 25241 25242 @Override 25243 public void setSmsAppPackagesProvider(PackagesProvider provider) { 25244 synchronized (mPackages) { 25245 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 25246 } 25247 } 25248 25249 @Override 25250 public void setDialerAppPackagesProvider(PackagesProvider provider) { 25251 synchronized (mPackages) { 25252 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 25253 } 25254 } 25255 25256 @Override 25257 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 25258 synchronized (mPackages) { 25259 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 25260 } 25261 } 25262 25263 @Override 25264 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 25265 synchronized (mPackages) { 25266 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 25267 } 25268 } 25269 25270 @Override 25271 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 25272 synchronized (mPackages) { 25273 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 25274 packageName, userId); 25275 } 25276 } 25277 25278 @Override 25279 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 25280 synchronized (mPackages) { 25281 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 25282 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 25283 packageName, userId); 25284 } 25285 } 25286 25287 @Override 25288 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 25289 synchronized (mPackages) { 25290 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 25291 packageName, userId); 25292 } 25293 } 25294 25295 @Override 25296 public void setKeepUninstalledPackages(final List<String> packageList) { 25297 Preconditions.checkNotNull(packageList); 25298 List<String> removedFromList = null; 25299 synchronized (mPackages) { 25300 if (mKeepUninstalledPackages != null) { 25301 final int packagesCount = mKeepUninstalledPackages.size(); 25302 for (int i = 0; i < packagesCount; i++) { 25303 String oldPackage = mKeepUninstalledPackages.get(i); 25304 if (packageList != null && packageList.contains(oldPackage)) { 25305 continue; 25306 } 25307 if (removedFromList == null) { 25308 removedFromList = new ArrayList<>(); 25309 } 25310 removedFromList.add(oldPackage); 25311 } 25312 } 25313 mKeepUninstalledPackages = new ArrayList<>(packageList); 25314 if (removedFromList != null) { 25315 final int removedCount = removedFromList.size(); 25316 for (int i = 0; i < removedCount; i++) { 25317 deletePackageIfUnusedLPr(removedFromList.get(i)); 25318 } 25319 } 25320 } 25321 } 25322 25323 @Override 25324 public boolean isPermissionsReviewRequired(String packageName, int userId) { 25325 synchronized (mPackages) { 25326 // If we do not support permission review, done. 25327 if (!mPermissionReviewRequired) { 25328 return false; 25329 } 25330 25331 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 25332 if (packageSetting == null) { 25333 return false; 25334 } 25335 25336 // Permission review applies only to apps not supporting the new permission model. 25337 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 25338 return false; 25339 } 25340 25341 // Legacy apps have the permission and get user consent on launch. 25342 PermissionsState permissionsState = packageSetting.getPermissionsState(); 25343 return permissionsState.isPermissionReviewRequired(userId); 25344 } 25345 } 25346 25347 @Override 25348 public PackageInfo getPackageInfo( 25349 String packageName, int flags, int filterCallingUid, int userId) { 25350 return PackageManagerService.this 25351 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 25352 flags, filterCallingUid, userId); 25353 } 25354 25355 @Override 25356 public ApplicationInfo getApplicationInfo( 25357 String packageName, int flags, int filterCallingUid, int userId) { 25358 return PackageManagerService.this 25359 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 25360 } 25361 25362 @Override 25363 public ActivityInfo getActivityInfo( 25364 ComponentName component, int flags, int filterCallingUid, int userId) { 25365 return PackageManagerService.this 25366 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 25367 } 25368 25369 @Override 25370 public List<ResolveInfo> queryIntentActivities( 25371 Intent intent, int flags, int filterCallingUid, int userId) { 25372 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 25373 return PackageManagerService.this 25374 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 25375 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 25376 } 25377 25378 @Override 25379 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 25380 int userId) { 25381 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 25382 } 25383 25384 @Override 25385 public void setDeviceAndProfileOwnerPackages( 25386 int deviceOwnerUserId, String deviceOwnerPackage, 25387 SparseArray<String> profileOwnerPackages) { 25388 mProtectedPackages.setDeviceAndProfileOwnerPackages( 25389 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 25390 } 25391 25392 @Override 25393 public boolean isPackageDataProtected(int userId, String packageName) { 25394 return mProtectedPackages.isPackageDataProtected(userId, packageName); 25395 } 25396 25397 @Override 25398 public boolean isPackageEphemeral(int userId, String packageName) { 25399 synchronized (mPackages) { 25400 final PackageSetting ps = mSettings.mPackages.get(packageName); 25401 return ps != null ? ps.getInstantApp(userId) : false; 25402 } 25403 } 25404 25405 @Override 25406 public boolean wasPackageEverLaunched(String packageName, int userId) { 25407 synchronized (mPackages) { 25408 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 25409 } 25410 } 25411 25412 @Override 25413 public void grantRuntimePermission(String packageName, String name, int userId, 25414 boolean overridePolicy) { 25415 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 25416 overridePolicy); 25417 } 25418 25419 @Override 25420 public void revokeRuntimePermission(String packageName, String name, int userId, 25421 boolean overridePolicy) { 25422 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 25423 overridePolicy); 25424 } 25425 25426 @Override 25427 public String getNameForUid(int uid) { 25428 return PackageManagerService.this.getNameForUid(uid); 25429 } 25430 25431 @Override 25432 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 25433 Intent origIntent, String resolvedType, String callingPackage, 25434 Bundle verificationBundle, int userId) { 25435 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 25436 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 25437 userId); 25438 } 25439 25440 @Override 25441 public void grantEphemeralAccess(int userId, Intent intent, 25442 int targetAppId, int ephemeralAppId) { 25443 synchronized (mPackages) { 25444 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 25445 targetAppId, ephemeralAppId); 25446 } 25447 } 25448 25449 @Override 25450 public boolean isInstantAppInstallerComponent(ComponentName component) { 25451 synchronized (mPackages) { 25452 return mInstantAppInstallerActivity != null 25453 && mInstantAppInstallerActivity.getComponentName().equals(component); 25454 } 25455 } 25456 25457 @Override 25458 public void pruneInstantApps() { 25459 mInstantAppRegistry.pruneInstantApps(); 25460 } 25461 25462 @Override 25463 public String getSetupWizardPackageName() { 25464 return mSetupWizardPackage; 25465 } 25466 25467 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 25468 if (policy != null) { 25469 mExternalSourcesPolicy = policy; 25470 } 25471 } 25472 25473 @Override 25474 public boolean isPackagePersistent(String packageName) { 25475 synchronized (mPackages) { 25476 PackageParser.Package pkg = mPackages.get(packageName); 25477 return pkg != null 25478 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 25479 | ApplicationInfo.FLAG_PERSISTENT)) == 25480 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 25481 : false; 25482 } 25483 } 25484 25485 @Override 25486 public List<PackageInfo> getOverlayPackages(int userId) { 25487 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 25488 synchronized (mPackages) { 25489 for (PackageParser.Package p : mPackages.values()) { 25490 if (p.mOverlayTarget != null) { 25491 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 25492 if (pkg != null) { 25493 overlayPackages.add(pkg); 25494 } 25495 } 25496 } 25497 } 25498 return overlayPackages; 25499 } 25500 25501 @Override 25502 public List<String> getTargetPackageNames(int userId) { 25503 List<String> targetPackages = new ArrayList<>(); 25504 synchronized (mPackages) { 25505 for (PackageParser.Package p : mPackages.values()) { 25506 if (p.mOverlayTarget == null) { 25507 targetPackages.add(p.packageName); 25508 } 25509 } 25510 } 25511 return targetPackages; 25512 } 25513 25514 @Override 25515 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 25516 @Nullable List<String> overlayPackageNames) { 25517 synchronized (mPackages) { 25518 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 25519 Slog.e(TAG, "failed to find package " + targetPackageName); 25520 return false; 25521 } 25522 ArrayList<String> overlayPaths = null; 25523 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 25524 final int N = overlayPackageNames.size(); 25525 overlayPaths = new ArrayList<>(N); 25526 for (int i = 0; i < N; i++) { 25527 final String packageName = overlayPackageNames.get(i); 25528 final PackageParser.Package pkg = mPackages.get(packageName); 25529 if (pkg == null) { 25530 Slog.e(TAG, "failed to find package " + packageName); 25531 return false; 25532 } 25533 overlayPaths.add(pkg.baseCodePath); 25534 } 25535 } 25536 25537 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 25538 ps.setOverlayPaths(overlayPaths, userId); 25539 return true; 25540 } 25541 } 25542 25543 @Override 25544 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 25545 int flags, int userId) { 25546 return resolveIntentInternal( 25547 intent, resolvedType, flags, userId, true /*resolveForStart*/); 25548 } 25549 25550 @Override 25551 public ResolveInfo resolveService(Intent intent, String resolvedType, 25552 int flags, int userId, int callingUid) { 25553 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 25554 } 25555 25556 @Override 25557 public void addIsolatedUid(int isolatedUid, int ownerUid) { 25558 synchronized (mPackages) { 25559 mIsolatedOwners.put(isolatedUid, ownerUid); 25560 } 25561 } 25562 25563 @Override 25564 public void removeIsolatedUid(int isolatedUid) { 25565 synchronized (mPackages) { 25566 mIsolatedOwners.delete(isolatedUid); 25567 } 25568 } 25569 25570 @Override 25571 public int getUidTargetSdkVersion(int uid) { 25572 synchronized (mPackages) { 25573 return getUidTargetSdkVersionLockedLPr(uid); 25574 } 25575 } 25576 25577 @Override 25578 public boolean canAccessInstantApps(int callingUid, int userId) { 25579 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 25580 } 25581 25582 @Override 25583 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 25584 synchronized (mPackages) { 25585 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 25586 } 25587 } 25588 25589 @Override 25590 public void notifyPackageUse(String packageName, int reason) { 25591 synchronized (mPackages) { 25592 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 25593 } 25594 } 25595 } 25596 25597 @Override 25598 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 25599 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 25600 synchronized (mPackages) { 25601 final long identity = Binder.clearCallingIdentity(); 25602 try { 25603 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 25604 packageNames, userId); 25605 } finally { 25606 Binder.restoreCallingIdentity(identity); 25607 } 25608 } 25609 } 25610 25611 @Override 25612 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 25613 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 25614 synchronized (mPackages) { 25615 final long identity = Binder.clearCallingIdentity(); 25616 try { 25617 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 25618 packageNames, userId); 25619 } finally { 25620 Binder.restoreCallingIdentity(identity); 25621 } 25622 } 25623 } 25624 25625 private static void enforceSystemOrPhoneCaller(String tag) { 25626 int callingUid = Binder.getCallingUid(); 25627 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 25628 throw new SecurityException( 25629 "Cannot call " + tag + " from UID " + callingUid); 25630 } 25631 } 25632 25633 boolean isHistoricalPackageUsageAvailable() { 25634 return mPackageUsage.isHistoricalPackageUsageAvailable(); 25635 } 25636 25637 /** 25638 * Return a <b>copy</b> of the collection of packages known to the package manager. 25639 * @return A copy of the values of mPackages. 25640 */ 25641 Collection<PackageParser.Package> getPackages() { 25642 synchronized (mPackages) { 25643 return new ArrayList<>(mPackages.values()); 25644 } 25645 } 25646 25647 /** 25648 * Logs process start information (including base APK hash) to the security log. 25649 * @hide 25650 */ 25651 @Override 25652 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 25653 String apkFile, int pid) { 25654 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 25655 return; 25656 } 25657 if (!SecurityLog.isLoggingEnabled()) { 25658 return; 25659 } 25660 Bundle data = new Bundle(); 25661 data.putLong("startTimestamp", System.currentTimeMillis()); 25662 data.putString("processName", processName); 25663 data.putInt("uid", uid); 25664 data.putString("seinfo", seinfo); 25665 data.putString("apkFile", apkFile); 25666 data.putInt("pid", pid); 25667 Message msg = mProcessLoggingHandler.obtainMessage( 25668 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 25669 msg.setData(data); 25670 mProcessLoggingHandler.sendMessage(msg); 25671 } 25672 25673 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 25674 return mCompilerStats.getPackageStats(pkgName); 25675 } 25676 25677 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 25678 return getOrCreateCompilerPackageStats(pkg.packageName); 25679 } 25680 25681 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 25682 return mCompilerStats.getOrCreatePackageStats(pkgName); 25683 } 25684 25685 public void deleteCompilerPackageStats(String pkgName) { 25686 mCompilerStats.deletePackageStats(pkgName); 25687 } 25688 25689 @Override 25690 public int getInstallReason(String packageName, int userId) { 25691 final int callingUid = Binder.getCallingUid(); 25692 enforceCrossUserPermission(callingUid, userId, 25693 true /* requireFullPermission */, false /* checkShell */, 25694 "get install reason"); 25695 synchronized (mPackages) { 25696 final PackageSetting ps = mSettings.mPackages.get(packageName); 25697 if (filterAppAccessLPr(ps, callingUid, userId)) { 25698 return PackageManager.INSTALL_REASON_UNKNOWN; 25699 } 25700 if (ps != null) { 25701 return ps.getInstallReason(userId); 25702 } 25703 } 25704 return PackageManager.INSTALL_REASON_UNKNOWN; 25705 } 25706 25707 @Override 25708 public boolean canRequestPackageInstalls(String packageName, int userId) { 25709 return canRequestPackageInstallsInternal(packageName, 0, userId, 25710 true /* throwIfPermNotDeclared*/); 25711 } 25712 25713 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 25714 boolean throwIfPermNotDeclared) { 25715 int callingUid = Binder.getCallingUid(); 25716 int uid = getPackageUid(packageName, 0, userId); 25717 if (callingUid != uid && callingUid != Process.ROOT_UID 25718 && callingUid != Process.SYSTEM_UID) { 25719 throw new SecurityException( 25720 "Caller uid " + callingUid + " does not own package " + packageName); 25721 } 25722 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 25723 if (info == null) { 25724 return false; 25725 } 25726 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 25727 return false; 25728 } 25729 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 25730 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 25731 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 25732 if (throwIfPermNotDeclared) { 25733 throw new SecurityException("Need to declare " + appOpPermission 25734 + " to call this api"); 25735 } else { 25736 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 25737 return false; 25738 } 25739 } 25740 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 25741 return false; 25742 } 25743 if (mExternalSourcesPolicy != null) { 25744 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 25745 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 25746 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 25747 } 25748 } 25749 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 25750 } 25751 25752 @Override 25753 public ComponentName getInstantAppResolverSettingsComponent() { 25754 return mInstantAppResolverSettingsComponent; 25755 } 25756 25757 @Override 25758 public ComponentName getInstantAppInstallerComponent() { 25759 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 25760 return null; 25761 } 25762 return mInstantAppInstallerActivity == null 25763 ? null : mInstantAppInstallerActivity.getComponentName(); 25764 } 25765 25766 @Override 25767 public String getInstantAppAndroidId(String packageName, int userId) { 25768 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 25769 "getInstantAppAndroidId"); 25770 enforceCrossUserPermission(Binder.getCallingUid(), userId, 25771 true /* requireFullPermission */, false /* checkShell */, 25772 "getInstantAppAndroidId"); 25773 // Make sure the target is an Instant App. 25774 if (!isInstantApp(packageName, userId)) { 25775 return null; 25776 } 25777 synchronized (mPackages) { 25778 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 25779 } 25780 } 25781 25782 boolean canHaveOatDir(String packageName) { 25783 synchronized (mPackages) { 25784 PackageParser.Package p = mPackages.get(packageName); 25785 if (p == null) { 25786 return false; 25787 } 25788 return p.canHaveOatDir(); 25789 } 25790 } 25791 25792 private String getOatDir(PackageParser.Package pkg) { 25793 if (!pkg.canHaveOatDir()) { 25794 return null; 25795 } 25796 File codePath = new File(pkg.codePath); 25797 if (codePath.isDirectory()) { 25798 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 25799 } 25800 return null; 25801 } 25802 25803 void deleteOatArtifactsOfPackage(String packageName) { 25804 final String[] instructionSets; 25805 final List<String> codePaths; 25806 final String oatDir; 25807 final PackageParser.Package pkg; 25808 synchronized (mPackages) { 25809 pkg = mPackages.get(packageName); 25810 } 25811 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 25812 codePaths = pkg.getAllCodePaths(); 25813 oatDir = getOatDir(pkg); 25814 25815 for (String codePath : codePaths) { 25816 for (String isa : instructionSets) { 25817 try { 25818 mInstaller.deleteOdex(codePath, isa, oatDir); 25819 } catch (InstallerException e) { 25820 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 25821 } 25822 } 25823 } 25824 } 25825 25826 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 25827 Set<String> unusedPackages = new HashSet<>(); 25828 long currentTimeInMillis = System.currentTimeMillis(); 25829 synchronized (mPackages) { 25830 for (PackageParser.Package pkg : mPackages.values()) { 25831 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 25832 if (ps == null) { 25833 continue; 25834 } 25835 PackageDexUsage.PackageUseInfo packageUseInfo = 25836 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 25837 if (PackageManagerServiceUtils 25838 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 25839 downgradeTimeThresholdMillis, packageUseInfo, 25840 pkg.getLatestPackageUseTimeInMills(), 25841 pkg.getLatestForegroundPackageUseTimeInMills())) { 25842 unusedPackages.add(pkg.packageName); 25843 } 25844 } 25845 } 25846 return unusedPackages; 25847 } 25848 } 25849 25850 interface PackageSender { 25851 void sendPackageBroadcast(final String action, final String pkg, 25852 final Bundle extras, final int flags, final String targetPkg, 25853 final IIntentReceiver finishedReceiver, final int[] userIds); 25854 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 25855 boolean includeStopped, int appId, int... userIds); 25856 } 25857