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.READ_EXTERNAL_STORAGE; 22 import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 23 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 24 import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 25 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 26 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 27 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 28 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 29 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 30 import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 31 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 32 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 33 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 34 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 35 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 36 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 37 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 38 import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 39 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 40 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 41 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 42 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 43 import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 44 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 45 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 46 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 47 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 48 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 49 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 50 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 51 import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE; 52 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 53 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 54 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 55 import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 56 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 57 import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 58 import static android.content.pm.PackageManager.INSTALL_INTERNAL; 59 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 60 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED; 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_OPERATION_PENDING; 81 import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 82 import static android.content.pm.PackageManager.PERMISSION_DENIED; 83 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 84 import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 85 import static android.content.pm.PackageParser.isApkFile; 86 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 87 import static android.system.OsConstants.O_CREAT; 88 import static android.system.OsConstants.O_RDWR; 89 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 90 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 91 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 92 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 93 import static com.android.internal.util.ArrayUtils.appendInt; 94 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 95 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 96 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 97 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 98 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 99 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 100 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 101 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 102 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 103 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 104 import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter; 105 106 import android.Manifest; 107 import android.annotation.IntDef; 108 import android.annotation.NonNull; 109 import android.annotation.Nullable; 110 import android.app.ActivityManager; 111 import android.app.AppOpsManager; 112 import android.app.IActivityManager; 113 import android.app.ResourcesManager; 114 import android.app.admin.IDevicePolicyManager; 115 import android.app.admin.SecurityLog; 116 import android.app.backup.IBackupManager; 117 import android.content.BroadcastReceiver; 118 import android.content.ComponentName; 119 import android.content.ContentResolver; 120 import android.content.Context; 121 import android.content.IIntentReceiver; 122 import android.content.Intent; 123 import android.content.IntentFilter; 124 import android.content.IntentSender; 125 import android.content.IntentSender.SendIntentException; 126 import android.content.ServiceConnection; 127 import android.content.pm.ActivityInfo; 128 import android.content.pm.ApplicationInfo; 129 import android.content.pm.AppsQueryHelper; 130 import android.content.pm.AuxiliaryResolveInfo; 131 import android.content.pm.ChangedPackages; 132 import android.content.pm.FallbackCategoryProvider; 133 import android.content.pm.FeatureInfo; 134 import android.content.pm.IOnPermissionsChangeListener; 135 import android.content.pm.IPackageDataObserver; 136 import android.content.pm.IPackageDeleteObserver; 137 import android.content.pm.IPackageDeleteObserver2; 138 import android.content.pm.IPackageInstallObserver2; 139 import android.content.pm.IPackageInstaller; 140 import android.content.pm.IPackageManager; 141 import android.content.pm.IPackageMoveObserver; 142 import android.content.pm.IPackageStatsObserver; 143 import android.content.pm.InstantAppInfo; 144 import android.content.pm.InstantAppRequest; 145 import android.content.pm.InstantAppResolveInfo; 146 import android.content.pm.InstrumentationInfo; 147 import android.content.pm.IntentFilterVerificationInfo; 148 import android.content.pm.KeySet; 149 import android.content.pm.PackageCleanItem; 150 import android.content.pm.PackageInfo; 151 import android.content.pm.PackageInfoLite; 152 import android.content.pm.PackageInstaller; 153 import android.content.pm.PackageManager; 154 import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 155 import android.content.pm.PackageManagerInternal; 156 import android.content.pm.PackageParser; 157 import android.content.pm.PackageParser.ActivityIntentInfo; 158 import android.content.pm.PackageParser.PackageLite; 159 import android.content.pm.PackageParser.PackageParserException; 160 import android.content.pm.PackageStats; 161 import android.content.pm.PackageUserState; 162 import android.content.pm.ParceledListSlice; 163 import android.content.pm.PermissionGroupInfo; 164 import android.content.pm.PermissionInfo; 165 import android.content.pm.ProviderInfo; 166 import android.content.pm.ResolveInfo; 167 import android.content.pm.ServiceInfo; 168 import android.content.pm.SharedLibraryInfo; 169 import android.content.pm.Signature; 170 import android.content.pm.UserInfo; 171 import android.content.pm.VerifierDeviceIdentity; 172 import android.content.pm.VerifierInfo; 173 import android.content.pm.VersionedPackage; 174 import android.content.res.Resources; 175 import android.database.ContentObserver; 176 import android.graphics.Bitmap; 177 import android.hardware.display.DisplayManager; 178 import android.net.Uri; 179 import android.os.Binder; 180 import android.os.Build; 181 import android.os.Bundle; 182 import android.os.Debug; 183 import android.os.Environment; 184 import android.os.Environment.UserEnvironment; 185 import android.os.FileUtils; 186 import android.os.Handler; 187 import android.os.IBinder; 188 import android.os.Looper; 189 import android.os.Message; 190 import android.os.Parcel; 191 import android.os.ParcelFileDescriptor; 192 import android.os.PatternMatcher; 193 import android.os.Process; 194 import android.os.RemoteCallbackList; 195 import android.os.RemoteException; 196 import android.os.ResultReceiver; 197 import android.os.SELinux; 198 import android.os.ServiceManager; 199 import android.os.ShellCallback; 200 import android.os.SystemClock; 201 import android.os.SystemProperties; 202 import android.os.Trace; 203 import android.os.UserHandle; 204 import android.os.UserManager; 205 import android.os.UserManagerInternal; 206 import android.os.storage.IStorageManager; 207 import android.os.storage.StorageEventListener; 208 import android.os.storage.StorageManager; 209 import android.os.storage.StorageManagerInternal; 210 import android.os.storage.VolumeInfo; 211 import android.os.storage.VolumeRecord; 212 import android.provider.Settings.Global; 213 import android.provider.Settings.Secure; 214 import android.security.KeyStore; 215 import android.security.SystemKeyStore; 216 import android.service.pm.PackageServiceDumpProto; 217 import android.system.ErrnoException; 218 import android.system.Os; 219 import android.text.TextUtils; 220 import android.text.format.DateUtils; 221 import android.util.ArrayMap; 222 import android.util.ArraySet; 223 import android.util.Base64; 224 import android.util.BootTimingsTraceLog; 225 import android.util.DisplayMetrics; 226 import android.util.EventLog; 227 import android.util.ExceptionUtils; 228 import android.util.Log; 229 import android.util.LogPrinter; 230 import android.util.MathUtils; 231 import android.util.PackageUtils; 232 import android.util.Pair; 233 import android.util.PrintStreamPrinter; 234 import android.util.Slog; 235 import android.util.SparseArray; 236 import android.util.SparseBooleanArray; 237 import android.util.SparseIntArray; 238 import android.util.Xml; 239 import android.util.jar.StrictJarFile; 240 import android.util.proto.ProtoOutputStream; 241 import android.view.Display; 242 243 import com.android.internal.R; 244 import com.android.internal.annotations.GuardedBy; 245 import com.android.internal.app.IMediaContainerService; 246 import com.android.internal.app.ResolverActivity; 247 import com.android.internal.content.NativeLibraryHelper; 248 import com.android.internal.content.PackageHelper; 249 import com.android.internal.logging.MetricsLogger; 250 import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 251 import com.android.internal.os.IParcelFileDescriptorFactory; 252 import com.android.internal.os.RoSystemProperties; 253 import com.android.internal.os.SomeArgs; 254 import com.android.internal.os.Zygote; 255 import com.android.internal.telephony.CarrierAppUtils; 256 import com.android.internal.util.ArrayUtils; 257 import com.android.internal.util.ConcurrentUtils; 258 import com.android.internal.util.DumpUtils; 259 import com.android.internal.util.FastPrintWriter; 260 import com.android.internal.util.FastXmlSerializer; 261 import com.android.internal.util.IndentingPrintWriter; 262 import com.android.internal.util.Preconditions; 263 import com.android.internal.util.XmlUtils; 264 import com.android.server.AttributeCache; 265 import com.android.server.DeviceIdleController; 266 import com.android.server.EventLogTags; 267 import com.android.server.FgThread; 268 import com.android.server.IntentResolver; 269 import com.android.server.LocalServices; 270 import com.android.server.LockGuard; 271 import com.android.server.ServiceThread; 272 import com.android.server.SystemConfig; 273 import com.android.server.SystemServerInitThreadPool; 274 import com.android.server.Watchdog; 275 import com.android.server.net.NetworkPolicyManagerInternal; 276 import com.android.server.pm.Installer.InstallerException; 277 import com.android.server.pm.PermissionsState.PermissionState; 278 import com.android.server.pm.Settings.DatabaseVersion; 279 import com.android.server.pm.Settings.VersionInfo; 280 import com.android.server.pm.dex.DexManager; 281 import com.android.server.storage.DeviceStorageMonitorInternal; 282 283 import dalvik.system.CloseGuard; 284 import dalvik.system.DexFile; 285 import dalvik.system.VMRuntime; 286 287 import libcore.io.IoUtils; 288 import libcore.util.EmptyArray; 289 290 import org.xmlpull.v1.XmlPullParser; 291 import org.xmlpull.v1.XmlPullParserException; 292 import org.xmlpull.v1.XmlSerializer; 293 294 import java.io.BufferedOutputStream; 295 import java.io.BufferedReader; 296 import java.io.ByteArrayInputStream; 297 import java.io.ByteArrayOutputStream; 298 import java.io.File; 299 import java.io.FileDescriptor; 300 import java.io.FileInputStream; 301 import java.io.FileOutputStream; 302 import java.io.FileReader; 303 import java.io.FilenameFilter; 304 import java.io.IOException; 305 import java.io.PrintWriter; 306 import java.lang.annotation.Retention; 307 import java.lang.annotation.RetentionPolicy; 308 import java.nio.charset.StandardCharsets; 309 import java.security.DigestInputStream; 310 import java.security.MessageDigest; 311 import java.security.NoSuchAlgorithmException; 312 import java.security.PublicKey; 313 import java.security.SecureRandom; 314 import java.security.cert.Certificate; 315 import java.security.cert.CertificateEncodingException; 316 import java.security.cert.CertificateException; 317 import java.text.SimpleDateFormat; 318 import java.util.ArrayList; 319 import java.util.Arrays; 320 import java.util.Collection; 321 import java.util.Collections; 322 import java.util.Comparator; 323 import java.util.Date; 324 import java.util.HashMap; 325 import java.util.HashSet; 326 import java.util.Iterator; 327 import java.util.List; 328 import java.util.Map; 329 import java.util.Objects; 330 import java.util.Set; 331 import java.util.concurrent.CountDownLatch; 332 import java.util.concurrent.Future; 333 import java.util.concurrent.TimeUnit; 334 import java.util.concurrent.atomic.AtomicBoolean; 335 import java.util.concurrent.atomic.AtomicInteger; 336 337 /** 338 * Keep track of all those APKs everywhere. 339 * <p> 340 * Internally there are two important locks: 341 * <ul> 342 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 343 * and other related state. It is a fine-grained lock that should only be held 344 * momentarily, as it's one of the most contended locks in the system. 345 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 346 * operations typically involve heavy lifting of application data on disk. Since 347 * {@code installd} is single-threaded, and it's operations can often be slow, 348 * this lock should never be acquired while already holding {@link #mPackages}. 349 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 350 * holding {@link #mInstallLock}. 351 * </ul> 352 * Many internal methods rely on the caller to hold the appropriate locks, and 353 * this contract is expressed through method name suffixes: 354 * <ul> 355 * <li>fooLI(): the caller must hold {@link #mInstallLock} 356 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 357 * being modified must be frozen 358 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 359 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 360 * </ul> 361 * <p> 362 * Because this class is very central to the platform's security; please run all 363 * CTS and unit tests whenever making modifications: 364 * 365 * <pre> 366 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 367 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 368 * </pre> 369 */ 370 public class PackageManagerService extends IPackageManager.Stub 371 implements PackageSender { 372 static final String TAG = "PackageManager"; 373 static final boolean DEBUG_SETTINGS = false; 374 static final boolean DEBUG_PREFERRED = false; 375 static final boolean DEBUG_UPGRADE = false; 376 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 377 private static final boolean DEBUG_BACKUP = false; 378 private static final boolean DEBUG_INSTALL = false; 379 private static final boolean DEBUG_REMOVE = false; 380 private static final boolean DEBUG_BROADCASTS = false; 381 private static final boolean DEBUG_SHOW_INFO = false; 382 private static final boolean DEBUG_PACKAGE_INFO = false; 383 private static final boolean DEBUG_INTENT_MATCHING = false; 384 private static final boolean DEBUG_PACKAGE_SCANNING = false; 385 private static final boolean DEBUG_VERIFY = false; 386 private static final boolean DEBUG_FILTERS = false; 387 private static final boolean DEBUG_PERMISSIONS = false; 388 private static final boolean DEBUG_SHARED_LIBRARIES = false; 389 390 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 391 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 392 // user, but by default initialize to this. 393 public static final boolean DEBUG_DEXOPT = false; 394 395 private static final boolean DEBUG_ABI_SELECTION = false; 396 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 397 private static final boolean DEBUG_TRIAGED_MISSING = false; 398 private static final boolean DEBUG_APP_DATA = false; 399 400 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 401 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 402 403 private static final boolean HIDE_EPHEMERAL_APIS = false; 404 405 private static final boolean ENABLE_FREE_CACHE_V2 = 406 SystemProperties.getBoolean("fw.free_cache_v2", true); 407 408 private static final int RADIO_UID = Process.PHONE_UID; 409 private static final int LOG_UID = Process.LOG_UID; 410 private static final int NFC_UID = Process.NFC_UID; 411 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 412 private static final int SHELL_UID = Process.SHELL_UID; 413 414 // Cap the size of permission trees that 3rd party apps can define 415 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 416 417 // Suffix used during package installation when copying/moving 418 // package apks to install directory. 419 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 420 421 static final int SCAN_NO_DEX = 1<<1; 422 static final int SCAN_FORCE_DEX = 1<<2; 423 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 424 static final int SCAN_NEW_INSTALL = 1<<4; 425 static final int SCAN_UPDATE_TIME = 1<<5; 426 static final int SCAN_BOOTING = 1<<6; 427 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 428 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 429 static final int SCAN_REPLACING = 1<<9; 430 static final int SCAN_REQUIRE_KNOWN = 1<<10; 431 static final int SCAN_MOVE = 1<<11; 432 static final int SCAN_INITIAL = 1<<12; 433 static final int SCAN_CHECK_ONLY = 1<<13; 434 static final int SCAN_DONT_KILL_APP = 1<<14; 435 static final int SCAN_IGNORE_FROZEN = 1<<15; 436 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 437 static final int SCAN_AS_INSTANT_APP = 1<<17; 438 static final int SCAN_AS_FULL_APP = 1<<18; 439 /** Should not be with the scan flags */ 440 static final int FLAGS_REMOVE_CHATTY = 1<<31; 441 442 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 443 444 private static final int[] EMPTY_INT_ARRAY = new int[0]; 445 446 private static final int TYPE_UNKNOWN = 0; 447 private static final int TYPE_ACTIVITY = 1; 448 private static final int TYPE_RECEIVER = 2; 449 private static final int TYPE_SERVICE = 3; 450 private static final int TYPE_PROVIDER = 4; 451 @IntDef(prefix = { "TYPE_" }, value = { 452 TYPE_UNKNOWN, 453 TYPE_ACTIVITY, 454 TYPE_RECEIVER, 455 TYPE_SERVICE, 456 TYPE_PROVIDER, 457 }) 458 @Retention(RetentionPolicy.SOURCE) 459 public @interface ComponentType {} 460 461 /** 462 * Timeout (in milliseconds) after which the watchdog should declare that 463 * our handler thread is wedged. The usual default for such things is one 464 * minute but we sometimes do very lengthy I/O operations on this thread, 465 * such as installing multi-gigabyte applications, so ours needs to be longer. 466 */ 467 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 468 469 /** 470 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 471 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 472 * settings entry if available, otherwise we use the hardcoded default. If it's been 473 * more than this long since the last fstrim, we force one during the boot sequence. 474 * 475 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 476 * one gets run at the next available charging+idle time. This final mandatory 477 * no-fstrim check kicks in only of the other scheduling criteria is never met. 478 */ 479 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 480 481 /** 482 * Whether verification is enabled by default. 483 */ 484 private static final boolean DEFAULT_VERIFY_ENABLE = true; 485 486 /** 487 * The default maximum time to wait for the verification agent to return in 488 * milliseconds. 489 */ 490 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 491 492 /** 493 * The default response for package verification timeout. 494 * 495 * This can be either PackageManager.VERIFICATION_ALLOW or 496 * PackageManager.VERIFICATION_REJECT. 497 */ 498 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 499 500 static final String PLATFORM_PACKAGE_NAME = "android"; 501 502 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 503 504 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 505 DEFAULT_CONTAINER_PACKAGE, 506 "com.android.defcontainer.DefaultContainerService"); 507 508 private static final String KILL_APP_REASON_GIDS_CHANGED = 509 "permission grant or revoke changed gids"; 510 511 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 512 "permissions revoked"; 513 514 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 515 516 private static final String PACKAGE_SCHEME = "package"; 517 518 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 519 520 /** Permission grant: not grant the permission. */ 521 private static final int GRANT_DENIED = 1; 522 523 /** Permission grant: grant the permission as an install permission. */ 524 private static final int GRANT_INSTALL = 2; 525 526 /** Permission grant: grant the permission as a runtime one. */ 527 private static final int GRANT_RUNTIME = 3; 528 529 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 530 private static final int GRANT_UPGRADE = 4; 531 532 /** Canonical intent used to identify what counts as a "web browser" app */ 533 private static final Intent sBrowserIntent; 534 static { 535 sBrowserIntent = new Intent(); 536 sBrowserIntent.setAction(Intent.ACTION_VIEW); 537 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 538 sBrowserIntent.setData(Uri.parse("http:")); 539 } 540 541 /** 542 * The set of all protected actions [i.e. those actions for which a high priority 543 * intent filter is disallowed]. 544 */ 545 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 546 static { 547 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 548 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 549 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 550 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 551 } 552 553 // Compilation reasons. 554 public static final int REASON_FIRST_BOOT = 0; 555 public static final int REASON_BOOT = 1; 556 public static final int REASON_INSTALL = 2; 557 public static final int REASON_BACKGROUND_DEXOPT = 3; 558 public static final int REASON_AB_OTA = 4; 559 560 public static final int REASON_LAST = REASON_AB_OTA; 561 562 /** All dangerous permission names in the same order as the events in MetricsEvent */ 563 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 564 Manifest.permission.READ_CALENDAR, 565 Manifest.permission.WRITE_CALENDAR, 566 Manifest.permission.CAMERA, 567 Manifest.permission.READ_CONTACTS, 568 Manifest.permission.WRITE_CONTACTS, 569 Manifest.permission.GET_ACCOUNTS, 570 Manifest.permission.ACCESS_FINE_LOCATION, 571 Manifest.permission.ACCESS_COARSE_LOCATION, 572 Manifest.permission.RECORD_AUDIO, 573 Manifest.permission.READ_PHONE_STATE, 574 Manifest.permission.CALL_PHONE, 575 Manifest.permission.READ_CALL_LOG, 576 Manifest.permission.WRITE_CALL_LOG, 577 Manifest.permission.ADD_VOICEMAIL, 578 Manifest.permission.USE_SIP, 579 Manifest.permission.PROCESS_OUTGOING_CALLS, 580 Manifest.permission.READ_CELL_BROADCASTS, 581 Manifest.permission.BODY_SENSORS, 582 Manifest.permission.SEND_SMS, 583 Manifest.permission.RECEIVE_SMS, 584 Manifest.permission.READ_SMS, 585 Manifest.permission.RECEIVE_WAP_PUSH, 586 Manifest.permission.RECEIVE_MMS, 587 Manifest.permission.READ_EXTERNAL_STORAGE, 588 Manifest.permission.WRITE_EXTERNAL_STORAGE, 589 Manifest.permission.READ_PHONE_NUMBERS, 590 Manifest.permission.ANSWER_PHONE_CALLS); 591 592 593 /** 594 * Version number for the package parser cache. Increment this whenever the format or 595 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 596 */ 597 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 598 599 /** 600 * Whether the package parser cache is enabled. 601 */ 602 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 603 604 final ServiceThread mHandlerThread; 605 606 final PackageHandler mHandler; 607 608 private final ProcessLoggingHandler mProcessLoggingHandler; 609 610 /** 611 * Messages for {@link #mHandler} that need to wait for system ready before 612 * being dispatched. 613 */ 614 private ArrayList<Message> mPostSystemReadyMessages; 615 616 final int mSdkVersion = Build.VERSION.SDK_INT; 617 618 final Context mContext; 619 final boolean mFactoryTest; 620 final boolean mOnlyCore; 621 final DisplayMetrics mMetrics; 622 final int mDefParseFlags; 623 final String[] mSeparateProcesses; 624 final boolean mIsUpgrade; 625 final boolean mIsPreNUpgrade; 626 final boolean mIsPreNMR1Upgrade; 627 628 // Have we told the Activity Manager to whitelist the default container service by uid yet? 629 @GuardedBy("mPackages") 630 boolean mDefaultContainerWhitelisted = false; 631 632 @GuardedBy("mPackages") 633 private boolean mDexOptDialogShown; 634 635 /** The location for ASEC container files on internal storage. */ 636 final String mAsecInternalPath; 637 638 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 639 // LOCK HELD. Can be called with mInstallLock held. 640 @GuardedBy("mInstallLock") 641 final Installer mInstaller; 642 643 /** Directory where installed third-party apps stored */ 644 final File mAppInstallDir; 645 646 /** 647 * Directory to which applications installed internally have their 648 * 32 bit native libraries copied. 649 */ 650 private File mAppLib32InstallDir; 651 652 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 653 // apps. 654 final File mDrmAppPrivateInstallDir; 655 656 // ---------------------------------------------------------------- 657 658 // Lock for state used when installing and doing other long running 659 // operations. Methods that must be called with this lock held have 660 // the suffix "LI". 661 final Object mInstallLock = new Object(); 662 663 // ---------------------------------------------------------------- 664 665 // Keys are String (package name), values are Package. This also serves 666 // as the lock for the global state. Methods that must be called with 667 // this lock held have the prefix "LP". 668 @GuardedBy("mPackages") 669 final ArrayMap<String, PackageParser.Package> mPackages = 670 new ArrayMap<String, PackageParser.Package>(); 671 672 final ArrayMap<String, Set<String>> mKnownCodebase = 673 new ArrayMap<String, Set<String>>(); 674 675 // Keys are isolated uids and values are the uid of the application 676 // that created the isolated proccess. 677 @GuardedBy("mPackages") 678 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 679 680 /** 681 * Tracks new system packages [received in an OTA] that we expect to 682 * find updated user-installed versions. Keys are package name, values 683 * are package location. 684 */ 685 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 686 /** 687 * Tracks high priority intent filters for protected actions. During boot, certain 688 * filter actions are protected and should never be allowed to have a high priority 689 * intent filter for them. However, there is one, and only one exception -- the 690 * setup wizard. It must be able to define a high priority intent filter for these 691 * actions to ensure there are no escapes from the wizard. We need to delay processing 692 * of these during boot as we need to look at all of the system packages in order 693 * to know which component is the setup wizard. 694 */ 695 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 696 /** 697 * Whether or not processing protected filters should be deferred. 698 */ 699 private boolean mDeferProtectedFilters = true; 700 701 /** 702 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 703 */ 704 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 705 /** 706 * Whether or not system app permissions should be promoted from install to runtime. 707 */ 708 boolean mPromoteSystemApps; 709 710 @GuardedBy("mPackages") 711 final Settings mSettings; 712 713 /** 714 * Set of package names that are currently "frozen", which means active 715 * surgery is being done on the code/data for that package. The platform 716 * will refuse to launch frozen packages to avoid race conditions. 717 * 718 * @see PackageFreezer 719 */ 720 @GuardedBy("mPackages") 721 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 722 723 final ProtectedPackages mProtectedPackages; 724 725 boolean mFirstBoot; 726 727 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 728 729 // System configuration read by SystemConfig. 730 final int[] mGlobalGids; 731 final SparseArray<ArraySet<String>> mSystemPermissions; 732 @GuardedBy("mAvailableFeatures") 733 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 734 735 // If mac_permissions.xml was found for seinfo labeling. 736 boolean mFoundPolicyFile; 737 738 private final InstantAppRegistry mInstantAppRegistry; 739 740 @GuardedBy("mPackages") 741 int mChangedPackagesSequenceNumber; 742 /** 743 * List of changed [installed, removed or updated] packages. 744 * mapping from user id -> sequence number -> package name 745 */ 746 @GuardedBy("mPackages") 747 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 748 /** 749 * The sequence number of the last change to a package. 750 * mapping from user id -> package name -> sequence number 751 */ 752 @GuardedBy("mPackages") 753 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 754 755 class PackageParserCallback implements PackageParser.Callback { 756 @Override public final boolean hasFeature(String feature) { 757 return PackageManagerService.this.hasSystemFeature(feature, 0); 758 } 759 760 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 761 Collection<PackageParser.Package> allPackages, String targetPackageName) { 762 List<PackageParser.Package> overlayPackages = null; 763 for (PackageParser.Package p : allPackages) { 764 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) { 765 if (overlayPackages == null) { 766 overlayPackages = new ArrayList<PackageParser.Package>(); 767 } 768 overlayPackages.add(p); 769 } 770 } 771 if (overlayPackages != null) { 772 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 773 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 774 return p1.mOverlayPriority - p2.mOverlayPriority; 775 } 776 }; 777 Collections.sort(overlayPackages, cmp); 778 } 779 return overlayPackages; 780 } 781 782 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 783 String targetPackageName, String targetPath) { 784 if ("android".equals(targetPackageName)) { 785 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 786 // native AssetManager. 787 return null; 788 } 789 List<PackageParser.Package> overlayPackages = 790 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 791 if (overlayPackages == null || overlayPackages.isEmpty()) { 792 return null; 793 } 794 List<String> overlayPathList = null; 795 for (PackageParser.Package overlayPackage : overlayPackages) { 796 if (targetPath == null) { 797 if (overlayPathList == null) { 798 overlayPathList = new ArrayList<String>(); 799 } 800 overlayPathList.add(overlayPackage.baseCodePath); 801 continue; 802 } 803 804 try { 805 // Creates idmaps for system to parse correctly the Android manifest of the 806 // target package. 807 // 808 // OverlayManagerService will update each of them with a correct gid from its 809 // target package app id. 810 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 811 UserHandle.getSharedAppGid( 812 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 813 if (overlayPathList == null) { 814 overlayPathList = new ArrayList<String>(); 815 } 816 overlayPathList.add(overlayPackage.baseCodePath); 817 } catch (InstallerException e) { 818 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 819 overlayPackage.baseCodePath); 820 } 821 } 822 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 823 } 824 825 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 826 synchronized (mPackages) { 827 return getStaticOverlayPathsLocked( 828 mPackages.values(), targetPackageName, targetPath); 829 } 830 } 831 832 @Override public final String[] getOverlayApks(String targetPackageName) { 833 return getStaticOverlayPaths(targetPackageName, null); 834 } 835 836 @Override public final String[] getOverlayPaths(String targetPackageName, 837 String targetPath) { 838 return getStaticOverlayPaths(targetPackageName, targetPath); 839 } 840 }; 841 842 class ParallelPackageParserCallback extends PackageParserCallback { 843 List<PackageParser.Package> mOverlayPackages = null; 844 845 void findStaticOverlayPackages() { 846 synchronized (mPackages) { 847 for (PackageParser.Package p : mPackages.values()) { 848 if (p.mIsStaticOverlay) { 849 if (mOverlayPackages == null) { 850 mOverlayPackages = new ArrayList<PackageParser.Package>(); 851 } 852 mOverlayPackages.add(p); 853 } 854 } 855 } 856 } 857 858 @Override 859 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 860 // We can trust mOverlayPackages without holding mPackages because package uninstall 861 // can't happen while running parallel parsing. 862 // Moreover holding mPackages on each parsing thread causes dead-lock. 863 return mOverlayPackages == null ? null : 864 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 865 } 866 } 867 868 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 869 final ParallelPackageParserCallback mParallelPackageParserCallback = 870 new ParallelPackageParserCallback(); 871 872 public static final class SharedLibraryEntry { 873 public final @Nullable String path; 874 public final @Nullable String apk; 875 public final @NonNull SharedLibraryInfo info; 876 877 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 878 String declaringPackageName, int declaringPackageVersionCode) { 879 path = _path; 880 apk = _apk; 881 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 882 declaringPackageName, declaringPackageVersionCode), null); 883 } 884 } 885 886 // Currently known shared libraries. 887 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 888 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 889 new ArrayMap<>(); 890 891 // All available activities, for your resolving pleasure. 892 final ActivityIntentResolver mActivities = 893 new ActivityIntentResolver(); 894 895 // All available receivers, for your resolving pleasure. 896 final ActivityIntentResolver mReceivers = 897 new ActivityIntentResolver(); 898 899 // All available services, for your resolving pleasure. 900 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 901 902 // All available providers, for your resolving pleasure. 903 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 904 905 // Mapping from provider base names (first directory in content URI codePath) 906 // to the provider information. 907 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 908 new ArrayMap<String, PackageParser.Provider>(); 909 910 // Mapping from instrumentation class names to info about them. 911 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 912 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 913 914 // Mapping from permission names to info about them. 915 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 916 new ArrayMap<String, PackageParser.PermissionGroup>(); 917 918 // Packages whose data we have transfered into another package, thus 919 // should no longer exist. 920 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 921 922 // Broadcast actions that are only available to the system. 923 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 924 925 /** List of packages waiting for verification. */ 926 final SparseArray<PackageVerificationState> mPendingVerification 927 = new SparseArray<PackageVerificationState>(); 928 929 /** Set of packages associated with each app op permission. */ 930 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 931 932 final PackageInstallerService mInstallerService; 933 934 private final PackageDexOptimizer mPackageDexOptimizer; 935 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 936 // is used by other apps). 937 private final DexManager mDexManager; 938 939 private AtomicInteger mNextMoveId = new AtomicInteger(); 940 private final MoveCallbacks mMoveCallbacks; 941 942 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 943 944 // Cache of users who need badging. 945 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 946 947 /** Token for keys in mPendingVerification. */ 948 private int mPendingVerificationToken = 0; 949 950 volatile boolean mSystemReady; 951 volatile boolean mSafeMode; 952 volatile boolean mHasSystemUidErrors; 953 private volatile boolean mEphemeralAppsDisabled; 954 955 ApplicationInfo mAndroidApplication; 956 final ActivityInfo mResolveActivity = new ActivityInfo(); 957 final ResolveInfo mResolveInfo = new ResolveInfo(); 958 ComponentName mResolveComponentName; 959 PackageParser.Package mPlatformPackage; 960 ComponentName mCustomResolverComponentName; 961 962 boolean mResolverReplaced = false; 963 964 private final @Nullable ComponentName mIntentFilterVerifierComponent; 965 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 966 967 private int mIntentFilterVerificationToken = 0; 968 969 /** The service connection to the ephemeral resolver */ 970 final EphemeralResolverConnection mInstantAppResolverConnection; 971 /** Component used to show resolver settings for Instant Apps */ 972 final ComponentName mInstantAppResolverSettingsComponent; 973 974 /** Activity used to install instant applications */ 975 ActivityInfo mInstantAppInstallerActivity; 976 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 977 978 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 979 = new SparseArray<IntentFilterVerificationState>(); 980 981 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 982 983 // List of packages names to keep cached, even if they are uninstalled for all users 984 private List<String> mKeepUninstalledPackages; 985 986 private UserManagerInternal mUserManagerInternal; 987 988 private DeviceIdleController.LocalService mDeviceIdleController; 989 990 private File mCacheDir; 991 992 private ArraySet<String> mPrivappPermissionsViolations; 993 994 private Future<?> mPrepareAppDataFuture; 995 996 private static class IFVerificationParams { 997 PackageParser.Package pkg; 998 boolean replacing; 999 int userId; 1000 int verifierUid; 1001 1002 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1003 int _userId, int _verifierUid) { 1004 pkg = _pkg; 1005 replacing = _replacing; 1006 userId = _userId; 1007 replacing = _replacing; 1008 verifierUid = _verifierUid; 1009 } 1010 } 1011 1012 private interface IntentFilterVerifier<T extends IntentFilter> { 1013 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1014 T filter, String packageName); 1015 void startVerifications(int userId); 1016 void receiveVerificationResponse(int verificationId); 1017 } 1018 1019 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1020 private Context mContext; 1021 private ComponentName mIntentFilterVerifierComponent; 1022 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1023 1024 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1025 mContext = context; 1026 mIntentFilterVerifierComponent = verifierComponent; 1027 } 1028 1029 private String getDefaultScheme() { 1030 return IntentFilter.SCHEME_HTTPS; 1031 } 1032 1033 @Override 1034 public void startVerifications(int userId) { 1035 // Launch verifications requests 1036 int count = mCurrentIntentFilterVerifications.size(); 1037 for (int n=0; n<count; n++) { 1038 int verificationId = mCurrentIntentFilterVerifications.get(n); 1039 final IntentFilterVerificationState ivs = 1040 mIntentFilterVerificationStates.get(verificationId); 1041 1042 String packageName = ivs.getPackageName(); 1043 1044 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1045 final int filterCount = filters.size(); 1046 ArraySet<String> domainsSet = new ArraySet<>(); 1047 for (int m=0; m<filterCount; m++) { 1048 PackageParser.ActivityIntentInfo filter = filters.get(m); 1049 domainsSet.addAll(filter.getHostsList()); 1050 } 1051 synchronized (mPackages) { 1052 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1053 packageName, domainsSet) != null) { 1054 scheduleWriteSettingsLocked(); 1055 } 1056 } 1057 sendVerificationRequest(userId, verificationId, ivs); 1058 } 1059 mCurrentIntentFilterVerifications.clear(); 1060 } 1061 1062 private void sendVerificationRequest(int userId, int verificationId, 1063 IntentFilterVerificationState ivs) { 1064 1065 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1066 verificationIntent.putExtra( 1067 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1068 verificationId); 1069 verificationIntent.putExtra( 1070 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1071 getDefaultScheme()); 1072 verificationIntent.putExtra( 1073 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1074 ivs.getHostsString()); 1075 verificationIntent.putExtra( 1076 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1077 ivs.getPackageName()); 1078 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1079 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1080 1081 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1082 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1083 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1084 userId, false, "intent filter verifier"); 1085 1086 UserHandle user = new UserHandle(userId); 1087 mContext.sendBroadcastAsUser(verificationIntent, user); 1088 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1089 "Sending IntentFilter verification broadcast"); 1090 } 1091 1092 public void receiveVerificationResponse(int verificationId) { 1093 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1094 1095 final boolean verified = ivs.isVerified(); 1096 1097 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1098 final int count = filters.size(); 1099 if (DEBUG_DOMAIN_VERIFICATION) { 1100 Slog.i(TAG, "Received verification response " + verificationId 1101 + " for " + count + " filters, verified=" + verified); 1102 } 1103 for (int n=0; n<count; n++) { 1104 PackageParser.ActivityIntentInfo filter = filters.get(n); 1105 filter.setVerified(verified); 1106 1107 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1108 + " verified with result:" + verified + " and hosts:" 1109 + ivs.getHostsString()); 1110 } 1111 1112 mIntentFilterVerificationStates.remove(verificationId); 1113 1114 final String packageName = ivs.getPackageName(); 1115 IntentFilterVerificationInfo ivi = null; 1116 1117 synchronized (mPackages) { 1118 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1119 } 1120 if (ivi == null) { 1121 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1122 + verificationId + " packageName:" + packageName); 1123 return; 1124 } 1125 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1126 "Updating IntentFilterVerificationInfo for package " + packageName 1127 +" verificationId:" + verificationId); 1128 1129 synchronized (mPackages) { 1130 if (verified) { 1131 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1132 } else { 1133 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1134 } 1135 scheduleWriteSettingsLocked(); 1136 1137 final int userId = ivs.getUserId(); 1138 if (userId != UserHandle.USER_ALL) { 1139 final int userStatus = 1140 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1141 1142 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1143 boolean needUpdate = false; 1144 1145 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1146 // already been set by the User thru the Disambiguation dialog 1147 switch (userStatus) { 1148 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1149 if (verified) { 1150 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1151 } else { 1152 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1153 } 1154 needUpdate = true; 1155 break; 1156 1157 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1158 if (verified) { 1159 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1160 needUpdate = true; 1161 } 1162 break; 1163 1164 default: 1165 // Nothing to do 1166 } 1167 1168 if (needUpdate) { 1169 mSettings.updateIntentFilterVerificationStatusLPw( 1170 packageName, updatedStatus, userId); 1171 scheduleWritePackageRestrictionsLocked(userId); 1172 } 1173 } 1174 } 1175 } 1176 1177 @Override 1178 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1179 ActivityIntentInfo filter, String packageName) { 1180 if (!hasValidDomains(filter)) { 1181 return false; 1182 } 1183 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1184 if (ivs == null) { 1185 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1186 packageName); 1187 } 1188 if (DEBUG_DOMAIN_VERIFICATION) { 1189 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1190 } 1191 ivs.addFilter(filter); 1192 return true; 1193 } 1194 1195 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1196 int userId, int verificationId, String packageName) { 1197 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1198 verifierUid, userId, packageName); 1199 ivs.setPendingState(); 1200 synchronized (mPackages) { 1201 mIntentFilterVerificationStates.append(verificationId, ivs); 1202 mCurrentIntentFilterVerifications.add(verificationId); 1203 } 1204 return ivs; 1205 } 1206 } 1207 1208 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1209 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1210 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1211 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1212 } 1213 1214 // Set of pending broadcasts for aggregating enable/disable of components. 1215 static class PendingPackageBroadcasts { 1216 // for each user id, a map of <package name -> components within that package> 1217 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1218 1219 public PendingPackageBroadcasts() { 1220 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1221 } 1222 1223 public ArrayList<String> get(int userId, String packageName) { 1224 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1225 return packages.get(packageName); 1226 } 1227 1228 public void put(int userId, String packageName, ArrayList<String> components) { 1229 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1230 packages.put(packageName, components); 1231 } 1232 1233 public void remove(int userId, String packageName) { 1234 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1235 if (packages != null) { 1236 packages.remove(packageName); 1237 } 1238 } 1239 1240 public void remove(int userId) { 1241 mUidMap.remove(userId); 1242 } 1243 1244 public int userIdCount() { 1245 return mUidMap.size(); 1246 } 1247 1248 public int userIdAt(int n) { 1249 return mUidMap.keyAt(n); 1250 } 1251 1252 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1253 return mUidMap.get(userId); 1254 } 1255 1256 public int size() { 1257 // total number of pending broadcast entries across all userIds 1258 int num = 0; 1259 for (int i = 0; i< mUidMap.size(); i++) { 1260 num += mUidMap.valueAt(i).size(); 1261 } 1262 return num; 1263 } 1264 1265 public void clear() { 1266 mUidMap.clear(); 1267 } 1268 1269 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1270 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1271 if (map == null) { 1272 map = new ArrayMap<String, ArrayList<String>>(); 1273 mUidMap.put(userId, map); 1274 } 1275 return map; 1276 } 1277 } 1278 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1279 1280 // Service Connection to remote media container service to copy 1281 // package uri's from external media onto secure containers 1282 // or internal storage. 1283 private IMediaContainerService mContainerService = null; 1284 1285 static final int SEND_PENDING_BROADCAST = 1; 1286 static final int MCS_BOUND = 3; 1287 static final int END_COPY = 4; 1288 static final int INIT_COPY = 5; 1289 static final int MCS_UNBIND = 6; 1290 static final int START_CLEANING_PACKAGE = 7; 1291 static final int FIND_INSTALL_LOC = 8; 1292 static final int POST_INSTALL = 9; 1293 static final int MCS_RECONNECT = 10; 1294 static final int MCS_GIVE_UP = 11; 1295 static final int UPDATED_MEDIA_STATUS = 12; 1296 static final int WRITE_SETTINGS = 13; 1297 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1298 static final int PACKAGE_VERIFIED = 15; 1299 static final int CHECK_PENDING_VERIFICATION = 16; 1300 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1301 static final int INTENT_FILTER_VERIFIED = 18; 1302 static final int WRITE_PACKAGE_LIST = 19; 1303 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1304 1305 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1306 1307 // Delay time in millisecs 1308 static final int BROADCAST_DELAY = 10 * 1000; 1309 1310 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1311 2 * 60 * 60 * 1000L; /* two hours */ 1312 1313 static UserManagerService sUserManager; 1314 1315 // Stores a list of users whose package restrictions file needs to be updated 1316 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1317 1318 final private DefaultContainerConnection mDefContainerConn = 1319 new DefaultContainerConnection(); 1320 class DefaultContainerConnection implements ServiceConnection { 1321 public void onServiceConnected(ComponentName name, IBinder service) { 1322 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1323 final IMediaContainerService imcs = IMediaContainerService.Stub 1324 .asInterface(Binder.allowBlocking(service)); 1325 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1326 } 1327 1328 public void onServiceDisconnected(ComponentName name) { 1329 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1330 } 1331 } 1332 1333 // Recordkeeping of restore-after-install operations that are currently in flight 1334 // between the Package Manager and the Backup Manager 1335 static class PostInstallData { 1336 public InstallArgs args; 1337 public PackageInstalledInfo res; 1338 1339 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1340 args = _a; 1341 res = _r; 1342 } 1343 } 1344 1345 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1346 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1347 1348 // XML tags for backup/restore of various bits of state 1349 private static final String TAG_PREFERRED_BACKUP = "pa"; 1350 private static final String TAG_DEFAULT_APPS = "da"; 1351 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1352 1353 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1354 private static final String TAG_ALL_GRANTS = "rt-grants"; 1355 private static final String TAG_GRANT = "grant"; 1356 private static final String ATTR_PACKAGE_NAME = "pkg"; 1357 1358 private static final String TAG_PERMISSION = "perm"; 1359 private static final String ATTR_PERMISSION_NAME = "name"; 1360 private static final String ATTR_IS_GRANTED = "g"; 1361 private static final String ATTR_USER_SET = "set"; 1362 private static final String ATTR_USER_FIXED = "fixed"; 1363 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1364 1365 // System/policy permission grants are not backed up 1366 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1367 FLAG_PERMISSION_POLICY_FIXED 1368 | FLAG_PERMISSION_SYSTEM_FIXED 1369 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1370 1371 // And we back up these user-adjusted states 1372 private static final int USER_RUNTIME_GRANT_MASK = 1373 FLAG_PERMISSION_USER_SET 1374 | FLAG_PERMISSION_USER_FIXED 1375 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1376 1377 final @Nullable String mRequiredVerifierPackage; 1378 final @NonNull String mRequiredInstallerPackage; 1379 final @NonNull String mRequiredUninstallerPackage; 1380 final @Nullable String mSetupWizardPackage; 1381 final @Nullable String mStorageManagerPackage; 1382 final @NonNull String mServicesSystemSharedLibraryPackageName; 1383 final @NonNull String mSharedSystemSharedLibraryPackageName; 1384 1385 final boolean mPermissionReviewRequired; 1386 1387 private final PackageUsage mPackageUsage = new PackageUsage(); 1388 private final CompilerStats mCompilerStats = new CompilerStats(); 1389 1390 class PackageHandler extends Handler { 1391 private boolean mBound = false; 1392 final ArrayList<HandlerParams> mPendingInstalls = 1393 new ArrayList<HandlerParams>(); 1394 1395 private boolean connectToService() { 1396 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1397 " DefaultContainerService"); 1398 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1399 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1400 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1401 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1402 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1403 mBound = true; 1404 return true; 1405 } 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1407 return false; 1408 } 1409 1410 private void disconnectService() { 1411 mContainerService = null; 1412 mBound = false; 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1414 mContext.unbindService(mDefContainerConn); 1415 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1416 } 1417 1418 PackageHandler(Looper looper) { 1419 super(looper); 1420 } 1421 1422 public void handleMessage(Message msg) { 1423 try { 1424 doHandleMessage(msg); 1425 } finally { 1426 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1427 } 1428 } 1429 1430 void doHandleMessage(Message msg) { 1431 switch (msg.what) { 1432 case INIT_COPY: { 1433 HandlerParams params = (HandlerParams) msg.obj; 1434 int idx = mPendingInstalls.size(); 1435 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1436 // If a bind was already initiated we dont really 1437 // need to do anything. The pending install 1438 // will be processed later on. 1439 if (!mBound) { 1440 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1441 System.identityHashCode(mHandler)); 1442 // If this is the only one pending we might 1443 // have to bind to the service again. 1444 if (!connectToService()) { 1445 Slog.e(TAG, "Failed to bind to media container service"); 1446 params.serviceError(); 1447 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1448 System.identityHashCode(mHandler)); 1449 if (params.traceMethod != null) { 1450 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1451 params.traceCookie); 1452 } 1453 return; 1454 } else { 1455 // Once we bind to the service, the first 1456 // pending request will be processed. 1457 mPendingInstalls.add(idx, params); 1458 } 1459 } else { 1460 mPendingInstalls.add(idx, params); 1461 // Already bound to the service. Just make 1462 // sure we trigger off processing the first request. 1463 if (idx == 0) { 1464 mHandler.sendEmptyMessage(MCS_BOUND); 1465 } 1466 } 1467 break; 1468 } 1469 case MCS_BOUND: { 1470 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1471 if (msg.obj != null) { 1472 mContainerService = (IMediaContainerService) msg.obj; 1473 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1474 System.identityHashCode(mHandler)); 1475 } 1476 if (mContainerService == null) { 1477 if (!mBound) { 1478 // Something seriously wrong since we are not bound and we are not 1479 // waiting for connection. Bail out. 1480 Slog.e(TAG, "Cannot bind to media container service"); 1481 for (HandlerParams params : mPendingInstalls) { 1482 // Indicate service bind error 1483 params.serviceError(); 1484 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1485 System.identityHashCode(params)); 1486 if (params.traceMethod != null) { 1487 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1488 params.traceMethod, params.traceCookie); 1489 } 1490 return; 1491 } 1492 mPendingInstalls.clear(); 1493 } else { 1494 Slog.w(TAG, "Waiting to connect to media container service"); 1495 } 1496 } else if (mPendingInstalls.size() > 0) { 1497 HandlerParams params = mPendingInstalls.get(0); 1498 if (params != null) { 1499 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1500 System.identityHashCode(params)); 1501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1502 if (params.startCopy()) { 1503 // We are done... look for more work or to 1504 // go idle. 1505 if (DEBUG_SD_INSTALL) Log.i(TAG, 1506 "Checking for more work or unbind..."); 1507 // Delete pending install 1508 if (mPendingInstalls.size() > 0) { 1509 mPendingInstalls.remove(0); 1510 } 1511 if (mPendingInstalls.size() == 0) { 1512 if (mBound) { 1513 if (DEBUG_SD_INSTALL) Log.i(TAG, 1514 "Posting delayed MCS_UNBIND"); 1515 removeMessages(MCS_UNBIND); 1516 Message ubmsg = obtainMessage(MCS_UNBIND); 1517 // Unbind after a little delay, to avoid 1518 // continual thrashing. 1519 sendMessageDelayed(ubmsg, 10000); 1520 } 1521 } else { 1522 // There are more pending requests in queue. 1523 // Just post MCS_BOUND message to trigger processing 1524 // of next pending install. 1525 if (DEBUG_SD_INSTALL) Log.i(TAG, 1526 "Posting MCS_BOUND for next work"); 1527 mHandler.sendEmptyMessage(MCS_BOUND); 1528 } 1529 } 1530 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1531 } 1532 } else { 1533 // Should never happen ideally. 1534 Slog.w(TAG, "Empty queue"); 1535 } 1536 break; 1537 } 1538 case MCS_RECONNECT: { 1539 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1540 if (mPendingInstalls.size() > 0) { 1541 if (mBound) { 1542 disconnectService(); 1543 } 1544 if (!connectToService()) { 1545 Slog.e(TAG, "Failed to bind to media container service"); 1546 for (HandlerParams params : mPendingInstalls) { 1547 // Indicate service bind error 1548 params.serviceError(); 1549 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1550 System.identityHashCode(params)); 1551 } 1552 mPendingInstalls.clear(); 1553 } 1554 } 1555 break; 1556 } 1557 case MCS_UNBIND: { 1558 // If there is no actual work left, then time to unbind. 1559 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1560 1561 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1562 if (mBound) { 1563 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1564 1565 disconnectService(); 1566 } 1567 } else if (mPendingInstalls.size() > 0) { 1568 // There are more pending requests in queue. 1569 // Just post MCS_BOUND message to trigger processing 1570 // of next pending install. 1571 mHandler.sendEmptyMessage(MCS_BOUND); 1572 } 1573 1574 break; 1575 } 1576 case MCS_GIVE_UP: { 1577 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1578 HandlerParams params = mPendingInstalls.remove(0); 1579 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1580 System.identityHashCode(params)); 1581 break; 1582 } 1583 case SEND_PENDING_BROADCAST: { 1584 String packages[]; 1585 ArrayList<String> components[]; 1586 int size = 0; 1587 int uids[]; 1588 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1589 synchronized (mPackages) { 1590 if (mPendingBroadcasts == null) { 1591 return; 1592 } 1593 size = mPendingBroadcasts.size(); 1594 if (size <= 0) { 1595 // Nothing to be done. Just return 1596 return; 1597 } 1598 packages = new String[size]; 1599 components = new ArrayList[size]; 1600 uids = new int[size]; 1601 int i = 0; // filling out the above arrays 1602 1603 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1604 int packageUserId = mPendingBroadcasts.userIdAt(n); 1605 Iterator<Map.Entry<String, ArrayList<String>>> it 1606 = mPendingBroadcasts.packagesForUserId(packageUserId) 1607 .entrySet().iterator(); 1608 while (it.hasNext() && i < size) { 1609 Map.Entry<String, ArrayList<String>> ent = it.next(); 1610 packages[i] = ent.getKey(); 1611 components[i] = ent.getValue(); 1612 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1613 uids[i] = (ps != null) 1614 ? UserHandle.getUid(packageUserId, ps.appId) 1615 : -1; 1616 i++; 1617 } 1618 } 1619 size = i; 1620 mPendingBroadcasts.clear(); 1621 } 1622 // Send broadcasts 1623 for (int i = 0; i < size; i++) { 1624 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1625 } 1626 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1627 break; 1628 } 1629 case START_CLEANING_PACKAGE: { 1630 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1631 final String packageName = (String)msg.obj; 1632 final int userId = msg.arg1; 1633 final boolean andCode = msg.arg2 != 0; 1634 synchronized (mPackages) { 1635 if (userId == UserHandle.USER_ALL) { 1636 int[] users = sUserManager.getUserIds(); 1637 for (int user : users) { 1638 mSettings.addPackageToCleanLPw( 1639 new PackageCleanItem(user, packageName, andCode)); 1640 } 1641 } else { 1642 mSettings.addPackageToCleanLPw( 1643 new PackageCleanItem(userId, packageName, andCode)); 1644 } 1645 } 1646 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1647 startCleaningPackages(); 1648 } break; 1649 case POST_INSTALL: { 1650 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1651 1652 PostInstallData data = mRunningInstalls.get(msg.arg1); 1653 final boolean didRestore = (msg.arg2 != 0); 1654 mRunningInstalls.delete(msg.arg1); 1655 1656 if (data != null) { 1657 InstallArgs args = data.args; 1658 PackageInstalledInfo parentRes = data.res; 1659 1660 final boolean grantPermissions = (args.installFlags 1661 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1662 final boolean killApp = (args.installFlags 1663 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1664 final String[] grantedPermissions = args.installGrantPermissions; 1665 1666 // Handle the parent package 1667 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1668 grantedPermissions, didRestore, args.installerPackageName, 1669 args.observer); 1670 1671 // Handle the child packages 1672 final int childCount = (parentRes.addedChildPackages != null) 1673 ? parentRes.addedChildPackages.size() : 0; 1674 for (int i = 0; i < childCount; i++) { 1675 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1676 handlePackagePostInstall(childRes, grantPermissions, killApp, 1677 grantedPermissions, false, args.installerPackageName, 1678 args.observer); 1679 } 1680 1681 // Log tracing if needed 1682 if (args.traceMethod != null) { 1683 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1684 args.traceCookie); 1685 } 1686 } else { 1687 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1688 } 1689 1690 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1691 } break; 1692 case UPDATED_MEDIA_STATUS: { 1693 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1694 boolean reportStatus = msg.arg1 == 1; 1695 boolean doGc = msg.arg2 == 1; 1696 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1697 if (doGc) { 1698 // Force a gc to clear up stale containers. 1699 Runtime.getRuntime().gc(); 1700 } 1701 if (msg.obj != null) { 1702 @SuppressWarnings("unchecked") 1703 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1704 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1705 // Unload containers 1706 unloadAllContainers(args); 1707 } 1708 if (reportStatus) { 1709 try { 1710 if (DEBUG_SD_INSTALL) Log.i(TAG, 1711 "Invoking StorageManagerService call back"); 1712 PackageHelper.getStorageManager().finishMediaUpdate(); 1713 } catch (RemoteException e) { 1714 Log.e(TAG, "StorageManagerService not running?"); 1715 } 1716 } 1717 } break; 1718 case WRITE_SETTINGS: { 1719 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1720 synchronized (mPackages) { 1721 removeMessages(WRITE_SETTINGS); 1722 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1723 mSettings.writeLPr(); 1724 mDirtyUsers.clear(); 1725 } 1726 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1727 } break; 1728 case WRITE_PACKAGE_RESTRICTIONS: { 1729 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1730 synchronized (mPackages) { 1731 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1732 for (int userId : mDirtyUsers) { 1733 mSettings.writePackageRestrictionsLPr(userId); 1734 } 1735 mDirtyUsers.clear(); 1736 } 1737 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1738 } break; 1739 case WRITE_PACKAGE_LIST: { 1740 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1741 synchronized (mPackages) { 1742 removeMessages(WRITE_PACKAGE_LIST); 1743 mSettings.writePackageListLPr(msg.arg1); 1744 } 1745 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1746 } break; 1747 case CHECK_PENDING_VERIFICATION: { 1748 final int verificationId = msg.arg1; 1749 final PackageVerificationState state = mPendingVerification.get(verificationId); 1750 1751 if ((state != null) && !state.timeoutExtended()) { 1752 final InstallArgs args = state.getInstallArgs(); 1753 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1754 1755 Slog.i(TAG, "Verification timed out for " + originUri); 1756 mPendingVerification.remove(verificationId); 1757 1758 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1759 1760 final UserHandle user = args.getUser(); 1761 if (getDefaultVerificationResponse(user) 1762 == PackageManager.VERIFICATION_ALLOW) { 1763 Slog.i(TAG, "Continuing with installation of " + originUri); 1764 state.setVerifierResponse(Binder.getCallingUid(), 1765 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1766 broadcastPackageVerified(verificationId, originUri, 1767 PackageManager.VERIFICATION_ALLOW, user); 1768 try { 1769 ret = args.copyApk(mContainerService, true); 1770 } catch (RemoteException e) { 1771 Slog.e(TAG, "Could not contact the ContainerService"); 1772 } 1773 } else { 1774 broadcastPackageVerified(verificationId, originUri, 1775 PackageManager.VERIFICATION_REJECT, user); 1776 } 1777 1778 Trace.asyncTraceEnd( 1779 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1780 1781 processPendingInstall(args, ret); 1782 mHandler.sendEmptyMessage(MCS_UNBIND); 1783 } 1784 break; 1785 } 1786 case PACKAGE_VERIFIED: { 1787 final int verificationId = msg.arg1; 1788 1789 final PackageVerificationState state = mPendingVerification.get(verificationId); 1790 if (state == null) { 1791 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1792 break; 1793 } 1794 1795 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1796 1797 state.setVerifierResponse(response.callerUid, response.code); 1798 1799 if (state.isVerificationComplete()) { 1800 mPendingVerification.remove(verificationId); 1801 1802 final InstallArgs args = state.getInstallArgs(); 1803 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1804 1805 int ret; 1806 if (state.isInstallAllowed()) { 1807 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1808 broadcastPackageVerified(verificationId, originUri, 1809 response.code, state.getInstallArgs().getUser()); 1810 try { 1811 ret = args.copyApk(mContainerService, true); 1812 } catch (RemoteException e) { 1813 Slog.e(TAG, "Could not contact the ContainerService"); 1814 } 1815 } else { 1816 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1817 } 1818 1819 Trace.asyncTraceEnd( 1820 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1821 1822 processPendingInstall(args, ret); 1823 mHandler.sendEmptyMessage(MCS_UNBIND); 1824 } 1825 1826 break; 1827 } 1828 case START_INTENT_FILTER_VERIFICATIONS: { 1829 IFVerificationParams params = (IFVerificationParams) msg.obj; 1830 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1831 params.replacing, params.pkg); 1832 break; 1833 } 1834 case INTENT_FILTER_VERIFIED: { 1835 final int verificationId = msg.arg1; 1836 1837 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1838 verificationId); 1839 if (state == null) { 1840 Slog.w(TAG, "Invalid IntentFilter verification token " 1841 + verificationId + " received"); 1842 break; 1843 } 1844 1845 final int userId = state.getUserId(); 1846 1847 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1848 "Processing IntentFilter verification with token:" 1849 + verificationId + " and userId:" + userId); 1850 1851 final IntentFilterVerificationResponse response = 1852 (IntentFilterVerificationResponse) msg.obj; 1853 1854 state.setVerifierResponse(response.callerUid, response.code); 1855 1856 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1857 "IntentFilter verification with token:" + verificationId 1858 + " and userId:" + userId 1859 + " is settings verifier response with response code:" 1860 + response.code); 1861 1862 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1863 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1864 + response.getFailedDomainsString()); 1865 } 1866 1867 if (state.isVerificationComplete()) { 1868 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1869 } else { 1870 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1871 "IntentFilter verification with token:" + verificationId 1872 + " was not said to be complete"); 1873 } 1874 1875 break; 1876 } 1877 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1878 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1879 mInstantAppResolverConnection, 1880 (InstantAppRequest) msg.obj, 1881 mInstantAppInstallerActivity, 1882 mHandler); 1883 } 1884 } 1885 } 1886 } 1887 1888 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1889 boolean killApp, String[] grantedPermissions, 1890 boolean launchedForRestore, String installerPackage, 1891 IPackageInstallObserver2 installObserver) { 1892 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1893 // Send the removed broadcasts 1894 if (res.removedInfo != null) { 1895 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1896 } 1897 1898 // Now that we successfully installed the package, grant runtime 1899 // permissions if requested before broadcasting the install. Also 1900 // for legacy apps in permission review mode we clear the permission 1901 // review flag which is used to emulate runtime permissions for 1902 // legacy apps. 1903 if (grantPermissions) { 1904 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1905 } 1906 1907 final boolean update = res.removedInfo != null 1908 && res.removedInfo.removedPackage != null; 1909 final String origInstallerPackageName = res.removedInfo != null 1910 ? res.removedInfo.installerPackageName : null; 1911 1912 // If this is the first time we have child packages for a disabled privileged 1913 // app that had no children, we grant requested runtime permissions to the new 1914 // children if the parent on the system image had them already granted. 1915 if (res.pkg.parentPackage != null) { 1916 synchronized (mPackages) { 1917 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1918 } 1919 } 1920 1921 synchronized (mPackages) { 1922 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1923 } 1924 1925 final String packageName = res.pkg.applicationInfo.packageName; 1926 1927 // Determine the set of users who are adding this package for 1928 // the first time vs. those who are seeing an update. 1929 int[] firstUsers = EMPTY_INT_ARRAY; 1930 int[] updateUsers = EMPTY_INT_ARRAY; 1931 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1932 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1933 for (int newUser : res.newUsers) { 1934 if (ps.getInstantApp(newUser)) { 1935 continue; 1936 } 1937 if (allNewUsers) { 1938 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1939 continue; 1940 } 1941 boolean isNew = true; 1942 for (int origUser : res.origUsers) { 1943 if (origUser == newUser) { 1944 isNew = false; 1945 break; 1946 } 1947 } 1948 if (isNew) { 1949 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1950 } else { 1951 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1952 } 1953 } 1954 1955 // Send installed broadcasts if the package is not a static shared lib. 1956 if (res.pkg.staticSharedLibName == null) { 1957 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1958 1959 // Send added for users that see the package for the first time 1960 // sendPackageAddedForNewUsers also deals with system apps 1961 int appId = UserHandle.getAppId(res.uid); 1962 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1963 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1964 1965 // Send added for users that don't see the package for the first time 1966 Bundle extras = new Bundle(1); 1967 extras.putInt(Intent.EXTRA_UID, res.uid); 1968 if (update) { 1969 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1970 } 1971 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1972 extras, 0 /*flags*/, 1973 null /*targetPackage*/, null /*finishedReceiver*/, updateUsers); 1974 if (origInstallerPackageName != null) { 1975 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1976 extras, 0 /*flags*/, 1977 origInstallerPackageName, null /*finishedReceiver*/, updateUsers); 1978 } 1979 1980 // Send replaced for users that don't see the package for the first time 1981 if (update) { 1982 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1983 packageName, extras, 0 /*flags*/, 1984 null /*targetPackage*/, null /*finishedReceiver*/, 1985 updateUsers); 1986 if (origInstallerPackageName != null) { 1987 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 1988 extras, 0 /*flags*/, 1989 origInstallerPackageName, null /*finishedReceiver*/, updateUsers); 1990 } 1991 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1992 null /*package*/, null /*extras*/, 0 /*flags*/, 1993 packageName /*targetPackage*/, 1994 null /*finishedReceiver*/, updateUsers); 1995 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1996 // First-install and we did a restore, so we're responsible for the 1997 // first-launch broadcast. 1998 if (DEBUG_BACKUP) { 1999 Slog.i(TAG, "Post-restore of " + packageName 2000 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 2001 } 2002 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 2003 } 2004 2005 // Send broadcast package appeared if forward locked/external for all users 2006 // treat asec-hosted packages like removable media on upgrade 2007 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2008 if (DEBUG_INSTALL) { 2009 Slog.i(TAG, "upgrading pkg " + res.pkg 2010 + " is ASEC-hosted -> AVAILABLE"); 2011 } 2012 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2013 ArrayList<String> pkgList = new ArrayList<>(1); 2014 pkgList.add(packageName); 2015 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2016 } 2017 } 2018 2019 // Work that needs to happen on first install within each user 2020 if (firstUsers != null && firstUsers.length > 0) { 2021 synchronized (mPackages) { 2022 for (int userId : firstUsers) { 2023 // If this app is a browser and it's newly-installed for some 2024 // users, clear any default-browser state in those users. The 2025 // app's nature doesn't depend on the user, so we can just check 2026 // its browser nature in any user and generalize. 2027 if (packageIsBrowser(packageName, userId)) { 2028 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2029 } 2030 2031 // We may also need to apply pending (restored) runtime 2032 // permission grants within these users. 2033 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2034 } 2035 } 2036 } 2037 2038 // Log current value of "unknown sources" setting 2039 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2040 getUnknownSourcesSettings()); 2041 2042 // Remove the replaced package's older resources safely now 2043 // We delete after a gc for applications on sdcard. 2044 if (res.removedInfo != null && res.removedInfo.args != null) { 2045 Runtime.getRuntime().gc(); 2046 synchronized (mInstallLock) { 2047 res.removedInfo.args.doPostDeleteLI(true); 2048 } 2049 } else { 2050 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2051 // and not block here. 2052 VMRuntime.getRuntime().requestConcurrentGC(); 2053 } 2054 2055 // Notify DexManager that the package was installed for new users. 2056 // The updated users should already be indexed and the package code paths 2057 // should not change. 2058 // Don't notify the manager for ephemeral apps as they are not expected to 2059 // survive long enough to benefit of background optimizations. 2060 for (int userId : firstUsers) { 2061 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2062 // There's a race currently where some install events may interleave with an uninstall. 2063 // This can lead to package info being null (b/36642664). 2064 if (info != null) { 2065 mDexManager.notifyPackageInstalled(info, userId); 2066 } 2067 } 2068 } 2069 2070 // If someone is watching installs - notify them 2071 if (installObserver != null) { 2072 try { 2073 Bundle extras = extrasForInstallResult(res); 2074 installObserver.onPackageInstalled(res.name, res.returnCode, 2075 res.returnMsg, extras); 2076 } catch (RemoteException e) { 2077 Slog.i(TAG, "Observer no longer exists."); 2078 } 2079 } 2080 } 2081 2082 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 2083 PackageParser.Package pkg) { 2084 if (pkg.parentPackage == null) { 2085 return; 2086 } 2087 if (pkg.requestedPermissions == null) { 2088 return; 2089 } 2090 final PackageSetting disabledSysParentPs = mSettings 2091 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 2092 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 2093 || !disabledSysParentPs.isPrivileged() 2094 || (disabledSysParentPs.childPackageNames != null 2095 && !disabledSysParentPs.childPackageNames.isEmpty())) { 2096 return; 2097 } 2098 final int[] allUserIds = sUserManager.getUserIds(); 2099 final int permCount = pkg.requestedPermissions.size(); 2100 for (int i = 0; i < permCount; i++) { 2101 String permission = pkg.requestedPermissions.get(i); 2102 BasePermission bp = mSettings.mPermissions.get(permission); 2103 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 2104 continue; 2105 } 2106 for (int userId : allUserIds) { 2107 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2108 permission, userId)) { 2109 grantRuntimePermission(pkg.packageName, permission, userId); 2110 } 2111 } 2112 } 2113 } 2114 2115 private StorageEventListener mStorageListener = new StorageEventListener() { 2116 @Override 2117 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2118 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2119 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2120 final String volumeUuid = vol.getFsUuid(); 2121 2122 // Clean up any users or apps that were removed or recreated 2123 // while this volume was missing 2124 sUserManager.reconcileUsers(volumeUuid); 2125 reconcileApps(volumeUuid); 2126 2127 // Clean up any install sessions that expired or were 2128 // cancelled while this volume was missing 2129 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2130 2131 loadPrivatePackages(vol); 2132 2133 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2134 unloadPrivatePackages(vol); 2135 } 2136 } 2137 2138 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2139 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2140 updateExternalMediaStatus(true, false); 2141 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2142 updateExternalMediaStatus(false, false); 2143 } 2144 } 2145 } 2146 2147 @Override 2148 public void onVolumeForgotten(String fsUuid) { 2149 if (TextUtils.isEmpty(fsUuid)) { 2150 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2151 return; 2152 } 2153 2154 // Remove any apps installed on the forgotten volume 2155 synchronized (mPackages) { 2156 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2157 for (PackageSetting ps : packages) { 2158 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2159 deletePackageVersioned(new VersionedPackage(ps.name, 2160 PackageManager.VERSION_CODE_HIGHEST), 2161 new LegacyPackageDeleteObserver(null).getBinder(), 2162 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2163 // Try very hard to release any references to this package 2164 // so we don't risk the system server being killed due to 2165 // open FDs 2166 AttributeCache.instance().removePackage(ps.name); 2167 } 2168 2169 mSettings.onVolumeForgotten(fsUuid); 2170 mSettings.writeLPr(); 2171 } 2172 } 2173 }; 2174 2175 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2176 String[] grantedPermissions) { 2177 for (int userId : userIds) { 2178 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2179 } 2180 } 2181 2182 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2183 String[] grantedPermissions) { 2184 PackageSetting ps = (PackageSetting) pkg.mExtras; 2185 if (ps == null) { 2186 return; 2187 } 2188 2189 PermissionsState permissionsState = ps.getPermissionsState(); 2190 2191 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2192 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2193 2194 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2195 >= Build.VERSION_CODES.M; 2196 2197 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2198 2199 for (String permission : pkg.requestedPermissions) { 2200 final BasePermission bp; 2201 synchronized (mPackages) { 2202 bp = mSettings.mPermissions.get(permission); 2203 } 2204 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2205 && (!instantApp || bp.isInstant()) 2206 && (supportsRuntimePermissions || !bp.isRuntimeOnly()) 2207 && (grantedPermissions == null 2208 || ArrayUtils.contains(grantedPermissions, permission))) { 2209 final int flags = permissionsState.getPermissionFlags(permission, userId); 2210 if (supportsRuntimePermissions) { 2211 // Installer cannot change immutable permissions. 2212 if ((flags & immutableFlags) == 0) { 2213 grantRuntimePermission(pkg.packageName, permission, userId); 2214 } 2215 } else if (mPermissionReviewRequired) { 2216 // In permission review mode we clear the review flag when we 2217 // are asked to install the app with all permissions granted. 2218 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2219 updatePermissionFlags(permission, pkg.packageName, 2220 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2221 } 2222 } 2223 } 2224 } 2225 } 2226 2227 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2228 Bundle extras = null; 2229 switch (res.returnCode) { 2230 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2231 extras = new Bundle(); 2232 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2233 res.origPermission); 2234 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2235 res.origPackage); 2236 break; 2237 } 2238 case PackageManager.INSTALL_SUCCEEDED: { 2239 extras = new Bundle(); 2240 extras.putBoolean(Intent.EXTRA_REPLACING, 2241 res.removedInfo != null && res.removedInfo.removedPackage != null); 2242 break; 2243 } 2244 } 2245 return extras; 2246 } 2247 2248 void scheduleWriteSettingsLocked() { 2249 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2250 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2251 } 2252 } 2253 2254 void scheduleWritePackageListLocked(int userId) { 2255 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2256 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2257 msg.arg1 = userId; 2258 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2259 } 2260 } 2261 2262 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2263 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2264 scheduleWritePackageRestrictionsLocked(userId); 2265 } 2266 2267 void scheduleWritePackageRestrictionsLocked(int userId) { 2268 final int[] userIds = (userId == UserHandle.USER_ALL) 2269 ? sUserManager.getUserIds() : new int[]{userId}; 2270 for (int nextUserId : userIds) { 2271 if (!sUserManager.exists(nextUserId)) return; 2272 mDirtyUsers.add(nextUserId); 2273 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2274 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2275 } 2276 } 2277 } 2278 2279 public static PackageManagerService main(Context context, Installer installer, 2280 boolean factoryTest, boolean onlyCore) { 2281 // Self-check for initial settings. 2282 PackageManagerServiceCompilerMapping.checkProperties(); 2283 2284 PackageManagerService m = new PackageManagerService(context, installer, 2285 factoryTest, onlyCore); 2286 m.enableSystemUserPackages(); 2287 ServiceManager.addService("package", m); 2288 return m; 2289 } 2290 2291 private void enableSystemUserPackages() { 2292 if (!UserManager.isSplitSystemUser()) { 2293 return; 2294 } 2295 // For system user, enable apps based on the following conditions: 2296 // - app is whitelisted or belong to one of these groups: 2297 // -- system app which has no launcher icons 2298 // -- system app which has INTERACT_ACROSS_USERS permission 2299 // -- system IME app 2300 // - app is not in the blacklist 2301 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2302 Set<String> enableApps = new ArraySet<>(); 2303 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2304 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2305 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2306 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2307 enableApps.addAll(wlApps); 2308 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2309 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2310 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2311 enableApps.removeAll(blApps); 2312 Log.i(TAG, "Applications installed for system user: " + enableApps); 2313 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2314 UserHandle.SYSTEM); 2315 final int allAppsSize = allAps.size(); 2316 synchronized (mPackages) { 2317 for (int i = 0; i < allAppsSize; i++) { 2318 String pName = allAps.get(i); 2319 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2320 // Should not happen, but we shouldn't be failing if it does 2321 if (pkgSetting == null) { 2322 continue; 2323 } 2324 boolean install = enableApps.contains(pName); 2325 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2326 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2327 + " for system user"); 2328 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2329 } 2330 } 2331 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2332 } 2333 } 2334 2335 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2336 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2337 Context.DISPLAY_SERVICE); 2338 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2339 } 2340 2341 /** 2342 * Requests that files preopted on a secondary system partition be copied to the data partition 2343 * if possible. Note that the actual copying of the files is accomplished by init for security 2344 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2345 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2346 */ 2347 private static void requestCopyPreoptedFiles() { 2348 final int WAIT_TIME_MS = 100; 2349 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2350 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2351 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2352 // We will wait for up to 100 seconds. 2353 final long timeStart = SystemClock.uptimeMillis(); 2354 final long timeEnd = timeStart + 100 * 1000; 2355 long timeNow = timeStart; 2356 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2357 try { 2358 Thread.sleep(WAIT_TIME_MS); 2359 } catch (InterruptedException e) { 2360 // Do nothing 2361 } 2362 timeNow = SystemClock.uptimeMillis(); 2363 if (timeNow > timeEnd) { 2364 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2365 Slog.wtf(TAG, "cppreopt did not finish!"); 2366 break; 2367 } 2368 } 2369 2370 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2371 } 2372 } 2373 2374 public PackageManagerService(Context context, Installer installer, 2375 boolean factoryTest, boolean onlyCore) { 2376 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2377 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2378 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2379 SystemClock.uptimeMillis()); 2380 2381 if (mSdkVersion <= 0) { 2382 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2383 } 2384 2385 mContext = context; 2386 2387 mPermissionReviewRequired = context.getResources().getBoolean( 2388 R.bool.config_permissionReviewRequired); 2389 2390 mFactoryTest = factoryTest; 2391 mOnlyCore = onlyCore; 2392 mMetrics = new DisplayMetrics(); 2393 mSettings = new Settings(mPackages); 2394 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2395 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2396 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2397 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2398 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2399 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2400 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2401 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2402 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2403 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2404 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2405 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2406 2407 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2408 if (separateProcesses != null && separateProcesses.length() > 0) { 2409 if ("*".equals(separateProcesses)) { 2410 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2411 mSeparateProcesses = null; 2412 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2413 } else { 2414 mDefParseFlags = 0; 2415 mSeparateProcesses = separateProcesses.split(","); 2416 Slog.w(TAG, "Running with debug.separate_processes: " 2417 + separateProcesses); 2418 } 2419 } else { 2420 mDefParseFlags = 0; 2421 mSeparateProcesses = null; 2422 } 2423 2424 mInstaller = installer; 2425 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2426 "*dexopt*"); 2427 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2428 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2429 2430 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2431 FgThread.get().getLooper()); 2432 2433 getDefaultDisplayMetrics(context, mMetrics); 2434 2435 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2436 SystemConfig systemConfig = SystemConfig.getInstance(); 2437 mGlobalGids = systemConfig.getGlobalGids(); 2438 mSystemPermissions = systemConfig.getSystemPermissions(); 2439 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2440 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2441 2442 mProtectedPackages = new ProtectedPackages(mContext); 2443 2444 synchronized (mInstallLock) { 2445 // writer 2446 synchronized (mPackages) { 2447 mHandlerThread = new ServiceThread(TAG, 2448 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2449 mHandlerThread.start(); 2450 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2451 mProcessLoggingHandler = new ProcessLoggingHandler(); 2452 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2453 2454 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2455 mInstantAppRegistry = new InstantAppRegistry(this); 2456 2457 File dataDir = Environment.getDataDirectory(); 2458 mAppInstallDir = new File(dataDir, "app"); 2459 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2460 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2461 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2462 sUserManager = new UserManagerService(context, this, 2463 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2464 2465 // Propagate permission configuration in to package manager. 2466 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2467 = systemConfig.getPermissions(); 2468 for (int i=0; i<permConfig.size(); i++) { 2469 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2470 BasePermission bp = mSettings.mPermissions.get(perm.name); 2471 if (bp == null) { 2472 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2473 mSettings.mPermissions.put(perm.name, bp); 2474 } 2475 if (perm.gids != null) { 2476 bp.setGids(perm.gids, perm.perUser); 2477 } 2478 } 2479 2480 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2481 final int builtInLibCount = libConfig.size(); 2482 for (int i = 0; i < builtInLibCount; i++) { 2483 String name = libConfig.keyAt(i); 2484 String path = libConfig.valueAt(i); 2485 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2486 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2487 } 2488 2489 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2490 2491 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2492 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2493 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2494 2495 // Clean up orphaned packages for which the code path doesn't exist 2496 // and they are an update to a system app - caused by bug/32321269 2497 final int packageSettingCount = mSettings.mPackages.size(); 2498 for (int i = packageSettingCount - 1; i >= 0; i--) { 2499 PackageSetting ps = mSettings.mPackages.valueAt(i); 2500 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2501 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2502 mSettings.mPackages.removeAt(i); 2503 mSettings.enableSystemPackageLPw(ps.name); 2504 } 2505 } 2506 2507 if (mFirstBoot) { 2508 requestCopyPreoptedFiles(); 2509 } 2510 2511 String customResolverActivity = Resources.getSystem().getString( 2512 R.string.config_customResolverActivity); 2513 if (TextUtils.isEmpty(customResolverActivity)) { 2514 customResolverActivity = null; 2515 } else { 2516 mCustomResolverComponentName = ComponentName.unflattenFromString( 2517 customResolverActivity); 2518 } 2519 2520 long startTime = SystemClock.uptimeMillis(); 2521 2522 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2523 startTime); 2524 2525 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2526 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2527 2528 if (bootClassPath == null) { 2529 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2530 } 2531 2532 if (systemServerClassPath == null) { 2533 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2534 } 2535 2536 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2537 2538 final VersionInfo ver = mSettings.getInternalVersion(); 2539 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2540 if (mIsUpgrade) { 2541 logCriticalInfo(Log.INFO, 2542 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2543 } 2544 2545 // when upgrading from pre-M, promote system app permissions from install to runtime 2546 mPromoteSystemApps = 2547 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2548 2549 // When upgrading from pre-N, we need to handle package extraction like first boot, 2550 // as there is no profiling data available. 2551 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2552 2553 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2554 2555 // save off the names of pre-existing system packages prior to scanning; we don't 2556 // want to automatically grant runtime permissions for new system apps 2557 if (mPromoteSystemApps) { 2558 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2559 while (pkgSettingIter.hasNext()) { 2560 PackageSetting ps = pkgSettingIter.next(); 2561 if (isSystemApp(ps)) { 2562 mExistingSystemPackages.add(ps.name); 2563 } 2564 } 2565 } 2566 2567 mCacheDir = preparePackageParserCache(mIsUpgrade); 2568 2569 // Set flag to monitor and not change apk file paths when 2570 // scanning install directories. 2571 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2572 2573 if (mIsUpgrade || mFirstBoot) { 2574 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2575 } 2576 2577 // Collect vendor overlay packages. (Do this before scanning any apps.) 2578 // For security and version matching reason, only consider 2579 // overlay packages if they reside in the right directory. 2580 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2581 | PackageParser.PARSE_IS_SYSTEM 2582 | PackageParser.PARSE_IS_SYSTEM_DIR 2583 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2584 2585 mParallelPackageParserCallback.findStaticOverlayPackages(); 2586 2587 // Find base frameworks (resource packages without code). 2588 scanDirTracedLI(frameworkDir, mDefParseFlags 2589 | PackageParser.PARSE_IS_SYSTEM 2590 | PackageParser.PARSE_IS_SYSTEM_DIR 2591 | PackageParser.PARSE_IS_PRIVILEGED, 2592 scanFlags | SCAN_NO_DEX, 0); 2593 2594 // Collected privileged system packages. 2595 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2596 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2597 | PackageParser.PARSE_IS_SYSTEM 2598 | PackageParser.PARSE_IS_SYSTEM_DIR 2599 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2600 2601 // Collect ordinary system packages. 2602 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2603 scanDirTracedLI(systemAppDir, mDefParseFlags 2604 | PackageParser.PARSE_IS_SYSTEM 2605 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2606 2607 // Collect all vendor packages. 2608 File vendorAppDir = new File("/vendor/app"); 2609 try { 2610 vendorAppDir = vendorAppDir.getCanonicalFile(); 2611 } catch (IOException e) { 2612 // failed to look up canonical path, continue with original one 2613 } 2614 scanDirTracedLI(vendorAppDir, mDefParseFlags 2615 | PackageParser.PARSE_IS_SYSTEM 2616 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2617 2618 // Collect all OEM packages. 2619 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2620 scanDirTracedLI(oemAppDir, mDefParseFlags 2621 | PackageParser.PARSE_IS_SYSTEM 2622 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2623 2624 // Prune any system packages that no longer exist. 2625 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2626 if (!mOnlyCore) { 2627 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2628 while (psit.hasNext()) { 2629 PackageSetting ps = psit.next(); 2630 2631 /* 2632 * If this is not a system app, it can't be a 2633 * disable system app. 2634 */ 2635 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2636 continue; 2637 } 2638 2639 /* 2640 * If the package is scanned, it's not erased. 2641 */ 2642 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2643 if (scannedPkg != null) { 2644 /* 2645 * If the system app is both scanned and in the 2646 * disabled packages list, then it must have been 2647 * added via OTA. Remove it from the currently 2648 * scanned package so the previously user-installed 2649 * application can be scanned. 2650 */ 2651 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2652 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2653 + ps.name + "; removing system app. Last known codePath=" 2654 + ps.codePathString + ", installStatus=" + ps.installStatus 2655 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2656 + scannedPkg.mVersionCode); 2657 removePackageLI(scannedPkg, true); 2658 mExpectingBetter.put(ps.name, ps.codePath); 2659 } 2660 2661 continue; 2662 } 2663 2664 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2665 psit.remove(); 2666 logCriticalInfo(Log.WARN, "System package " + ps.name 2667 + " no longer exists; it's data will be wiped"); 2668 // Actual deletion of code and data will be handled by later 2669 // reconciliation step 2670 } else { 2671 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2672 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2673 possiblyDeletedUpdatedSystemApps.add(ps.name); 2674 } 2675 } 2676 } 2677 } 2678 2679 //look for any incomplete package installations 2680 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2681 for (int i = 0; i < deletePkgsList.size(); i++) { 2682 // Actual deletion of code and data will be handled by later 2683 // reconciliation step 2684 final String packageName = deletePkgsList.get(i).name; 2685 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2686 synchronized (mPackages) { 2687 mSettings.removePackageLPw(packageName); 2688 } 2689 } 2690 2691 //delete tmp files 2692 deleteTempPackageFiles(); 2693 2694 // Remove any shared userIDs that have no associated packages 2695 mSettings.pruneSharedUsersLPw(); 2696 2697 if (!mOnlyCore) { 2698 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2699 SystemClock.uptimeMillis()); 2700 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2701 2702 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2703 | PackageParser.PARSE_FORWARD_LOCK, 2704 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2705 2706 /** 2707 * Remove disable package settings for any updated system 2708 * apps that were removed via an OTA. If they're not a 2709 * previously-updated app, remove them completely. 2710 * Otherwise, just revoke their system-level permissions. 2711 */ 2712 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2713 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2714 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2715 2716 String msg; 2717 if (deletedPkg == null) { 2718 msg = "Updated system package " + deletedAppName 2719 + " no longer exists; it's data will be wiped"; 2720 // Actual deletion of code and data will be handled by later 2721 // reconciliation step 2722 } else { 2723 msg = "Updated system app + " + deletedAppName 2724 + " no longer present; removing system privileges for " 2725 + deletedAppName; 2726 2727 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2728 2729 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2730 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2731 } 2732 logCriticalInfo(Log.WARN, msg); 2733 } 2734 2735 /** 2736 * Make sure all system apps that we expected to appear on 2737 * the userdata partition actually showed up. If they never 2738 * appeared, crawl back and revive the system version. 2739 */ 2740 for (int i = 0; i < mExpectingBetter.size(); i++) { 2741 final String packageName = mExpectingBetter.keyAt(i); 2742 if (!mPackages.containsKey(packageName)) { 2743 final File scanFile = mExpectingBetter.valueAt(i); 2744 2745 logCriticalInfo(Log.WARN, "Expected better " + packageName 2746 + " but never showed up; reverting to system"); 2747 2748 int reparseFlags = mDefParseFlags; 2749 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2750 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2751 | PackageParser.PARSE_IS_SYSTEM_DIR 2752 | PackageParser.PARSE_IS_PRIVILEGED; 2753 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2754 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2755 | PackageParser.PARSE_IS_SYSTEM_DIR; 2756 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2757 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2758 | PackageParser.PARSE_IS_SYSTEM_DIR; 2759 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2760 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2761 | PackageParser.PARSE_IS_SYSTEM_DIR; 2762 } else { 2763 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2764 continue; 2765 } 2766 2767 mSettings.enableSystemPackageLPw(packageName); 2768 2769 try { 2770 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2771 } catch (PackageManagerException e) { 2772 Slog.e(TAG, "Failed to parse original system package: " 2773 + e.getMessage()); 2774 } 2775 } 2776 } 2777 } 2778 mExpectingBetter.clear(); 2779 2780 // Resolve the storage manager. 2781 mStorageManagerPackage = getStorageManagerPackageName(); 2782 2783 // Resolve protected action filters. Only the setup wizard is allowed to 2784 // have a high priority filter for these actions. 2785 mSetupWizardPackage = getSetupWizardPackageName(); 2786 if (mProtectedFilters.size() > 0) { 2787 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2788 Slog.i(TAG, "No setup wizard;" 2789 + " All protected intents capped to priority 0"); 2790 } 2791 for (ActivityIntentInfo filter : mProtectedFilters) { 2792 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2793 if (DEBUG_FILTERS) { 2794 Slog.i(TAG, "Found setup wizard;" 2795 + " allow priority " + filter.getPriority() + ";" 2796 + " package: " + filter.activity.info.packageName 2797 + " activity: " + filter.activity.className 2798 + " priority: " + filter.getPriority()); 2799 } 2800 // skip setup wizard; allow it to keep the high priority filter 2801 continue; 2802 } 2803 if (DEBUG_FILTERS) { 2804 Slog.i(TAG, "Protected action; cap priority to 0;" 2805 + " package: " + filter.activity.info.packageName 2806 + " activity: " + filter.activity.className 2807 + " origPrio: " + filter.getPriority()); 2808 } 2809 filter.setPriority(0); 2810 } 2811 } 2812 mDeferProtectedFilters = false; 2813 mProtectedFilters.clear(); 2814 2815 // Now that we know all of the shared libraries, update all clients to have 2816 // the correct library paths. 2817 updateAllSharedLibrariesLPw(null); 2818 2819 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2820 // NOTE: We ignore potential failures here during a system scan (like 2821 // the rest of the commands above) because there's precious little we 2822 // can do about it. A settings error is reported, though. 2823 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2824 } 2825 2826 // Now that we know all the packages we are keeping, 2827 // read and update their last usage times. 2828 mPackageUsage.read(mPackages); 2829 mCompilerStats.read(); 2830 2831 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2832 SystemClock.uptimeMillis()); 2833 Slog.i(TAG, "Time to scan packages: " 2834 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2835 + " seconds"); 2836 2837 // If the platform SDK has changed since the last time we booted, 2838 // we need to re-grant app permission to catch any new ones that 2839 // appear. This is really a hack, and means that apps can in some 2840 // cases get permissions that the user didn't initially explicitly 2841 // allow... it would be nice to have some better way to handle 2842 // this situation. 2843 int updateFlags = UPDATE_PERMISSIONS_ALL; 2844 if (ver.sdkVersion != mSdkVersion) { 2845 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2846 + mSdkVersion + "; regranting permissions for internal storage"); 2847 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2848 } 2849 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2850 ver.sdkVersion = mSdkVersion; 2851 2852 // If this is the first boot or an update from pre-M, and it is a normal 2853 // boot, then we need to initialize the default preferred apps across 2854 // all defined users. 2855 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2856 for (UserInfo user : sUserManager.getUsers(true)) { 2857 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2858 applyFactoryDefaultBrowserLPw(user.id); 2859 primeDomainVerificationsLPw(user.id); 2860 } 2861 } 2862 2863 // Prepare storage for system user really early during boot, 2864 // since core system apps like SettingsProvider and SystemUI 2865 // can't wait for user to start 2866 final int storageFlags; 2867 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2868 storageFlags = StorageManager.FLAG_STORAGE_DE; 2869 } else { 2870 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2871 } 2872 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2873 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2874 true /* onlyCoreApps */); 2875 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2876 BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync", 2877 Trace.TRACE_TAG_PACKAGE_MANAGER); 2878 traceLog.traceBegin("AppDataFixup"); 2879 try { 2880 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2881 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2882 } catch (InstallerException e) { 2883 Slog.w(TAG, "Trouble fixing GIDs", e); 2884 } 2885 traceLog.traceEnd(); 2886 2887 traceLog.traceBegin("AppDataPrepare"); 2888 if (deferPackages == null || deferPackages.isEmpty()) { 2889 return; 2890 } 2891 int count = 0; 2892 for (String pkgName : deferPackages) { 2893 PackageParser.Package pkg = null; 2894 synchronized (mPackages) { 2895 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2896 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2897 pkg = ps.pkg; 2898 } 2899 } 2900 if (pkg != null) { 2901 synchronized (mInstallLock) { 2902 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2903 true /* maybeMigrateAppData */); 2904 } 2905 count++; 2906 } 2907 } 2908 traceLog.traceEnd(); 2909 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2910 }, "prepareAppData"); 2911 2912 // If this is first boot after an OTA, and a normal boot, then 2913 // we need to clear code cache directories. 2914 // Note that we do *not* clear the application profiles. These remain valid 2915 // across OTAs and are used to drive profile verification (post OTA) and 2916 // profile compilation (without waiting to collect a fresh set of profiles). 2917 if (mIsUpgrade && !onlyCore) { 2918 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2919 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2920 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2921 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2922 // No apps are running this early, so no need to freeze 2923 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2924 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2925 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2926 } 2927 } 2928 ver.fingerprint = Build.FINGERPRINT; 2929 } 2930 2931 checkDefaultBrowser(); 2932 2933 // clear only after permissions and other defaults have been updated 2934 mExistingSystemPackages.clear(); 2935 mPromoteSystemApps = false; 2936 2937 // All the changes are done during package scanning. 2938 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2939 2940 // can downgrade to reader 2941 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2942 mSettings.writeLPr(); 2943 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2944 2945 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2946 SystemClock.uptimeMillis()); 2947 2948 if (!mOnlyCore) { 2949 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2950 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2951 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2952 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2953 if (mIntentFilterVerifierComponent != null) { 2954 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2955 mIntentFilterVerifierComponent); 2956 } else { 2957 mIntentFilterVerifier = null; 2958 } 2959 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2960 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2961 SharedLibraryInfo.VERSION_UNDEFINED); 2962 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2963 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2964 SharedLibraryInfo.VERSION_UNDEFINED); 2965 } else { 2966 mRequiredVerifierPackage = null; 2967 mRequiredInstallerPackage = null; 2968 mRequiredUninstallerPackage = null; 2969 mIntentFilterVerifierComponent = null; 2970 mIntentFilterVerifier = null; 2971 mServicesSystemSharedLibraryPackageName = null; 2972 mSharedSystemSharedLibraryPackageName = null; 2973 } 2974 2975 mInstallerService = new PackageInstallerService(context, this); 2976 final Pair<ComponentName, String> instantAppResolverComponent = 2977 getInstantAppResolverLPr(); 2978 if (instantAppResolverComponent != null) { 2979 if (DEBUG_EPHEMERAL) { 2980 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 2981 } 2982 mInstantAppResolverConnection = new EphemeralResolverConnection( 2983 mContext, instantAppResolverComponent.first, 2984 instantAppResolverComponent.second); 2985 mInstantAppResolverSettingsComponent = 2986 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 2987 } else { 2988 mInstantAppResolverConnection = null; 2989 mInstantAppResolverSettingsComponent = null; 2990 } 2991 updateInstantAppInstallerLocked(null); 2992 2993 // Read and update the usage of dex files. 2994 // Do this at the end of PM init so that all the packages have their 2995 // data directory reconciled. 2996 // At this point we know the code paths of the packages, so we can validate 2997 // the disk file and build the internal cache. 2998 // The usage file is expected to be small so loading and verifying it 2999 // should take a fairly small time compare to the other activities (e.g. package 3000 // scanning). 3001 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3002 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3003 for (int userId : currentUserIds) { 3004 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3005 } 3006 mDexManager.load(userPackages); 3007 } // synchronized (mPackages) 3008 } // synchronized (mInstallLock) 3009 3010 // Now after opening every single application zip, make sure they 3011 // are all flushed. Not really needed, but keeps things nice and 3012 // tidy. 3013 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3014 Runtime.getRuntime().gc(); 3015 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3016 3017 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3018 FallbackCategoryProvider.loadFallbacks(); 3019 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3020 3021 // The initial scanning above does many calls into installd while 3022 // holding the mPackages lock, but we're mostly interested in yelling 3023 // once we have a booted system. 3024 mInstaller.setWarnIfHeld(mPackages); 3025 3026 // Expose private service for system components to use. 3027 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 3028 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3029 } 3030 3031 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3032 // we're only interested in updating the installer appliction when 1) it's not 3033 // already set or 2) the modified package is the installer 3034 if (mInstantAppInstallerActivity != null 3035 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3036 .equals(modifiedPackage)) { 3037 return; 3038 } 3039 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3040 } 3041 3042 private static File preparePackageParserCache(boolean isUpgrade) { 3043 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3044 return null; 3045 } 3046 3047 // Disable package parsing on eng builds to allow for faster incremental development. 3048 if ("eng".equals(Build.TYPE)) { 3049 return null; 3050 } 3051 3052 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3053 Slog.i(TAG, "Disabling package parser cache due to system property."); 3054 return null; 3055 } 3056 3057 // The base directory for the package parser cache lives under /data/system/. 3058 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3059 "package_cache"); 3060 if (cacheBaseDir == null) { 3061 return null; 3062 } 3063 3064 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3065 // This also serves to "GC" unused entries when the package cache version changes (which 3066 // can only happen during upgrades). 3067 if (isUpgrade) { 3068 FileUtils.deleteContents(cacheBaseDir); 3069 } 3070 3071 3072 // Return the versioned package cache directory. This is something like 3073 // "/data/system/package_cache/1" 3074 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3075 3076 // The following is a workaround to aid development on non-numbered userdebug 3077 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3078 // the system partition is newer. 3079 // 3080 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3081 // that starts with "eng." to signify that this is an engineering build and not 3082 // destined for release. 3083 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3084 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3085 3086 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3087 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3088 // in general and should not be used for production changes. In this specific case, 3089 // we know that they will work. 3090 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3091 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3092 FileUtils.deleteContents(cacheBaseDir); 3093 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3094 } 3095 } 3096 3097 return cacheDir; 3098 } 3099 3100 @Override 3101 public boolean isFirstBoot() { 3102 // allow instant applications 3103 return mFirstBoot; 3104 } 3105 3106 @Override 3107 public boolean isOnlyCoreApps() { 3108 // allow instant applications 3109 return mOnlyCore; 3110 } 3111 3112 @Override 3113 public boolean isUpgrade() { 3114 // allow instant applications 3115 return mIsUpgrade; 3116 } 3117 3118 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3119 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3120 3121 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3122 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3123 UserHandle.USER_SYSTEM); 3124 if (matches.size() == 1) { 3125 return matches.get(0).getComponentInfo().packageName; 3126 } else if (matches.size() == 0) { 3127 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3128 return null; 3129 } 3130 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3131 } 3132 3133 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3134 synchronized (mPackages) { 3135 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3136 if (libraryEntry == null) { 3137 throw new IllegalStateException("Missing required shared library:" + name); 3138 } 3139 return libraryEntry.apk; 3140 } 3141 } 3142 3143 private @NonNull String getRequiredInstallerLPr() { 3144 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3145 intent.addCategory(Intent.CATEGORY_DEFAULT); 3146 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3147 3148 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3149 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3150 UserHandle.USER_SYSTEM); 3151 if (matches.size() == 1) { 3152 ResolveInfo resolveInfo = matches.get(0); 3153 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3154 throw new RuntimeException("The installer must be a privileged app"); 3155 } 3156 return matches.get(0).getComponentInfo().packageName; 3157 } else { 3158 throw new RuntimeException("There must be exactly one installer; found " + matches); 3159 } 3160 } 3161 3162 private @NonNull String getRequiredUninstallerLPr() { 3163 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3164 intent.addCategory(Intent.CATEGORY_DEFAULT); 3165 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3166 3167 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3168 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3169 UserHandle.USER_SYSTEM); 3170 if (resolveInfo == null || 3171 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3172 throw new RuntimeException("There must be exactly one uninstaller; found " 3173 + resolveInfo); 3174 } 3175 return resolveInfo.getComponentInfo().packageName; 3176 } 3177 3178 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3179 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3180 3181 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3182 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3183 UserHandle.USER_SYSTEM); 3184 ResolveInfo best = null; 3185 final int N = matches.size(); 3186 for (int i = 0; i < N; i++) { 3187 final ResolveInfo cur = matches.get(i); 3188 final String packageName = cur.getComponentInfo().packageName; 3189 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3190 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3191 continue; 3192 } 3193 3194 if (best == null || cur.priority > best.priority) { 3195 best = cur; 3196 } 3197 } 3198 3199 if (best != null) { 3200 return best.getComponentInfo().getComponentName(); 3201 } 3202 Slog.w(TAG, "Intent filter verifier not found"); 3203 return null; 3204 } 3205 3206 @Override 3207 public @Nullable ComponentName getInstantAppResolverComponent() { 3208 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3209 return null; 3210 } 3211 synchronized (mPackages) { 3212 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3213 if (instantAppResolver == null) { 3214 return null; 3215 } 3216 return instantAppResolver.first; 3217 } 3218 } 3219 3220 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3221 final String[] packageArray = 3222 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3223 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3224 if (DEBUG_EPHEMERAL) { 3225 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3226 } 3227 return null; 3228 } 3229 3230 final int callingUid = Binder.getCallingUid(); 3231 final int resolveFlags = 3232 MATCH_DIRECT_BOOT_AWARE 3233 | MATCH_DIRECT_BOOT_UNAWARE 3234 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3235 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3236 final Intent resolverIntent = new Intent(actionName); 3237 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3238 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3239 // temporarily look for the old action 3240 if (resolvers.size() == 0) { 3241 if (DEBUG_EPHEMERAL) { 3242 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3243 } 3244 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3245 resolverIntent.setAction(actionName); 3246 resolvers = queryIntentServicesInternal(resolverIntent, null, 3247 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3248 } 3249 final int N = resolvers.size(); 3250 if (N == 0) { 3251 if (DEBUG_EPHEMERAL) { 3252 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3253 } 3254 return null; 3255 } 3256 3257 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3258 for (int i = 0; i < N; i++) { 3259 final ResolveInfo info = resolvers.get(i); 3260 3261 if (info.serviceInfo == null) { 3262 continue; 3263 } 3264 3265 final String packageName = info.serviceInfo.packageName; 3266 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3267 if (DEBUG_EPHEMERAL) { 3268 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3269 + " pkg: " + packageName + ", info:" + info); 3270 } 3271 continue; 3272 } 3273 3274 if (DEBUG_EPHEMERAL) { 3275 Slog.v(TAG, "Ephemeral resolver found;" 3276 + " pkg: " + packageName + ", info:" + info); 3277 } 3278 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3279 } 3280 if (DEBUG_EPHEMERAL) { 3281 Slog.v(TAG, "Ephemeral resolver NOT found"); 3282 } 3283 return null; 3284 } 3285 3286 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3287 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3288 intent.addCategory(Intent.CATEGORY_DEFAULT); 3289 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3290 3291 final int resolveFlags = 3292 MATCH_DIRECT_BOOT_AWARE 3293 | MATCH_DIRECT_BOOT_UNAWARE 3294 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3295 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3296 resolveFlags, UserHandle.USER_SYSTEM); 3297 // temporarily look for the old action 3298 if (matches.isEmpty()) { 3299 if (DEBUG_EPHEMERAL) { 3300 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3301 } 3302 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3303 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3304 resolveFlags, UserHandle.USER_SYSTEM); 3305 } 3306 Iterator<ResolveInfo> iter = matches.iterator(); 3307 while (iter.hasNext()) { 3308 final ResolveInfo rInfo = iter.next(); 3309 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3310 if (ps != null) { 3311 final PermissionsState permissionsState = ps.getPermissionsState(); 3312 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3313 continue; 3314 } 3315 } 3316 iter.remove(); 3317 } 3318 if (matches.size() == 0) { 3319 return null; 3320 } else if (matches.size() == 1) { 3321 return (ActivityInfo) matches.get(0).getComponentInfo(); 3322 } else { 3323 throw new RuntimeException( 3324 "There must be at most one ephemeral installer; found " + matches); 3325 } 3326 } 3327 3328 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3329 @NonNull ComponentName resolver) { 3330 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3331 .addCategory(Intent.CATEGORY_DEFAULT) 3332 .setPackage(resolver.getPackageName()); 3333 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3334 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3335 UserHandle.USER_SYSTEM); 3336 // temporarily look for the old action 3337 if (matches.isEmpty()) { 3338 if (DEBUG_EPHEMERAL) { 3339 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3340 } 3341 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3342 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3343 UserHandle.USER_SYSTEM); 3344 } 3345 if (matches.isEmpty()) { 3346 return null; 3347 } 3348 return matches.get(0).getComponentInfo().getComponentName(); 3349 } 3350 3351 private void primeDomainVerificationsLPw(int userId) { 3352 if (DEBUG_DOMAIN_VERIFICATION) { 3353 Slog.d(TAG, "Priming domain verifications in user " + userId); 3354 } 3355 3356 SystemConfig systemConfig = SystemConfig.getInstance(); 3357 ArraySet<String> packages = systemConfig.getLinkedApps(); 3358 3359 for (String packageName : packages) { 3360 PackageParser.Package pkg = mPackages.get(packageName); 3361 if (pkg != null) { 3362 if (!pkg.isSystemApp()) { 3363 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3364 continue; 3365 } 3366 3367 ArraySet<String> domains = null; 3368 for (PackageParser.Activity a : pkg.activities) { 3369 for (ActivityIntentInfo filter : a.intents) { 3370 if (hasValidDomains(filter)) { 3371 if (domains == null) { 3372 domains = new ArraySet<String>(); 3373 } 3374 domains.addAll(filter.getHostsList()); 3375 } 3376 } 3377 } 3378 3379 if (domains != null && domains.size() > 0) { 3380 if (DEBUG_DOMAIN_VERIFICATION) { 3381 Slog.v(TAG, " + " + packageName); 3382 } 3383 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3384 // state w.r.t. the formal app-linkage "no verification attempted" state; 3385 // and then 'always' in the per-user state actually used for intent resolution. 3386 final IntentFilterVerificationInfo ivi; 3387 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3388 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3389 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3390 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3391 } else { 3392 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3393 + "' does not handle web links"); 3394 } 3395 } else { 3396 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3397 } 3398 } 3399 3400 scheduleWritePackageRestrictionsLocked(userId); 3401 scheduleWriteSettingsLocked(); 3402 } 3403 3404 private void applyFactoryDefaultBrowserLPw(int userId) { 3405 // The default browser app's package name is stored in a string resource, 3406 // with a product-specific overlay used for vendor customization. 3407 String browserPkg = mContext.getResources().getString( 3408 com.android.internal.R.string.default_browser); 3409 if (!TextUtils.isEmpty(browserPkg)) { 3410 // non-empty string => required to be a known package 3411 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3412 if (ps == null) { 3413 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3414 browserPkg = null; 3415 } else { 3416 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3417 } 3418 } 3419 3420 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3421 // default. If there's more than one, just leave everything alone. 3422 if (browserPkg == null) { 3423 calculateDefaultBrowserLPw(userId); 3424 } 3425 } 3426 3427 private void calculateDefaultBrowserLPw(int userId) { 3428 List<String> allBrowsers = resolveAllBrowserApps(userId); 3429 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3430 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3431 } 3432 3433 private List<String> resolveAllBrowserApps(int userId) { 3434 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3435 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3436 PackageManager.MATCH_ALL, userId); 3437 3438 final int count = list.size(); 3439 List<String> result = new ArrayList<String>(count); 3440 for (int i=0; i<count; i++) { 3441 ResolveInfo info = list.get(i); 3442 if (info.activityInfo == null 3443 || !info.handleAllWebDataURI 3444 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3445 || result.contains(info.activityInfo.packageName)) { 3446 continue; 3447 } 3448 result.add(info.activityInfo.packageName); 3449 } 3450 3451 return result; 3452 } 3453 3454 private boolean packageIsBrowser(String packageName, int userId) { 3455 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3456 PackageManager.MATCH_ALL, userId); 3457 final int N = list.size(); 3458 for (int i = 0; i < N; i++) { 3459 ResolveInfo info = list.get(i); 3460 if (packageName.equals(info.activityInfo.packageName)) { 3461 return true; 3462 } 3463 } 3464 return false; 3465 } 3466 3467 private void checkDefaultBrowser() { 3468 final int myUserId = UserHandle.myUserId(); 3469 final String packageName = getDefaultBrowserPackageName(myUserId); 3470 if (packageName != null) { 3471 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3472 if (info == null) { 3473 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3474 synchronized (mPackages) { 3475 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3476 } 3477 } 3478 } 3479 } 3480 3481 @Override 3482 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3483 throws RemoteException { 3484 try { 3485 return super.onTransact(code, data, reply, flags); 3486 } catch (RuntimeException e) { 3487 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3488 Slog.wtf(TAG, "Package Manager Crash", e); 3489 } 3490 throw e; 3491 } 3492 } 3493 3494 static int[] appendInts(int[] cur, int[] add) { 3495 if (add == null) return cur; 3496 if (cur == null) return add; 3497 final int N = add.length; 3498 for (int i=0; i<N; i++) { 3499 cur = appendInt(cur, add[i]); 3500 } 3501 return cur; 3502 } 3503 3504 /** 3505 * Returns whether or not a full application can see an instant application. 3506 * <p> 3507 * Currently, there are three cases in which this can occur: 3508 * <ol> 3509 * <li>The calling application is a "special" process. The special 3510 * processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID} 3511 * and {@code 0}</li> 3512 * <li>The calling application has the permission 3513 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li> 3514 * <li>The calling application is the default launcher on the 3515 * system partition.</li> 3516 * </ol> 3517 */ 3518 private boolean canViewInstantApps(int callingUid, int userId) { 3519 if (callingUid == Process.SYSTEM_UID 3520 || callingUid == Process.SHELL_UID 3521 || callingUid == Process.ROOT_UID) { 3522 return true; 3523 } 3524 if (mContext.checkCallingOrSelfPermission( 3525 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3526 return true; 3527 } 3528 if (mContext.checkCallingOrSelfPermission( 3529 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3530 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3531 if (homeComponent != null 3532 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3533 return true; 3534 } 3535 } 3536 return false; 3537 } 3538 3539 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3540 if (!sUserManager.exists(userId)) return null; 3541 if (ps == null) { 3542 return null; 3543 } 3544 PackageParser.Package p = ps.pkg; 3545 if (p == null) { 3546 return null; 3547 } 3548 final int callingUid = Binder.getCallingUid(); 3549 // Filter out ephemeral app metadata: 3550 // * The system/shell/root can see metadata for any app 3551 // * An installed app can see metadata for 1) other installed apps 3552 // and 2) ephemeral apps that have explicitly interacted with it 3553 // * Ephemeral apps can only see their own data and exposed installed apps 3554 // * Holding a signature permission allows seeing instant apps 3555 if (filterAppAccessLPr(ps, callingUid, userId)) { 3556 return null; 3557 } 3558 3559 final PermissionsState permissionsState = ps.getPermissionsState(); 3560 3561 // Compute GIDs only if requested 3562 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3563 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3564 // Compute granted permissions only if package has requested permissions 3565 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3566 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3567 final PackageUserState state = ps.readUserState(userId); 3568 3569 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3570 && ps.isSystem()) { 3571 flags |= MATCH_ANY_USER; 3572 } 3573 3574 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3575 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3576 3577 if (packageInfo == null) { 3578 return null; 3579 } 3580 3581 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3582 resolveExternalPackageNameLPr(p); 3583 3584 return packageInfo; 3585 } 3586 3587 @Override 3588 public void checkPackageStartable(String packageName, int userId) { 3589 final int callingUid = Binder.getCallingUid(); 3590 if (getInstantAppPackageName(callingUid) != null) { 3591 throw new SecurityException("Instant applications don't have access to this method"); 3592 } 3593 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3594 synchronized (mPackages) { 3595 final PackageSetting ps = mSettings.mPackages.get(packageName); 3596 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3597 throw new SecurityException("Package " + packageName + " was not found!"); 3598 } 3599 3600 if (!ps.getInstalled(userId)) { 3601 throw new SecurityException( 3602 "Package " + packageName + " was not installed for user " + userId + "!"); 3603 } 3604 3605 if (mSafeMode && !ps.isSystem()) { 3606 throw new SecurityException("Package " + packageName + " not a system app!"); 3607 } 3608 3609 if (mFrozenPackages.contains(packageName)) { 3610 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3611 } 3612 3613 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3614 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3615 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3616 } 3617 } 3618 } 3619 3620 @Override 3621 public boolean isPackageAvailable(String packageName, int userId) { 3622 if (!sUserManager.exists(userId)) return false; 3623 final int callingUid = Binder.getCallingUid(); 3624 enforceCrossUserPermission(callingUid, userId, 3625 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3626 synchronized (mPackages) { 3627 PackageParser.Package p = mPackages.get(packageName); 3628 if (p != null) { 3629 final PackageSetting ps = (PackageSetting) p.mExtras; 3630 if (filterAppAccessLPr(ps, callingUid, userId)) { 3631 return false; 3632 } 3633 if (ps != null) { 3634 final PackageUserState state = ps.readUserState(userId); 3635 if (state != null) { 3636 return PackageParser.isAvailable(state); 3637 } 3638 } 3639 } 3640 } 3641 return false; 3642 } 3643 3644 @Override 3645 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3646 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3647 flags, Binder.getCallingUid(), userId); 3648 } 3649 3650 @Override 3651 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3652 int flags, int userId) { 3653 return getPackageInfoInternal(versionedPackage.getPackageName(), 3654 versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId); 3655 } 3656 3657 /** 3658 * Important: The provided filterCallingUid is used exclusively to filter out packages 3659 * that can be seen based on user state. It's typically the original caller uid prior 3660 * to clearing. Because it can only be provided by trusted code, it's value can be 3661 * trusted and will be used as-is; unlike userId which will be validated by this method. 3662 */ 3663 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3664 int flags, int filterCallingUid, int userId) { 3665 if (!sUserManager.exists(userId)) return null; 3666 flags = updateFlagsForPackage(flags, userId, packageName); 3667 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3668 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3669 3670 // reader 3671 synchronized (mPackages) { 3672 // Normalize package name to handle renamed packages and static libs 3673 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3674 3675 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3676 if (matchFactoryOnly) { 3677 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3678 if (ps != null) { 3679 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3680 return null; 3681 } 3682 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3683 return null; 3684 } 3685 return generatePackageInfo(ps, flags, userId); 3686 } 3687 } 3688 3689 PackageParser.Package p = mPackages.get(packageName); 3690 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3691 return null; 3692 } 3693 if (DEBUG_PACKAGE_INFO) 3694 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3695 if (p != null) { 3696 final PackageSetting ps = (PackageSetting) p.mExtras; 3697 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3698 return null; 3699 } 3700 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 3701 return null; 3702 } 3703 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3704 } 3705 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3706 final PackageSetting ps = mSettings.mPackages.get(packageName); 3707 if (ps == null) return null; 3708 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3709 return null; 3710 } 3711 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3712 return null; 3713 } 3714 return generatePackageInfo(ps, flags, userId); 3715 } 3716 } 3717 return null; 3718 } 3719 3720 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 3721 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 3722 return true; 3723 } 3724 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 3725 return true; 3726 } 3727 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 3728 return true; 3729 } 3730 return false; 3731 } 3732 3733 private boolean isComponentVisibleToInstantApp( 3734 @Nullable ComponentName component, @ComponentType int type) { 3735 if (type == TYPE_ACTIVITY) { 3736 final PackageParser.Activity activity = mActivities.mActivities.get(component); 3737 return activity != null 3738 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3739 : false; 3740 } else if (type == TYPE_RECEIVER) { 3741 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 3742 return activity != null 3743 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3744 : false; 3745 } else if (type == TYPE_SERVICE) { 3746 final PackageParser.Service service = mServices.mServices.get(component); 3747 return service != null 3748 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3749 : false; 3750 } else if (type == TYPE_PROVIDER) { 3751 final PackageParser.Provider provider = mProviders.mProviders.get(component); 3752 return provider != null 3753 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3754 : false; 3755 } else if (type == TYPE_UNKNOWN) { 3756 return isComponentVisibleToInstantApp(component); 3757 } 3758 return false; 3759 } 3760 3761 /** 3762 * Returns whether or not access to the application should be filtered. 3763 * <p> 3764 * Access may be limited based upon whether the calling or target applications 3765 * are instant applications. 3766 * 3767 * @see #canAccessInstantApps(int) 3768 */ 3769 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 3770 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 3771 // if we're in an isolated process, get the real calling UID 3772 if (Process.isIsolated(callingUid)) { 3773 callingUid = mIsolatedOwners.get(callingUid); 3774 } 3775 final String instantAppPkgName = getInstantAppPackageName(callingUid); 3776 final boolean callerIsInstantApp = instantAppPkgName != null; 3777 if (ps == null) { 3778 if (callerIsInstantApp) { 3779 // pretend the application exists, but, needs to be filtered 3780 return true; 3781 } 3782 return false; 3783 } 3784 // if the target and caller are the same application, don't filter 3785 if (isCallerSameApp(ps.name, callingUid)) { 3786 return false; 3787 } 3788 if (callerIsInstantApp) { 3789 // request for a specific component; if it hasn't been explicitly exposed, filter 3790 if (component != null) { 3791 return !isComponentVisibleToInstantApp(component, componentType); 3792 } 3793 // request for application; if no components have been explicitly exposed, filter 3794 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps; 3795 } 3796 if (ps.getInstantApp(userId)) { 3797 // caller can see all components of all instant applications, don't filter 3798 if (canViewInstantApps(callingUid, userId)) { 3799 return false; 3800 } 3801 // request for a specific instant application component, filter 3802 if (component != null) { 3803 return true; 3804 } 3805 // request for an instant application; if the caller hasn't been granted access, filter 3806 return !mInstantAppRegistry.isInstantAccessGranted( 3807 userId, UserHandle.getAppId(callingUid), ps.appId); 3808 } 3809 return false; 3810 } 3811 3812 /** 3813 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 3814 */ 3815 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 3816 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 3817 } 3818 3819 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 3820 int flags) { 3821 // Callers can access only the libs they depend on, otherwise they need to explicitly 3822 // ask for the shared libraries given the caller is allowed to access all static libs. 3823 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 3824 // System/shell/root get to see all static libs 3825 final int appId = UserHandle.getAppId(uid); 3826 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3827 || appId == Process.ROOT_UID) { 3828 return false; 3829 } 3830 } 3831 3832 // No package means no static lib as it is always on internal storage 3833 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3834 return false; 3835 } 3836 3837 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3838 ps.pkg.staticSharedLibVersion); 3839 if (libEntry == null) { 3840 return false; 3841 } 3842 3843 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3844 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3845 if (uidPackageNames == null) { 3846 return true; 3847 } 3848 3849 for (String uidPackageName : uidPackageNames) { 3850 if (ps.name.equals(uidPackageName)) { 3851 return false; 3852 } 3853 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3854 if (uidPs != null) { 3855 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3856 libEntry.info.getName()); 3857 if (index < 0) { 3858 continue; 3859 } 3860 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3861 return false; 3862 } 3863 } 3864 } 3865 return true; 3866 } 3867 3868 @Override 3869 public String[] currentToCanonicalPackageNames(String[] names) { 3870 final int callingUid = Binder.getCallingUid(); 3871 if (getInstantAppPackageName(callingUid) != null) { 3872 return names; 3873 } 3874 final String[] out = new String[names.length]; 3875 // reader 3876 synchronized (mPackages) { 3877 final int callingUserId = UserHandle.getUserId(callingUid); 3878 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 3879 for (int i=names.length-1; i>=0; i--) { 3880 final PackageSetting ps = mSettings.mPackages.get(names[i]); 3881 boolean translateName = false; 3882 if (ps != null && ps.realName != null) { 3883 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 3884 translateName = !targetIsInstantApp 3885 || canViewInstantApps 3886 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 3887 UserHandle.getAppId(callingUid), ps.appId); 3888 } 3889 out[i] = translateName ? ps.realName : names[i]; 3890 } 3891 } 3892 return out; 3893 } 3894 3895 @Override 3896 public String[] canonicalToCurrentPackageNames(String[] names) { 3897 final int callingUid = Binder.getCallingUid(); 3898 if (getInstantAppPackageName(callingUid) != null) { 3899 return names; 3900 } 3901 final String[] out = new String[names.length]; 3902 // reader 3903 synchronized (mPackages) { 3904 final int callingUserId = UserHandle.getUserId(callingUid); 3905 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 3906 for (int i=names.length-1; i>=0; i--) { 3907 final String cur = mSettings.getRenamedPackageLPr(names[i]); 3908 boolean translateName = false; 3909 if (cur != null) { 3910 final PackageSetting ps = mSettings.mPackages.get(names[i]); 3911 final boolean targetIsInstantApp = 3912 ps != null && ps.getInstantApp(callingUserId); 3913 translateName = !targetIsInstantApp 3914 || canViewInstantApps 3915 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 3916 UserHandle.getAppId(callingUid), ps.appId); 3917 } 3918 out[i] = translateName ? cur : names[i]; 3919 } 3920 } 3921 return out; 3922 } 3923 3924 @Override 3925 public int getPackageUid(String packageName, int flags, int userId) { 3926 if (!sUserManager.exists(userId)) return -1; 3927 final int callingUid = Binder.getCallingUid(); 3928 flags = updateFlagsForPackage(flags, userId, packageName); 3929 enforceCrossUserPermission(callingUid, userId, 3930 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 3931 3932 // reader 3933 synchronized (mPackages) { 3934 final PackageParser.Package p = mPackages.get(packageName); 3935 if (p != null && p.isMatch(flags)) { 3936 PackageSetting ps = (PackageSetting) p.mExtras; 3937 if (filterAppAccessLPr(ps, callingUid, userId)) { 3938 return -1; 3939 } 3940 return UserHandle.getUid(userId, p.applicationInfo.uid); 3941 } 3942 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3943 final PackageSetting ps = mSettings.mPackages.get(packageName); 3944 if (ps != null && ps.isMatch(flags) 3945 && !filterAppAccessLPr(ps, callingUid, userId)) { 3946 return UserHandle.getUid(userId, ps.appId); 3947 } 3948 } 3949 } 3950 3951 return -1; 3952 } 3953 3954 @Override 3955 public int[] getPackageGids(String packageName, int flags, int userId) { 3956 if (!sUserManager.exists(userId)) return null; 3957 final int callingUid = Binder.getCallingUid(); 3958 flags = updateFlagsForPackage(flags, userId, packageName); 3959 enforceCrossUserPermission(callingUid, userId, 3960 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 3961 3962 // reader 3963 synchronized (mPackages) { 3964 final PackageParser.Package p = mPackages.get(packageName); 3965 if (p != null && p.isMatch(flags)) { 3966 PackageSetting ps = (PackageSetting) p.mExtras; 3967 if (filterAppAccessLPr(ps, callingUid, userId)) { 3968 return null; 3969 } 3970 // TODO: Shouldn't this be checking for package installed state for userId and 3971 // return null? 3972 return ps.getPermissionsState().computeGids(userId); 3973 } 3974 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3975 final PackageSetting ps = mSettings.mPackages.get(packageName); 3976 if (ps != null && ps.isMatch(flags) 3977 && !filterAppAccessLPr(ps, callingUid, userId)) { 3978 return ps.getPermissionsState().computeGids(userId); 3979 } 3980 } 3981 } 3982 3983 return null; 3984 } 3985 3986 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3987 if (bp.perm != null) { 3988 return PackageParser.generatePermissionInfo(bp.perm, flags); 3989 } 3990 PermissionInfo pi = new PermissionInfo(); 3991 pi.name = bp.name; 3992 pi.packageName = bp.sourcePackage; 3993 pi.nonLocalizedLabel = bp.name; 3994 pi.protectionLevel = bp.protectionLevel; 3995 return pi; 3996 } 3997 3998 @Override 3999 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4000 final int callingUid = Binder.getCallingUid(); 4001 if (getInstantAppPackageName(callingUid) != null) { 4002 return null; 4003 } 4004 // reader 4005 synchronized (mPackages) { 4006 final BasePermission p = mSettings.mPermissions.get(name); 4007 if (p == null) { 4008 return null; 4009 } 4010 // If the caller is an app that targets pre 26 SDK drop protection flags. 4011 final PermissionInfo permissionInfo = generatePermissionInfo(p, flags); 4012 if (permissionInfo != null) { 4013 permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr( 4014 permissionInfo.protectionLevel, packageName, callingUid); 4015 } 4016 return permissionInfo; 4017 } 4018 } 4019 4020 private int adjustPermissionProtectionFlagsLPr(int protectionLevel, 4021 String packageName, int uid) { 4022 // Signature permission flags area always reported 4023 final int protectionLevelMasked = protectionLevel 4024 & (PermissionInfo.PROTECTION_NORMAL 4025 | PermissionInfo.PROTECTION_DANGEROUS 4026 | PermissionInfo.PROTECTION_SIGNATURE); 4027 if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) { 4028 return protectionLevel; 4029 } 4030 4031 // System sees all flags. 4032 final int appId = UserHandle.getAppId(uid); 4033 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID 4034 || appId == Process.SHELL_UID) { 4035 return protectionLevel; 4036 } 4037 4038 // Normalize package name to handle renamed packages and static libs 4039 packageName = resolveInternalPackageNameLPr(packageName, 4040 PackageManager.VERSION_CODE_HIGHEST); 4041 4042 // Apps that target O see flags for all protection levels. 4043 final PackageSetting ps = mSettings.mPackages.get(packageName); 4044 if (ps == null) { 4045 return protectionLevel; 4046 } 4047 if (ps.appId != appId) { 4048 return protectionLevel; 4049 } 4050 4051 final PackageParser.Package pkg = mPackages.get(packageName); 4052 if (pkg == null) { 4053 return protectionLevel; 4054 } 4055 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 4056 return protectionLevelMasked; 4057 } 4058 4059 return protectionLevel; 4060 } 4061 4062 @Override 4063 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 4064 int flags) { 4065 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4066 return null; 4067 } 4068 // reader 4069 synchronized (mPackages) { 4070 if (group != null && !mPermissionGroups.containsKey(group)) { 4071 // This is thrown as NameNotFoundException 4072 return null; 4073 } 4074 4075 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 4076 for (BasePermission p : mSettings.mPermissions.values()) { 4077 if (group == null) { 4078 if (p.perm == null || p.perm.info.group == null) { 4079 out.add(generatePermissionInfo(p, flags)); 4080 } 4081 } else { 4082 if (p.perm != null && group.equals(p.perm.info.group)) { 4083 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 4084 } 4085 } 4086 } 4087 return new ParceledListSlice<>(out); 4088 } 4089 } 4090 4091 @Override 4092 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 4093 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4094 return null; 4095 } 4096 // reader 4097 synchronized (mPackages) { 4098 return PackageParser.generatePermissionGroupInfo( 4099 mPermissionGroups.get(name), flags); 4100 } 4101 } 4102 4103 @Override 4104 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4105 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4106 return ParceledListSlice.emptyList(); 4107 } 4108 // reader 4109 synchronized (mPackages) { 4110 final int N = mPermissionGroups.size(); 4111 ArrayList<PermissionGroupInfo> out 4112 = new ArrayList<PermissionGroupInfo>(N); 4113 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 4114 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 4115 } 4116 return new ParceledListSlice<>(out); 4117 } 4118 } 4119 4120 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4121 int filterCallingUid, int userId) { 4122 if (!sUserManager.exists(userId)) return null; 4123 PackageSetting ps = mSettings.mPackages.get(packageName); 4124 if (ps != null) { 4125 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4126 return null; 4127 } 4128 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4129 return null; 4130 } 4131 if (ps.pkg == null) { 4132 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4133 if (pInfo != null) { 4134 return pInfo.applicationInfo; 4135 } 4136 return null; 4137 } 4138 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4139 ps.readUserState(userId), userId); 4140 if (ai != null) { 4141 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4142 } 4143 return ai; 4144 } 4145 return null; 4146 } 4147 4148 @Override 4149 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4150 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4151 } 4152 4153 /** 4154 * Important: The provided filterCallingUid is used exclusively to filter out applications 4155 * that can be seen based on user state. It's typically the original caller uid prior 4156 * to clearing. Because it can only be provided by trusted code, it's value can be 4157 * trusted and will be used as-is; unlike userId which will be validated by this method. 4158 */ 4159 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4160 int filterCallingUid, int userId) { 4161 if (!sUserManager.exists(userId)) return null; 4162 flags = updateFlagsForApplication(flags, userId, packageName); 4163 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4164 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4165 4166 // writer 4167 synchronized (mPackages) { 4168 // Normalize package name to handle renamed packages and static libs 4169 packageName = resolveInternalPackageNameLPr(packageName, 4170 PackageManager.VERSION_CODE_HIGHEST); 4171 4172 PackageParser.Package p = mPackages.get(packageName); 4173 if (DEBUG_PACKAGE_INFO) Log.v( 4174 TAG, "getApplicationInfo " + packageName 4175 + ": " + p); 4176 if (p != null) { 4177 PackageSetting ps = mSettings.mPackages.get(packageName); 4178 if (ps == null) return null; 4179 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4180 return null; 4181 } 4182 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4183 return null; 4184 } 4185 // Note: isEnabledLP() does not apply here - always return info 4186 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4187 p, flags, ps.readUserState(userId), userId); 4188 if (ai != null) { 4189 ai.packageName = resolveExternalPackageNameLPr(p); 4190 } 4191 return ai; 4192 } 4193 if ("android".equals(packageName)||"system".equals(packageName)) { 4194 return mAndroidApplication; 4195 } 4196 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4197 // Already generates the external package name 4198 return generateApplicationInfoFromSettingsLPw(packageName, 4199 flags, filterCallingUid, userId); 4200 } 4201 } 4202 return null; 4203 } 4204 4205 private String normalizePackageNameLPr(String packageName) { 4206 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4207 return normalizedPackageName != null ? normalizedPackageName : packageName; 4208 } 4209 4210 @Override 4211 public void deletePreloadsFileCache() { 4212 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4213 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4214 } 4215 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4216 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4217 FileUtils.deleteContents(dir); 4218 } 4219 4220 @Override 4221 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4222 final int storageFlags, final IPackageDataObserver observer) { 4223 mContext.enforceCallingOrSelfPermission( 4224 android.Manifest.permission.CLEAR_APP_CACHE, null); 4225 mHandler.post(() -> { 4226 boolean success = false; 4227 try { 4228 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4229 success = true; 4230 } catch (IOException e) { 4231 Slog.w(TAG, e); 4232 } 4233 if (observer != null) { 4234 try { 4235 observer.onRemoveCompleted(null, success); 4236 } catch (RemoteException e) { 4237 Slog.w(TAG, e); 4238 } 4239 } 4240 }); 4241 } 4242 4243 @Override 4244 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4245 final int storageFlags, final IntentSender pi) { 4246 mContext.enforceCallingOrSelfPermission( 4247 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4248 mHandler.post(() -> { 4249 boolean success = false; 4250 try { 4251 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4252 success = true; 4253 } catch (IOException e) { 4254 Slog.w(TAG, e); 4255 } 4256 if (pi != null) { 4257 try { 4258 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4259 } catch (SendIntentException e) { 4260 Slog.w(TAG, e); 4261 } 4262 } 4263 }); 4264 } 4265 4266 /** 4267 * Blocking call to clear various types of cached data across the system 4268 * until the requested bytes are available. 4269 */ 4270 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4271 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4272 final File file = storage.findPathForUuid(volumeUuid); 4273 if (file.getUsableSpace() >= bytes) return; 4274 4275 if (ENABLE_FREE_CACHE_V2) { 4276 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4277 volumeUuid); 4278 final boolean aggressive = (storageFlags 4279 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4280 final boolean defyReserved = (storageFlags 4281 & StorageManager.FLAG_ALLOCATE_DEFY_RESERVED) != 0; 4282 final long reservedBytes = (aggressive || defyReserved) ? 0 4283 : storage.getStorageCacheBytes(file); 4284 4285 // 1. Pre-flight to determine if we have any chance to succeed 4286 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4287 if (internalVolume && (aggressive || SystemProperties 4288 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4289 deletePreloadsFileCache(); 4290 if (file.getUsableSpace() >= bytes) return; 4291 } 4292 4293 // 3. Consider parsed APK data (aggressive only) 4294 if (internalVolume && aggressive) { 4295 FileUtils.deleteContents(mCacheDir); 4296 if (file.getUsableSpace() >= bytes) return; 4297 } 4298 4299 // 4. Consider cached app data (above quotas) 4300 try { 4301 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4302 Installer.FLAG_FREE_CACHE_V2); 4303 } catch (InstallerException ignored) { 4304 } 4305 if (file.getUsableSpace() >= bytes) return; 4306 4307 // 5. Consider shared libraries with refcount=0 and age>min cache period 4308 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4309 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4310 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4311 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4312 return; 4313 } 4314 4315 // 6. Consider dexopt output (aggressive only) 4316 // TODO: Implement 4317 4318 // 7. Consider installed instant apps unused longer than min cache period 4319 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4320 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4321 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4322 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4323 return; 4324 } 4325 4326 // 8. Consider cached app data (below quotas) 4327 try { 4328 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4329 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4330 } catch (InstallerException ignored) { 4331 } 4332 if (file.getUsableSpace() >= bytes) return; 4333 4334 // 9. Consider DropBox entries 4335 // TODO: Implement 4336 4337 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4338 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4339 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4340 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4341 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4342 return; 4343 } 4344 } else { 4345 try { 4346 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4347 } catch (InstallerException ignored) { 4348 } 4349 if (file.getUsableSpace() >= bytes) return; 4350 } 4351 4352 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4353 } 4354 4355 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4356 throws IOException { 4357 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4358 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4359 4360 List<VersionedPackage> packagesToDelete = null; 4361 final long now = System.currentTimeMillis(); 4362 4363 synchronized (mPackages) { 4364 final int[] allUsers = sUserManager.getUserIds(); 4365 final int libCount = mSharedLibraries.size(); 4366 for (int i = 0; i < libCount; i++) { 4367 final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4368 if (versionedLib == null) { 4369 continue; 4370 } 4371 final int versionCount = versionedLib.size(); 4372 for (int j = 0; j < versionCount; j++) { 4373 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4374 // Skip packages that are not static shared libs. 4375 if (!libInfo.isStatic()) { 4376 break; 4377 } 4378 // Important: We skip static shared libs used for some user since 4379 // in such a case we need to keep the APK on the device. The check for 4380 // a lib being used for any user is performed by the uninstall call. 4381 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4382 // Resolve the package name - we use synthetic package names internally 4383 final String internalPackageName = resolveInternalPackageNameLPr( 4384 declaringPackage.getPackageName(), declaringPackage.getVersionCode()); 4385 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4386 // Skip unused static shared libs cached less than the min period 4387 // to prevent pruning a lib needed by a subsequently installed package. 4388 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4389 continue; 4390 } 4391 if (packagesToDelete == null) { 4392 packagesToDelete = new ArrayList<>(); 4393 } 4394 packagesToDelete.add(new VersionedPackage(internalPackageName, 4395 declaringPackage.getVersionCode())); 4396 } 4397 } 4398 } 4399 4400 if (packagesToDelete != null) { 4401 final int packageCount = packagesToDelete.size(); 4402 for (int i = 0; i < packageCount; i++) { 4403 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4404 // Delete the package synchronously (will fail of the lib used for any user). 4405 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(), 4406 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4407 == PackageManager.DELETE_SUCCEEDED) { 4408 if (volume.getUsableSpace() >= neededSpace) { 4409 return true; 4410 } 4411 } 4412 } 4413 } 4414 4415 return false; 4416 } 4417 4418 /** 4419 * Update given flags based on encryption status of current user. 4420 */ 4421 private int updateFlags(int flags, int userId) { 4422 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4423 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4424 // Caller expressed an explicit opinion about what encryption 4425 // aware/unaware components they want to see, so fall through and 4426 // give them what they want 4427 } else { 4428 // Caller expressed no opinion, so match based on user state 4429 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4430 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4431 } else { 4432 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4433 } 4434 } 4435 return flags; 4436 } 4437 4438 private UserManagerInternal getUserManagerInternal() { 4439 if (mUserManagerInternal == null) { 4440 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4441 } 4442 return mUserManagerInternal; 4443 } 4444 4445 private DeviceIdleController.LocalService getDeviceIdleController() { 4446 if (mDeviceIdleController == null) { 4447 mDeviceIdleController = 4448 LocalServices.getService(DeviceIdleController.LocalService.class); 4449 } 4450 return mDeviceIdleController; 4451 } 4452 4453 /** 4454 * Update given flags when being used to request {@link PackageInfo}. 4455 */ 4456 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4457 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4458 boolean triaged = true; 4459 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4460 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4461 // Caller is asking for component details, so they'd better be 4462 // asking for specific encryption matching behavior, or be triaged 4463 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4464 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4465 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4466 triaged = false; 4467 } 4468 } 4469 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4470 | PackageManager.MATCH_SYSTEM_ONLY 4471 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4472 triaged = false; 4473 } 4474 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4475 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 4476 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4477 + Debug.getCallers(5)); 4478 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4479 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4480 // If the caller wants all packages and has a restricted profile associated with it, 4481 // then match all users. This is to make sure that launchers that need to access work 4482 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4483 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4484 flags |= PackageManager.MATCH_ANY_USER; 4485 } 4486 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4487 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4488 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4489 } 4490 return updateFlags(flags, userId); 4491 } 4492 4493 /** 4494 * Update given flags when being used to request {@link ApplicationInfo}. 4495 */ 4496 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4497 return updateFlagsForPackage(flags, userId, cookie); 4498 } 4499 4500 /** 4501 * Update given flags when being used to request {@link ComponentInfo}. 4502 */ 4503 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4504 if (cookie instanceof Intent) { 4505 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4506 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4507 } 4508 } 4509 4510 boolean triaged = true; 4511 // Caller is asking for component details, so they'd better be 4512 // asking for specific encryption matching behavior, or be triaged 4513 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4514 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4515 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4516 triaged = false; 4517 } 4518 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4519 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4520 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4521 } 4522 4523 return updateFlags(flags, userId); 4524 } 4525 4526 /** 4527 * Update given intent when being used to request {@link ResolveInfo}. 4528 */ 4529 private Intent updateIntentForResolve(Intent intent) { 4530 if (intent.getSelector() != null) { 4531 intent = intent.getSelector(); 4532 } 4533 if (DEBUG_PREFERRED) { 4534 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4535 } 4536 return intent; 4537 } 4538 4539 /** 4540 * Update given flags when being used to request {@link ResolveInfo}. 4541 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4542 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4543 * flag set. However, this flag is only honoured in three circumstances: 4544 * <ul> 4545 * <li>when called from a system process</li> 4546 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4547 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4548 * action and a {@code android.intent.category.BROWSABLE} category</li> 4549 * </ul> 4550 */ 4551 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4552 return updateFlagsForResolve(flags, userId, intent, callingUid, 4553 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4554 } 4555 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4556 boolean wantInstantApps) { 4557 return updateFlagsForResolve(flags, userId, intent, callingUid, 4558 wantInstantApps, false /*onlyExposedExplicitly*/); 4559 } 4560 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4561 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4562 // Safe mode means we shouldn't match any third-party components 4563 if (mSafeMode) { 4564 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4565 } 4566 if (getInstantAppPackageName(callingUid) != null) { 4567 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4568 if (onlyExposedExplicitly) { 4569 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4570 } 4571 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4572 flags |= PackageManager.MATCH_INSTANT; 4573 } else { 4574 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4575 final boolean allowMatchInstant = 4576 (wantInstantApps 4577 && Intent.ACTION_VIEW.equals(intent.getAction()) 4578 && hasWebURI(intent)) 4579 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4580 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4581 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4582 if (!allowMatchInstant) { 4583 flags &= ~PackageManager.MATCH_INSTANT; 4584 } 4585 } 4586 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4587 } 4588 4589 @Override 4590 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4591 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4592 } 4593 4594 /** 4595 * Important: The provided filterCallingUid is used exclusively to filter out activities 4596 * that can be seen based on user state. It's typically the original caller uid prior 4597 * to clearing. Because it can only be provided by trusted code, it's value can be 4598 * trusted and will be used as-is; unlike userId which will be validated by this method. 4599 */ 4600 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4601 int filterCallingUid, int userId) { 4602 if (!sUserManager.exists(userId)) return null; 4603 flags = updateFlagsForComponent(flags, userId, component); 4604 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4605 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4606 synchronized (mPackages) { 4607 PackageParser.Activity a = mActivities.mActivities.get(component); 4608 4609 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4610 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4611 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4612 if (ps == null) return null; 4613 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4614 return null; 4615 } 4616 return PackageParser.generateActivityInfo( 4617 a, flags, ps.readUserState(userId), userId); 4618 } 4619 if (mResolveComponentName.equals(component)) { 4620 return PackageParser.generateActivityInfo( 4621 mResolveActivity, flags, new PackageUserState(), userId); 4622 } 4623 } 4624 return null; 4625 } 4626 4627 @Override 4628 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4629 String resolvedType) { 4630 synchronized (mPackages) { 4631 if (component.equals(mResolveComponentName)) { 4632 // The resolver supports EVERYTHING! 4633 return true; 4634 } 4635 final int callingUid = Binder.getCallingUid(); 4636 final int callingUserId = UserHandle.getUserId(callingUid); 4637 PackageParser.Activity a = mActivities.mActivities.get(component); 4638 if (a == null) { 4639 return false; 4640 } 4641 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4642 if (ps == null) { 4643 return false; 4644 } 4645 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4646 return false; 4647 } 4648 for (int i=0; i<a.intents.size(); i++) { 4649 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4650 intent.getData(), intent.getCategories(), TAG) >= 0) { 4651 return true; 4652 } 4653 } 4654 return false; 4655 } 4656 } 4657 4658 @Override 4659 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4660 if (!sUserManager.exists(userId)) return null; 4661 final int callingUid = Binder.getCallingUid(); 4662 flags = updateFlagsForComponent(flags, userId, component); 4663 enforceCrossUserPermission(callingUid, userId, 4664 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4665 synchronized (mPackages) { 4666 PackageParser.Activity a = mReceivers.mActivities.get(component); 4667 if (DEBUG_PACKAGE_INFO) Log.v( 4668 TAG, "getReceiverInfo " + component + ": " + a); 4669 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4670 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4671 if (ps == null) return null; 4672 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4673 return null; 4674 } 4675 return PackageParser.generateActivityInfo( 4676 a, flags, ps.readUserState(userId), userId); 4677 } 4678 } 4679 return null; 4680 } 4681 4682 @Override 4683 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4684 int flags, int userId) { 4685 if (!sUserManager.exists(userId)) return null; 4686 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4687 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4688 return null; 4689 } 4690 4691 flags = updateFlagsForPackage(flags, userId, null); 4692 4693 final boolean canSeeStaticLibraries = 4694 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4695 == PERMISSION_GRANTED 4696 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4697 == PERMISSION_GRANTED 4698 || canRequestPackageInstallsInternal(packageName, 4699 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4700 false /* throwIfPermNotDeclared*/) 4701 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4702 == PERMISSION_GRANTED; 4703 4704 synchronized (mPackages) { 4705 List<SharedLibraryInfo> result = null; 4706 4707 final int libCount = mSharedLibraries.size(); 4708 for (int i = 0; i < libCount; i++) { 4709 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4710 if (versionedLib == null) { 4711 continue; 4712 } 4713 4714 final int versionCount = versionedLib.size(); 4715 for (int j = 0; j < versionCount; j++) { 4716 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4717 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4718 break; 4719 } 4720 final long identity = Binder.clearCallingIdentity(); 4721 try { 4722 PackageInfo packageInfo = getPackageInfoVersioned( 4723 libInfo.getDeclaringPackage(), flags 4724 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 4725 if (packageInfo == null) { 4726 continue; 4727 } 4728 } finally { 4729 Binder.restoreCallingIdentity(identity); 4730 } 4731 4732 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4733 libInfo.getVersion(), libInfo.getType(), 4734 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4735 flags, userId)); 4736 4737 if (result == null) { 4738 result = new ArrayList<>(); 4739 } 4740 result.add(resLibInfo); 4741 } 4742 } 4743 4744 return result != null ? new ParceledListSlice<>(result) : null; 4745 } 4746 } 4747 4748 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4749 SharedLibraryInfo libInfo, int flags, int userId) { 4750 List<VersionedPackage> versionedPackages = null; 4751 final int packageCount = mSettings.mPackages.size(); 4752 for (int i = 0; i < packageCount; i++) { 4753 PackageSetting ps = mSettings.mPackages.valueAt(i); 4754 4755 if (ps == null) { 4756 continue; 4757 } 4758 4759 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4760 continue; 4761 } 4762 4763 final String libName = libInfo.getName(); 4764 if (libInfo.isStatic()) { 4765 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4766 if (libIdx < 0) { 4767 continue; 4768 } 4769 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4770 continue; 4771 } 4772 if (versionedPackages == null) { 4773 versionedPackages = new ArrayList<>(); 4774 } 4775 // If the dependent is a static shared lib, use the public package name 4776 String dependentPackageName = ps.name; 4777 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4778 dependentPackageName = ps.pkg.manifestPackageName; 4779 } 4780 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4781 } else if (ps.pkg != null) { 4782 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4783 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4784 if (versionedPackages == null) { 4785 versionedPackages = new ArrayList<>(); 4786 } 4787 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4788 } 4789 } 4790 } 4791 4792 return versionedPackages; 4793 } 4794 4795 @Override 4796 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4797 if (!sUserManager.exists(userId)) return null; 4798 final int callingUid = Binder.getCallingUid(); 4799 flags = updateFlagsForComponent(flags, userId, component); 4800 enforceCrossUserPermission(callingUid, userId, 4801 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4802 synchronized (mPackages) { 4803 PackageParser.Service s = mServices.mServices.get(component); 4804 if (DEBUG_PACKAGE_INFO) Log.v( 4805 TAG, "getServiceInfo " + component + ": " + s); 4806 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4807 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4808 if (ps == null) return null; 4809 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 4810 return null; 4811 } 4812 return PackageParser.generateServiceInfo( 4813 s, flags, ps.readUserState(userId), userId); 4814 } 4815 } 4816 return null; 4817 } 4818 4819 @Override 4820 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4821 if (!sUserManager.exists(userId)) return null; 4822 final int callingUid = Binder.getCallingUid(); 4823 flags = updateFlagsForComponent(flags, userId, component); 4824 enforceCrossUserPermission(callingUid, userId, 4825 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4826 synchronized (mPackages) { 4827 PackageParser.Provider p = mProviders.mProviders.get(component); 4828 if (DEBUG_PACKAGE_INFO) Log.v( 4829 TAG, "getProviderInfo " + component + ": " + p); 4830 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4831 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4832 if (ps == null) return null; 4833 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 4834 return null; 4835 } 4836 return PackageParser.generateProviderInfo( 4837 p, flags, ps.readUserState(userId), userId); 4838 } 4839 } 4840 return null; 4841 } 4842 4843 @Override 4844 public String[] getSystemSharedLibraryNames() { 4845 // allow instant applications 4846 synchronized (mPackages) { 4847 Set<String> libs = null; 4848 final int libCount = mSharedLibraries.size(); 4849 for (int i = 0; i < libCount; i++) { 4850 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4851 if (versionedLib == null) { 4852 continue; 4853 } 4854 final int versionCount = versionedLib.size(); 4855 for (int j = 0; j < versionCount; j++) { 4856 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4857 if (!libEntry.info.isStatic()) { 4858 if (libs == null) { 4859 libs = new ArraySet<>(); 4860 } 4861 libs.add(libEntry.info.getName()); 4862 break; 4863 } 4864 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4865 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4866 UserHandle.getUserId(Binder.getCallingUid()), 4867 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 4868 if (libs == null) { 4869 libs = new ArraySet<>(); 4870 } 4871 libs.add(libEntry.info.getName()); 4872 break; 4873 } 4874 } 4875 } 4876 4877 if (libs != null) { 4878 String[] libsArray = new String[libs.size()]; 4879 libs.toArray(libsArray); 4880 return libsArray; 4881 } 4882 4883 return null; 4884 } 4885 } 4886 4887 @Override 4888 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4889 // allow instant applications 4890 synchronized (mPackages) { 4891 return mServicesSystemSharedLibraryPackageName; 4892 } 4893 } 4894 4895 @Override 4896 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4897 // allow instant applications 4898 synchronized (mPackages) { 4899 return mSharedSystemSharedLibraryPackageName; 4900 } 4901 } 4902 4903 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 4904 for (int i = userList.length - 1; i >= 0; --i) { 4905 final int userId = userList[i]; 4906 // don't add instant app to the list of updates 4907 if (pkgSetting.getInstantApp(userId)) { 4908 continue; 4909 } 4910 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4911 if (changedPackages == null) { 4912 changedPackages = new SparseArray<>(); 4913 mChangedPackages.put(userId, changedPackages); 4914 } 4915 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4916 if (sequenceNumbers == null) { 4917 sequenceNumbers = new HashMap<>(); 4918 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4919 } 4920 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 4921 if (sequenceNumber != null) { 4922 changedPackages.remove(sequenceNumber); 4923 } 4924 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 4925 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 4926 } 4927 mChangedPackagesSequenceNumber++; 4928 } 4929 4930 @Override 4931 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4932 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4933 return null; 4934 } 4935 synchronized (mPackages) { 4936 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4937 return null; 4938 } 4939 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4940 if (changedPackages == null) { 4941 return null; 4942 } 4943 final List<String> packageNames = 4944 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4945 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4946 final String packageName = changedPackages.get(i); 4947 if (packageName != null) { 4948 packageNames.add(packageName); 4949 } 4950 } 4951 return packageNames.isEmpty() 4952 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4953 } 4954 } 4955 4956 @Override 4957 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4958 // allow instant applications 4959 ArrayList<FeatureInfo> res; 4960 synchronized (mAvailableFeatures) { 4961 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4962 res.addAll(mAvailableFeatures.values()); 4963 } 4964 final FeatureInfo fi = new FeatureInfo(); 4965 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4966 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4967 res.add(fi); 4968 4969 return new ParceledListSlice<>(res); 4970 } 4971 4972 @Override 4973 public boolean hasSystemFeature(String name, int version) { 4974 // allow instant applications 4975 synchronized (mAvailableFeatures) { 4976 final FeatureInfo feat = mAvailableFeatures.get(name); 4977 if (feat == null) { 4978 return false; 4979 } else { 4980 return feat.version >= version; 4981 } 4982 } 4983 } 4984 4985 @Override 4986 public int checkPermission(String permName, String pkgName, int userId) { 4987 if (!sUserManager.exists(userId)) { 4988 return PackageManager.PERMISSION_DENIED; 4989 } 4990 final int callingUid = Binder.getCallingUid(); 4991 4992 synchronized (mPackages) { 4993 final PackageParser.Package p = mPackages.get(pkgName); 4994 if (p != null && p.mExtras != null) { 4995 final PackageSetting ps = (PackageSetting) p.mExtras; 4996 if (filterAppAccessLPr(ps, callingUid, userId)) { 4997 return PackageManager.PERMISSION_DENIED; 4998 } 4999 final boolean instantApp = ps.getInstantApp(userId); 5000 final PermissionsState permissionsState = ps.getPermissionsState(); 5001 if (permissionsState.hasPermission(permName, userId)) { 5002 if (instantApp) { 5003 BasePermission bp = mSettings.mPermissions.get(permName); 5004 if (bp != null && bp.isInstant()) { 5005 return PackageManager.PERMISSION_GRANTED; 5006 } 5007 } else { 5008 return PackageManager.PERMISSION_GRANTED; 5009 } 5010 } 5011 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 5012 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 5013 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 5014 return PackageManager.PERMISSION_GRANTED; 5015 } 5016 } 5017 } 5018 5019 return PackageManager.PERMISSION_DENIED; 5020 } 5021 5022 @Override 5023 public int checkUidPermission(String permName, int uid) { 5024 final int callingUid = Binder.getCallingUid(); 5025 final int callingUserId = UserHandle.getUserId(callingUid); 5026 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5027 final boolean isUidInstantApp = getInstantAppPackageName(uid) != null; 5028 final int userId = UserHandle.getUserId(uid); 5029 if (!sUserManager.exists(userId)) { 5030 return PackageManager.PERMISSION_DENIED; 5031 } 5032 5033 synchronized (mPackages) { 5034 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5035 if (obj != null) { 5036 if (obj instanceof SharedUserSetting) { 5037 if (isCallerInstantApp) { 5038 return PackageManager.PERMISSION_DENIED; 5039 } 5040 } else if (obj instanceof PackageSetting) { 5041 final PackageSetting ps = (PackageSetting) obj; 5042 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5043 return PackageManager.PERMISSION_DENIED; 5044 } 5045 } 5046 final SettingBase settingBase = (SettingBase) obj; 5047 final PermissionsState permissionsState = settingBase.getPermissionsState(); 5048 if (permissionsState.hasPermission(permName, userId)) { 5049 if (isUidInstantApp) { 5050 BasePermission bp = mSettings.mPermissions.get(permName); 5051 if (bp != null && bp.isInstant()) { 5052 return PackageManager.PERMISSION_GRANTED; 5053 } 5054 } else { 5055 return PackageManager.PERMISSION_GRANTED; 5056 } 5057 } 5058 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 5059 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 5060 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 5061 return PackageManager.PERMISSION_GRANTED; 5062 } 5063 } else { 5064 ArraySet<String> perms = mSystemPermissions.get(uid); 5065 if (perms != null) { 5066 if (perms.contains(permName)) { 5067 return PackageManager.PERMISSION_GRANTED; 5068 } 5069 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 5070 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 5071 return PackageManager.PERMISSION_GRANTED; 5072 } 5073 } 5074 } 5075 } 5076 5077 return PackageManager.PERMISSION_DENIED; 5078 } 5079 5080 @Override 5081 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5082 if (UserHandle.getCallingUserId() != userId) { 5083 mContext.enforceCallingPermission( 5084 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5085 "isPermissionRevokedByPolicy for user " + userId); 5086 } 5087 5088 if (checkPermission(permission, packageName, userId) 5089 == PackageManager.PERMISSION_GRANTED) { 5090 return false; 5091 } 5092 5093 final int callingUid = Binder.getCallingUid(); 5094 if (getInstantAppPackageName(callingUid) != null) { 5095 if (!isCallerSameApp(packageName, callingUid)) { 5096 return false; 5097 } 5098 } else { 5099 if (isInstantApp(packageName, userId)) { 5100 return false; 5101 } 5102 } 5103 5104 final long identity = Binder.clearCallingIdentity(); 5105 try { 5106 final int flags = getPermissionFlags(permission, packageName, userId); 5107 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5108 } finally { 5109 Binder.restoreCallingIdentity(identity); 5110 } 5111 } 5112 5113 @Override 5114 public String getPermissionControllerPackageName() { 5115 synchronized (mPackages) { 5116 return mRequiredInstallerPackage; 5117 } 5118 } 5119 5120 /** 5121 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 5122 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 5123 * @param checkShell whether to prevent shell from access if there's a debugging restriction 5124 * @param message the message to log on security exception 5125 */ 5126 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 5127 boolean checkShell, String message) { 5128 if (userId < 0) { 5129 throw new IllegalArgumentException("Invalid userId " + userId); 5130 } 5131 if (checkShell) { 5132 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 5133 } 5134 if (userId == UserHandle.getUserId(callingUid)) return; 5135 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5136 if (requireFullPermission) { 5137 mContext.enforceCallingOrSelfPermission( 5138 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 5139 } else { 5140 try { 5141 mContext.enforceCallingOrSelfPermission( 5142 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 5143 } catch (SecurityException se) { 5144 mContext.enforceCallingOrSelfPermission( 5145 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 5146 } 5147 } 5148 } 5149 } 5150 5151 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 5152 if (callingUid == Process.SHELL_UID) { 5153 if (userHandle >= 0 5154 && sUserManager.hasUserRestriction(restriction, userHandle)) { 5155 throw new SecurityException("Shell does not have permission to access user " 5156 + userHandle); 5157 } else if (userHandle < 0) { 5158 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 5159 + Debug.getCallers(3)); 5160 } 5161 } 5162 } 5163 5164 private BasePermission findPermissionTreeLP(String permName) { 5165 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 5166 if (permName.startsWith(bp.name) && 5167 permName.length() > bp.name.length() && 5168 permName.charAt(bp.name.length()) == '.') { 5169 return bp; 5170 } 5171 } 5172 return null; 5173 } 5174 5175 private BasePermission checkPermissionTreeLP(String permName) { 5176 if (permName != null) { 5177 BasePermission bp = findPermissionTreeLP(permName); 5178 if (bp != null) { 5179 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 5180 return bp; 5181 } 5182 throw new SecurityException("Calling uid " 5183 + Binder.getCallingUid() 5184 + " is not allowed to add to permission tree " 5185 + bp.name + " owned by uid " + bp.uid); 5186 } 5187 } 5188 throw new SecurityException("No permission tree found for " + permName); 5189 } 5190 5191 static boolean compareStrings(CharSequence s1, CharSequence s2) { 5192 if (s1 == null) { 5193 return s2 == null; 5194 } 5195 if (s2 == null) { 5196 return false; 5197 } 5198 if (s1.getClass() != s2.getClass()) { 5199 return false; 5200 } 5201 return s1.equals(s2); 5202 } 5203 5204 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 5205 if (pi1.icon != pi2.icon) return false; 5206 if (pi1.logo != pi2.logo) return false; 5207 if (pi1.protectionLevel != pi2.protectionLevel) return false; 5208 if (!compareStrings(pi1.name, pi2.name)) return false; 5209 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 5210 // We'll take care of setting this one. 5211 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 5212 // These are not currently stored in settings. 5213 //if (!compareStrings(pi1.group, pi2.group)) return false; 5214 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 5215 //if (pi1.labelRes != pi2.labelRes) return false; 5216 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 5217 return true; 5218 } 5219 5220 int permissionInfoFootprint(PermissionInfo info) { 5221 int size = info.name.length(); 5222 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 5223 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 5224 return size; 5225 } 5226 5227 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 5228 int size = 0; 5229 for (BasePermission perm : mSettings.mPermissions.values()) { 5230 if (perm.uid == tree.uid) { 5231 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 5232 } 5233 } 5234 return size; 5235 } 5236 5237 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 5238 // We calculate the max size of permissions defined by this uid and throw 5239 // if that plus the size of 'info' would exceed our stated maximum. 5240 if (tree.uid != Process.SYSTEM_UID) { 5241 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 5242 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 5243 throw new SecurityException("Permission tree size cap exceeded"); 5244 } 5245 } 5246 } 5247 5248 boolean addPermissionLocked(PermissionInfo info, boolean async) { 5249 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5250 throw new SecurityException("Instant apps can't add permissions"); 5251 } 5252 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 5253 throw new SecurityException("Label must be specified in permission"); 5254 } 5255 BasePermission tree = checkPermissionTreeLP(info.name); 5256 BasePermission bp = mSettings.mPermissions.get(info.name); 5257 boolean added = bp == null; 5258 boolean changed = true; 5259 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 5260 if (added) { 5261 enforcePermissionCapLocked(info, tree); 5262 bp = new BasePermission(info.name, tree.sourcePackage, 5263 BasePermission.TYPE_DYNAMIC); 5264 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 5265 throw new SecurityException( 5266 "Not allowed to modify non-dynamic permission " 5267 + info.name); 5268 } else { 5269 if (bp.protectionLevel == fixedLevel 5270 && bp.perm.owner.equals(tree.perm.owner) 5271 && bp.uid == tree.uid 5272 && comparePermissionInfos(bp.perm.info, info)) { 5273 changed = false; 5274 } 5275 } 5276 bp.protectionLevel = fixedLevel; 5277 info = new PermissionInfo(info); 5278 info.protectionLevel = fixedLevel; 5279 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 5280 bp.perm.info.packageName = tree.perm.info.packageName; 5281 bp.uid = tree.uid; 5282 if (added) { 5283 mSettings.mPermissions.put(info.name, bp); 5284 } 5285 if (changed) { 5286 if (!async) { 5287 mSettings.writeLPr(); 5288 } else { 5289 scheduleWriteSettingsLocked(); 5290 } 5291 } 5292 return added; 5293 } 5294 5295 @Override 5296 public boolean addPermission(PermissionInfo info) { 5297 synchronized (mPackages) { 5298 return addPermissionLocked(info, false); 5299 } 5300 } 5301 5302 @Override 5303 public boolean addPermissionAsync(PermissionInfo info) { 5304 synchronized (mPackages) { 5305 return addPermissionLocked(info, true); 5306 } 5307 } 5308 5309 @Override 5310 public void removePermission(String name) { 5311 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5312 throw new SecurityException("Instant applications don't have access to this method"); 5313 } 5314 synchronized (mPackages) { 5315 checkPermissionTreeLP(name); 5316 BasePermission bp = mSettings.mPermissions.get(name); 5317 if (bp != null) { 5318 if (bp.type != BasePermission.TYPE_DYNAMIC) { 5319 throw new SecurityException( 5320 "Not allowed to modify non-dynamic permission " 5321 + name); 5322 } 5323 mSettings.mPermissions.remove(name); 5324 mSettings.writeLPr(); 5325 } 5326 } 5327 } 5328 5329 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission( 5330 PackageParser.Package pkg, BasePermission bp) { 5331 int index = pkg.requestedPermissions.indexOf(bp.name); 5332 if (index == -1) { 5333 throw new SecurityException("Package " + pkg.packageName 5334 + " has not requested permission " + bp.name); 5335 } 5336 if (!bp.isRuntime() && !bp.isDevelopment()) { 5337 throw new SecurityException("Permission " + bp.name 5338 + " is not a changeable permission type"); 5339 } 5340 } 5341 5342 @Override 5343 public void grantRuntimePermission(String packageName, String name, final int userId) { 5344 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 5345 } 5346 5347 private void grantRuntimePermission(String packageName, String name, final int userId, 5348 boolean overridePolicy) { 5349 if (!sUserManager.exists(userId)) { 5350 Log.e(TAG, "No such user:" + userId); 5351 return; 5352 } 5353 final int callingUid = Binder.getCallingUid(); 5354 5355 mContext.enforceCallingOrSelfPermission( 5356 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 5357 "grantRuntimePermission"); 5358 5359 enforceCrossUserPermission(callingUid, userId, 5360 true /* requireFullPermission */, true /* checkShell */, 5361 "grantRuntimePermission"); 5362 5363 final int uid; 5364 final PackageSetting ps; 5365 5366 synchronized (mPackages) { 5367 final PackageParser.Package pkg = mPackages.get(packageName); 5368 if (pkg == null) { 5369 throw new IllegalArgumentException("Unknown package: " + packageName); 5370 } 5371 final BasePermission bp = mSettings.mPermissions.get(name); 5372 if (bp == null) { 5373 throw new IllegalArgumentException("Unknown permission: " + name); 5374 } 5375 ps = (PackageSetting) pkg.mExtras; 5376 if (ps == null 5377 || filterAppAccessLPr(ps, callingUid, userId)) { 5378 throw new IllegalArgumentException("Unknown package: " + packageName); 5379 } 5380 5381 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 5382 5383 // If a permission review is required for legacy apps we represent 5384 // their permissions as always granted runtime ones since we need 5385 // to keep the review required permission flag per user while an 5386 // install permission's state is shared across all users. 5387 if (mPermissionReviewRequired 5388 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 5389 && bp.isRuntime()) { 5390 return; 5391 } 5392 5393 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 5394 5395 final PermissionsState permissionsState = ps.getPermissionsState(); 5396 5397 final int flags = permissionsState.getPermissionFlags(name, userId); 5398 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 5399 throw new SecurityException("Cannot grant system fixed permission " 5400 + name + " for package " + packageName); 5401 } 5402 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 5403 throw new SecurityException("Cannot grant policy fixed permission " 5404 + name + " for package " + packageName); 5405 } 5406 5407 if (bp.isDevelopment()) { 5408 // Development permissions must be handled specially, since they are not 5409 // normal runtime permissions. For now they apply to all users. 5410 if (permissionsState.grantInstallPermission(bp) != 5411 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5412 scheduleWriteSettingsLocked(); 5413 } 5414 return; 5415 } 5416 5417 if (ps.getInstantApp(userId) && !bp.isInstant()) { 5418 throw new SecurityException("Cannot grant non-ephemeral permission" 5419 + name + " for package " + packageName); 5420 } 5421 5422 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 5423 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 5424 return; 5425 } 5426 5427 final int result = permissionsState.grantRuntimePermission(bp, userId); 5428 switch (result) { 5429 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 5430 return; 5431 } 5432 5433 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 5434 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 5435 mHandler.post(new Runnable() { 5436 @Override 5437 public void run() { 5438 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 5439 } 5440 }); 5441 } 5442 break; 5443 } 5444 5445 if (bp.isRuntime()) { 5446 logPermissionGranted(mContext, name, packageName); 5447 } 5448 5449 mOnPermissionChangeListeners.onPermissionsChanged(uid); 5450 5451 // Not critical if that is lost - app has to request again. 5452 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5453 } 5454 5455 // Only need to do this if user is initialized. Otherwise it's a new user 5456 // and there are no processes running as the user yet and there's no need 5457 // to make an expensive call to remount processes for the changed permissions. 5458 if (READ_EXTERNAL_STORAGE.equals(name) 5459 || WRITE_EXTERNAL_STORAGE.equals(name)) { 5460 final long token = Binder.clearCallingIdentity(); 5461 try { 5462 if (sUserManager.isInitialized(userId)) { 5463 StorageManagerInternal storageManagerInternal = LocalServices.getService( 5464 StorageManagerInternal.class); 5465 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 5466 } 5467 } finally { 5468 Binder.restoreCallingIdentity(token); 5469 } 5470 } 5471 } 5472 5473 @Override 5474 public void revokeRuntimePermission(String packageName, String name, int userId) { 5475 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 5476 } 5477 5478 private void revokeRuntimePermission(String packageName, String name, int userId, 5479 boolean overridePolicy) { 5480 if (!sUserManager.exists(userId)) { 5481 Log.e(TAG, "No such user:" + userId); 5482 return; 5483 } 5484 5485 mContext.enforceCallingOrSelfPermission( 5486 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5487 "revokeRuntimePermission"); 5488 5489 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5490 true /* requireFullPermission */, true /* checkShell */, 5491 "revokeRuntimePermission"); 5492 5493 final int appId; 5494 5495 synchronized (mPackages) { 5496 final PackageParser.Package pkg = mPackages.get(packageName); 5497 if (pkg == null) { 5498 throw new IllegalArgumentException("Unknown package: " + packageName); 5499 } 5500 final PackageSetting ps = (PackageSetting) pkg.mExtras; 5501 if (ps == null 5502 || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 5503 throw new IllegalArgumentException("Unknown package: " + packageName); 5504 } 5505 final BasePermission bp = mSettings.mPermissions.get(name); 5506 if (bp == null) { 5507 throw new IllegalArgumentException("Unknown permission: " + name); 5508 } 5509 5510 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 5511 5512 // If a permission review is required for legacy apps we represent 5513 // their permissions as always granted runtime ones since we need 5514 // to keep the review required permission flag per user while an 5515 // install permission's state is shared across all users. 5516 if (mPermissionReviewRequired 5517 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 5518 && bp.isRuntime()) { 5519 return; 5520 } 5521 5522 final PermissionsState permissionsState = ps.getPermissionsState(); 5523 5524 final int flags = permissionsState.getPermissionFlags(name, userId); 5525 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 5526 throw new SecurityException("Cannot revoke system fixed permission " 5527 + name + " for package " + packageName); 5528 } 5529 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 5530 throw new SecurityException("Cannot revoke policy fixed permission " 5531 + name + " for package " + packageName); 5532 } 5533 5534 if (bp.isDevelopment()) { 5535 // Development permissions must be handled specially, since they are not 5536 // normal runtime permissions. For now they apply to all users. 5537 if (permissionsState.revokeInstallPermission(bp) != 5538 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5539 scheduleWriteSettingsLocked(); 5540 } 5541 return; 5542 } 5543 5544 if (permissionsState.revokeRuntimePermission(bp, userId) == 5545 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5546 return; 5547 } 5548 5549 if (bp.isRuntime()) { 5550 logPermissionRevoked(mContext, name, packageName); 5551 } 5552 5553 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 5554 5555 // Critical, after this call app should never have the permission. 5556 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 5557 5558 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 5559 } 5560 5561 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 5562 } 5563 5564 /** 5565 * Get the first event id for the permission. 5566 * 5567 * <p>There are four events for each permission: <ul> 5568 * <li>Request permission: first id + 0</li> 5569 * <li>Grant permission: first id + 1</li> 5570 * <li>Request for permission denied: first id + 2</li> 5571 * <li>Revoke permission: first id + 3</li> 5572 * </ul></p> 5573 * 5574 * @param name name of the permission 5575 * 5576 * @return The first event id for the permission 5577 */ 5578 private static int getBaseEventId(@NonNull String name) { 5579 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 5580 5581 if (eventIdIndex == -1) { 5582 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 5583 || "user".equals(Build.TYPE)) { 5584 Log.i(TAG, "Unknown permission " + name); 5585 5586 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 5587 } else { 5588 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 5589 // 5590 // Also update 5591 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 5592 // - metrics_constants.proto 5593 throw new IllegalStateException("Unknown permission " + name); 5594 } 5595 } 5596 5597 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 5598 } 5599 5600 /** 5601 * Log that a permission was revoked. 5602 * 5603 * @param context Context of the caller 5604 * @param name name of the permission 5605 * @param packageName package permission if for 5606 */ 5607 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5608 @NonNull String packageName) { 5609 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5610 } 5611 5612 /** 5613 * Log that a permission request was granted. 5614 * 5615 * @param context Context of the caller 5616 * @param name name of the permission 5617 * @param packageName package permission if for 5618 */ 5619 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5620 @NonNull String packageName) { 5621 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5622 } 5623 5624 @Override 5625 public void resetRuntimePermissions() { 5626 mContext.enforceCallingOrSelfPermission( 5627 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5628 "revokeRuntimePermission"); 5629 5630 int callingUid = Binder.getCallingUid(); 5631 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5632 mContext.enforceCallingOrSelfPermission( 5633 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5634 "resetRuntimePermissions"); 5635 } 5636 5637 synchronized (mPackages) { 5638 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5639 for (int userId : UserManagerService.getInstance().getUserIds()) { 5640 final int packageCount = mPackages.size(); 5641 for (int i = 0; i < packageCount; i++) { 5642 PackageParser.Package pkg = mPackages.valueAt(i); 5643 if (!(pkg.mExtras instanceof PackageSetting)) { 5644 continue; 5645 } 5646 PackageSetting ps = (PackageSetting) pkg.mExtras; 5647 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5648 } 5649 } 5650 } 5651 } 5652 5653 @Override 5654 public int getPermissionFlags(String name, String packageName, int userId) { 5655 if (!sUserManager.exists(userId)) { 5656 return 0; 5657 } 5658 5659 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5660 5661 final int callingUid = Binder.getCallingUid(); 5662 enforceCrossUserPermission(callingUid, userId, 5663 true /* requireFullPermission */, false /* checkShell */, 5664 "getPermissionFlags"); 5665 5666 synchronized (mPackages) { 5667 final PackageParser.Package pkg = mPackages.get(packageName); 5668 if (pkg == null) { 5669 return 0; 5670 } 5671 final BasePermission bp = mSettings.mPermissions.get(name); 5672 if (bp == null) { 5673 return 0; 5674 } 5675 final PackageSetting ps = (PackageSetting) pkg.mExtras; 5676 if (ps == null 5677 || filterAppAccessLPr(ps, callingUid, userId)) { 5678 return 0; 5679 } 5680 PermissionsState permissionsState = ps.getPermissionsState(); 5681 return permissionsState.getPermissionFlags(name, userId); 5682 } 5683 } 5684 5685 @Override 5686 public void updatePermissionFlags(String name, String packageName, int flagMask, 5687 int flagValues, int userId) { 5688 if (!sUserManager.exists(userId)) { 5689 return; 5690 } 5691 5692 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5693 5694 final int callingUid = Binder.getCallingUid(); 5695 enforceCrossUserPermission(callingUid, userId, 5696 true /* requireFullPermission */, true /* checkShell */, 5697 "updatePermissionFlags"); 5698 5699 // Only the system can change these flags and nothing else. 5700 if (getCallingUid() != Process.SYSTEM_UID) { 5701 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5702 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5703 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5704 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5705 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5706 } 5707 5708 synchronized (mPackages) { 5709 final PackageParser.Package pkg = mPackages.get(packageName); 5710 if (pkg == null) { 5711 throw new IllegalArgumentException("Unknown package: " + packageName); 5712 } 5713 final PackageSetting ps = (PackageSetting) pkg.mExtras; 5714 if (ps == null 5715 || filterAppAccessLPr(ps, callingUid, userId)) { 5716 throw new IllegalArgumentException("Unknown package: " + packageName); 5717 } 5718 5719 final BasePermission bp = mSettings.mPermissions.get(name); 5720 if (bp == null) { 5721 throw new IllegalArgumentException("Unknown permission: " + name); 5722 } 5723 5724 PermissionsState permissionsState = ps.getPermissionsState(); 5725 5726 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5727 5728 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5729 // Install and runtime permissions are stored in different places, 5730 // so figure out what permission changed and persist the change. 5731 if (permissionsState.getInstallPermissionState(name) != null) { 5732 scheduleWriteSettingsLocked(); 5733 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5734 || hadState) { 5735 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5736 } 5737 } 5738 } 5739 } 5740 5741 /** 5742 * Update the permission flags for all packages and runtime permissions of a user in order 5743 * to allow device or profile owner to remove POLICY_FIXED. 5744 */ 5745 @Override 5746 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5747 if (!sUserManager.exists(userId)) { 5748 return; 5749 } 5750 5751 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5752 5753 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5754 true /* requireFullPermission */, true /* checkShell */, 5755 "updatePermissionFlagsForAllApps"); 5756 5757 // Only the system can change system fixed flags. 5758 if (getCallingUid() != Process.SYSTEM_UID) { 5759 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5760 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5761 } 5762 5763 synchronized (mPackages) { 5764 boolean changed = false; 5765 final int packageCount = mPackages.size(); 5766 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5767 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5768 final PackageSetting ps = (PackageSetting) pkg.mExtras; 5769 if (ps == null) { 5770 continue; 5771 } 5772 PermissionsState permissionsState = ps.getPermissionsState(); 5773 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5774 userId, flagMask, flagValues); 5775 } 5776 if (changed) { 5777 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5778 } 5779 } 5780 } 5781 5782 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5783 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5784 != PackageManager.PERMISSION_GRANTED 5785 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5786 != PackageManager.PERMISSION_GRANTED) { 5787 throw new SecurityException(message + " requires " 5788 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5789 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5790 } 5791 } 5792 5793 @Override 5794 public boolean shouldShowRequestPermissionRationale(String permissionName, 5795 String packageName, int userId) { 5796 if (UserHandle.getCallingUserId() != userId) { 5797 mContext.enforceCallingPermission( 5798 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5799 "canShowRequestPermissionRationale for user " + userId); 5800 } 5801 5802 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5803 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5804 return false; 5805 } 5806 5807 if (checkPermission(permissionName, packageName, userId) 5808 == PackageManager.PERMISSION_GRANTED) { 5809 return false; 5810 } 5811 5812 final int flags; 5813 5814 final long identity = Binder.clearCallingIdentity(); 5815 try { 5816 flags = getPermissionFlags(permissionName, 5817 packageName, userId); 5818 } finally { 5819 Binder.restoreCallingIdentity(identity); 5820 } 5821 5822 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5823 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5824 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5825 5826 if ((flags & fixedFlags) != 0) { 5827 return false; 5828 } 5829 5830 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5831 } 5832 5833 @Override 5834 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5835 mContext.enforceCallingOrSelfPermission( 5836 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5837 "addOnPermissionsChangeListener"); 5838 5839 synchronized (mPackages) { 5840 mOnPermissionChangeListeners.addListenerLocked(listener); 5841 } 5842 } 5843 5844 @Override 5845 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5846 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5847 throw new SecurityException("Instant applications don't have access to this method"); 5848 } 5849 synchronized (mPackages) { 5850 mOnPermissionChangeListeners.removeListenerLocked(listener); 5851 } 5852 } 5853 5854 @Override 5855 public boolean isProtectedBroadcast(String actionName) { 5856 // allow instant applications 5857 synchronized (mPackages) { 5858 if (mProtectedBroadcasts.contains(actionName)) { 5859 return true; 5860 } else if (actionName != null) { 5861 // TODO: remove these terrible hacks 5862 if (actionName.startsWith("android.net.netmon.lingerExpired") 5863 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5864 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5865 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5866 return true; 5867 } 5868 } 5869 } 5870 return false; 5871 } 5872 5873 @Override 5874 public int checkSignatures(String pkg1, String pkg2) { 5875 synchronized (mPackages) { 5876 final PackageParser.Package p1 = mPackages.get(pkg1); 5877 final PackageParser.Package p2 = mPackages.get(pkg2); 5878 if (p1 == null || p1.mExtras == null 5879 || p2 == null || p2.mExtras == null) { 5880 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5881 } 5882 final int callingUid = Binder.getCallingUid(); 5883 final int callingUserId = UserHandle.getUserId(callingUid); 5884 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5885 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5886 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5887 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5888 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5889 } 5890 return compareSignatures(p1.mSignatures, p2.mSignatures); 5891 } 5892 } 5893 5894 @Override 5895 public int checkUidSignatures(int uid1, int uid2) { 5896 final int callingUid = Binder.getCallingUid(); 5897 final int callingUserId = UserHandle.getUserId(callingUid); 5898 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5899 // Map to base uids. 5900 uid1 = UserHandle.getAppId(uid1); 5901 uid2 = UserHandle.getAppId(uid2); 5902 // reader 5903 synchronized (mPackages) { 5904 Signature[] s1; 5905 Signature[] s2; 5906 Object obj = mSettings.getUserIdLPr(uid1); 5907 if (obj != null) { 5908 if (obj instanceof SharedUserSetting) { 5909 if (isCallerInstantApp) { 5910 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5911 } 5912 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5913 } else if (obj instanceof PackageSetting) { 5914 final PackageSetting ps = (PackageSetting) obj; 5915 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5916 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5917 } 5918 s1 = ps.signatures.mSignatures; 5919 } else { 5920 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5921 } 5922 } else { 5923 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5924 } 5925 obj = mSettings.getUserIdLPr(uid2); 5926 if (obj != null) { 5927 if (obj instanceof SharedUserSetting) { 5928 if (isCallerInstantApp) { 5929 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5930 } 5931 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5932 } else if (obj instanceof PackageSetting) { 5933 final PackageSetting ps = (PackageSetting) obj; 5934 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5935 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5936 } 5937 s2 = ps.signatures.mSignatures; 5938 } else { 5939 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5940 } 5941 } else { 5942 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5943 } 5944 return compareSignatures(s1, s2); 5945 } 5946 } 5947 5948 /** 5949 * This method should typically only be used when granting or revoking 5950 * permissions, since the app may immediately restart after this call. 5951 * <p> 5952 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5953 * guard your work against the app being relaunched. 5954 */ 5955 private void killUid(int appId, int userId, String reason) { 5956 final long identity = Binder.clearCallingIdentity(); 5957 try { 5958 IActivityManager am = ActivityManager.getService(); 5959 if (am != null) { 5960 try { 5961 am.killUid(appId, userId, reason); 5962 } catch (RemoteException e) { 5963 /* ignore - same process */ 5964 } 5965 } 5966 } finally { 5967 Binder.restoreCallingIdentity(identity); 5968 } 5969 } 5970 5971 /** 5972 * Compares two sets of signatures. Returns: 5973 * <br /> 5974 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5975 * <br /> 5976 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5977 * <br /> 5978 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5979 * <br /> 5980 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5981 * <br /> 5982 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5983 */ 5984 static int compareSignatures(Signature[] s1, Signature[] s2) { 5985 if (s1 == null) { 5986 return s2 == null 5987 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5988 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5989 } 5990 5991 if (s2 == null) { 5992 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5993 } 5994 5995 if (s1.length != s2.length) { 5996 return PackageManager.SIGNATURE_NO_MATCH; 5997 } 5998 5999 // Since both signature sets are of size 1, we can compare without HashSets. 6000 if (s1.length == 1) { 6001 return s1[0].equals(s2[0]) ? 6002 PackageManager.SIGNATURE_MATCH : 6003 PackageManager.SIGNATURE_NO_MATCH; 6004 } 6005 6006 ArraySet<Signature> set1 = new ArraySet<Signature>(); 6007 for (Signature sig : s1) { 6008 set1.add(sig); 6009 } 6010 ArraySet<Signature> set2 = new ArraySet<Signature>(); 6011 for (Signature sig : s2) { 6012 set2.add(sig); 6013 } 6014 // Make sure s2 contains all signatures in s1. 6015 if (set1.equals(set2)) { 6016 return PackageManager.SIGNATURE_MATCH; 6017 } 6018 return PackageManager.SIGNATURE_NO_MATCH; 6019 } 6020 6021 /** 6022 * If the database version for this type of package (internal storage or 6023 * external storage) is less than the version where package signatures 6024 * were updated, return true. 6025 */ 6026 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 6027 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 6028 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 6029 } 6030 6031 /** 6032 * Used for backward compatibility to make sure any packages with 6033 * certificate chains get upgraded to the new style. {@code existingSigs} 6034 * will be in the old format (since they were stored on disk from before the 6035 * system upgrade) and {@code scannedSigs} will be in the newer format. 6036 */ 6037 private int compareSignaturesCompat(PackageSignatures existingSigs, 6038 PackageParser.Package scannedPkg) { 6039 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 6040 return PackageManager.SIGNATURE_NO_MATCH; 6041 } 6042 6043 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 6044 for (Signature sig : existingSigs.mSignatures) { 6045 existingSet.add(sig); 6046 } 6047 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 6048 for (Signature sig : scannedPkg.mSignatures) { 6049 try { 6050 Signature[] chainSignatures = sig.getChainSignatures(); 6051 for (Signature chainSig : chainSignatures) { 6052 scannedCompatSet.add(chainSig); 6053 } 6054 } catch (CertificateEncodingException e) { 6055 scannedCompatSet.add(sig); 6056 } 6057 } 6058 /* 6059 * Make sure the expanded scanned set contains all signatures in the 6060 * existing one. 6061 */ 6062 if (scannedCompatSet.equals(existingSet)) { 6063 // Migrate the old signatures to the new scheme. 6064 existingSigs.assignSignatures(scannedPkg.mSignatures); 6065 // The new KeySets will be re-added later in the scanning process. 6066 synchronized (mPackages) { 6067 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 6068 } 6069 return PackageManager.SIGNATURE_MATCH; 6070 } 6071 return PackageManager.SIGNATURE_NO_MATCH; 6072 } 6073 6074 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 6075 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 6076 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 6077 } 6078 6079 private int compareSignaturesRecover(PackageSignatures existingSigs, 6080 PackageParser.Package scannedPkg) { 6081 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 6082 return PackageManager.SIGNATURE_NO_MATCH; 6083 } 6084 6085 String msg = null; 6086 try { 6087 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 6088 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 6089 + scannedPkg.packageName); 6090 return PackageManager.SIGNATURE_MATCH; 6091 } 6092 } catch (CertificateException e) { 6093 msg = e.getMessage(); 6094 } 6095 6096 logCriticalInfo(Log.INFO, 6097 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 6098 return PackageManager.SIGNATURE_NO_MATCH; 6099 } 6100 6101 @Override 6102 public List<String> getAllPackages() { 6103 final int callingUid = Binder.getCallingUid(); 6104 final int callingUserId = UserHandle.getUserId(callingUid); 6105 synchronized (mPackages) { 6106 if (canViewInstantApps(callingUid, callingUserId)) { 6107 return new ArrayList<String>(mPackages.keySet()); 6108 } 6109 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6110 final List<String> result = new ArrayList<>(); 6111 if (instantAppPkgName != null) { 6112 // caller is an instant application; filter unexposed applications 6113 for (PackageParser.Package pkg : mPackages.values()) { 6114 if (!pkg.visibleToInstantApps) { 6115 continue; 6116 } 6117 result.add(pkg.packageName); 6118 } 6119 } else { 6120 // caller is a normal application; filter instant applications 6121 for (PackageParser.Package pkg : mPackages.values()) { 6122 final PackageSetting ps = 6123 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 6124 if (ps != null 6125 && ps.getInstantApp(callingUserId) 6126 && !mInstantAppRegistry.isInstantAccessGranted( 6127 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 6128 continue; 6129 } 6130 result.add(pkg.packageName); 6131 } 6132 } 6133 return result; 6134 } 6135 } 6136 6137 @Override 6138 public String[] getPackagesForUid(int uid) { 6139 final int callingUid = Binder.getCallingUid(); 6140 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 6141 final int userId = UserHandle.getUserId(uid); 6142 uid = UserHandle.getAppId(uid); 6143 // reader 6144 synchronized (mPackages) { 6145 Object obj = mSettings.getUserIdLPr(uid); 6146 if (obj instanceof SharedUserSetting) { 6147 if (isCallerInstantApp) { 6148 return null; 6149 } 6150 final SharedUserSetting sus = (SharedUserSetting) obj; 6151 final int N = sus.packages.size(); 6152 String[] res = new String[N]; 6153 final Iterator<PackageSetting> it = sus.packages.iterator(); 6154 int i = 0; 6155 while (it.hasNext()) { 6156 PackageSetting ps = it.next(); 6157 if (ps.getInstalled(userId)) { 6158 res[i++] = ps.name; 6159 } else { 6160 res = ArrayUtils.removeElement(String.class, res, res[i]); 6161 } 6162 } 6163 return res; 6164 } else if (obj instanceof PackageSetting) { 6165 final PackageSetting ps = (PackageSetting) obj; 6166 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 6167 return new String[]{ps.name}; 6168 } 6169 } 6170 } 6171 return null; 6172 } 6173 6174 @Override 6175 public String getNameForUid(int uid) { 6176 final int callingUid = Binder.getCallingUid(); 6177 if (getInstantAppPackageName(callingUid) != null) { 6178 return null; 6179 } 6180 synchronized (mPackages) { 6181 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 6182 if (obj instanceof SharedUserSetting) { 6183 final SharedUserSetting sus = (SharedUserSetting) obj; 6184 return sus.name + ":" + sus.userId; 6185 } else if (obj instanceof PackageSetting) { 6186 final PackageSetting ps = (PackageSetting) obj; 6187 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6188 return null; 6189 } 6190 return ps.name; 6191 } 6192 } 6193 return null; 6194 } 6195 6196 @Override 6197 public int getUidForSharedUser(String sharedUserName) { 6198 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6199 return -1; 6200 } 6201 if (sharedUserName == null) { 6202 return -1; 6203 } 6204 // reader 6205 synchronized (mPackages) { 6206 SharedUserSetting suid; 6207 try { 6208 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 6209 if (suid != null) { 6210 return suid.userId; 6211 } 6212 } catch (PackageManagerException ignore) { 6213 // can't happen, but, still need to catch it 6214 } 6215 return -1; 6216 } 6217 } 6218 6219 @Override 6220 public int getFlagsForUid(int uid) { 6221 final int callingUid = Binder.getCallingUid(); 6222 if (getInstantAppPackageName(callingUid) != null) { 6223 return 0; 6224 } 6225 synchronized (mPackages) { 6226 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 6227 if (obj instanceof SharedUserSetting) { 6228 final SharedUserSetting sus = (SharedUserSetting) obj; 6229 return sus.pkgFlags; 6230 } else if (obj instanceof PackageSetting) { 6231 final PackageSetting ps = (PackageSetting) obj; 6232 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6233 return 0; 6234 } 6235 return ps.pkgFlags; 6236 } 6237 } 6238 return 0; 6239 } 6240 6241 @Override 6242 public int getPrivateFlagsForUid(int uid) { 6243 final int callingUid = Binder.getCallingUid(); 6244 if (getInstantAppPackageName(callingUid) != null) { 6245 return 0; 6246 } 6247 synchronized (mPackages) { 6248 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 6249 if (obj instanceof SharedUserSetting) { 6250 final SharedUserSetting sus = (SharedUserSetting) obj; 6251 return sus.pkgPrivateFlags; 6252 } else if (obj instanceof PackageSetting) { 6253 final PackageSetting ps = (PackageSetting) obj; 6254 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6255 return 0; 6256 } 6257 return ps.pkgPrivateFlags; 6258 } 6259 } 6260 return 0; 6261 } 6262 6263 @Override 6264 public boolean isUidPrivileged(int uid) { 6265 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6266 return false; 6267 } 6268 uid = UserHandle.getAppId(uid); 6269 // reader 6270 synchronized (mPackages) { 6271 Object obj = mSettings.getUserIdLPr(uid); 6272 if (obj instanceof SharedUserSetting) { 6273 final SharedUserSetting sus = (SharedUserSetting) obj; 6274 final Iterator<PackageSetting> it = sus.packages.iterator(); 6275 while (it.hasNext()) { 6276 if (it.next().isPrivileged()) { 6277 return true; 6278 } 6279 } 6280 } else if (obj instanceof PackageSetting) { 6281 final PackageSetting ps = (PackageSetting) obj; 6282 return ps.isPrivileged(); 6283 } 6284 } 6285 return false; 6286 } 6287 6288 @Override 6289 public String[] getAppOpPermissionPackages(String permissionName) { 6290 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6291 return null; 6292 } 6293 synchronized (mPackages) { 6294 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 6295 if (pkgs == null) { 6296 return null; 6297 } 6298 return pkgs.toArray(new String[pkgs.size()]); 6299 } 6300 } 6301 6302 @Override 6303 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 6304 int flags, int userId) { 6305 return resolveIntentInternal( 6306 intent, resolvedType, flags, userId, false /*includeInstantApps*/); 6307 } 6308 6309 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 6310 int flags, int userId, boolean resolveForStart) { 6311 try { 6312 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 6313 6314 if (!sUserManager.exists(userId)) return null; 6315 final int callingUid = Binder.getCallingUid(); 6316 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 6317 enforceCrossUserPermission(callingUid, userId, 6318 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 6319 6320 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6321 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 6322 flags, callingUid, userId, resolveForStart); 6323 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6324 6325 final ResolveInfo bestChoice = 6326 chooseBestActivity(intent, resolvedType, flags, query, userId); 6327 return bestChoice; 6328 } finally { 6329 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6330 } 6331 } 6332 6333 @Override 6334 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 6335 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 6336 throw new SecurityException( 6337 "findPersistentPreferredActivity can only be run by the system"); 6338 } 6339 if (!sUserManager.exists(userId)) { 6340 return null; 6341 } 6342 final int callingUid = Binder.getCallingUid(); 6343 intent = updateIntentForResolve(intent); 6344 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 6345 final int flags = updateFlagsForResolve( 6346 0, userId, intent, callingUid, false /*includeInstantApps*/); 6347 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6348 userId); 6349 synchronized (mPackages) { 6350 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 6351 userId); 6352 } 6353 } 6354 6355 @Override 6356 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 6357 IntentFilter filter, int match, ComponentName activity) { 6358 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6359 return; 6360 } 6361 final int userId = UserHandle.getCallingUserId(); 6362 if (DEBUG_PREFERRED) { 6363 Log.v(TAG, "setLastChosenActivity intent=" + intent 6364 + " resolvedType=" + resolvedType 6365 + " flags=" + flags 6366 + " filter=" + filter 6367 + " match=" + match 6368 + " activity=" + activity); 6369 filter.dump(new PrintStreamPrinter(System.out), " "); 6370 } 6371 intent.setComponent(null); 6372 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6373 userId); 6374 // Find any earlier preferred or last chosen entries and nuke them 6375 findPreferredActivity(intent, resolvedType, 6376 flags, query, 0, false, true, false, userId); 6377 // Add the new activity as the last chosen for this filter 6378 addPreferredActivityInternal(filter, match, null, activity, false, userId, 6379 "Setting last chosen"); 6380 } 6381 6382 @Override 6383 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 6384 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6385 return null; 6386 } 6387 final int userId = UserHandle.getCallingUserId(); 6388 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 6389 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6390 userId); 6391 return findPreferredActivity(intent, resolvedType, flags, query, 0, 6392 false, false, false, userId); 6393 } 6394 6395 /** 6396 * Returns whether or not instant apps have been disabled remotely. 6397 */ 6398 private boolean isEphemeralDisabled() { 6399 return mEphemeralAppsDisabled; 6400 } 6401 6402 private boolean isInstantAppAllowed( 6403 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 6404 boolean skipPackageCheck) { 6405 if (mInstantAppResolverConnection == null) { 6406 return false; 6407 } 6408 if (mInstantAppInstallerActivity == null) { 6409 return false; 6410 } 6411 if (intent.getComponent() != null) { 6412 return false; 6413 } 6414 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 6415 return false; 6416 } 6417 if (!skipPackageCheck && intent.getPackage() != null) { 6418 return false; 6419 } 6420 final boolean isWebUri = hasWebURI(intent); 6421 if (!isWebUri || intent.getData().getHost() == null) { 6422 return false; 6423 } 6424 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 6425 // Or if there's already an ephemeral app installed that handles the action 6426 synchronized (mPackages) { 6427 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 6428 for (int n = 0; n < count; n++) { 6429 final ResolveInfo info = resolvedActivities.get(n); 6430 final String packageName = info.activityInfo.packageName; 6431 final PackageSetting ps = mSettings.mPackages.get(packageName); 6432 if (ps != null) { 6433 // only check domain verification status if the app is not a browser 6434 if (!info.handleAllWebDataURI) { 6435 // Try to get the status from User settings first 6436 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6437 final int status = (int) (packedStatus >> 32); 6438 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 6439 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6440 if (DEBUG_EPHEMERAL) { 6441 Slog.v(TAG, "DENY instant app;" 6442 + " pkg: " + packageName + ", status: " + status); 6443 } 6444 return false; 6445 } 6446 } 6447 if (ps.getInstantApp(userId)) { 6448 if (DEBUG_EPHEMERAL) { 6449 Slog.v(TAG, "DENY instant app installed;" 6450 + " pkg: " + packageName); 6451 } 6452 return false; 6453 } 6454 } 6455 } 6456 } 6457 // We've exhausted all ways to deny ephemeral application; let the system look for them. 6458 return true; 6459 } 6460 6461 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 6462 Intent origIntent, String resolvedType, String callingPackage, 6463 Bundle verificationBundle, int userId) { 6464 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 6465 new InstantAppRequest(responseObj, origIntent, resolvedType, 6466 callingPackage, userId, verificationBundle)); 6467 mHandler.sendMessage(msg); 6468 } 6469 6470 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 6471 int flags, List<ResolveInfo> query, int userId) { 6472 if (query != null) { 6473 final int N = query.size(); 6474 if (N == 1) { 6475 return query.get(0); 6476 } else if (N > 1) { 6477 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 6478 // If there is more than one activity with the same priority, 6479 // then let the user decide between them. 6480 ResolveInfo r0 = query.get(0); 6481 ResolveInfo r1 = query.get(1); 6482 if (DEBUG_INTENT_MATCHING || debug) { 6483 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 6484 + r1.activityInfo.name + "=" + r1.priority); 6485 } 6486 // If the first activity has a higher priority, or a different 6487 // default, then it is always desirable to pick it. 6488 if (r0.priority != r1.priority 6489 || r0.preferredOrder != r1.preferredOrder 6490 || r0.isDefault != r1.isDefault) { 6491 return query.get(0); 6492 } 6493 // If we have saved a preference for a preferred activity for 6494 // this Intent, use that. 6495 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 6496 flags, query, r0.priority, true, false, debug, userId); 6497 if (ri != null) { 6498 return ri; 6499 } 6500 // If we have an ephemeral app, use it 6501 for (int i = 0; i < N; i++) { 6502 ri = query.get(i); 6503 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6504 final String packageName = ri.activityInfo.packageName; 6505 final PackageSetting ps = mSettings.mPackages.get(packageName); 6506 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6507 final int status = (int)(packedStatus >> 32); 6508 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6509 return ri; 6510 } 6511 } 6512 } 6513 ri = new ResolveInfo(mResolveInfo); 6514 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6515 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6516 // If all of the options come from the same package, show the application's 6517 // label and icon instead of the generic resolver's. 6518 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6519 // and then throw away the ResolveInfo itself, meaning that the caller loses 6520 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6521 // a fallback for this case; we only set the target package's resources on 6522 // the ResolveInfo, not the ActivityInfo. 6523 final String intentPackage = intent.getPackage(); 6524 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6525 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6526 ri.resolvePackageName = intentPackage; 6527 if (userNeedsBadging(userId)) { 6528 ri.noResourceId = true; 6529 } else { 6530 ri.icon = appi.icon; 6531 } 6532 ri.iconResourceId = appi.icon; 6533 ri.labelRes = appi.labelRes; 6534 } 6535 ri.activityInfo.applicationInfo = new ApplicationInfo( 6536 ri.activityInfo.applicationInfo); 6537 if (userId != 0) { 6538 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6539 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6540 } 6541 // Make sure that the resolver is displayable in car mode 6542 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6543 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6544 return ri; 6545 } 6546 } 6547 return null; 6548 } 6549 6550 /** 6551 * Return true if the given list is not empty and all of its contents have 6552 * an activityInfo with the given package name. 6553 */ 6554 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6555 if (ArrayUtils.isEmpty(list)) { 6556 return false; 6557 } 6558 for (int i = 0, N = list.size(); i < N; i++) { 6559 final ResolveInfo ri = list.get(i); 6560 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6561 if (ai == null || !packageName.equals(ai.packageName)) { 6562 return false; 6563 } 6564 } 6565 return true; 6566 } 6567 6568 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6569 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6570 final int N = query.size(); 6571 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6572 .get(userId); 6573 // Get the list of persistent preferred activities that handle the intent 6574 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6575 List<PersistentPreferredActivity> pprefs = ppir != null 6576 ? ppir.queryIntent(intent, resolvedType, 6577 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6578 userId) 6579 : null; 6580 if (pprefs != null && pprefs.size() > 0) { 6581 final int M = pprefs.size(); 6582 for (int i=0; i<M; i++) { 6583 final PersistentPreferredActivity ppa = pprefs.get(i); 6584 if (DEBUG_PREFERRED || debug) { 6585 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6586 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6587 + "\n component=" + ppa.mComponent); 6588 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6589 } 6590 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6591 flags | MATCH_DISABLED_COMPONENTS, userId); 6592 if (DEBUG_PREFERRED || debug) { 6593 Slog.v(TAG, "Found persistent preferred activity:"); 6594 if (ai != null) { 6595 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6596 } else { 6597 Slog.v(TAG, " null"); 6598 } 6599 } 6600 if (ai == null) { 6601 // This previously registered persistent preferred activity 6602 // component is no longer known. Ignore it and do NOT remove it. 6603 continue; 6604 } 6605 for (int j=0; j<N; j++) { 6606 final ResolveInfo ri = query.get(j); 6607 if (!ri.activityInfo.applicationInfo.packageName 6608 .equals(ai.applicationInfo.packageName)) { 6609 continue; 6610 } 6611 if (!ri.activityInfo.name.equals(ai.name)) { 6612 continue; 6613 } 6614 // Found a persistent preference that can handle the intent. 6615 if (DEBUG_PREFERRED || debug) { 6616 Slog.v(TAG, "Returning persistent preferred activity: " + 6617 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6618 } 6619 return ri; 6620 } 6621 } 6622 } 6623 return null; 6624 } 6625 6626 // TODO: handle preferred activities missing while user has amnesia 6627 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6628 List<ResolveInfo> query, int priority, boolean always, 6629 boolean removeMatches, boolean debug, int userId) { 6630 if (!sUserManager.exists(userId)) return null; 6631 final int callingUid = Binder.getCallingUid(); 6632 flags = updateFlagsForResolve( 6633 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6634 intent = updateIntentForResolve(intent); 6635 // writer 6636 synchronized (mPackages) { 6637 // Try to find a matching persistent preferred activity. 6638 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6639 debug, userId); 6640 6641 // If a persistent preferred activity matched, use it. 6642 if (pri != null) { 6643 return pri; 6644 } 6645 6646 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6647 // Get the list of preferred activities that handle the intent 6648 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6649 List<PreferredActivity> prefs = pir != null 6650 ? pir.queryIntent(intent, resolvedType, 6651 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6652 userId) 6653 : null; 6654 if (prefs != null && prefs.size() > 0) { 6655 boolean changed = false; 6656 try { 6657 // First figure out how good the original match set is. 6658 // We will only allow preferred activities that came 6659 // from the same match quality. 6660 int match = 0; 6661 6662 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6663 6664 final int N = query.size(); 6665 for (int j=0; j<N; j++) { 6666 final ResolveInfo ri = query.get(j); 6667 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6668 + ": 0x" + Integer.toHexString(match)); 6669 if (ri.match > match) { 6670 match = ri.match; 6671 } 6672 } 6673 6674 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6675 + Integer.toHexString(match)); 6676 6677 match &= IntentFilter.MATCH_CATEGORY_MASK; 6678 final int M = prefs.size(); 6679 for (int i=0; i<M; i++) { 6680 final PreferredActivity pa = prefs.get(i); 6681 if (DEBUG_PREFERRED || debug) { 6682 Slog.v(TAG, "Checking PreferredActivity ds=" 6683 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6684 + "\n component=" + pa.mPref.mComponent); 6685 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6686 } 6687 if (pa.mPref.mMatch != match) { 6688 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6689 + Integer.toHexString(pa.mPref.mMatch)); 6690 continue; 6691 } 6692 // If it's not an "always" type preferred activity and that's what we're 6693 // looking for, skip it. 6694 if (always && !pa.mPref.mAlways) { 6695 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6696 continue; 6697 } 6698 final ActivityInfo ai = getActivityInfo( 6699 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6700 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6701 userId); 6702 if (DEBUG_PREFERRED || debug) { 6703 Slog.v(TAG, "Found preferred activity:"); 6704 if (ai != null) { 6705 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6706 } else { 6707 Slog.v(TAG, " null"); 6708 } 6709 } 6710 if (ai == null) { 6711 // This previously registered preferred activity 6712 // component is no longer known. Most likely an update 6713 // to the app was installed and in the new version this 6714 // component no longer exists. Clean it up by removing 6715 // it from the preferred activities list, and skip it. 6716 Slog.w(TAG, "Removing dangling preferred activity: " 6717 + pa.mPref.mComponent); 6718 pir.removeFilter(pa); 6719 changed = true; 6720 continue; 6721 } 6722 for (int j=0; j<N; j++) { 6723 final ResolveInfo ri = query.get(j); 6724 if (!ri.activityInfo.applicationInfo.packageName 6725 .equals(ai.applicationInfo.packageName)) { 6726 continue; 6727 } 6728 if (!ri.activityInfo.name.equals(ai.name)) { 6729 continue; 6730 } 6731 6732 if (removeMatches) { 6733 pir.removeFilter(pa); 6734 changed = true; 6735 if (DEBUG_PREFERRED) { 6736 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6737 } 6738 break; 6739 } 6740 6741 // Okay we found a previously set preferred or last chosen app. 6742 // If the result set is different from when this 6743 // was created, we need to clear it and re-ask the 6744 // user their preference, if we're looking for an "always" type entry. 6745 if (always && !pa.mPref.sameSet(query)) { 6746 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6747 + intent + " type " + resolvedType); 6748 if (DEBUG_PREFERRED) { 6749 Slog.v(TAG, "Removing preferred activity since set changed " 6750 + pa.mPref.mComponent); 6751 } 6752 pir.removeFilter(pa); 6753 // Re-add the filter as a "last chosen" entry (!always) 6754 PreferredActivity lastChosen = new PreferredActivity( 6755 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6756 pir.addFilter(lastChosen); 6757 changed = true; 6758 return null; 6759 } 6760 6761 // Yay! Either the set matched or we're looking for the last chosen 6762 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6763 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6764 return ri; 6765 } 6766 } 6767 } finally { 6768 if (changed) { 6769 if (DEBUG_PREFERRED) { 6770 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6771 } 6772 scheduleWritePackageRestrictionsLocked(userId); 6773 } 6774 } 6775 } 6776 } 6777 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6778 return null; 6779 } 6780 6781 /* 6782 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6783 */ 6784 @Override 6785 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6786 int targetUserId) { 6787 mContext.enforceCallingOrSelfPermission( 6788 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6789 List<CrossProfileIntentFilter> matches = 6790 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6791 if (matches != null) { 6792 int size = matches.size(); 6793 for (int i = 0; i < size; i++) { 6794 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6795 } 6796 } 6797 if (hasWebURI(intent)) { 6798 // cross-profile app linking works only towards the parent. 6799 final int callingUid = Binder.getCallingUid(); 6800 final UserInfo parent = getProfileParent(sourceUserId); 6801 synchronized(mPackages) { 6802 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6803 false /*includeInstantApps*/); 6804 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6805 intent, resolvedType, flags, sourceUserId, parent.id); 6806 return xpDomainInfo != null; 6807 } 6808 } 6809 return false; 6810 } 6811 6812 private UserInfo getProfileParent(int userId) { 6813 final long identity = Binder.clearCallingIdentity(); 6814 try { 6815 return sUserManager.getProfileParent(userId); 6816 } finally { 6817 Binder.restoreCallingIdentity(identity); 6818 } 6819 } 6820 6821 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6822 String resolvedType, int userId) { 6823 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6824 if (resolver != null) { 6825 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6826 } 6827 return null; 6828 } 6829 6830 @Override 6831 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6832 String resolvedType, int flags, int userId) { 6833 try { 6834 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6835 6836 return new ParceledListSlice<>( 6837 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6838 } finally { 6839 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6840 } 6841 } 6842 6843 /** 6844 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6845 * instant, returns {@code null}. 6846 */ 6847 private String getInstantAppPackageName(int callingUid) { 6848 synchronized (mPackages) { 6849 // If the caller is an isolated app use the owner's uid for the lookup. 6850 if (Process.isIsolated(callingUid)) { 6851 callingUid = mIsolatedOwners.get(callingUid); 6852 } 6853 final int appId = UserHandle.getAppId(callingUid); 6854 final Object obj = mSettings.getUserIdLPr(appId); 6855 if (obj instanceof PackageSetting) { 6856 final PackageSetting ps = (PackageSetting) obj; 6857 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6858 return isInstantApp ? ps.pkg.packageName : null; 6859 } 6860 } 6861 return null; 6862 } 6863 6864 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6865 String resolvedType, int flags, int userId) { 6866 return queryIntentActivitiesInternal( 6867 intent, resolvedType, flags, Binder.getCallingUid(), userId, false); 6868 } 6869 6870 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6871 String resolvedType, int flags, int filterCallingUid, int userId, 6872 boolean resolveForStart) { 6873 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6874 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6875 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6876 false /* requireFullPermission */, false /* checkShell */, 6877 "query intent activities"); 6878 final String pkgName = intent.getPackage(); 6879 ComponentName comp = intent.getComponent(); 6880 if (comp == null) { 6881 if (intent.getSelector() != null) { 6882 intent = intent.getSelector(); 6883 comp = intent.getComponent(); 6884 } 6885 } 6886 6887 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6888 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6889 if (comp != null) { 6890 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6891 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6892 if (ai != null) { 6893 // When specifying an explicit component, we prevent the activity from being 6894 // used when either 1) the calling package is normal and the activity is within 6895 // an ephemeral application or 2) the calling package is ephemeral and the 6896 // activity is not visible to ephemeral applications. 6897 final boolean matchInstantApp = 6898 (flags & PackageManager.MATCH_INSTANT) != 0; 6899 final boolean matchVisibleToInstantAppOnly = 6900 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6901 final boolean matchExplicitlyVisibleOnly = 6902 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6903 final boolean isCallerInstantApp = 6904 instantAppPkgName != null; 6905 final boolean isTargetSameInstantApp = 6906 comp.getPackageName().equals(instantAppPkgName); 6907 final boolean isTargetInstantApp = 6908 (ai.applicationInfo.privateFlags 6909 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6910 final boolean isTargetVisibleToInstantApp = 6911 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6912 final boolean isTargetExplicitlyVisibleToInstantApp = 6913 isTargetVisibleToInstantApp 6914 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6915 final boolean isTargetHiddenFromInstantApp = 6916 !isTargetVisibleToInstantApp 6917 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6918 final boolean blockResolution = 6919 !isTargetSameInstantApp 6920 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6921 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6922 && isTargetHiddenFromInstantApp)); 6923 if (!blockResolution) { 6924 final ResolveInfo ri = new ResolveInfo(); 6925 ri.activityInfo = ai; 6926 list.add(ri); 6927 } 6928 } 6929 return applyPostResolutionFilter(list, instantAppPkgName); 6930 } 6931 6932 // reader 6933 boolean sortResult = false; 6934 boolean addEphemeral = false; 6935 List<ResolveInfo> result; 6936 final boolean ephemeralDisabled = isEphemeralDisabled(); 6937 synchronized (mPackages) { 6938 if (pkgName == null) { 6939 List<CrossProfileIntentFilter> matchingFilters = 6940 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6941 // Check for results that need to skip the current profile. 6942 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6943 resolvedType, flags, userId); 6944 if (xpResolveInfo != null) { 6945 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6946 xpResult.add(xpResolveInfo); 6947 return applyPostResolutionFilter( 6948 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6949 } 6950 6951 // Check for results in the current profile. 6952 result = filterIfNotSystemUser(mActivities.queryIntent( 6953 intent, resolvedType, flags, userId), userId); 6954 addEphemeral = !ephemeralDisabled 6955 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 6956 // Check for cross profile results. 6957 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6958 xpResolveInfo = queryCrossProfileIntents( 6959 matchingFilters, intent, resolvedType, flags, userId, 6960 hasNonNegativePriorityResult); 6961 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6962 boolean isVisibleToUser = filterIfNotSystemUser( 6963 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6964 if (isVisibleToUser) { 6965 result.add(xpResolveInfo); 6966 sortResult = true; 6967 } 6968 } 6969 if (hasWebURI(intent)) { 6970 CrossProfileDomainInfo xpDomainInfo = null; 6971 final UserInfo parent = getProfileParent(userId); 6972 if (parent != null) { 6973 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6974 flags, userId, parent.id); 6975 } 6976 if (xpDomainInfo != null) { 6977 if (xpResolveInfo != null) { 6978 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6979 // in the result. 6980 result.remove(xpResolveInfo); 6981 } 6982 if (result.size() == 0 && !addEphemeral) { 6983 // No result in current profile, but found candidate in parent user. 6984 // And we are not going to add emphemeral app, so we can return the 6985 // result straight away. 6986 result.add(xpDomainInfo.resolveInfo); 6987 return applyPostResolutionFilter(result, instantAppPkgName); 6988 } 6989 } else if (result.size() <= 1 && !addEphemeral) { 6990 // No result in parent user and <= 1 result in current profile, and we 6991 // are not going to add emphemeral app, so we can return the result without 6992 // further processing. 6993 return applyPostResolutionFilter(result, instantAppPkgName); 6994 } 6995 // We have more than one candidate (combining results from current and parent 6996 // profile), so we need filtering and sorting. 6997 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6998 intent, flags, result, xpDomainInfo, userId); 6999 sortResult = true; 7000 } 7001 } else { 7002 final PackageParser.Package pkg = mPackages.get(pkgName); 7003 result = null; 7004 if (pkg != null) { 7005 result = filterIfNotSystemUser( 7006 mActivities.queryIntentForPackage( 7007 intent, resolvedType, flags, pkg.activities, userId), 7008 userId); 7009 } 7010 if (result == null || result.size() == 0) { 7011 // the caller wants to resolve for a particular package; however, there 7012 // were no installed results, so, try to find an ephemeral result 7013 addEphemeral = !ephemeralDisabled 7014 && isInstantAppAllowed( 7015 intent, null /*result*/, userId, true /*skipPackageCheck*/); 7016 if (result == null) { 7017 result = new ArrayList<>(); 7018 } 7019 } 7020 } 7021 } 7022 if (addEphemeral) { 7023 result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId); 7024 } 7025 if (sortResult) { 7026 Collections.sort(result, mResolvePrioritySorter); 7027 } 7028 return applyPostResolutionFilter(result, instantAppPkgName); 7029 } 7030 7031 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 7032 String resolvedType, int flags, int userId) { 7033 // first, check to see if we've got an instant app already installed 7034 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 7035 ResolveInfo localInstantApp = null; 7036 boolean blockResolution = false; 7037 if (!alreadyResolvedLocally) { 7038 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 7039 flags 7040 | PackageManager.GET_RESOLVED_FILTER 7041 | PackageManager.MATCH_INSTANT 7042 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 7043 userId); 7044 for (int i = instantApps.size() - 1; i >= 0; --i) { 7045 final ResolveInfo info = instantApps.get(i); 7046 final String packageName = info.activityInfo.packageName; 7047 final PackageSetting ps = mSettings.mPackages.get(packageName); 7048 if (ps.getInstantApp(userId)) { 7049 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 7050 final int status = (int)(packedStatus >> 32); 7051 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 7052 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7053 // there's a local instant application installed, but, the user has 7054 // chosen to never use it; skip resolution and don't acknowledge 7055 // an instant application is even available 7056 if (DEBUG_EPHEMERAL) { 7057 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 7058 } 7059 blockResolution = true; 7060 break; 7061 } else { 7062 // we have a locally installed instant application; skip resolution 7063 // but acknowledge there's an instant application available 7064 if (DEBUG_EPHEMERAL) { 7065 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 7066 } 7067 localInstantApp = info; 7068 break; 7069 } 7070 } 7071 } 7072 } 7073 // no app installed, let's see if one's available 7074 AuxiliaryResolveInfo auxiliaryResponse = null; 7075 if (!blockResolution) { 7076 if (localInstantApp == null) { 7077 // we don't have an instant app locally, resolve externally 7078 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 7079 final InstantAppRequest requestObject = new InstantAppRequest( 7080 null /*responseObj*/, intent /*origIntent*/, resolvedType, 7081 null /*callingPackage*/, userId, null /*verificationBundle*/); 7082 auxiliaryResponse = 7083 InstantAppResolver.doInstantAppResolutionPhaseOne( 7084 mContext, mInstantAppResolverConnection, requestObject); 7085 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7086 } else { 7087 // we have an instant application locally, but, we can't admit that since 7088 // callers shouldn't be able to determine prior browsing. create a dummy 7089 // auxiliary response so the downstream code behaves as if there's an 7090 // instant application available externally. when it comes time to start 7091 // the instant application, we'll do the right thing. 7092 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 7093 auxiliaryResponse = new AuxiliaryResolveInfo( 7094 ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/); 7095 } 7096 } 7097 if (auxiliaryResponse != null) { 7098 if (DEBUG_EPHEMERAL) { 7099 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7100 } 7101 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 7102 final PackageSetting ps = 7103 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 7104 if (ps != null) { 7105 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 7106 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 7107 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 7108 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 7109 // make sure this resolver is the default 7110 ephemeralInstaller.isDefault = true; 7111 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7112 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7113 // add a non-generic filter 7114 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 7115 ephemeralInstaller.filter.addDataPath( 7116 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 7117 ephemeralInstaller.isInstantAppAvailable = true; 7118 result.add(ephemeralInstaller); 7119 } 7120 } 7121 return result; 7122 } 7123 7124 private static class CrossProfileDomainInfo { 7125 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 7126 ResolveInfo resolveInfo; 7127 /* Best domain verification status of the activities found in the other profile */ 7128 int bestDomainVerificationStatus; 7129 } 7130 7131 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 7132 String resolvedType, int flags, int sourceUserId, int parentUserId) { 7133 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 7134 sourceUserId)) { 7135 return null; 7136 } 7137 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7138 resolvedType, flags, parentUserId); 7139 7140 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 7141 return null; 7142 } 7143 CrossProfileDomainInfo result = null; 7144 int size = resultTargetUser.size(); 7145 for (int i = 0; i < size; i++) { 7146 ResolveInfo riTargetUser = resultTargetUser.get(i); 7147 // Intent filter verification is only for filters that specify a host. So don't return 7148 // those that handle all web uris. 7149 if (riTargetUser.handleAllWebDataURI) { 7150 continue; 7151 } 7152 String packageName = riTargetUser.activityInfo.packageName; 7153 PackageSetting ps = mSettings.mPackages.get(packageName); 7154 if (ps == null) { 7155 continue; 7156 } 7157 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 7158 int status = (int)(verificationState >> 32); 7159 if (result == null) { 7160 result = new CrossProfileDomainInfo(); 7161 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 7162 sourceUserId, parentUserId); 7163 result.bestDomainVerificationStatus = status; 7164 } else { 7165 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 7166 result.bestDomainVerificationStatus); 7167 } 7168 } 7169 // Don't consider matches with status NEVER across profiles. 7170 if (result != null && result.bestDomainVerificationStatus 7171 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7172 return null; 7173 } 7174 return result; 7175 } 7176 7177 /** 7178 * Verification statuses are ordered from the worse to the best, except for 7179 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 7180 */ 7181 private int bestDomainVerificationStatus(int status1, int status2) { 7182 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7183 return status2; 7184 } 7185 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7186 return status1; 7187 } 7188 return (int) MathUtils.max(status1, status2); 7189 } 7190 7191 private boolean isUserEnabled(int userId) { 7192 long callingId = Binder.clearCallingIdentity(); 7193 try { 7194 UserInfo userInfo = sUserManager.getUserInfo(userId); 7195 return userInfo != null && userInfo.isEnabled(); 7196 } finally { 7197 Binder.restoreCallingIdentity(callingId); 7198 } 7199 } 7200 7201 /** 7202 * Filter out activities with systemUserOnly flag set, when current user is not System. 7203 * 7204 * @return filtered list 7205 */ 7206 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 7207 if (userId == UserHandle.USER_SYSTEM) { 7208 return resolveInfos; 7209 } 7210 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7211 ResolveInfo info = resolveInfos.get(i); 7212 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 7213 resolveInfos.remove(i); 7214 } 7215 } 7216 return resolveInfos; 7217 } 7218 7219 /** 7220 * Filters out ephemeral activities. 7221 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 7222 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 7223 * 7224 * @param resolveInfos The pre-filtered list of resolved activities 7225 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 7226 * is performed. 7227 * @return A filtered list of resolved activities. 7228 */ 7229 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 7230 String ephemeralPkgName) { 7231 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7232 final ResolveInfo info = resolveInfos.get(i); 7233 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 7234 // TODO: When adding on-demand split support for non-instant apps, remove this check 7235 // and always apply post filtering 7236 // allow activities that are defined in the provided package 7237 if (isEphemeralApp) { 7238 if (info.activityInfo.splitName != null 7239 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 7240 info.activityInfo.splitName)) { 7241 // requested activity is defined in a split that hasn't been installed yet. 7242 // add the installer to the resolve list 7243 if (DEBUG_EPHEMERAL) { 7244 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7245 } 7246 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7247 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7248 info.activityInfo.packageName, info.activityInfo.splitName, 7249 info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/); 7250 // make sure this resolver is the default 7251 installerInfo.isDefault = true; 7252 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7253 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7254 // add a non-generic filter 7255 installerInfo.filter = new IntentFilter(); 7256 // load resources from the correct package 7257 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7258 resolveInfos.set(i, installerInfo); 7259 continue; 7260 } 7261 } 7262 // caller is a full app, don't need to apply any other filtering 7263 if (ephemeralPkgName == null) { 7264 continue; 7265 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 7266 // caller is same app; don't need to apply any other filtering 7267 continue; 7268 } 7269 // allow activities that have been explicitly exposed to ephemeral apps 7270 if (!isEphemeralApp 7271 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7272 continue; 7273 } 7274 resolveInfos.remove(i); 7275 } 7276 return resolveInfos; 7277 } 7278 7279 /** 7280 * @param resolveInfos list of resolve infos in descending priority order 7281 * @return if the list contains a resolve info with non-negative priority 7282 */ 7283 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 7284 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 7285 } 7286 7287 private static boolean hasWebURI(Intent intent) { 7288 if (intent.getData() == null) { 7289 return false; 7290 } 7291 final String scheme = intent.getScheme(); 7292 if (TextUtils.isEmpty(scheme)) { 7293 return false; 7294 } 7295 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 7296 } 7297 7298 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 7299 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 7300 int userId) { 7301 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 7302 7303 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7304 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 7305 candidates.size()); 7306 } 7307 7308 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 7309 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 7310 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 7311 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 7312 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 7313 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 7314 7315 synchronized (mPackages) { 7316 final int count = candidates.size(); 7317 // First, try to use linked apps. Partition the candidates into four lists: 7318 // one for the final results, one for the "do not use ever", one for "undefined status" 7319 // and finally one for "browser app type". 7320 for (int n=0; n<count; n++) { 7321 ResolveInfo info = candidates.get(n); 7322 String packageName = info.activityInfo.packageName; 7323 PackageSetting ps = mSettings.mPackages.get(packageName); 7324 if (ps != null) { 7325 // Add to the special match all list (Browser use case) 7326 if (info.handleAllWebDataURI) { 7327 matchAllList.add(info); 7328 continue; 7329 } 7330 // Try to get the status from User settings first 7331 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 7332 int status = (int)(packedStatus >> 32); 7333 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 7334 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 7335 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7336 Slog.i(TAG, " + always: " + info.activityInfo.packageName 7337 + " : linkgen=" + linkGeneration); 7338 } 7339 // Use link-enabled generation as preferredOrder, i.e. 7340 // prefer newly-enabled over earlier-enabled. 7341 info.preferredOrder = linkGeneration; 7342 alwaysList.add(info); 7343 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7344 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7345 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 7346 } 7347 neverList.add(info); 7348 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 7349 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7350 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 7351 } 7352 alwaysAskList.add(info); 7353 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 7354 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 7355 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7356 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 7357 } 7358 undefinedList.add(info); 7359 } 7360 } 7361 } 7362 7363 // We'll want to include browser possibilities in a few cases 7364 boolean includeBrowser = false; 7365 7366 // First try to add the "always" resolution(s) for the current user, if any 7367 if (alwaysList.size() > 0) { 7368 result.addAll(alwaysList); 7369 } else { 7370 // Add all undefined apps as we want them to appear in the disambiguation dialog. 7371 result.addAll(undefinedList); 7372 // Maybe add one for the other profile. 7373 if (xpDomainInfo != null && ( 7374 xpDomainInfo.bestDomainVerificationStatus 7375 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 7376 result.add(xpDomainInfo.resolveInfo); 7377 } 7378 includeBrowser = true; 7379 } 7380 7381 // The presence of any 'always ask' alternatives means we'll also offer browsers. 7382 // If there were 'always' entries their preferred order has been set, so we also 7383 // back that off to make the alternatives equivalent 7384 if (alwaysAskList.size() > 0) { 7385 for (ResolveInfo i : result) { 7386 i.preferredOrder = 0; 7387 } 7388 result.addAll(alwaysAskList); 7389 includeBrowser = true; 7390 } 7391 7392 if (includeBrowser) { 7393 // Also add browsers (all of them or only the default one) 7394 if (DEBUG_DOMAIN_VERIFICATION) { 7395 Slog.v(TAG, " ...including browsers in candidate set"); 7396 } 7397 if ((matchFlags & MATCH_ALL) != 0) { 7398 result.addAll(matchAllList); 7399 } else { 7400 // Browser/generic handling case. If there's a default browser, go straight 7401 // to that (but only if there is no other higher-priority match). 7402 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7403 int maxMatchPrio = 0; 7404 ResolveInfo defaultBrowserMatch = null; 7405 final int numCandidates = matchAllList.size(); 7406 for (int n = 0; n < numCandidates; n++) { 7407 ResolveInfo info = matchAllList.get(n); 7408 // track the highest overall match priority... 7409 if (info.priority > maxMatchPrio) { 7410 maxMatchPrio = info.priority; 7411 } 7412 // ...and the highest-priority default browser match 7413 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7414 if (defaultBrowserMatch == null 7415 || (defaultBrowserMatch.priority < info.priority)) { 7416 if (debug) { 7417 Slog.v(TAG, "Considering default browser match " + info); 7418 } 7419 defaultBrowserMatch = info; 7420 } 7421 } 7422 } 7423 if (defaultBrowserMatch != null 7424 && defaultBrowserMatch.priority >= maxMatchPrio 7425 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7426 { 7427 if (debug) { 7428 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7429 } 7430 result.add(defaultBrowserMatch); 7431 } else { 7432 result.addAll(matchAllList); 7433 } 7434 } 7435 7436 // If there is nothing selected, add all candidates and remove the ones that the user 7437 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7438 if (result.size() == 0) { 7439 result.addAll(candidates); 7440 result.removeAll(neverList); 7441 } 7442 } 7443 } 7444 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7445 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7446 result.size()); 7447 for (ResolveInfo info : result) { 7448 Slog.v(TAG, " + " + info.activityInfo); 7449 } 7450 } 7451 return result; 7452 } 7453 7454 // Returns a packed value as a long: 7455 // 7456 // high 'int'-sized word: link status: undefined/ask/never/always. 7457 // low 'int'-sized word: relative priority among 'always' results. 7458 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7459 long result = ps.getDomainVerificationStatusForUser(userId); 7460 // if none available, get the master status 7461 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7462 if (ps.getIntentFilterVerificationInfo() != null) { 7463 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7464 } 7465 } 7466 return result; 7467 } 7468 7469 private ResolveInfo querySkipCurrentProfileIntents( 7470 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7471 int flags, int sourceUserId) { 7472 if (matchingFilters != null) { 7473 int size = matchingFilters.size(); 7474 for (int i = 0; i < size; i ++) { 7475 CrossProfileIntentFilter filter = matchingFilters.get(i); 7476 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7477 // Checking if there are activities in the target user that can handle the 7478 // intent. 7479 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7480 resolvedType, flags, sourceUserId); 7481 if (resolveInfo != null) { 7482 return resolveInfo; 7483 } 7484 } 7485 } 7486 } 7487 return null; 7488 } 7489 7490 // Return matching ResolveInfo in target user if any. 7491 private ResolveInfo queryCrossProfileIntents( 7492 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7493 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7494 if (matchingFilters != null) { 7495 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7496 // match the same intent. For performance reasons, it is better not to 7497 // run queryIntent twice for the same userId 7498 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7499 int size = matchingFilters.size(); 7500 for (int i = 0; i < size; i++) { 7501 CrossProfileIntentFilter filter = matchingFilters.get(i); 7502 int targetUserId = filter.getTargetUserId(); 7503 boolean skipCurrentProfile = 7504 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7505 boolean skipCurrentProfileIfNoMatchFound = 7506 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7507 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7508 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7509 // Checking if there are activities in the target user that can handle the 7510 // intent. 7511 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7512 resolvedType, flags, sourceUserId); 7513 if (resolveInfo != null) return resolveInfo; 7514 alreadyTriedUserIds.put(targetUserId, true); 7515 } 7516 } 7517 } 7518 return null; 7519 } 7520 7521 /** 7522 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7523 * will forward the intent to the filter's target user. 7524 * Otherwise, returns null. 7525 */ 7526 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7527 String resolvedType, int flags, int sourceUserId) { 7528 int targetUserId = filter.getTargetUserId(); 7529 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7530 resolvedType, flags, targetUserId); 7531 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7532 // If all the matches in the target profile are suspended, return null. 7533 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7534 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7535 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7536 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7537 targetUserId); 7538 } 7539 } 7540 } 7541 return null; 7542 } 7543 7544 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7545 int sourceUserId, int targetUserId) { 7546 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7547 long ident = Binder.clearCallingIdentity(); 7548 boolean targetIsProfile; 7549 try { 7550 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7551 } finally { 7552 Binder.restoreCallingIdentity(ident); 7553 } 7554 String className; 7555 if (targetIsProfile) { 7556 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7557 } else { 7558 className = FORWARD_INTENT_TO_PARENT; 7559 } 7560 ComponentName forwardingActivityComponentName = new ComponentName( 7561 mAndroidApplication.packageName, className); 7562 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7563 sourceUserId); 7564 if (!targetIsProfile) { 7565 forwardingActivityInfo.showUserIcon = targetUserId; 7566 forwardingResolveInfo.noResourceId = true; 7567 } 7568 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7569 forwardingResolveInfo.priority = 0; 7570 forwardingResolveInfo.preferredOrder = 0; 7571 forwardingResolveInfo.match = 0; 7572 forwardingResolveInfo.isDefault = true; 7573 forwardingResolveInfo.filter = filter; 7574 forwardingResolveInfo.targetUserId = targetUserId; 7575 return forwardingResolveInfo; 7576 } 7577 7578 @Override 7579 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7580 Intent[] specifics, String[] specificTypes, Intent intent, 7581 String resolvedType, int flags, int userId) { 7582 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7583 specificTypes, intent, resolvedType, flags, userId)); 7584 } 7585 7586 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7587 Intent[] specifics, String[] specificTypes, Intent intent, 7588 String resolvedType, int flags, int userId) { 7589 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7590 final int callingUid = Binder.getCallingUid(); 7591 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7592 false /*includeInstantApps*/); 7593 enforceCrossUserPermission(callingUid, userId, 7594 false /*requireFullPermission*/, false /*checkShell*/, 7595 "query intent activity options"); 7596 final String resultsAction = intent.getAction(); 7597 7598 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7599 | PackageManager.GET_RESOLVED_FILTER, userId); 7600 7601 if (DEBUG_INTENT_MATCHING) { 7602 Log.v(TAG, "Query " + intent + ": " + results); 7603 } 7604 7605 int specificsPos = 0; 7606 int N; 7607 7608 // todo: note that the algorithm used here is O(N^2). This 7609 // isn't a problem in our current environment, but if we start running 7610 // into situations where we have more than 5 or 10 matches then this 7611 // should probably be changed to something smarter... 7612 7613 // First we go through and resolve each of the specific items 7614 // that were supplied, taking care of removing any corresponding 7615 // duplicate items in the generic resolve list. 7616 if (specifics != null) { 7617 for (int i=0; i<specifics.length; i++) { 7618 final Intent sintent = specifics[i]; 7619 if (sintent == null) { 7620 continue; 7621 } 7622 7623 if (DEBUG_INTENT_MATCHING) { 7624 Log.v(TAG, "Specific #" + i + ": " + sintent); 7625 } 7626 7627 String action = sintent.getAction(); 7628 if (resultsAction != null && resultsAction.equals(action)) { 7629 // If this action was explicitly requested, then don't 7630 // remove things that have it. 7631 action = null; 7632 } 7633 7634 ResolveInfo ri = null; 7635 ActivityInfo ai = null; 7636 7637 ComponentName comp = sintent.getComponent(); 7638 if (comp == null) { 7639 ri = resolveIntent( 7640 sintent, 7641 specificTypes != null ? specificTypes[i] : null, 7642 flags, userId); 7643 if (ri == null) { 7644 continue; 7645 } 7646 if (ri == mResolveInfo) { 7647 // ACK! Must do something better with this. 7648 } 7649 ai = ri.activityInfo; 7650 comp = new ComponentName(ai.applicationInfo.packageName, 7651 ai.name); 7652 } else { 7653 ai = getActivityInfo(comp, flags, userId); 7654 if (ai == null) { 7655 continue; 7656 } 7657 } 7658 7659 // Look for any generic query activities that are duplicates 7660 // of this specific one, and remove them from the results. 7661 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7662 N = results.size(); 7663 int j; 7664 for (j=specificsPos; j<N; j++) { 7665 ResolveInfo sri = results.get(j); 7666 if ((sri.activityInfo.name.equals(comp.getClassName()) 7667 && sri.activityInfo.applicationInfo.packageName.equals( 7668 comp.getPackageName())) 7669 || (action != null && sri.filter.matchAction(action))) { 7670 results.remove(j); 7671 if (DEBUG_INTENT_MATCHING) Log.v( 7672 TAG, "Removing duplicate item from " + j 7673 + " due to specific " + specificsPos); 7674 if (ri == null) { 7675 ri = sri; 7676 } 7677 j--; 7678 N--; 7679 } 7680 } 7681 7682 // Add this specific item to its proper place. 7683 if (ri == null) { 7684 ri = new ResolveInfo(); 7685 ri.activityInfo = ai; 7686 } 7687 results.add(specificsPos, ri); 7688 ri.specificIndex = i; 7689 specificsPos++; 7690 } 7691 } 7692 7693 // Now we go through the remaining generic results and remove any 7694 // duplicate actions that are found here. 7695 N = results.size(); 7696 for (int i=specificsPos; i<N-1; i++) { 7697 final ResolveInfo rii = results.get(i); 7698 if (rii.filter == null) { 7699 continue; 7700 } 7701 7702 // Iterate over all of the actions of this result's intent 7703 // filter... typically this should be just one. 7704 final Iterator<String> it = rii.filter.actionsIterator(); 7705 if (it == null) { 7706 continue; 7707 } 7708 while (it.hasNext()) { 7709 final String action = it.next(); 7710 if (resultsAction != null && resultsAction.equals(action)) { 7711 // If this action was explicitly requested, then don't 7712 // remove things that have it. 7713 continue; 7714 } 7715 for (int j=i+1; j<N; j++) { 7716 final ResolveInfo rij = results.get(j); 7717 if (rij.filter != null && rij.filter.hasAction(action)) { 7718 results.remove(j); 7719 if (DEBUG_INTENT_MATCHING) Log.v( 7720 TAG, "Removing duplicate item from " + j 7721 + " due to action " + action + " at " + i); 7722 j--; 7723 N--; 7724 } 7725 } 7726 } 7727 7728 // If the caller didn't request filter information, drop it now 7729 // so we don't have to marshall/unmarshall it. 7730 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7731 rii.filter = null; 7732 } 7733 } 7734 7735 // Filter out the caller activity if so requested. 7736 if (caller != null) { 7737 N = results.size(); 7738 for (int i=0; i<N; i++) { 7739 ActivityInfo ainfo = results.get(i).activityInfo; 7740 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7741 && caller.getClassName().equals(ainfo.name)) { 7742 results.remove(i); 7743 break; 7744 } 7745 } 7746 } 7747 7748 // If the caller didn't request filter information, 7749 // drop them now so we don't have to 7750 // marshall/unmarshall it. 7751 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7752 N = results.size(); 7753 for (int i=0; i<N; i++) { 7754 results.get(i).filter = null; 7755 } 7756 } 7757 7758 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7759 return results; 7760 } 7761 7762 @Override 7763 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7764 String resolvedType, int flags, int userId) { 7765 return new ParceledListSlice<>( 7766 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 7767 } 7768 7769 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7770 String resolvedType, int flags, int userId) { 7771 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7772 final int callingUid = Binder.getCallingUid(); 7773 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7774 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7775 false /*includeInstantApps*/); 7776 ComponentName comp = intent.getComponent(); 7777 if (comp == null) { 7778 if (intent.getSelector() != null) { 7779 intent = intent.getSelector(); 7780 comp = intent.getComponent(); 7781 } 7782 } 7783 if (comp != null) { 7784 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7785 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7786 if (ai != null) { 7787 // When specifying an explicit component, we prevent the activity from being 7788 // used when either 1) the calling package is normal and the activity is within 7789 // an instant application or 2) the calling package is ephemeral and the 7790 // activity is not visible to instant applications. 7791 final boolean matchInstantApp = 7792 (flags & PackageManager.MATCH_INSTANT) != 0; 7793 final boolean matchVisibleToInstantAppOnly = 7794 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7795 final boolean matchExplicitlyVisibleOnly = 7796 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7797 final boolean isCallerInstantApp = 7798 instantAppPkgName != null; 7799 final boolean isTargetSameInstantApp = 7800 comp.getPackageName().equals(instantAppPkgName); 7801 final boolean isTargetInstantApp = 7802 (ai.applicationInfo.privateFlags 7803 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7804 final boolean isTargetVisibleToInstantApp = 7805 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7806 final boolean isTargetExplicitlyVisibleToInstantApp = 7807 isTargetVisibleToInstantApp 7808 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7809 final boolean isTargetHiddenFromInstantApp = 7810 !isTargetVisibleToInstantApp 7811 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7812 final boolean blockResolution = 7813 !isTargetSameInstantApp 7814 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7815 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7816 && isTargetHiddenFromInstantApp)); 7817 if (!blockResolution) { 7818 ResolveInfo ri = new ResolveInfo(); 7819 ri.activityInfo = ai; 7820 list.add(ri); 7821 } 7822 } 7823 return applyPostResolutionFilter(list, instantAppPkgName); 7824 } 7825 7826 // reader 7827 synchronized (mPackages) { 7828 String pkgName = intent.getPackage(); 7829 if (pkgName == null) { 7830 final List<ResolveInfo> result = 7831 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7832 return applyPostResolutionFilter(result, instantAppPkgName); 7833 } 7834 final PackageParser.Package pkg = mPackages.get(pkgName); 7835 if (pkg != null) { 7836 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7837 intent, resolvedType, flags, pkg.receivers, userId); 7838 return applyPostResolutionFilter(result, instantAppPkgName); 7839 } 7840 return Collections.emptyList(); 7841 } 7842 } 7843 7844 @Override 7845 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7846 final int callingUid = Binder.getCallingUid(); 7847 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7848 } 7849 7850 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7851 int userId, int callingUid) { 7852 if (!sUserManager.exists(userId)) return null; 7853 flags = updateFlagsForResolve( 7854 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7855 List<ResolveInfo> query = queryIntentServicesInternal( 7856 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7857 if (query != null) { 7858 if (query.size() >= 1) { 7859 // If there is more than one service with the same priority, 7860 // just arbitrarily pick the first one. 7861 return query.get(0); 7862 } 7863 } 7864 return null; 7865 } 7866 7867 @Override 7868 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7869 String resolvedType, int flags, int userId) { 7870 final int callingUid = Binder.getCallingUid(); 7871 return new ParceledListSlice<>(queryIntentServicesInternal( 7872 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7873 } 7874 7875 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7876 String resolvedType, int flags, int userId, int callingUid, 7877 boolean includeInstantApps) { 7878 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7879 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7880 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7881 ComponentName comp = intent.getComponent(); 7882 if (comp == null) { 7883 if (intent.getSelector() != null) { 7884 intent = intent.getSelector(); 7885 comp = intent.getComponent(); 7886 } 7887 } 7888 if (comp != null) { 7889 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7890 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7891 if (si != null) { 7892 // When specifying an explicit component, we prevent the service from being 7893 // used when either 1) the service is in an instant application and the 7894 // caller is not the same instant application or 2) the calling package is 7895 // ephemeral and the activity is not visible to ephemeral applications. 7896 final boolean matchInstantApp = 7897 (flags & PackageManager.MATCH_INSTANT) != 0; 7898 final boolean matchVisibleToInstantAppOnly = 7899 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7900 final boolean isCallerInstantApp = 7901 instantAppPkgName != null; 7902 final boolean isTargetSameInstantApp = 7903 comp.getPackageName().equals(instantAppPkgName); 7904 final boolean isTargetInstantApp = 7905 (si.applicationInfo.privateFlags 7906 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7907 final boolean isTargetHiddenFromInstantApp = 7908 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7909 final boolean blockResolution = 7910 !isTargetSameInstantApp 7911 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7912 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7913 && isTargetHiddenFromInstantApp)); 7914 if (!blockResolution) { 7915 final ResolveInfo ri = new ResolveInfo(); 7916 ri.serviceInfo = si; 7917 list.add(ri); 7918 } 7919 } 7920 return list; 7921 } 7922 7923 // reader 7924 synchronized (mPackages) { 7925 String pkgName = intent.getPackage(); 7926 if (pkgName == null) { 7927 return applyPostServiceResolutionFilter( 7928 mServices.queryIntent(intent, resolvedType, flags, userId), 7929 instantAppPkgName); 7930 } 7931 final PackageParser.Package pkg = mPackages.get(pkgName); 7932 if (pkg != null) { 7933 return applyPostServiceResolutionFilter( 7934 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7935 userId), 7936 instantAppPkgName); 7937 } 7938 return Collections.emptyList(); 7939 } 7940 } 7941 7942 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7943 String instantAppPkgName) { 7944 // TODO: When adding on-demand split support for non-instant apps, remove this check 7945 // and always apply post filtering 7946 if (instantAppPkgName == null) { 7947 return resolveInfos; 7948 } 7949 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7950 final ResolveInfo info = resolveInfos.get(i); 7951 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7952 // allow services that are defined in the provided package 7953 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7954 if (info.serviceInfo.splitName != null 7955 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7956 info.serviceInfo.splitName)) { 7957 // requested service is defined in a split that hasn't been installed yet. 7958 // add the installer to the resolve list 7959 if (DEBUG_EPHEMERAL) { 7960 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7961 } 7962 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7963 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7964 info.serviceInfo.packageName, info.serviceInfo.splitName, 7965 info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/); 7966 // make sure this resolver is the default 7967 installerInfo.isDefault = true; 7968 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7969 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7970 // add a non-generic filter 7971 installerInfo.filter = new IntentFilter(); 7972 // load resources from the correct package 7973 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7974 resolveInfos.set(i, installerInfo); 7975 } 7976 continue; 7977 } 7978 // allow services that have been explicitly exposed to ephemeral apps 7979 if (!isEphemeralApp 7980 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7981 continue; 7982 } 7983 resolveInfos.remove(i); 7984 } 7985 return resolveInfos; 7986 } 7987 7988 @Override 7989 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7990 String resolvedType, int flags, int userId) { 7991 return new ParceledListSlice<>( 7992 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7993 } 7994 7995 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7996 Intent intent, String resolvedType, int flags, int userId) { 7997 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7998 final int callingUid = Binder.getCallingUid(); 7999 final String instantAppPkgName = getInstantAppPackageName(callingUid); 8000 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 8001 false /*includeInstantApps*/); 8002 ComponentName comp = intent.getComponent(); 8003 if (comp == null) { 8004 if (intent.getSelector() != null) { 8005 intent = intent.getSelector(); 8006 comp = intent.getComponent(); 8007 } 8008 } 8009 if (comp != null) { 8010 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 8011 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 8012 if (pi != null) { 8013 // When specifying an explicit component, we prevent the provider from being 8014 // used when either 1) the provider is in an instant application and the 8015 // caller is not the same instant application or 2) the calling package is an 8016 // instant application and the provider is not visible to instant applications. 8017 final boolean matchInstantApp = 8018 (flags & PackageManager.MATCH_INSTANT) != 0; 8019 final boolean matchVisibleToInstantAppOnly = 8020 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 8021 final boolean isCallerInstantApp = 8022 instantAppPkgName != null; 8023 final boolean isTargetSameInstantApp = 8024 comp.getPackageName().equals(instantAppPkgName); 8025 final boolean isTargetInstantApp = 8026 (pi.applicationInfo.privateFlags 8027 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 8028 final boolean isTargetHiddenFromInstantApp = 8029 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 8030 final boolean blockResolution = 8031 !isTargetSameInstantApp 8032 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 8033 || (matchVisibleToInstantAppOnly && isCallerInstantApp 8034 && isTargetHiddenFromInstantApp)); 8035 if (!blockResolution) { 8036 final ResolveInfo ri = new ResolveInfo(); 8037 ri.providerInfo = pi; 8038 list.add(ri); 8039 } 8040 } 8041 return list; 8042 } 8043 8044 // reader 8045 synchronized (mPackages) { 8046 String pkgName = intent.getPackage(); 8047 if (pkgName == null) { 8048 return applyPostContentProviderResolutionFilter( 8049 mProviders.queryIntent(intent, resolvedType, flags, userId), 8050 instantAppPkgName); 8051 } 8052 final PackageParser.Package pkg = mPackages.get(pkgName); 8053 if (pkg != null) { 8054 return applyPostContentProviderResolutionFilter( 8055 mProviders.queryIntentForPackage( 8056 intent, resolvedType, flags, pkg.providers, userId), 8057 instantAppPkgName); 8058 } 8059 return Collections.emptyList(); 8060 } 8061 } 8062 8063 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 8064 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 8065 // TODO: When adding on-demand split support for non-instant applications, remove 8066 // this check and always apply post filtering 8067 if (instantAppPkgName == null) { 8068 return resolveInfos; 8069 } 8070 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 8071 final ResolveInfo info = resolveInfos.get(i); 8072 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 8073 // allow providers that are defined in the provided package 8074 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 8075 if (info.providerInfo.splitName != null 8076 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 8077 info.providerInfo.splitName)) { 8078 // requested provider is defined in a split that hasn't been installed yet. 8079 // add the installer to the resolve list 8080 if (DEBUG_EPHEMERAL) { 8081 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 8082 } 8083 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 8084 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 8085 info.providerInfo.packageName, info.providerInfo.splitName, 8086 info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/); 8087 // make sure this resolver is the default 8088 installerInfo.isDefault = true; 8089 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 8090 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 8091 // add a non-generic filter 8092 installerInfo.filter = new IntentFilter(); 8093 // load resources from the correct package 8094 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 8095 resolveInfos.set(i, installerInfo); 8096 } 8097 continue; 8098 } 8099 // allow providers that have been explicitly exposed to instant applications 8100 if (!isEphemeralApp 8101 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 8102 continue; 8103 } 8104 resolveInfos.remove(i); 8105 } 8106 return resolveInfos; 8107 } 8108 8109 @Override 8110 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 8111 final int callingUid = Binder.getCallingUid(); 8112 if (getInstantAppPackageName(callingUid) != null) { 8113 return ParceledListSlice.emptyList(); 8114 } 8115 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8116 flags = updateFlagsForPackage(flags, userId, null); 8117 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8118 enforceCrossUserPermission(callingUid, userId, 8119 true /* requireFullPermission */, false /* checkShell */, 8120 "get installed packages"); 8121 8122 // writer 8123 synchronized (mPackages) { 8124 ArrayList<PackageInfo> list; 8125 if (listUninstalled) { 8126 list = new ArrayList<>(mSettings.mPackages.size()); 8127 for (PackageSetting ps : mSettings.mPackages.values()) { 8128 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 8129 continue; 8130 } 8131 if (filterAppAccessLPr(ps, callingUid, userId)) { 8132 return null; 8133 } 8134 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 8135 if (pi != null) { 8136 list.add(pi); 8137 } 8138 } 8139 } else { 8140 list = new ArrayList<>(mPackages.size()); 8141 for (PackageParser.Package p : mPackages.values()) { 8142 final PackageSetting ps = (PackageSetting) p.mExtras; 8143 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 8144 continue; 8145 } 8146 if (filterAppAccessLPr(ps, callingUid, userId)) { 8147 return null; 8148 } 8149 final PackageInfo pi = generatePackageInfo((PackageSetting) 8150 p.mExtras, flags, userId); 8151 if (pi != null) { 8152 list.add(pi); 8153 } 8154 } 8155 } 8156 8157 return new ParceledListSlice<>(list); 8158 } 8159 } 8160 8161 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 8162 String[] permissions, boolean[] tmp, int flags, int userId) { 8163 int numMatch = 0; 8164 final PermissionsState permissionsState = ps.getPermissionsState(); 8165 for (int i=0; i<permissions.length; i++) { 8166 final String permission = permissions[i]; 8167 if (permissionsState.hasPermission(permission, userId)) { 8168 tmp[i] = true; 8169 numMatch++; 8170 } else { 8171 tmp[i] = false; 8172 } 8173 } 8174 if (numMatch == 0) { 8175 return; 8176 } 8177 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 8178 8179 // The above might return null in cases of uninstalled apps or install-state 8180 // skew across users/profiles. 8181 if (pi != null) { 8182 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 8183 if (numMatch == permissions.length) { 8184 pi.requestedPermissions = permissions; 8185 } else { 8186 pi.requestedPermissions = new String[numMatch]; 8187 numMatch = 0; 8188 for (int i=0; i<permissions.length; i++) { 8189 if (tmp[i]) { 8190 pi.requestedPermissions[numMatch] = permissions[i]; 8191 numMatch++; 8192 } 8193 } 8194 } 8195 } 8196 list.add(pi); 8197 } 8198 } 8199 8200 @Override 8201 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 8202 String[] permissions, int flags, int userId) { 8203 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8204 flags = updateFlagsForPackage(flags, userId, permissions); 8205 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8206 true /* requireFullPermission */, false /* checkShell */, 8207 "get packages holding permissions"); 8208 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8209 8210 // writer 8211 synchronized (mPackages) { 8212 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 8213 boolean[] tmpBools = new boolean[permissions.length]; 8214 if (listUninstalled) { 8215 for (PackageSetting ps : mSettings.mPackages.values()) { 8216 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 8217 userId); 8218 } 8219 } else { 8220 for (PackageParser.Package pkg : mPackages.values()) { 8221 PackageSetting ps = (PackageSetting)pkg.mExtras; 8222 if (ps != null) { 8223 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 8224 userId); 8225 } 8226 } 8227 } 8228 8229 return new ParceledListSlice<PackageInfo>(list); 8230 } 8231 } 8232 8233 @Override 8234 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 8235 final int callingUid = Binder.getCallingUid(); 8236 if (getInstantAppPackageName(callingUid) != null) { 8237 return ParceledListSlice.emptyList(); 8238 } 8239 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8240 flags = updateFlagsForApplication(flags, userId, null); 8241 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8242 8243 // writer 8244 synchronized (mPackages) { 8245 ArrayList<ApplicationInfo> list; 8246 if (listUninstalled) { 8247 list = new ArrayList<>(mSettings.mPackages.size()); 8248 for (PackageSetting ps : mSettings.mPackages.values()) { 8249 ApplicationInfo ai; 8250 int effectiveFlags = flags; 8251 if (ps.isSystem()) { 8252 effectiveFlags |= PackageManager.MATCH_ANY_USER; 8253 } 8254 if (ps.pkg != null) { 8255 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 8256 continue; 8257 } 8258 if (filterAppAccessLPr(ps, callingUid, userId)) { 8259 return null; 8260 } 8261 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 8262 ps.readUserState(userId), userId); 8263 if (ai != null) { 8264 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 8265 } 8266 } else { 8267 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 8268 // and already converts to externally visible package name 8269 ai = generateApplicationInfoFromSettingsLPw(ps.name, 8270 callingUid, effectiveFlags, userId); 8271 } 8272 if (ai != null) { 8273 list.add(ai); 8274 } 8275 } 8276 } else { 8277 list = new ArrayList<>(mPackages.size()); 8278 for (PackageParser.Package p : mPackages.values()) { 8279 if (p.mExtras != null) { 8280 PackageSetting ps = (PackageSetting) p.mExtras; 8281 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 8282 continue; 8283 } 8284 if (filterAppAccessLPr(ps, callingUid, userId)) { 8285 return null; 8286 } 8287 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8288 ps.readUserState(userId), userId); 8289 if (ai != null) { 8290 ai.packageName = resolveExternalPackageNameLPr(p); 8291 list.add(ai); 8292 } 8293 } 8294 } 8295 } 8296 8297 return new ParceledListSlice<>(list); 8298 } 8299 } 8300 8301 @Override 8302 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 8303 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8304 return null; 8305 } 8306 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8307 "getEphemeralApplications"); 8308 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8309 true /* requireFullPermission */, false /* checkShell */, 8310 "getEphemeralApplications"); 8311 synchronized (mPackages) { 8312 List<InstantAppInfo> instantApps = mInstantAppRegistry 8313 .getInstantAppsLPr(userId); 8314 if (instantApps != null) { 8315 return new ParceledListSlice<>(instantApps); 8316 } 8317 } 8318 return null; 8319 } 8320 8321 @Override 8322 public boolean isInstantApp(String packageName, int userId) { 8323 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8324 true /* requireFullPermission */, false /* checkShell */, 8325 "isInstantApp"); 8326 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8327 return false; 8328 } 8329 int callingUid = Binder.getCallingUid(); 8330 if (Process.isIsolated(callingUid)) { 8331 callingUid = mIsolatedOwners.get(callingUid); 8332 } 8333 8334 synchronized (mPackages) { 8335 final PackageSetting ps = mSettings.mPackages.get(packageName); 8336 PackageParser.Package pkg = mPackages.get(packageName); 8337 final boolean returnAllowed = 8338 ps != null 8339 && (isCallerSameApp(packageName, callingUid) 8340 || canViewInstantApps(callingUid, userId) 8341 || mInstantAppRegistry.isInstantAccessGranted( 8342 userId, UserHandle.getAppId(callingUid), ps.appId)); 8343 if (returnAllowed) { 8344 return ps.getInstantApp(userId); 8345 } 8346 } 8347 return false; 8348 } 8349 8350 @Override 8351 public byte[] getInstantAppCookie(String packageName, int userId) { 8352 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8353 return null; 8354 } 8355 8356 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8357 true /* requireFullPermission */, false /* checkShell */, 8358 "getInstantAppCookie"); 8359 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8360 return null; 8361 } 8362 synchronized (mPackages) { 8363 return mInstantAppRegistry.getInstantAppCookieLPw( 8364 packageName, userId); 8365 } 8366 } 8367 8368 @Override 8369 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 8370 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8371 return true; 8372 } 8373 8374 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8375 true /* requireFullPermission */, true /* checkShell */, 8376 "setInstantAppCookie"); 8377 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8378 return false; 8379 } 8380 synchronized (mPackages) { 8381 return mInstantAppRegistry.setInstantAppCookieLPw( 8382 packageName, cookie, userId); 8383 } 8384 } 8385 8386 @Override 8387 public Bitmap getInstantAppIcon(String packageName, int userId) { 8388 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8389 return null; 8390 } 8391 8392 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8393 "getInstantAppIcon"); 8394 8395 enforceCrossUserPermission(Binder.getCallingUid(), userId, 8396 true /* requireFullPermission */, false /* checkShell */, 8397 "getInstantAppIcon"); 8398 8399 synchronized (mPackages) { 8400 return mInstantAppRegistry.getInstantAppIconLPw( 8401 packageName, userId); 8402 } 8403 } 8404 8405 private boolean isCallerSameApp(String packageName, int uid) { 8406 PackageParser.Package pkg = mPackages.get(packageName); 8407 return pkg != null 8408 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8409 } 8410 8411 @Override 8412 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8413 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8414 return ParceledListSlice.emptyList(); 8415 } 8416 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8417 } 8418 8419 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8420 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 8421 8422 // reader 8423 synchronized (mPackages) { 8424 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8425 final int userId = UserHandle.getCallingUserId(); 8426 while (i.hasNext()) { 8427 final PackageParser.Package p = i.next(); 8428 if (p.applicationInfo == null) continue; 8429 8430 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8431 && !p.applicationInfo.isDirectBootAware(); 8432 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8433 && p.applicationInfo.isDirectBootAware(); 8434 8435 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8436 && (!mSafeMode || isSystemApp(p)) 8437 && (matchesUnaware || matchesAware)) { 8438 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8439 if (ps != null) { 8440 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8441 ps.readUserState(userId), userId); 8442 if (ai != null) { 8443 finalList.add(ai); 8444 } 8445 } 8446 } 8447 } 8448 } 8449 8450 return finalList; 8451 } 8452 8453 @Override 8454 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8455 if (!sUserManager.exists(userId)) return null; 8456 flags = updateFlagsForComponent(flags, userId, name); 8457 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 8458 // reader 8459 synchronized (mPackages) { 8460 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8461 PackageSetting ps = provider != null 8462 ? mSettings.mPackages.get(provider.owner.packageName) 8463 : null; 8464 if (ps != null) { 8465 final boolean isInstantApp = ps.getInstantApp(userId); 8466 // normal application; filter out instant application provider 8467 if (instantAppPkgName == null && isInstantApp) { 8468 return null; 8469 } 8470 // instant application; filter out other instant applications 8471 if (instantAppPkgName != null 8472 && isInstantApp 8473 && !provider.owner.packageName.equals(instantAppPkgName)) { 8474 return null; 8475 } 8476 // instant application; filter out non-exposed provider 8477 if (instantAppPkgName != null 8478 && !isInstantApp 8479 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 8480 return null; 8481 } 8482 // provider not enabled 8483 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8484 return null; 8485 } 8486 return PackageParser.generateProviderInfo( 8487 provider, flags, ps.readUserState(userId), userId); 8488 } 8489 return null; 8490 } 8491 } 8492 8493 /** 8494 * @deprecated 8495 */ 8496 @Deprecated 8497 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8498 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8499 return; 8500 } 8501 // reader 8502 synchronized (mPackages) { 8503 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8504 .entrySet().iterator(); 8505 final int userId = UserHandle.getCallingUserId(); 8506 while (i.hasNext()) { 8507 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8508 PackageParser.Provider p = entry.getValue(); 8509 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8510 8511 if (ps != null && p.syncable 8512 && (!mSafeMode || (p.info.applicationInfo.flags 8513 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8514 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8515 ps.readUserState(userId), userId); 8516 if (info != null) { 8517 outNames.add(entry.getKey()); 8518 outInfo.add(info); 8519 } 8520 } 8521 } 8522 } 8523 } 8524 8525 @Override 8526 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8527 int uid, int flags, String metaDataKey) { 8528 final int callingUid = Binder.getCallingUid(); 8529 final int userId = processName != null ? UserHandle.getUserId(uid) 8530 : UserHandle.getCallingUserId(); 8531 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8532 flags = updateFlagsForComponent(flags, userId, processName); 8533 ArrayList<ProviderInfo> finalList = null; 8534 // reader 8535 synchronized (mPackages) { 8536 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8537 while (i.hasNext()) { 8538 final PackageParser.Provider p = i.next(); 8539 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8540 if (ps != null && p.info.authority != null 8541 && (processName == null 8542 || (p.info.processName.equals(processName) 8543 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8544 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8545 8546 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8547 // parameter. 8548 if (metaDataKey != null 8549 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8550 continue; 8551 } 8552 final ComponentName component = 8553 new ComponentName(p.info.packageName, p.info.name); 8554 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8555 continue; 8556 } 8557 if (finalList == null) { 8558 finalList = new ArrayList<ProviderInfo>(3); 8559 } 8560 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8561 ps.readUserState(userId), userId); 8562 if (info != null) { 8563 finalList.add(info); 8564 } 8565 } 8566 } 8567 } 8568 8569 if (finalList != null) { 8570 Collections.sort(finalList, mProviderInitOrderSorter); 8571 return new ParceledListSlice<ProviderInfo>(finalList); 8572 } 8573 8574 return ParceledListSlice.emptyList(); 8575 } 8576 8577 @Override 8578 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8579 // reader 8580 synchronized (mPackages) { 8581 final int callingUid = Binder.getCallingUid(); 8582 final int callingUserId = UserHandle.getUserId(callingUid); 8583 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8584 if (ps == null) return null; 8585 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8586 return null; 8587 } 8588 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8589 return PackageParser.generateInstrumentationInfo(i, flags); 8590 } 8591 } 8592 8593 @Override 8594 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8595 String targetPackage, int flags) { 8596 final int callingUid = Binder.getCallingUid(); 8597 final int callingUserId = UserHandle.getUserId(callingUid); 8598 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8599 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8600 return ParceledListSlice.emptyList(); 8601 } 8602 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8603 } 8604 8605 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8606 int flags) { 8607 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8608 8609 // reader 8610 synchronized (mPackages) { 8611 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8612 while (i.hasNext()) { 8613 final PackageParser.Instrumentation p = i.next(); 8614 if (targetPackage == null 8615 || targetPackage.equals(p.info.targetPackage)) { 8616 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8617 flags); 8618 if (ii != null) { 8619 finalList.add(ii); 8620 } 8621 } 8622 } 8623 } 8624 8625 return finalList; 8626 } 8627 8628 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 8629 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 8630 try { 8631 scanDirLI(dir, parseFlags, scanFlags, currentTime); 8632 } finally { 8633 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8634 } 8635 } 8636 8637 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 8638 final File[] files = dir.listFiles(); 8639 if (ArrayUtils.isEmpty(files)) { 8640 Log.d(TAG, "No files in app dir " + dir); 8641 return; 8642 } 8643 8644 if (DEBUG_PACKAGE_SCANNING) { 8645 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 8646 + " flags=0x" + Integer.toHexString(parseFlags)); 8647 } 8648 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8649 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8650 mParallelPackageParserCallback); 8651 8652 // Submit files for parsing in parallel 8653 int fileCount = 0; 8654 for (File file : files) { 8655 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8656 && !PackageInstallerService.isStageName(file.getName()); 8657 if (!isPackage) { 8658 // Ignore entries which are not packages 8659 continue; 8660 } 8661 parallelPackageParser.submit(file, parseFlags); 8662 fileCount++; 8663 } 8664 8665 // Process results one by one 8666 for (; fileCount > 0; fileCount--) { 8667 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8668 Throwable throwable = parseResult.throwable; 8669 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8670 8671 if (throwable == null) { 8672 // Static shared libraries have synthetic package names 8673 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8674 renameStaticSharedLibraryPackage(parseResult.pkg); 8675 } 8676 try { 8677 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8678 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 8679 currentTime, null); 8680 } 8681 } catch (PackageManagerException e) { 8682 errorCode = e.error; 8683 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8684 } 8685 } else if (throwable instanceof PackageParser.PackageParserException) { 8686 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8687 throwable; 8688 errorCode = e.error; 8689 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8690 } else { 8691 throw new IllegalStateException("Unexpected exception occurred while parsing " 8692 + parseResult.scanFile, throwable); 8693 } 8694 8695 // Delete invalid userdata apps 8696 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 8697 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8698 logCriticalInfo(Log.WARN, 8699 "Deleting invalid package at " + parseResult.scanFile); 8700 removeCodePathLI(parseResult.scanFile); 8701 } 8702 } 8703 parallelPackageParser.close(); 8704 } 8705 8706 private static File getSettingsProblemFile() { 8707 File dataDir = Environment.getDataDirectory(); 8708 File systemDir = new File(dataDir, "system"); 8709 File fname = new File(systemDir, "uiderrors.txt"); 8710 return fname; 8711 } 8712 8713 static void reportSettingsProblem(int priority, String msg) { 8714 logCriticalInfo(priority, msg); 8715 } 8716 8717 public static void logCriticalInfo(int priority, String msg) { 8718 Slog.println(priority, TAG, msg); 8719 EventLogTags.writePmCriticalInfo(msg); 8720 try { 8721 File fname = getSettingsProblemFile(); 8722 FileOutputStream out = new FileOutputStream(fname, true); 8723 PrintWriter pw = new FastPrintWriter(out); 8724 SimpleDateFormat formatter = new SimpleDateFormat(); 8725 String dateString = formatter.format(new Date(System.currentTimeMillis())); 8726 pw.println(dateString + ": " + msg); 8727 pw.close(); 8728 FileUtils.setPermissions( 8729 fname.toString(), 8730 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 8731 -1, -1); 8732 } catch (java.io.IOException e) { 8733 } 8734 } 8735 8736 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 8737 if (srcFile.isDirectory()) { 8738 final File baseFile = new File(pkg.baseCodePath); 8739 long maxModifiedTime = baseFile.lastModified(); 8740 if (pkg.splitCodePaths != null) { 8741 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 8742 final File splitFile = new File(pkg.splitCodePaths[i]); 8743 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 8744 } 8745 } 8746 return maxModifiedTime; 8747 } 8748 return srcFile.lastModified(); 8749 } 8750 8751 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 8752 final int policyFlags) throws PackageManagerException { 8753 // When upgrading from pre-N MR1, verify the package time stamp using the package 8754 // directory and not the APK file. 8755 final long lastModifiedTime = mIsPreNMR1Upgrade 8756 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 8757 if (ps != null 8758 && ps.codePath.equals(srcFile) 8759 && ps.timeStamp == lastModifiedTime 8760 && !isCompatSignatureUpdateNeeded(pkg) 8761 && !isRecoverSignatureUpdateNeeded(pkg)) { 8762 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 8763 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8764 ArraySet<PublicKey> signingKs; 8765 synchronized (mPackages) { 8766 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 8767 } 8768 if (ps.signatures.mSignatures != null 8769 && ps.signatures.mSignatures.length != 0 8770 && signingKs != null) { 8771 // Optimization: reuse the existing cached certificates 8772 // if the package appears to be unchanged. 8773 pkg.mSignatures = ps.signatures.mSignatures; 8774 pkg.mSigningKeys = signingKs; 8775 return; 8776 } 8777 8778 Slog.w(TAG, "PackageSetting for " + ps.name 8779 + " is missing signatures. Collecting certs again to recover them."); 8780 } else { 8781 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 8782 } 8783 8784 try { 8785 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8786 PackageParser.collectCertificates(pkg, policyFlags); 8787 } catch (PackageParserException e) { 8788 throw PackageManagerException.from(e); 8789 } finally { 8790 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8791 } 8792 } 8793 8794 /** 8795 * Traces a package scan. 8796 * @see #scanPackageLI(File, int, int, long, UserHandle) 8797 */ 8798 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8799 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8800 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8801 try { 8802 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8803 } finally { 8804 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8805 } 8806 } 8807 8808 /** 8809 * Scans a package and returns the newly parsed package. 8810 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8811 */ 8812 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8813 long currentTime, UserHandle user) throws PackageManagerException { 8814 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8815 PackageParser pp = new PackageParser(); 8816 pp.setSeparateProcesses(mSeparateProcesses); 8817 pp.setOnlyCoreApps(mOnlyCore); 8818 pp.setDisplayMetrics(mMetrics); 8819 pp.setCallback(mPackageParserCallback); 8820 8821 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 8822 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 8823 } 8824 8825 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8826 final PackageParser.Package pkg; 8827 try { 8828 pkg = pp.parsePackage(scanFile, parseFlags); 8829 } catch (PackageParserException e) { 8830 throw PackageManagerException.from(e); 8831 } finally { 8832 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8833 } 8834 8835 // Static shared libraries have synthetic package names 8836 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8837 renameStaticSharedLibraryPackage(pkg); 8838 } 8839 8840 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 8841 } 8842 8843 /** 8844 * Scans a package and returns the newly parsed package. 8845 * @throws PackageManagerException on a parse error. 8846 */ 8847 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 8848 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8849 throws PackageManagerException { 8850 // If the package has children and this is the first dive in the function 8851 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8852 // packages (parent and children) would be successfully scanned before the 8853 // actual scan since scanning mutates internal state and we want to atomically 8854 // install the package and its children. 8855 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8856 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8857 scanFlags |= SCAN_CHECK_ONLY; 8858 } 8859 } else { 8860 scanFlags &= ~SCAN_CHECK_ONLY; 8861 } 8862 8863 // Scan the parent 8864 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 8865 scanFlags, currentTime, user); 8866 8867 // Scan the children 8868 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8869 for (int i = 0; i < childCount; i++) { 8870 PackageParser.Package childPackage = pkg.childPackages.get(i); 8871 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 8872 currentTime, user); 8873 } 8874 8875 8876 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8877 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 8878 } 8879 8880 return scannedPkg; 8881 } 8882 8883 /** 8884 * Scans a package and returns the newly parsed package. 8885 * @throws PackageManagerException on a parse error. 8886 */ 8887 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 8888 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8889 throws PackageManagerException { 8890 PackageSetting ps = null; 8891 PackageSetting updatedPkg; 8892 // reader 8893 synchronized (mPackages) { 8894 // Look to see if we already know about this package. 8895 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 8896 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 8897 // This package has been renamed to its original name. Let's 8898 // use that. 8899 ps = mSettings.getPackageLPr(oldName); 8900 } 8901 // If there was no original package, see one for the real package name. 8902 if (ps == null) { 8903 ps = mSettings.getPackageLPr(pkg.packageName); 8904 } 8905 // Check to see if this package could be hiding/updating a system 8906 // package. Must look for it either under the original or real 8907 // package name depending on our state. 8908 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 8909 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 8910 8911 // If this is a package we don't know about on the system partition, we 8912 // may need to remove disabled child packages on the system partition 8913 // or may need to not add child packages if the parent apk is updated 8914 // on the data partition and no longer defines this child package. 8915 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8916 // If this is a parent package for an updated system app and this system 8917 // app got an OTA update which no longer defines some of the child packages 8918 // we have to prune them from the disabled system packages. 8919 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8920 if (disabledPs != null) { 8921 final int scannedChildCount = (pkg.childPackages != null) 8922 ? pkg.childPackages.size() : 0; 8923 final int disabledChildCount = disabledPs.childPackageNames != null 8924 ? disabledPs.childPackageNames.size() : 0; 8925 for (int i = 0; i < disabledChildCount; i++) { 8926 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 8927 boolean disabledPackageAvailable = false; 8928 for (int j = 0; j < scannedChildCount; j++) { 8929 PackageParser.Package childPkg = pkg.childPackages.get(j); 8930 if (childPkg.packageName.equals(disabledChildPackageName)) { 8931 disabledPackageAvailable = true; 8932 break; 8933 } 8934 } 8935 if (!disabledPackageAvailable) { 8936 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8937 } 8938 } 8939 } 8940 } 8941 } 8942 8943 boolean updatedPkgBetter = false; 8944 // First check if this is a system package that may involve an update 8945 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8946 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 8947 // it needs to drop FLAG_PRIVILEGED. 8948 if (locationIsPrivileged(scanFile)) { 8949 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8950 } else { 8951 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8952 } 8953 8954 if (ps != null && !ps.codePath.equals(scanFile)) { 8955 // The path has changed from what was last scanned... check the 8956 // version of the new path against what we have stored to determine 8957 // what to do. 8958 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 8959 if (pkg.mVersionCode <= ps.versionCode) { 8960 // The system package has been updated and the code path does not match 8961 // Ignore entry. Skip it. 8962 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 8963 + " ignored: updated version " + ps.versionCode 8964 + " better than this " + pkg.mVersionCode); 8965 if (!updatedPkg.codePath.equals(scanFile)) { 8966 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 8967 + ps.name + " changing from " + updatedPkg.codePathString 8968 + " to " + scanFile); 8969 updatedPkg.codePath = scanFile; 8970 updatedPkg.codePathString = scanFile.toString(); 8971 updatedPkg.resourcePath = scanFile; 8972 updatedPkg.resourcePathString = scanFile.toString(); 8973 } 8974 updatedPkg.pkg = pkg; 8975 updatedPkg.versionCode = pkg.mVersionCode; 8976 8977 // Update the disabled system child packages to point to the package too. 8978 final int childCount = updatedPkg.childPackageNames != null 8979 ? updatedPkg.childPackageNames.size() : 0; 8980 for (int i = 0; i < childCount; i++) { 8981 String childPackageName = updatedPkg.childPackageNames.get(i); 8982 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8983 childPackageName); 8984 if (updatedChildPkg != null) { 8985 updatedChildPkg.pkg = pkg; 8986 updatedChildPkg.versionCode = pkg.mVersionCode; 8987 } 8988 } 8989 8990 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 8991 + scanFile + " ignored: updated version " + ps.versionCode 8992 + " better than this " + pkg.mVersionCode); 8993 } else { 8994 // The current app on the system partition is better than 8995 // what we have updated to on the data partition; switch 8996 // back to the system partition version. 8997 // At this point, its safely assumed that package installation for 8998 // apps in system partition will go through. If not there won't be a working 8999 // version of the app 9000 // writer 9001 synchronized (mPackages) { 9002 // Just remove the loaded entries from package lists. 9003 mPackages.remove(ps.name); 9004 } 9005 9006 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 9007 + " reverting from " + ps.codePathString 9008 + ": new version " + pkg.mVersionCode 9009 + " better than installed " + ps.versionCode); 9010 9011 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 9012 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 9013 synchronized (mInstallLock) { 9014 args.cleanUpResourcesLI(); 9015 } 9016 synchronized (mPackages) { 9017 mSettings.enableSystemPackageLPw(ps.name); 9018 } 9019 updatedPkgBetter = true; 9020 } 9021 } 9022 } 9023 9024 if (updatedPkg != null) { 9025 // An updated system app will not have the PARSE_IS_SYSTEM flag set 9026 // initially 9027 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 9028 9029 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 9030 // flag set initially 9031 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 9032 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9033 } 9034 } 9035 9036 // Verify certificates against what was last scanned 9037 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 9038 9039 /* 9040 * A new system app appeared, but we already had a non-system one of the 9041 * same name installed earlier. 9042 */ 9043 boolean shouldHideSystemApp = false; 9044 if (updatedPkg == null && ps != null 9045 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 9046 /* 9047 * Check to make sure the signatures match first. If they don't, 9048 * wipe the installed application and its data. 9049 */ 9050 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 9051 != PackageManager.SIGNATURE_MATCH) { 9052 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 9053 + " signatures don't match existing userdata copy; removing"); 9054 try (PackageFreezer freezer = freezePackage(pkg.packageName, 9055 "scanPackageInternalLI")) { 9056 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 9057 } 9058 ps = null; 9059 } else { 9060 /* 9061 * If the newly-added system app is an older version than the 9062 * already installed version, hide it. It will be scanned later 9063 * and re-added like an update. 9064 */ 9065 if (pkg.mVersionCode <= ps.versionCode) { 9066 shouldHideSystemApp = true; 9067 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 9068 + " but new version " + pkg.mVersionCode + " better than installed " 9069 + ps.versionCode + "; hiding system"); 9070 } else { 9071 /* 9072 * The newly found system app is a newer version that the 9073 * one previously installed. Simply remove the 9074 * already-installed application and replace it with our own 9075 * while keeping the application data. 9076 */ 9077 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 9078 + " reverting from " + ps.codePathString + ": new version " 9079 + pkg.mVersionCode + " better than installed " + ps.versionCode); 9080 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 9081 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 9082 synchronized (mInstallLock) { 9083 args.cleanUpResourcesLI(); 9084 } 9085 } 9086 } 9087 } 9088 9089 // The apk is forward locked (not public) if its code and resources 9090 // are kept in different files. (except for app in either system or 9091 // vendor path). 9092 // TODO grab this value from PackageSettings 9093 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9094 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 9095 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 9096 } 9097 } 9098 9099 // TODO: extend to support forward-locked splits 9100 String resourcePath = null; 9101 String baseResourcePath = null; 9102 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 9103 if (ps != null && ps.resourcePathString != null) { 9104 resourcePath = ps.resourcePathString; 9105 baseResourcePath = ps.resourcePathString; 9106 } else { 9107 // Should not happen at all. Just log an error. 9108 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 9109 } 9110 } else { 9111 resourcePath = pkg.codePath; 9112 baseResourcePath = pkg.baseCodePath; 9113 } 9114 9115 // Set application objects path explicitly. 9116 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 9117 pkg.setApplicationInfoCodePath(pkg.codePath); 9118 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 9119 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 9120 pkg.setApplicationInfoResourcePath(resourcePath); 9121 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 9122 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 9123 9124 final int userId = ((user == null) ? 0 : user.getIdentifier()); 9125 if (ps != null && ps.getInstantApp(userId)) { 9126 scanFlags |= SCAN_AS_INSTANT_APP; 9127 } 9128 9129 // Note that we invoke the following method only if we are about to unpack an application 9130 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 9131 | SCAN_UPDATE_SIGNATURE, currentTime, user); 9132 9133 /* 9134 * If the system app should be overridden by a previously installed 9135 * data, hide the system app now and let the /data/app scan pick it up 9136 * again. 9137 */ 9138 if (shouldHideSystemApp) { 9139 synchronized (mPackages) { 9140 mSettings.disableSystemPackageLPw(pkg.packageName, true); 9141 } 9142 } 9143 9144 return scannedPkg; 9145 } 9146 9147 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 9148 // Derive the new package synthetic package name 9149 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 9150 + pkg.staticSharedLibVersion); 9151 } 9152 9153 private static String fixProcessName(String defProcessName, 9154 String processName) { 9155 if (processName == null) { 9156 return defProcessName; 9157 } 9158 return processName; 9159 } 9160 9161 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 9162 throws PackageManagerException { 9163 if (pkgSetting.signatures.mSignatures != null) { 9164 // Already existing package. Make sure signatures match 9165 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 9166 == PackageManager.SIGNATURE_MATCH; 9167 if (!match) { 9168 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 9169 == PackageManager.SIGNATURE_MATCH; 9170 } 9171 if (!match) { 9172 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 9173 == PackageManager.SIGNATURE_MATCH; 9174 } 9175 if (!match) { 9176 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 9177 + pkg.packageName + " signatures do not match the " 9178 + "previously installed version; ignoring!"); 9179 } 9180 } 9181 9182 // Check for shared user signatures 9183 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 9184 // Already existing package. Make sure signatures match 9185 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 9186 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 9187 if (!match) { 9188 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 9189 == PackageManager.SIGNATURE_MATCH; 9190 } 9191 if (!match) { 9192 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 9193 == PackageManager.SIGNATURE_MATCH; 9194 } 9195 if (!match) { 9196 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 9197 "Package " + pkg.packageName 9198 + " has no signatures that match those in shared user " 9199 + pkgSetting.sharedUser.name + "; ignoring!"); 9200 } 9201 } 9202 } 9203 9204 /** 9205 * Enforces that only the system UID or root's UID can call a method exposed 9206 * via Binder. 9207 * 9208 * @param message used as message if SecurityException is thrown 9209 * @throws SecurityException if the caller is not system or root 9210 */ 9211 private static final void enforceSystemOrRoot(String message) { 9212 final int uid = Binder.getCallingUid(); 9213 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 9214 throw new SecurityException(message); 9215 } 9216 } 9217 9218 @Override 9219 public void performFstrimIfNeeded() { 9220 enforceSystemOrRoot("Only the system can request fstrim"); 9221 9222 // Before everything else, see whether we need to fstrim. 9223 try { 9224 IStorageManager sm = PackageHelper.getStorageManager(); 9225 if (sm != null) { 9226 boolean doTrim = false; 9227 final long interval = android.provider.Settings.Global.getLong( 9228 mContext.getContentResolver(), 9229 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 9230 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 9231 if (interval > 0) { 9232 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 9233 if (timeSinceLast > interval) { 9234 doTrim = true; 9235 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 9236 + "; running immediately"); 9237 } 9238 } 9239 if (doTrim) { 9240 final boolean dexOptDialogShown; 9241 synchronized (mPackages) { 9242 dexOptDialogShown = mDexOptDialogShown; 9243 } 9244 if (!isFirstBoot() && dexOptDialogShown) { 9245 try { 9246 ActivityManager.getService().showBootMessage( 9247 mContext.getResources().getString( 9248 R.string.android_upgrading_fstrim), true); 9249 } catch (RemoteException e) { 9250 } 9251 } 9252 sm.runMaintenance(); 9253 } 9254 } else { 9255 Slog.e(TAG, "storageManager service unavailable!"); 9256 } 9257 } catch (RemoteException e) { 9258 // Can't happen; StorageManagerService is local 9259 } 9260 } 9261 9262 @Override 9263 public void updatePackagesIfNeeded() { 9264 enforceSystemOrRoot("Only the system can request package update"); 9265 9266 // We need to re-extract after an OTA. 9267 boolean causeUpgrade = isUpgrade(); 9268 9269 // First boot or factory reset. 9270 // Note: we also handle devices that are upgrading to N right now as if it is their 9271 // first boot, as they do not have profile data. 9272 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 9273 9274 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 9275 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 9276 9277 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 9278 return; 9279 } 9280 9281 List<PackageParser.Package> pkgs; 9282 synchronized (mPackages) { 9283 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 9284 } 9285 9286 final long startTime = System.nanoTime(); 9287 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 9288 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 9289 9290 final int elapsedTimeSeconds = 9291 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 9292 9293 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 9294 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 9295 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 9296 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 9297 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 9298 } 9299 9300 /** 9301 * Performs dexopt on the set of packages in {@code packages} and returns an int array 9302 * containing statistics about the invocation. The array consists of three elements, 9303 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 9304 * and {@code numberOfPackagesFailed}. 9305 */ 9306 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 9307 String compilerFilter) { 9308 9309 int numberOfPackagesVisited = 0; 9310 int numberOfPackagesOptimized = 0; 9311 int numberOfPackagesSkipped = 0; 9312 int numberOfPackagesFailed = 0; 9313 final int numberOfPackagesToDexopt = pkgs.size(); 9314 9315 for (PackageParser.Package pkg : pkgs) { 9316 numberOfPackagesVisited++; 9317 9318 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 9319 if (DEBUG_DEXOPT) { 9320 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 9321 } 9322 numberOfPackagesSkipped++; 9323 continue; 9324 } 9325 9326 if (DEBUG_DEXOPT) { 9327 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 9328 numberOfPackagesToDexopt + ": " + pkg.packageName); 9329 } 9330 9331 if (showDialog) { 9332 try { 9333 ActivityManager.getService().showBootMessage( 9334 mContext.getResources().getString(R.string.android_upgrading_apk, 9335 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 9336 } catch (RemoteException e) { 9337 } 9338 synchronized (mPackages) { 9339 mDexOptDialogShown = true; 9340 } 9341 } 9342 9343 // If the OTA updates a system app which was previously preopted to a non-preopted state 9344 // the app might end up being verified at runtime. That's because by default the apps 9345 // are verify-profile but for preopted apps there's no profile. 9346 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 9347 // that before the OTA the app was preopted) the app gets compiled with a non-profile 9348 // filter (by default 'quicken'). 9349 // Note that at this stage unused apps are already filtered. 9350 if (isSystemApp(pkg) && 9351 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 9352 !Environment.getReferenceProfile(pkg.packageName).exists()) { 9353 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 9354 } 9355 9356 // checkProfiles is false to avoid merging profiles during boot which 9357 // might interfere with background compilation (b/28612421). 9358 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 9359 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 9360 // trade-off worth doing to save boot time work. 9361 int dexOptStatus = performDexOptTraced(pkg.packageName, 9362 false /* checkProfiles */, 9363 compilerFilter, 9364 false /* force */); 9365 switch (dexOptStatus) { 9366 case PackageDexOptimizer.DEX_OPT_PERFORMED: 9367 numberOfPackagesOptimized++; 9368 break; 9369 case PackageDexOptimizer.DEX_OPT_SKIPPED: 9370 numberOfPackagesSkipped++; 9371 break; 9372 case PackageDexOptimizer.DEX_OPT_FAILED: 9373 numberOfPackagesFailed++; 9374 break; 9375 default: 9376 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 9377 break; 9378 } 9379 } 9380 9381 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9382 numberOfPackagesFailed }; 9383 } 9384 9385 @Override 9386 public void notifyPackageUse(String packageName, int reason) { 9387 synchronized (mPackages) { 9388 final int callingUid = Binder.getCallingUid(); 9389 final int callingUserId = UserHandle.getUserId(callingUid); 9390 if (getInstantAppPackageName(callingUid) != null) { 9391 if (!isCallerSameApp(packageName, callingUid)) { 9392 return; 9393 } 9394 } else { 9395 if (isInstantApp(packageName, callingUserId)) { 9396 return; 9397 } 9398 } 9399 final PackageParser.Package p = mPackages.get(packageName); 9400 if (p == null) { 9401 return; 9402 } 9403 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9404 } 9405 } 9406 9407 @Override 9408 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 9409 int userId = UserHandle.getCallingUserId(); 9410 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9411 if (ai == null) { 9412 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9413 + loadingPackageName + ", user=" + userId); 9414 return; 9415 } 9416 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 9417 } 9418 9419 @Override 9420 public boolean performDexOpt(String packageName, 9421 boolean checkProfiles, int compileReason, boolean force) { 9422 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9423 return false; 9424 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9425 return false; 9426 } 9427 return performDexOptWithStatus(packageName, checkProfiles, compileReason, force) != 9428 PackageDexOptimizer.DEX_OPT_FAILED; 9429 } 9430 9431 /** 9432 * Perform dexopt on the given package and return one of following result: 9433 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9434 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9435 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9436 */ 9437 /* package */ int performDexOptWithStatus(String packageName, 9438 boolean checkProfiles, int compileReason, boolean force) { 9439 return performDexOptTraced(packageName, checkProfiles, 9440 getCompilerFilterForReason(compileReason), force); 9441 } 9442 9443 @Override 9444 public boolean performDexOptMode(String packageName, 9445 boolean checkProfiles, String targetCompilerFilter, boolean force) { 9446 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9447 return false; 9448 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9449 return false; 9450 } 9451 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 9452 targetCompilerFilter, force); 9453 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9454 } 9455 9456 private int performDexOptTraced(String packageName, 9457 boolean checkProfiles, String targetCompilerFilter, boolean force) { 9458 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9459 try { 9460 return performDexOptInternal(packageName, checkProfiles, 9461 targetCompilerFilter, force); 9462 } finally { 9463 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9464 } 9465 } 9466 9467 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9468 // if the package can now be considered up to date for the given filter. 9469 private int performDexOptInternal(String packageName, 9470 boolean checkProfiles, String targetCompilerFilter, boolean force) { 9471 PackageParser.Package p; 9472 synchronized (mPackages) { 9473 p = mPackages.get(packageName); 9474 if (p == null) { 9475 // Package could not be found. Report failure. 9476 return PackageDexOptimizer.DEX_OPT_FAILED; 9477 } 9478 mPackageUsage.maybeWriteAsync(mPackages); 9479 mCompilerStats.maybeWriteAsync(); 9480 } 9481 long callingId = Binder.clearCallingIdentity(); 9482 try { 9483 synchronized (mInstallLock) { 9484 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 9485 targetCompilerFilter, force); 9486 } 9487 } finally { 9488 Binder.restoreCallingIdentity(callingId); 9489 } 9490 } 9491 9492 public ArraySet<String> getOptimizablePackages() { 9493 ArraySet<String> pkgs = new ArraySet<String>(); 9494 synchronized (mPackages) { 9495 for (PackageParser.Package p : mPackages.values()) { 9496 if (PackageDexOptimizer.canOptimizePackage(p)) { 9497 pkgs.add(p.packageName); 9498 } 9499 } 9500 } 9501 return pkgs; 9502 } 9503 9504 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9505 boolean checkProfiles, String targetCompilerFilter, 9506 boolean force) { 9507 // Select the dex optimizer based on the force parameter. 9508 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9509 // allocate an object here. 9510 PackageDexOptimizer pdo = force 9511 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9512 : mPackageDexOptimizer; 9513 9514 // Dexopt all dependencies first. Note: we ignore the return value and march on 9515 // on errors. 9516 // Note that we are going to call performDexOpt on those libraries as many times as 9517 // they are referenced in packages. When we do a batch of performDexOpt (for example 9518 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9519 // and the first package that uses the library will dexopt it. The 9520 // others will see that the compiled code for the library is up to date. 9521 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9522 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9523 if (!deps.isEmpty()) { 9524 for (PackageParser.Package depPackage : deps) { 9525 // TODO: Analyze and investigate if we (should) profile libraries. 9526 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9527 false /* checkProfiles */, 9528 targetCompilerFilter, 9529 getOrCreateCompilerPackageStats(depPackage), 9530 true /* isUsedByOtherApps */); 9531 } 9532 } 9533 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 9534 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 9535 mDexManager.isUsedByOtherApps(p.packageName)); 9536 } 9537 9538 // Performs dexopt on the used secondary dex files belonging to the given package. 9539 // Returns true if all dex files were process successfully (which could mean either dexopt or 9540 // skip). Returns false if any of the files caused errors. 9541 @Override 9542 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9543 boolean force) { 9544 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9545 return false; 9546 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9547 return false; 9548 } 9549 mDexManager.reconcileSecondaryDexFiles(packageName); 9550 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 9551 } 9552 9553 public boolean performDexOptSecondary(String packageName, int compileReason, 9554 boolean force) { 9555 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 9556 } 9557 9558 /** 9559 * Reconcile the information we have about the secondary dex files belonging to 9560 * {@code packagName} and the actual dex files. For all dex files that were 9561 * deleted, update the internal records and delete the generated oat files. 9562 */ 9563 @Override 9564 public void reconcileSecondaryDexFiles(String packageName) { 9565 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9566 return; 9567 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9568 return; 9569 } 9570 mDexManager.reconcileSecondaryDexFiles(packageName); 9571 } 9572 9573 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9574 // a reference there. 9575 /*package*/ DexManager getDexManager() { 9576 return mDexManager; 9577 } 9578 9579 /** 9580 * Execute the background dexopt job immediately. 9581 */ 9582 @Override 9583 public boolean runBackgroundDexoptJob() { 9584 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9585 return false; 9586 } 9587 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 9588 } 9589 9590 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9591 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9592 || p.usesStaticLibraries != null) { 9593 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9594 Set<String> collectedNames = new HashSet<>(); 9595 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9596 9597 retValue.remove(p); 9598 9599 return retValue; 9600 } else { 9601 return Collections.emptyList(); 9602 } 9603 } 9604 9605 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9606 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9607 if (!collectedNames.contains(p.packageName)) { 9608 collectedNames.add(p.packageName); 9609 collected.add(p); 9610 9611 if (p.usesLibraries != null) { 9612 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9613 null, collected, collectedNames); 9614 } 9615 if (p.usesOptionalLibraries != null) { 9616 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9617 null, collected, collectedNames); 9618 } 9619 if (p.usesStaticLibraries != null) { 9620 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9621 p.usesStaticLibrariesVersions, collected, collectedNames); 9622 } 9623 } 9624 } 9625 9626 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 9627 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9628 final int libNameCount = libs.size(); 9629 for (int i = 0; i < libNameCount; i++) { 9630 String libName = libs.get(i); 9631 int version = (versions != null && versions.length == libNameCount) 9632 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9633 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9634 if (libPkg != null) { 9635 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9636 } 9637 } 9638 } 9639 9640 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 9641 synchronized (mPackages) { 9642 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9643 if (libEntry != null) { 9644 return mPackages.get(libEntry.apk); 9645 } 9646 return null; 9647 } 9648 } 9649 9650 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 9651 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9652 if (versionedLib == null) { 9653 return null; 9654 } 9655 return versionedLib.get(version); 9656 } 9657 9658 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9659 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9660 pkg.staticSharedLibName); 9661 if (versionedLib == null) { 9662 return null; 9663 } 9664 int previousLibVersion = -1; 9665 final int versionCount = versionedLib.size(); 9666 for (int i = 0; i < versionCount; i++) { 9667 final int libVersion = versionedLib.keyAt(i); 9668 if (libVersion < pkg.staticSharedLibVersion) { 9669 previousLibVersion = Math.max(previousLibVersion, libVersion); 9670 } 9671 } 9672 if (previousLibVersion >= 0) { 9673 return versionedLib.get(previousLibVersion); 9674 } 9675 return null; 9676 } 9677 9678 public void shutdown() { 9679 mPackageUsage.writeNow(mPackages); 9680 mCompilerStats.writeNow(); 9681 } 9682 9683 @Override 9684 public void dumpProfiles(String packageName) { 9685 PackageParser.Package pkg; 9686 synchronized (mPackages) { 9687 pkg = mPackages.get(packageName); 9688 if (pkg == null) { 9689 throw new IllegalArgumentException("Unknown package: " + packageName); 9690 } 9691 } 9692 /* Only the shell, root, or the app user should be able to dump profiles. */ 9693 int callingUid = Binder.getCallingUid(); 9694 if (callingUid != Process.SHELL_UID && 9695 callingUid != Process.ROOT_UID && 9696 callingUid != pkg.applicationInfo.uid) { 9697 throw new SecurityException("dumpProfiles"); 9698 } 9699 9700 synchronized (mInstallLock) { 9701 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9702 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 9703 try { 9704 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 9705 String codePaths = TextUtils.join(";", allCodePaths); 9706 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 9707 } catch (InstallerException e) { 9708 Slog.w(TAG, "Failed to dump profiles", e); 9709 } 9710 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9711 } 9712 } 9713 9714 @Override 9715 public void forceDexOpt(String packageName) { 9716 enforceSystemOrRoot("forceDexOpt"); 9717 9718 PackageParser.Package pkg; 9719 synchronized (mPackages) { 9720 pkg = mPackages.get(packageName); 9721 if (pkg == null) { 9722 throw new IllegalArgumentException("Unknown package: " + packageName); 9723 } 9724 } 9725 9726 synchronized (mInstallLock) { 9727 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9728 9729 // Whoever is calling forceDexOpt wants a compiled package. 9730 // Don't use profiles since that may cause compilation to be skipped. 9731 final int res = performDexOptInternalWithDependenciesLI(pkg, 9732 false /* checkProfiles */, getDefaultCompilerFilter(), 9733 true /* force */); 9734 9735 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9736 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9737 throw new IllegalStateException("Failed to dexopt: " + res); 9738 } 9739 } 9740 } 9741 9742 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9743 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9744 Slog.w(TAG, "Unable to update from " + oldPkg.name 9745 + " to " + newPkg.packageName 9746 + ": old package not in system partition"); 9747 return false; 9748 } else if (mPackages.get(oldPkg.name) != null) { 9749 Slog.w(TAG, "Unable to update from " + oldPkg.name 9750 + " to " + newPkg.packageName 9751 + ": old package still exists"); 9752 return false; 9753 } 9754 return true; 9755 } 9756 9757 void removeCodePathLI(File codePath) { 9758 if (codePath.isDirectory()) { 9759 try { 9760 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9761 } catch (InstallerException e) { 9762 Slog.w(TAG, "Failed to remove code path", e); 9763 } 9764 } else { 9765 codePath.delete(); 9766 } 9767 } 9768 9769 private int[] resolveUserIds(int userId) { 9770 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9771 } 9772 9773 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9774 if (pkg == null) { 9775 Slog.wtf(TAG, "Package was null!", new Throwable()); 9776 return; 9777 } 9778 clearAppDataLeafLIF(pkg, userId, flags); 9779 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9780 for (int i = 0; i < childCount; i++) { 9781 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9782 } 9783 } 9784 9785 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9786 final PackageSetting ps; 9787 synchronized (mPackages) { 9788 ps = mSettings.mPackages.get(pkg.packageName); 9789 } 9790 for (int realUserId : resolveUserIds(userId)) { 9791 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9792 try { 9793 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9794 ceDataInode); 9795 } catch (InstallerException e) { 9796 Slog.w(TAG, String.valueOf(e)); 9797 } 9798 } 9799 } 9800 9801 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9802 if (pkg == null) { 9803 Slog.wtf(TAG, "Package was null!", new Throwable()); 9804 return; 9805 } 9806 destroyAppDataLeafLIF(pkg, userId, flags); 9807 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9808 for (int i = 0; i < childCount; i++) { 9809 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9810 } 9811 } 9812 9813 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9814 final PackageSetting ps; 9815 synchronized (mPackages) { 9816 ps = mSettings.mPackages.get(pkg.packageName); 9817 } 9818 for (int realUserId : resolveUserIds(userId)) { 9819 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9820 try { 9821 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9822 ceDataInode); 9823 } catch (InstallerException e) { 9824 Slog.w(TAG, String.valueOf(e)); 9825 } 9826 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9827 } 9828 } 9829 9830 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9831 if (pkg == null) { 9832 Slog.wtf(TAG, "Package was null!", new Throwable()); 9833 return; 9834 } 9835 destroyAppProfilesLeafLIF(pkg); 9836 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9837 for (int i = 0; i < childCount; i++) { 9838 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9839 } 9840 } 9841 9842 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9843 try { 9844 mInstaller.destroyAppProfiles(pkg.packageName); 9845 } catch (InstallerException e) { 9846 Slog.w(TAG, String.valueOf(e)); 9847 } 9848 } 9849 9850 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9851 if (pkg == null) { 9852 Slog.wtf(TAG, "Package was null!", new Throwable()); 9853 return; 9854 } 9855 clearAppProfilesLeafLIF(pkg); 9856 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9857 for (int i = 0; i < childCount; i++) { 9858 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 9859 } 9860 } 9861 9862 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 9863 try { 9864 mInstaller.clearAppProfiles(pkg.packageName); 9865 } catch (InstallerException e) { 9866 Slog.w(TAG, String.valueOf(e)); 9867 } 9868 } 9869 9870 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9871 long lastUpdateTime) { 9872 // Set parent install/update time 9873 PackageSetting ps = (PackageSetting) pkg.mExtras; 9874 if (ps != null) { 9875 ps.firstInstallTime = firstInstallTime; 9876 ps.lastUpdateTime = lastUpdateTime; 9877 } 9878 // Set children install/update time 9879 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9880 for (int i = 0; i < childCount; i++) { 9881 PackageParser.Package childPkg = pkg.childPackages.get(i); 9882 ps = (PackageSetting) childPkg.mExtras; 9883 if (ps != null) { 9884 ps.firstInstallTime = firstInstallTime; 9885 ps.lastUpdateTime = lastUpdateTime; 9886 } 9887 } 9888 } 9889 9890 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 9891 PackageParser.Package changingLib) { 9892 if (file.path != null) { 9893 usesLibraryFiles.add(file.path); 9894 return; 9895 } 9896 PackageParser.Package p = mPackages.get(file.apk); 9897 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9898 // If we are doing this while in the middle of updating a library apk, 9899 // then we need to make sure to use that new apk for determining the 9900 // dependencies here. (We haven't yet finished committing the new apk 9901 // to the package manager state.) 9902 if (p == null || p.packageName.equals(changingLib.packageName)) { 9903 p = changingLib; 9904 } 9905 } 9906 if (p != null) { 9907 usesLibraryFiles.addAll(p.getAllCodePaths()); 9908 if (p.usesLibraryFiles != null) { 9909 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9910 } 9911 } 9912 } 9913 9914 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9915 PackageParser.Package changingLib) throws PackageManagerException { 9916 if (pkg == null) { 9917 return; 9918 } 9919 ArraySet<String> usesLibraryFiles = null; 9920 if (pkg.usesLibraries != null) { 9921 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9922 null, null, pkg.packageName, changingLib, true, null); 9923 } 9924 if (pkg.usesStaticLibraries != null) { 9925 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9926 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9927 pkg.packageName, changingLib, true, usesLibraryFiles); 9928 } 9929 if (pkg.usesOptionalLibraries != null) { 9930 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9931 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 9932 } 9933 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9934 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9935 } else { 9936 pkg.usesLibraryFiles = null; 9937 } 9938 } 9939 9940 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9941 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 9942 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9943 boolean required, @Nullable ArraySet<String> outUsedLibraries) 9944 throws PackageManagerException { 9945 final int libCount = requestedLibraries.size(); 9946 for (int i = 0; i < libCount; i++) { 9947 final String libName = requestedLibraries.get(i); 9948 final int libVersion = requiredVersions != null ? requiredVersions[i] 9949 : SharedLibraryInfo.VERSION_UNDEFINED; 9950 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9951 if (libEntry == null) { 9952 if (required) { 9953 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9954 "Package " + packageName + " requires unavailable shared library " 9955 + libName + "; failing!"); 9956 } else if (DEBUG_SHARED_LIBRARIES) { 9957 Slog.i(TAG, "Package " + packageName 9958 + " desires unavailable shared library " 9959 + libName + "; ignoring!"); 9960 } 9961 } else { 9962 if (requiredVersions != null && requiredCertDigests != null) { 9963 if (libEntry.info.getVersion() != requiredVersions[i]) { 9964 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9965 "Package " + packageName + " requires unavailable static shared" 9966 + " library " + libName + " version " 9967 + libEntry.info.getVersion() + "; failing!"); 9968 } 9969 9970 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9971 if (libPkg == null) { 9972 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9973 "Package " + packageName + " requires unavailable static shared" 9974 + " library; failing!"); 9975 } 9976 9977 String expectedCertDigest = requiredCertDigests[i]; 9978 String libCertDigest = PackageUtils.computeCertSha256Digest( 9979 libPkg.mSignatures[0]); 9980 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 9981 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9982 "Package " + packageName + " requires differently signed" + 9983 " static shared library; failing!"); 9984 } 9985 } 9986 9987 if (outUsedLibraries == null) { 9988 outUsedLibraries = new ArraySet<>(); 9989 } 9990 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9991 } 9992 } 9993 return outUsedLibraries; 9994 } 9995 9996 private static boolean hasString(List<String> list, List<String> which) { 9997 if (list == null) { 9998 return false; 9999 } 10000 for (int i=list.size()-1; i>=0; i--) { 10001 for (int j=which.size()-1; j>=0; j--) { 10002 if (which.get(j).equals(list.get(i))) { 10003 return true; 10004 } 10005 } 10006 } 10007 return false; 10008 } 10009 10010 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 10011 PackageParser.Package changingPkg) { 10012 ArrayList<PackageParser.Package> res = null; 10013 for (PackageParser.Package pkg : mPackages.values()) { 10014 if (changingPkg != null 10015 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 10016 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 10017 && !ArrayUtils.contains(pkg.usesStaticLibraries, 10018 changingPkg.staticSharedLibName)) { 10019 return null; 10020 } 10021 if (res == null) { 10022 res = new ArrayList<>(); 10023 } 10024 res.add(pkg); 10025 try { 10026 updateSharedLibrariesLPr(pkg, changingPkg); 10027 } catch (PackageManagerException e) { 10028 // If a system app update or an app and a required lib missing we 10029 // delete the package and for updated system apps keep the data as 10030 // it is better for the user to reinstall than to be in an limbo 10031 // state. Also libs disappearing under an app should never happen 10032 // - just in case. 10033 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 10034 final int flags = pkg.isUpdatedSystemApp() 10035 ? PackageManager.DELETE_KEEP_DATA : 0; 10036 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 10037 flags , null, true, null); 10038 } 10039 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 10040 } 10041 } 10042 return res; 10043 } 10044 10045 /** 10046 * Derive the value of the {@code cpuAbiOverride} based on the provided 10047 * value and an optional stored value from the package settings. 10048 */ 10049 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 10050 String cpuAbiOverride = null; 10051 10052 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 10053 cpuAbiOverride = null; 10054 } else if (abiOverride != null) { 10055 cpuAbiOverride = abiOverride; 10056 } else if (settings != null) { 10057 cpuAbiOverride = settings.cpuAbiOverrideString; 10058 } 10059 10060 return cpuAbiOverride; 10061 } 10062 10063 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 10064 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 10065 throws PackageManagerException { 10066 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 10067 // If the package has children and this is the first dive in the function 10068 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 10069 // whether all packages (parent and children) would be successfully scanned 10070 // before the actual scan since scanning mutates internal state and we want 10071 // to atomically install the package and its children. 10072 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10073 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 10074 scanFlags |= SCAN_CHECK_ONLY; 10075 } 10076 } else { 10077 scanFlags &= ~SCAN_CHECK_ONLY; 10078 } 10079 10080 final PackageParser.Package scannedPkg; 10081 try { 10082 // Scan the parent 10083 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 10084 // Scan the children 10085 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10086 for (int i = 0; i < childCount; i++) { 10087 PackageParser.Package childPkg = pkg.childPackages.get(i); 10088 scanPackageLI(childPkg, policyFlags, 10089 scanFlags, currentTime, user); 10090 } 10091 } finally { 10092 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10093 } 10094 10095 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10096 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 10097 } 10098 10099 return scannedPkg; 10100 } 10101 10102 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 10103 int scanFlags, long currentTime, @Nullable UserHandle user) 10104 throws PackageManagerException { 10105 boolean success = false; 10106 try { 10107 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 10108 currentTime, user); 10109 success = true; 10110 return res; 10111 } finally { 10112 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 10113 // DELETE_DATA_ON_FAILURES is only used by frozen paths 10114 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 10115 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 10116 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 10117 } 10118 } 10119 } 10120 10121 /** 10122 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10123 */ 10124 private static boolean apkHasCode(String fileName) { 10125 StrictJarFile jarFile = null; 10126 try { 10127 jarFile = new StrictJarFile(fileName, 10128 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10129 return jarFile.findEntry("classes.dex") != null; 10130 } catch (IOException ignore) { 10131 } finally { 10132 try { 10133 if (jarFile != null) { 10134 jarFile.close(); 10135 } 10136 } catch (IOException ignore) {} 10137 } 10138 return false; 10139 } 10140 10141 /** 10142 * Enforces code policy for the package. This ensures that if an APK has 10143 * declared hasCode="true" in its manifest that the APK actually contains 10144 * code. 10145 * 10146 * @throws PackageManagerException If bytecode could not be found when it should exist 10147 */ 10148 private static void assertCodePolicy(PackageParser.Package pkg) 10149 throws PackageManagerException { 10150 final boolean shouldHaveCode = 10151 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10152 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10153 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10154 "Package " + pkg.baseCodePath + " code is missing"); 10155 } 10156 10157 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10158 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10159 final boolean splitShouldHaveCode = 10160 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10161 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10162 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10163 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10164 } 10165 } 10166 } 10167 } 10168 10169 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 10170 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 10171 throws PackageManagerException { 10172 if (DEBUG_PACKAGE_SCANNING) { 10173 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 10174 Log.d(TAG, "Scanning package " + pkg.packageName); 10175 } 10176 10177 applyPolicy(pkg, policyFlags); 10178 10179 assertPackageIsValid(pkg, policyFlags, scanFlags); 10180 10181 // Initialize package source and resource directories 10182 final File scanFile = new File(pkg.codePath); 10183 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10184 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10185 10186 SharedUserSetting suid = null; 10187 PackageSetting pkgSetting = null; 10188 10189 // Getting the package setting may have a side-effect, so if we 10190 // are only checking if scan would succeed, stash a copy of the 10191 // old setting to restore at the end. 10192 PackageSetting nonMutatedPs = null; 10193 10194 // We keep references to the derived CPU Abis from settings in oder to reuse 10195 // them in the case where we're not upgrading or booting for the first time. 10196 String primaryCpuAbiFromSettings = null; 10197 String secondaryCpuAbiFromSettings = null; 10198 10199 // writer 10200 synchronized (mPackages) { 10201 if (pkg.mSharedUserId != null) { 10202 // SIDE EFFECTS; may potentially allocate a new shared user 10203 suid = mSettings.getSharedUserLPw( 10204 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 10205 if (DEBUG_PACKAGE_SCANNING) { 10206 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 10207 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 10208 + "): packages=" + suid.packages); 10209 } 10210 } 10211 10212 // Check if we are renaming from an original package name. 10213 PackageSetting origPackage = null; 10214 String realName = null; 10215 if (pkg.mOriginalPackages != null) { 10216 // This package may need to be renamed to a previously 10217 // installed name. Let's check on that... 10218 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 10219 if (pkg.mOriginalPackages.contains(renamed)) { 10220 // This package had originally been installed as the 10221 // original name, and we have already taken care of 10222 // transitioning to the new one. Just update the new 10223 // one to continue using the old name. 10224 realName = pkg.mRealPackage; 10225 if (!pkg.packageName.equals(renamed)) { 10226 // Callers into this function may have already taken 10227 // care of renaming the package; only do it here if 10228 // it is not already done. 10229 pkg.setPackageName(renamed); 10230 } 10231 } else { 10232 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 10233 if ((origPackage = mSettings.getPackageLPr( 10234 pkg.mOriginalPackages.get(i))) != null) { 10235 // We do have the package already installed under its 10236 // original name... should we use it? 10237 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 10238 // New package is not compatible with original. 10239 origPackage = null; 10240 continue; 10241 } else if (origPackage.sharedUser != null) { 10242 // Make sure uid is compatible between packages. 10243 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 10244 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 10245 + " to " + pkg.packageName + ": old uid " 10246 + origPackage.sharedUser.name 10247 + " differs from " + pkg.mSharedUserId); 10248 origPackage = null; 10249 continue; 10250 } 10251 // TODO: Add case when shared user id is added [b/28144775] 10252 } else { 10253 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10254 + pkg.packageName + " to old name " + origPackage.name); 10255 } 10256 break; 10257 } 10258 } 10259 } 10260 } 10261 10262 if (mTransferedPackages.contains(pkg.packageName)) { 10263 Slog.w(TAG, "Package " + pkg.packageName 10264 + " was transferred to another, but its .apk remains"); 10265 } 10266 10267 // See comments in nonMutatedPs declaration 10268 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10269 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 10270 if (foundPs != null) { 10271 nonMutatedPs = new PackageSetting(foundPs); 10272 } 10273 } 10274 10275 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 10276 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 10277 if (foundPs != null) { 10278 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 10279 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 10280 } 10281 } 10282 10283 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 10284 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 10285 PackageManagerService.reportSettingsProblem(Log.WARN, 10286 "Package " + pkg.packageName + " shared user changed from " 10287 + (pkgSetting.sharedUser != null 10288 ? pkgSetting.sharedUser.name : "<nothing>") 10289 + " to " 10290 + (suid != null ? suid.name : "<nothing>") 10291 + "; replacing with new"); 10292 pkgSetting = null; 10293 } 10294 final PackageSetting oldPkgSetting = 10295 pkgSetting == null ? null : new PackageSetting(pkgSetting); 10296 final PackageSetting disabledPkgSetting = 10297 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 10298 10299 String[] usesStaticLibraries = null; 10300 if (pkg.usesStaticLibraries != null) { 10301 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10302 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10303 } 10304 10305 if (pkgSetting == null) { 10306 final String parentPackageName = (pkg.parentPackage != null) 10307 ? pkg.parentPackage.packageName : null; 10308 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10309 // REMOVE SharedUserSetting from method; update in a separate call 10310 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 10311 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 10312 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 10313 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 10314 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 10315 true /*allowInstall*/, instantApp, parentPackageName, 10316 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10317 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10318 // SIDE EFFECTS; updates system state; move elsewhere 10319 if (origPackage != null) { 10320 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 10321 } 10322 mSettings.addUserToSettingLPw(pkgSetting); 10323 } else { 10324 // REMOVE SharedUserSetting from method; update in a separate call. 10325 // 10326 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10327 // secondaryCpuAbi are not known at this point so we always update them 10328 // to null here, only to reset them at a later point. 10329 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 10330 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 10331 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 10332 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 10333 UserManagerService.getInstance(), usesStaticLibraries, 10334 pkg.usesStaticLibrariesVersions); 10335 } 10336 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 10337 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 10338 10339 // SIDE EFFECTS; modifies system state; move elsewhere 10340 if (pkgSetting.origPackage != null) { 10341 // If we are first transitioning from an original package, 10342 // fix up the new package's name now. We need to do this after 10343 // looking up the package under its new name, so getPackageLP 10344 // can take care of fiddling things correctly. 10345 pkg.setPackageName(origPackage.name); 10346 10347 // File a report about this. 10348 String msg = "New package " + pkgSetting.realName 10349 + " renamed to replace old package " + pkgSetting.name; 10350 reportSettingsProblem(Log.WARN, msg); 10351 10352 // Make a note of it. 10353 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10354 mTransferedPackages.add(origPackage.name); 10355 } 10356 10357 // No longer need to retain this. 10358 pkgSetting.origPackage = null; 10359 } 10360 10361 // SIDE EFFECTS; modifies system state; move elsewhere 10362 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 10363 // Make a note of it. 10364 mTransferedPackages.add(pkg.packageName); 10365 } 10366 10367 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 10368 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10369 } 10370 10371 if ((scanFlags & SCAN_BOOTING) == 0 10372 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10373 // Check all shared libraries and map to their actual file path. 10374 // We only do this here for apps not on a system dir, because those 10375 // are the only ones that can fail an install due to this. We 10376 // will take care of the system apps by updating all of their 10377 // library paths after the scan is done. Also during the initial 10378 // scan don't update any libs as we do this wholesale after all 10379 // apps are scanned to avoid dependency based scanning. 10380 updateSharedLibrariesLPr(pkg, null); 10381 } 10382 10383 if (mFoundPolicyFile) { 10384 SELinuxMMAC.assignSeInfoValue(pkg); 10385 } 10386 pkg.applicationInfo.uid = pkgSetting.appId; 10387 pkg.mExtras = pkgSetting; 10388 10389 10390 // Static shared libs have same package with different versions where 10391 // we internally use a synthetic package name to allow multiple versions 10392 // of the same package, therefore we need to compare signatures against 10393 // the package setting for the latest library version. 10394 PackageSetting signatureCheckPs = pkgSetting; 10395 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10396 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 10397 if (libraryEntry != null) { 10398 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 10399 } 10400 } 10401 10402 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 10403 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 10404 // We just determined the app is signed correctly, so bring 10405 // over the latest parsed certs. 10406 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10407 } else { 10408 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10409 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10410 "Package " + pkg.packageName + " upgrade keys do not match the " 10411 + "previously installed version"); 10412 } else { 10413 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10414 String msg = "System package " + pkg.packageName 10415 + " signature changed; retaining data."; 10416 reportSettingsProblem(Log.WARN, msg); 10417 } 10418 } 10419 } else { 10420 try { 10421 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 10422 verifySignaturesLP(signatureCheckPs, pkg); 10423 // We just determined the app is signed correctly, so bring 10424 // over the latest parsed certs. 10425 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10426 } catch (PackageManagerException e) { 10427 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10428 throw e; 10429 } 10430 // The signature has changed, but this package is in the system 10431 // image... let's recover! 10432 pkgSetting.signatures.mSignatures = pkg.mSignatures; 10433 // However... if this package is part of a shared user, but it 10434 // doesn't match the signature of the shared user, let's fail. 10435 // What this means is that you can't change the signatures 10436 // associated with an overall shared user, which doesn't seem all 10437 // that unreasonable. 10438 if (signatureCheckPs.sharedUser != null) { 10439 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 10440 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10441 throw new PackageManagerException( 10442 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10443 "Signature mismatch for shared user: " 10444 + pkgSetting.sharedUser); 10445 } 10446 } 10447 // File a report about this. 10448 String msg = "System package " + pkg.packageName 10449 + " signature changed; retaining data."; 10450 reportSettingsProblem(Log.WARN, msg); 10451 } 10452 } 10453 10454 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 10455 // This package wants to adopt ownership of permissions from 10456 // another package. 10457 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 10458 final String origName = pkg.mAdoptPermissions.get(i); 10459 final PackageSetting orig = mSettings.getPackageLPr(origName); 10460 if (orig != null) { 10461 if (verifyPackageUpdateLPr(orig, pkg)) { 10462 Slog.i(TAG, "Adopting permissions from " + origName + " to " 10463 + pkg.packageName); 10464 // SIDE EFFECTS; updates permissions system state; move elsewhere 10465 mSettings.transferPermissionsLPw(origName, pkg.packageName); 10466 } 10467 } 10468 } 10469 } 10470 } 10471 10472 pkg.applicationInfo.processName = fixProcessName( 10473 pkg.applicationInfo.packageName, 10474 pkg.applicationInfo.processName); 10475 10476 if (pkg != mPlatformPackage) { 10477 // Get all of our default paths setup 10478 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10479 } 10480 10481 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10482 10483 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10484 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 10485 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10486 final boolean extractNativeLibs = !pkg.isLibrary(); 10487 derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs, 10488 mAppLib32InstallDir); 10489 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10490 10491 // Some system apps still use directory structure for native libraries 10492 // in which case we might end up not detecting abi solely based on apk 10493 // structure. Try to detect abi based on directory structure. 10494 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10495 pkg.applicationInfo.primaryCpuAbi == null) { 10496 setBundledAppAbisAndRoots(pkg, pkgSetting); 10497 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 10498 } 10499 } else { 10500 // This is not a first boot or an upgrade, don't bother deriving the 10501 // ABI during the scan. Instead, trust the value that was stored in the 10502 // package setting. 10503 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10504 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10505 10506 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 10507 10508 if (DEBUG_ABI_SELECTION) { 10509 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10510 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10511 pkg.applicationInfo.secondaryCpuAbi); 10512 } 10513 } 10514 } else { 10515 if ((scanFlags & SCAN_MOVE) != 0) { 10516 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10517 // but we already have this packages package info in the PackageSetting. We just 10518 // use that and derive the native library path based on the new codepath. 10519 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10520 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10521 } 10522 10523 // Set native library paths again. For moves, the path will be updated based on the 10524 // ABIs we've determined above. For non-moves, the path will be updated based on the 10525 // ABIs we determined during compilation, but the path will depend on the final 10526 // package path (after the rename away from the stage path). 10527 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 10528 } 10529 10530 // This is a special case for the "system" package, where the ABI is 10531 // dictated by the zygote configuration (and init.rc). We should keep track 10532 // of this ABI so that we can deal with "normal" applications that run under 10533 // the same UID correctly. 10534 if (mPlatformPackage == pkg) { 10535 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10536 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10537 } 10538 10539 // If there's a mismatch between the abi-override in the package setting 10540 // and the abiOverride specified for the install. Warn about this because we 10541 // would've already compiled the app without taking the package setting into 10542 // account. 10543 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10544 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 10545 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10546 " for package " + pkg.packageName); 10547 } 10548 } 10549 10550 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10551 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10552 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10553 10554 // Copy the derived override back to the parsed package, so that we can 10555 // update the package settings accordingly. 10556 pkg.cpuAbiOverride = cpuAbiOverride; 10557 10558 if (DEBUG_ABI_SELECTION) { 10559 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 10560 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10561 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10562 } 10563 10564 // Push the derived path down into PackageSettings so we know what to 10565 // clean up at uninstall time. 10566 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10567 10568 if (DEBUG_ABI_SELECTION) { 10569 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10570 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10571 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10572 } 10573 10574 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 10575 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10576 // We don't do this here during boot because we can do it all 10577 // at once after scanning all existing packages. 10578 // 10579 // We also do this *before* we perform dexopt on this package, so that 10580 // we can avoid redundant dexopts, and also to make sure we've got the 10581 // code and package path correct. 10582 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10583 } 10584 10585 if (mFactoryTest && pkg.requestedPermissions.contains( 10586 android.Manifest.permission.FACTORY_TEST)) { 10587 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10588 } 10589 10590 if (isSystemApp(pkg)) { 10591 pkgSetting.isOrphaned = true; 10592 } 10593 10594 // Take care of first install / last update times. 10595 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 10596 if (currentTime != 0) { 10597 if (pkgSetting.firstInstallTime == 0) { 10598 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10599 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10600 pkgSetting.lastUpdateTime = currentTime; 10601 } 10602 } else if (pkgSetting.firstInstallTime == 0) { 10603 // We need *something*. Take time time stamp of the file. 10604 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10605 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10606 if (scanFileTime != pkgSetting.timeStamp) { 10607 // A package on the system image has changed; consider this 10608 // to be an update. 10609 pkgSetting.lastUpdateTime = scanFileTime; 10610 } 10611 } 10612 pkgSetting.setTimeStamp(scanFileTime); 10613 10614 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10615 if (nonMutatedPs != null) { 10616 synchronized (mPackages) { 10617 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 10618 } 10619 } 10620 } else { 10621 final int userId = user == null ? 0 : user.getIdentifier(); 10622 // Modify state for the given package setting 10623 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10624 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10625 if (pkgSetting.getInstantApp(userId)) { 10626 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10627 } 10628 } 10629 return pkg; 10630 } 10631 10632 /** 10633 * Applies policy to the parsed package based upon the given policy flags. 10634 * Ensures the package is in a good state. 10635 * <p> 10636 * Implementation detail: This method must NOT have any side effect. It would 10637 * ideally be static, but, it requires locks to read system state. 10638 */ 10639 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 10640 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 10641 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10642 if (pkg.applicationInfo.isDirectBootAware()) { 10643 // we're direct boot aware; set for all components 10644 for (PackageParser.Service s : pkg.services) { 10645 s.info.encryptionAware = s.info.directBootAware = true; 10646 } 10647 for (PackageParser.Provider p : pkg.providers) { 10648 p.info.encryptionAware = p.info.directBootAware = true; 10649 } 10650 for (PackageParser.Activity a : pkg.activities) { 10651 a.info.encryptionAware = a.info.directBootAware = true; 10652 } 10653 for (PackageParser.Activity r : pkg.receivers) { 10654 r.info.encryptionAware = r.info.directBootAware = true; 10655 } 10656 } 10657 } else { 10658 // Only allow system apps to be flagged as core apps. 10659 pkg.coreApp = false; 10660 // clear flags not applicable to regular apps 10661 pkg.applicationInfo.privateFlags &= 10662 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10663 pkg.applicationInfo.privateFlags &= 10664 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10665 } 10666 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 10667 10668 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 10669 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10670 } 10671 10672 if (!isSystemApp(pkg)) { 10673 // Only system apps can use these features. 10674 pkg.mOriginalPackages = null; 10675 pkg.mRealPackage = null; 10676 pkg.mAdoptPermissions = null; 10677 } 10678 } 10679 10680 /** 10681 * Asserts the parsed package is valid according to the given policy. If the 10682 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10683 * <p> 10684 * Implementation detail: This method must NOT have any side effects. It would 10685 * ideally be static, but, it requires locks to read system state. 10686 * 10687 * @throws PackageManagerException If the package fails any of the validation checks 10688 */ 10689 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 10690 throws PackageManagerException { 10691 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10692 assertCodePolicy(pkg); 10693 } 10694 10695 if (pkg.applicationInfo.getCodePath() == null || 10696 pkg.applicationInfo.getResourcePath() == null) { 10697 // Bail out. The resource and code paths haven't been set. 10698 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10699 "Code and resource paths haven't been set correctly"); 10700 } 10701 10702 // Make sure we're not adding any bogus keyset info 10703 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10704 ksms.assertScannedPackageValid(pkg); 10705 10706 synchronized (mPackages) { 10707 // The special "android" package can only be defined once 10708 if (pkg.packageName.equals("android")) { 10709 if (mAndroidApplication != null) { 10710 Slog.w(TAG, "*************************************************"); 10711 Slog.w(TAG, "Core android package being redefined. Skipping."); 10712 Slog.w(TAG, " codePath=" + pkg.codePath); 10713 Slog.w(TAG, "*************************************************"); 10714 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10715 "Core android package being redefined. Skipping."); 10716 } 10717 } 10718 10719 // A package name must be unique; don't allow duplicates 10720 if (mPackages.containsKey(pkg.packageName)) { 10721 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10722 "Application package " + pkg.packageName 10723 + " already installed. Skipping duplicate."); 10724 } 10725 10726 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10727 // Static libs have a synthetic package name containing the version 10728 // but we still want the base name to be unique. 10729 if (mPackages.containsKey(pkg.manifestPackageName)) { 10730 throw new PackageManagerException( 10731 "Duplicate static shared lib provider package"); 10732 } 10733 10734 // Static shared libraries should have at least O target SDK 10735 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10736 throw new PackageManagerException( 10737 "Packages declaring static-shared libs must target O SDK or higher"); 10738 } 10739 10740 // Package declaring static a shared lib cannot be instant apps 10741 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10742 throw new PackageManagerException( 10743 "Packages declaring static-shared libs cannot be instant apps"); 10744 } 10745 10746 // Package declaring static a shared lib cannot be renamed since the package 10747 // name is synthetic and apps can't code around package manager internals. 10748 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10749 throw new PackageManagerException( 10750 "Packages declaring static-shared libs cannot be renamed"); 10751 } 10752 10753 // Package declaring static a shared lib cannot declare child packages 10754 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10755 throw new PackageManagerException( 10756 "Packages declaring static-shared libs cannot have child packages"); 10757 } 10758 10759 // Package declaring static a shared lib cannot declare dynamic libs 10760 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10761 throw new PackageManagerException( 10762 "Packages declaring static-shared libs cannot declare dynamic libs"); 10763 } 10764 10765 // Package declaring static a shared lib cannot declare shared users 10766 if (pkg.mSharedUserId != null) { 10767 throw new PackageManagerException( 10768 "Packages declaring static-shared libs cannot declare shared users"); 10769 } 10770 10771 // Static shared libs cannot declare activities 10772 if (!pkg.activities.isEmpty()) { 10773 throw new PackageManagerException( 10774 "Static shared libs cannot declare activities"); 10775 } 10776 10777 // Static shared libs cannot declare services 10778 if (!pkg.services.isEmpty()) { 10779 throw new PackageManagerException( 10780 "Static shared libs cannot declare services"); 10781 } 10782 10783 // Static shared libs cannot declare providers 10784 if (!pkg.providers.isEmpty()) { 10785 throw new PackageManagerException( 10786 "Static shared libs cannot declare content providers"); 10787 } 10788 10789 // Static shared libs cannot declare receivers 10790 if (!pkg.receivers.isEmpty()) { 10791 throw new PackageManagerException( 10792 "Static shared libs cannot declare broadcast receivers"); 10793 } 10794 10795 // Static shared libs cannot declare permission groups 10796 if (!pkg.permissionGroups.isEmpty()) { 10797 throw new PackageManagerException( 10798 "Static shared libs cannot declare permission groups"); 10799 } 10800 10801 // Static shared libs cannot declare permissions 10802 if (!pkg.permissions.isEmpty()) { 10803 throw new PackageManagerException( 10804 "Static shared libs cannot declare permissions"); 10805 } 10806 10807 // Static shared libs cannot declare protected broadcasts 10808 if (pkg.protectedBroadcasts != null) { 10809 throw new PackageManagerException( 10810 "Static shared libs cannot declare protected broadcasts"); 10811 } 10812 10813 // Static shared libs cannot be overlay targets 10814 if (pkg.mOverlayTarget != null) { 10815 throw new PackageManagerException( 10816 "Static shared libs cannot be overlay targets"); 10817 } 10818 10819 // The version codes must be ordered as lib versions 10820 int minVersionCode = Integer.MIN_VALUE; 10821 int maxVersionCode = Integer.MAX_VALUE; 10822 10823 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10824 pkg.staticSharedLibName); 10825 if (versionedLib != null) { 10826 final int versionCount = versionedLib.size(); 10827 for (int i = 0; i < versionCount; i++) { 10828 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10829 final int libVersionCode = libInfo.getDeclaringPackage() 10830 .getVersionCode(); 10831 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 10832 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10833 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 10834 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10835 } else { 10836 minVersionCode = maxVersionCode = libVersionCode; 10837 break; 10838 } 10839 } 10840 } 10841 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 10842 throw new PackageManagerException("Static shared" 10843 + " lib version codes must be ordered as lib versions"); 10844 } 10845 } 10846 10847 // Only privileged apps and updated privileged apps can add child packages. 10848 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10849 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 10850 throw new PackageManagerException("Only privileged apps can add child " 10851 + "packages. Ignoring package " + pkg.packageName); 10852 } 10853 final int childCount = pkg.childPackages.size(); 10854 for (int i = 0; i < childCount; i++) { 10855 PackageParser.Package childPkg = pkg.childPackages.get(i); 10856 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10857 childPkg.packageName)) { 10858 throw new PackageManagerException("Can't override child of " 10859 + "another disabled app. Ignoring package " + pkg.packageName); 10860 } 10861 } 10862 } 10863 10864 // If we're only installing presumed-existing packages, require that the 10865 // scanned APK is both already known and at the path previously established 10866 // for it. Previously unknown packages we pick up normally, but if we have an 10867 // a priori expectation about this package's install presence, enforce it. 10868 // With a singular exception for new system packages. When an OTA contains 10869 // a new system package, we allow the codepath to change from a system location 10870 // to the user-installed location. If we don't allow this change, any newer, 10871 // user-installed version of the application will be ignored. 10872 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10873 if (mExpectingBetter.containsKey(pkg.packageName)) { 10874 logCriticalInfo(Log.WARN, 10875 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10876 } else { 10877 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10878 if (known != null) { 10879 if (DEBUG_PACKAGE_SCANNING) { 10880 Log.d(TAG, "Examining " + pkg.codePath 10881 + " and requiring known paths " + known.codePathString 10882 + " & " + known.resourcePathString); 10883 } 10884 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10885 || !pkg.applicationInfo.getResourcePath().equals( 10886 known.resourcePathString)) { 10887 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10888 "Application package " + pkg.packageName 10889 + " found at " + pkg.applicationInfo.getCodePath() 10890 + " but expected at " + known.codePathString 10891 + "; ignoring."); 10892 } 10893 } 10894 } 10895 } 10896 10897 // Verify that this new package doesn't have any content providers 10898 // that conflict with existing packages. Only do this if the 10899 // package isn't already installed, since we don't want to break 10900 // things that are installed. 10901 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10902 final int N = pkg.providers.size(); 10903 int i; 10904 for (i=0; i<N; i++) { 10905 PackageParser.Provider p = pkg.providers.get(i); 10906 if (p.info.authority != null) { 10907 String names[] = p.info.authority.split(";"); 10908 for (int j = 0; j < names.length; j++) { 10909 if (mProvidersByAuthority.containsKey(names[j])) { 10910 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10911 final String otherPackageName = 10912 ((other != null && other.getComponentName() != null) ? 10913 other.getComponentName().getPackageName() : "?"); 10914 throw new PackageManagerException( 10915 INSTALL_FAILED_CONFLICTING_PROVIDER, 10916 "Can't install because provider name " + names[j] 10917 + " (in package " + pkg.applicationInfo.packageName 10918 + ") is already used by " + otherPackageName); 10919 } 10920 } 10921 } 10922 } 10923 } 10924 } 10925 } 10926 10927 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 10928 int type, String declaringPackageName, int declaringVersionCode) { 10929 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10930 if (versionedLib == null) { 10931 versionedLib = new SparseArray<>(); 10932 mSharedLibraries.put(name, versionedLib); 10933 if (type == SharedLibraryInfo.TYPE_STATIC) { 10934 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 10935 } 10936 } else if (versionedLib.indexOfKey(version) >= 0) { 10937 return false; 10938 } 10939 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 10940 version, type, declaringPackageName, declaringVersionCode); 10941 versionedLib.put(version, libEntry); 10942 return true; 10943 } 10944 10945 private boolean removeSharedLibraryLPw(String name, int version) { 10946 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10947 if (versionedLib == null) { 10948 return false; 10949 } 10950 final int libIdx = versionedLib.indexOfKey(version); 10951 if (libIdx < 0) { 10952 return false; 10953 } 10954 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 10955 versionedLib.remove(version); 10956 if (versionedLib.size() <= 0) { 10957 mSharedLibraries.remove(name); 10958 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 10959 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 10960 .getPackageName()); 10961 } 10962 } 10963 return true; 10964 } 10965 10966 /** 10967 * Adds a scanned package to the system. When this method is finished, the package will 10968 * be available for query, resolution, etc... 10969 */ 10970 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 10971 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 10972 final String pkgName = pkg.packageName; 10973 if (mCustomResolverComponentName != null && 10974 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 10975 setUpCustomResolverActivity(pkg); 10976 } 10977 10978 if (pkg.packageName.equals("android")) { 10979 synchronized (mPackages) { 10980 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10981 // Set up information for our fall-back user intent resolution activity. 10982 mPlatformPackage = pkg; 10983 pkg.mVersionCode = mSdkVersion; 10984 mAndroidApplication = pkg.applicationInfo; 10985 if (!mResolverReplaced) { 10986 mResolveActivity.applicationInfo = mAndroidApplication; 10987 mResolveActivity.name = ResolverActivity.class.getName(); 10988 mResolveActivity.packageName = mAndroidApplication.packageName; 10989 mResolveActivity.processName = "system:ui"; 10990 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10991 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10992 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10993 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10994 mResolveActivity.exported = true; 10995 mResolveActivity.enabled = true; 10996 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10997 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10998 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10999 | ActivityInfo.CONFIG_SCREEN_LAYOUT 11000 | ActivityInfo.CONFIG_ORIENTATION 11001 | ActivityInfo.CONFIG_KEYBOARD 11002 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 11003 mResolveInfo.activityInfo = mResolveActivity; 11004 mResolveInfo.priority = 0; 11005 mResolveInfo.preferredOrder = 0; 11006 mResolveInfo.match = 0; 11007 mResolveComponentName = new ComponentName( 11008 mAndroidApplication.packageName, mResolveActivity.name); 11009 } 11010 } 11011 } 11012 } 11013 11014 ArrayList<PackageParser.Package> clientLibPkgs = null; 11015 // writer 11016 synchronized (mPackages) { 11017 boolean hasStaticSharedLibs = false; 11018 11019 // Any app can add new static shared libraries 11020 if (pkg.staticSharedLibName != null) { 11021 // Static shared libs don't allow renaming as they have synthetic package 11022 // names to allow install of multiple versions, so use name from manifest. 11023 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 11024 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 11025 pkg.manifestPackageName, pkg.mVersionCode)) { 11026 hasStaticSharedLibs = true; 11027 } else { 11028 Slog.w(TAG, "Package " + pkg.packageName + " library " 11029 + pkg.staticSharedLibName + " already exists; skipping"); 11030 } 11031 // Static shared libs cannot be updated once installed since they 11032 // use synthetic package name which includes the version code, so 11033 // not need to update other packages's shared lib dependencies. 11034 } 11035 11036 if (!hasStaticSharedLibs 11037 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11038 // Only system apps can add new dynamic shared libraries. 11039 if (pkg.libraryNames != null) { 11040 for (int i = 0; i < pkg.libraryNames.size(); i++) { 11041 String name = pkg.libraryNames.get(i); 11042 boolean allowed = false; 11043 if (pkg.isUpdatedSystemApp()) { 11044 // New library entries can only be added through the 11045 // system image. This is important to get rid of a lot 11046 // of nasty edge cases: for example if we allowed a non- 11047 // system update of the app to add a library, then uninstalling 11048 // the update would make the library go away, and assumptions 11049 // we made such as through app install filtering would now 11050 // have allowed apps on the device which aren't compatible 11051 // with it. Better to just have the restriction here, be 11052 // conservative, and create many fewer cases that can negatively 11053 // impact the user experience. 11054 final PackageSetting sysPs = mSettings 11055 .getDisabledSystemPkgLPr(pkg.packageName); 11056 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 11057 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 11058 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 11059 allowed = true; 11060 break; 11061 } 11062 } 11063 } 11064 } else { 11065 allowed = true; 11066 } 11067 if (allowed) { 11068 if (!addSharedLibraryLPw(null, pkg.packageName, name, 11069 SharedLibraryInfo.VERSION_UNDEFINED, 11070 SharedLibraryInfo.TYPE_DYNAMIC, 11071 pkg.packageName, pkg.mVersionCode)) { 11072 Slog.w(TAG, "Package " + pkg.packageName + " library " 11073 + name + " already exists; skipping"); 11074 } 11075 } else { 11076 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 11077 + name + " that is not declared on system image; skipping"); 11078 } 11079 } 11080 11081 if ((scanFlags & SCAN_BOOTING) == 0) { 11082 // If we are not booting, we need to update any applications 11083 // that are clients of our shared library. If we are booting, 11084 // this will all be done once the scan is complete. 11085 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 11086 } 11087 } 11088 } 11089 } 11090 11091 if ((scanFlags & SCAN_BOOTING) != 0) { 11092 // No apps can run during boot scan, so they don't need to be frozen 11093 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 11094 // Caller asked to not kill app, so it's probably not frozen 11095 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 11096 // Caller asked us to ignore frozen check for some reason; they 11097 // probably didn't know the package name 11098 } else { 11099 // We're doing major surgery on this package, so it better be frozen 11100 // right now to keep it from launching 11101 checkPackageFrozen(pkgName); 11102 } 11103 11104 // Also need to kill any apps that are dependent on the library. 11105 if (clientLibPkgs != null) { 11106 for (int i=0; i<clientLibPkgs.size(); i++) { 11107 PackageParser.Package clientPkg = clientLibPkgs.get(i); 11108 killApplication(clientPkg.applicationInfo.packageName, 11109 clientPkg.applicationInfo.uid, "update lib"); 11110 } 11111 } 11112 11113 // writer 11114 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 11115 11116 synchronized (mPackages) { 11117 // We don't expect installation to fail beyond this point 11118 11119 // Add the new setting to mSettings 11120 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 11121 // Add the new setting to mPackages 11122 mPackages.put(pkg.applicationInfo.packageName, pkg); 11123 // Make sure we don't accidentally delete its data. 11124 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 11125 while (iter.hasNext()) { 11126 PackageCleanItem item = iter.next(); 11127 if (pkgName.equals(item.packageName)) { 11128 iter.remove(); 11129 } 11130 } 11131 11132 // Add the package's KeySets to the global KeySetManagerService 11133 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11134 ksms.addScannedPackageLPw(pkg); 11135 11136 int N = pkg.providers.size(); 11137 StringBuilder r = null; 11138 int i; 11139 for (i=0; i<N; i++) { 11140 PackageParser.Provider p = pkg.providers.get(i); 11141 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 11142 p.info.processName); 11143 mProviders.addProvider(p); 11144 p.syncable = p.info.isSyncable; 11145 if (p.info.authority != null) { 11146 String names[] = p.info.authority.split(";"); 11147 p.info.authority = null; 11148 for (int j = 0; j < names.length; j++) { 11149 if (j == 1 && p.syncable) { 11150 // We only want the first authority for a provider to possibly be 11151 // syncable, so if we already added this provider using a different 11152 // authority clear the syncable flag. We copy the provider before 11153 // changing it because the mProviders object contains a reference 11154 // to a provider that we don't want to change. 11155 // Only do this for the second authority since the resulting provider 11156 // object can be the same for all future authorities for this provider. 11157 p = new PackageParser.Provider(p); 11158 p.syncable = false; 11159 } 11160 if (!mProvidersByAuthority.containsKey(names[j])) { 11161 mProvidersByAuthority.put(names[j], p); 11162 if (p.info.authority == null) { 11163 p.info.authority = names[j]; 11164 } else { 11165 p.info.authority = p.info.authority + ";" + names[j]; 11166 } 11167 if (DEBUG_PACKAGE_SCANNING) { 11168 if (chatty) 11169 Log.d(TAG, "Registered content provider: " + names[j] 11170 + ", className = " + p.info.name + ", isSyncable = " 11171 + p.info.isSyncable); 11172 } 11173 } else { 11174 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11175 Slog.w(TAG, "Skipping provider name " + names[j] + 11176 " (in package " + pkg.applicationInfo.packageName + 11177 "): name already used by " 11178 + ((other != null && other.getComponentName() != null) 11179 ? other.getComponentName().getPackageName() : "?")); 11180 } 11181 } 11182 } 11183 if (chatty) { 11184 if (r == null) { 11185 r = new StringBuilder(256); 11186 } else { 11187 r.append(' '); 11188 } 11189 r.append(p.info.name); 11190 } 11191 } 11192 if (r != null) { 11193 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11194 } 11195 11196 N = pkg.services.size(); 11197 r = null; 11198 for (i=0; i<N; i++) { 11199 PackageParser.Service s = pkg.services.get(i); 11200 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11201 s.info.processName); 11202 mServices.addService(s); 11203 if (chatty) { 11204 if (r == null) { 11205 r = new StringBuilder(256); 11206 } else { 11207 r.append(' '); 11208 } 11209 r.append(s.info.name); 11210 } 11211 } 11212 if (r != null) { 11213 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11214 } 11215 11216 N = pkg.receivers.size(); 11217 r = null; 11218 for (i=0; i<N; i++) { 11219 PackageParser.Activity a = pkg.receivers.get(i); 11220 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11221 a.info.processName); 11222 mReceivers.addActivity(a, "receiver"); 11223 if (chatty) { 11224 if (r == null) { 11225 r = new StringBuilder(256); 11226 } else { 11227 r.append(' '); 11228 } 11229 r.append(a.info.name); 11230 } 11231 } 11232 if (r != null) { 11233 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11234 } 11235 11236 N = pkg.activities.size(); 11237 r = null; 11238 for (i=0; i<N; i++) { 11239 PackageParser.Activity a = pkg.activities.get(i); 11240 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11241 a.info.processName); 11242 mActivities.addActivity(a, "activity"); 11243 if (chatty) { 11244 if (r == null) { 11245 r = new StringBuilder(256); 11246 } else { 11247 r.append(' '); 11248 } 11249 r.append(a.info.name); 11250 } 11251 } 11252 if (r != null) { 11253 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11254 } 11255 11256 N = pkg.permissionGroups.size(); 11257 r = null; 11258 for (i=0; i<N; i++) { 11259 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 11260 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 11261 final String curPackageName = cur == null ? null : cur.info.packageName; 11262 // Dont allow ephemeral apps to define new permission groups. 11263 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11264 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 11265 + pg.info.packageName 11266 + " ignored: instant apps cannot define new permission groups."); 11267 continue; 11268 } 11269 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 11270 if (cur == null || isPackageUpdate) { 11271 mPermissionGroups.put(pg.info.name, pg); 11272 if (chatty) { 11273 if (r == null) { 11274 r = new StringBuilder(256); 11275 } else { 11276 r.append(' '); 11277 } 11278 if (isPackageUpdate) { 11279 r.append("UPD:"); 11280 } 11281 r.append(pg.info.name); 11282 } 11283 } else { 11284 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 11285 + pg.info.packageName + " ignored: original from " 11286 + cur.info.packageName); 11287 if (chatty) { 11288 if (r == null) { 11289 r = new StringBuilder(256); 11290 } else { 11291 r.append(' '); 11292 } 11293 r.append("DUP:"); 11294 r.append(pg.info.name); 11295 } 11296 } 11297 } 11298 if (r != null) { 11299 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 11300 } 11301 11302 N = pkg.permissions.size(); 11303 r = null; 11304 for (i=0; i<N; i++) { 11305 PackageParser.Permission p = pkg.permissions.get(i); 11306 11307 // Dont allow ephemeral apps to define new permissions. 11308 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11309 Slog.w(TAG, "Permission " + p.info.name + " from package " 11310 + p.info.packageName 11311 + " ignored: instant apps cannot define new permissions."); 11312 continue; 11313 } 11314 11315 // Assume by default that we did not install this permission into the system. 11316 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 11317 11318 // Now that permission groups have a special meaning, we ignore permission 11319 // groups for legacy apps to prevent unexpected behavior. In particular, 11320 // permissions for one app being granted to someone just because they happen 11321 // to be in a group defined by another app (before this had no implications). 11322 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 11323 p.group = mPermissionGroups.get(p.info.group); 11324 // Warn for a permission in an unknown group. 11325 if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) { 11326 Slog.i(TAG, "Permission " + p.info.name + " from package " 11327 + p.info.packageName + " in an unknown group " + p.info.group); 11328 } 11329 } 11330 11331 ArrayMap<String, BasePermission> permissionMap = 11332 p.tree ? mSettings.mPermissionTrees 11333 : mSettings.mPermissions; 11334 BasePermission bp = permissionMap.get(p.info.name); 11335 11336 // Allow system apps to redefine non-system permissions 11337 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 11338 final boolean currentOwnerIsSystem = (bp.perm != null 11339 && isSystemApp(bp.perm.owner)); 11340 if (isSystemApp(p.owner)) { 11341 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 11342 // It's a built-in permission and no owner, take ownership now 11343 bp.packageSetting = pkgSetting; 11344 bp.perm = p; 11345 bp.uid = pkg.applicationInfo.uid; 11346 bp.sourcePackage = p.info.packageName; 11347 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 11348 } else if (!currentOwnerIsSystem) { 11349 String msg = "New decl " + p.owner + " of permission " 11350 + p.info.name + " is system; overriding " + bp.sourcePackage; 11351 reportSettingsProblem(Log.WARN, msg); 11352 bp = null; 11353 } 11354 } 11355 } 11356 11357 if (bp == null) { 11358 bp = new BasePermission(p.info.name, p.info.packageName, 11359 BasePermission.TYPE_NORMAL); 11360 permissionMap.put(p.info.name, bp); 11361 } 11362 11363 if (bp.perm == null) { 11364 if (bp.sourcePackage == null 11365 || bp.sourcePackage.equals(p.info.packageName)) { 11366 BasePermission tree = findPermissionTreeLP(p.info.name); 11367 if (tree == null 11368 || tree.sourcePackage.equals(p.info.packageName)) { 11369 bp.packageSetting = pkgSetting; 11370 bp.perm = p; 11371 bp.uid = pkg.applicationInfo.uid; 11372 bp.sourcePackage = p.info.packageName; 11373 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 11374 if (chatty) { 11375 if (r == null) { 11376 r = new StringBuilder(256); 11377 } else { 11378 r.append(' '); 11379 } 11380 r.append(p.info.name); 11381 } 11382 } else { 11383 Slog.w(TAG, "Permission " + p.info.name + " from package " 11384 + p.info.packageName + " ignored: base tree " 11385 + tree.name + " is from package " 11386 + tree.sourcePackage); 11387 } 11388 } else { 11389 Slog.w(TAG, "Permission " + p.info.name + " from package " 11390 + p.info.packageName + " ignored: original from " 11391 + bp.sourcePackage); 11392 } 11393 } else if (chatty) { 11394 if (r == null) { 11395 r = new StringBuilder(256); 11396 } else { 11397 r.append(' '); 11398 } 11399 r.append("DUP:"); 11400 r.append(p.info.name); 11401 } 11402 if (bp.perm == p) { 11403 bp.protectionLevel = p.info.protectionLevel; 11404 } 11405 } 11406 11407 if (r != null) { 11408 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 11409 } 11410 11411 N = pkg.instrumentation.size(); 11412 r = null; 11413 for (i=0; i<N; i++) { 11414 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11415 a.info.packageName = pkg.applicationInfo.packageName; 11416 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11417 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11418 a.info.splitNames = pkg.splitNames; 11419 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11420 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11421 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11422 a.info.dataDir = pkg.applicationInfo.dataDir; 11423 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11424 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11425 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11426 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11427 mInstrumentation.put(a.getComponentName(), a); 11428 if (chatty) { 11429 if (r == null) { 11430 r = new StringBuilder(256); 11431 } else { 11432 r.append(' '); 11433 } 11434 r.append(a.info.name); 11435 } 11436 } 11437 if (r != null) { 11438 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11439 } 11440 11441 if (pkg.protectedBroadcasts != null) { 11442 N = pkg.protectedBroadcasts.size(); 11443 for (i=0; i<N; i++) { 11444 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11445 } 11446 } 11447 } 11448 11449 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11450 } 11451 11452 /** 11453 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11454 * is derived purely on the basis of the contents of {@code scanFile} and 11455 * {@code cpuAbiOverride}. 11456 * 11457 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11458 */ 11459 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 11460 String cpuAbiOverride, boolean extractLibs, 11461 File appLib32InstallDir) 11462 throws PackageManagerException { 11463 // Give ourselves some initial paths; we'll come back for another 11464 // pass once we've determined ABI below. 11465 setNativeLibraryPaths(pkg, appLib32InstallDir); 11466 11467 // We would never need to extract libs for forward-locked and external packages, 11468 // since the container service will do it for us. We shouldn't attempt to 11469 // extract libs from system app when it was not updated. 11470 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11471 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11472 extractLibs = false; 11473 } 11474 11475 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11476 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11477 11478 NativeLibraryHelper.Handle handle = null; 11479 try { 11480 handle = NativeLibraryHelper.Handle.create(pkg); 11481 // TODO(multiArch): This can be null for apps that didn't go through the 11482 // usual installation process. We can calculate it again, like we 11483 // do during install time. 11484 // 11485 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11486 // unnecessary. 11487 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11488 11489 // Null out the abis so that they can be recalculated. 11490 pkg.applicationInfo.primaryCpuAbi = null; 11491 pkg.applicationInfo.secondaryCpuAbi = null; 11492 if (isMultiArch(pkg.applicationInfo)) { 11493 // Warn if we've set an abiOverride for multi-lib packages.. 11494 // By definition, we need to copy both 32 and 64 bit libraries for 11495 // such packages. 11496 if (pkg.cpuAbiOverride != null 11497 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11498 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11499 } 11500 11501 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11502 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11503 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11504 if (extractLibs) { 11505 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11506 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11507 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11508 useIsaSpecificSubdirs); 11509 } else { 11510 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11511 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11512 } 11513 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11514 } 11515 11516 // Shared library native code should be in the APK zip aligned 11517 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11518 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11519 "Shared library native lib extraction not supported"); 11520 } 11521 11522 maybeThrowExceptionForMultiArchCopy( 11523 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11524 11525 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11526 if (extractLibs) { 11527 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11528 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11529 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11530 useIsaSpecificSubdirs); 11531 } else { 11532 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11533 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11534 } 11535 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11536 } 11537 11538 maybeThrowExceptionForMultiArchCopy( 11539 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11540 11541 if (abi64 >= 0) { 11542 // Shared library native libs should be in the APK zip aligned 11543 if (extractLibs && pkg.isLibrary()) { 11544 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11545 "Shared library native lib extraction not supported"); 11546 } 11547 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11548 } 11549 11550 if (abi32 >= 0) { 11551 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11552 if (abi64 >= 0) { 11553 if (pkg.use32bitAbi) { 11554 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11555 pkg.applicationInfo.primaryCpuAbi = abi; 11556 } else { 11557 pkg.applicationInfo.secondaryCpuAbi = abi; 11558 } 11559 } else { 11560 pkg.applicationInfo.primaryCpuAbi = abi; 11561 } 11562 } 11563 } else { 11564 String[] abiList = (cpuAbiOverride != null) ? 11565 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11566 11567 // Enable gross and lame hacks for apps that are built with old 11568 // SDK tools. We must scan their APKs for renderscript bitcode and 11569 // not launch them if it's present. Don't bother checking on devices 11570 // that don't have 64 bit support. 11571 boolean needsRenderScriptOverride = false; 11572 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11573 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11574 abiList = Build.SUPPORTED_32_BIT_ABIS; 11575 needsRenderScriptOverride = true; 11576 } 11577 11578 final int copyRet; 11579 if (extractLibs) { 11580 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11581 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11582 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11583 } else { 11584 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11585 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11586 } 11587 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11588 11589 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11590 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11591 "Error unpackaging native libs for app, errorCode=" + copyRet); 11592 } 11593 11594 if (copyRet >= 0) { 11595 // Shared libraries that have native libs must be multi-architecture 11596 if (pkg.isLibrary()) { 11597 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11598 "Shared library with native libs must be multiarch"); 11599 } 11600 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11601 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11602 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11603 } else if (needsRenderScriptOverride) { 11604 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11605 } 11606 } 11607 } catch (IOException ioe) { 11608 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11609 } finally { 11610 IoUtils.closeQuietly(handle); 11611 } 11612 11613 // Now that we've calculated the ABIs and determined if it's an internal app, 11614 // we will go ahead and populate the nativeLibraryPath. 11615 setNativeLibraryPaths(pkg, appLib32InstallDir); 11616 } 11617 11618 /** 11619 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11620 * i.e, so that all packages can be run inside a single process if required. 11621 * 11622 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11623 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11624 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11625 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11626 * updating a package that belongs to a shared user. 11627 * 11628 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11629 * adds unnecessary complexity. 11630 */ 11631 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 11632 PackageParser.Package scannedPackage) { 11633 String requiredInstructionSet = null; 11634 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11635 requiredInstructionSet = VMRuntime.getInstructionSet( 11636 scannedPackage.applicationInfo.primaryCpuAbi); 11637 } 11638 11639 PackageSetting requirer = null; 11640 for (PackageSetting ps : packagesForUser) { 11641 // If packagesForUser contains scannedPackage, we skip it. This will happen 11642 // when scannedPackage is an update of an existing package. Without this check, 11643 // we will never be able to change the ABI of any package belonging to a shared 11644 // user, even if it's compatible with other packages. 11645 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11646 if (ps.primaryCpuAbiString == null) { 11647 continue; 11648 } 11649 11650 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11651 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11652 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11653 // this but there's not much we can do. 11654 String errorMessage = "Instruction set mismatch, " 11655 + ((requirer == null) ? "[caller]" : requirer) 11656 + " requires " + requiredInstructionSet + " whereas " + ps 11657 + " requires " + instructionSet; 11658 Slog.w(TAG, errorMessage); 11659 } 11660 11661 if (requiredInstructionSet == null) { 11662 requiredInstructionSet = instructionSet; 11663 requirer = ps; 11664 } 11665 } 11666 } 11667 11668 if (requiredInstructionSet != null) { 11669 String adjustedAbi; 11670 if (requirer != null) { 11671 // requirer != null implies that either scannedPackage was null or that scannedPackage 11672 // did not require an ABI, in which case we have to adjust scannedPackage to match 11673 // the ABI of the set (which is the same as requirer's ABI) 11674 adjustedAbi = requirer.primaryCpuAbiString; 11675 if (scannedPackage != null) { 11676 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11677 } 11678 } else { 11679 // requirer == null implies that we're updating all ABIs in the set to 11680 // match scannedPackage. 11681 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11682 } 11683 11684 for (PackageSetting ps : packagesForUser) { 11685 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11686 if (ps.primaryCpuAbiString != null) { 11687 continue; 11688 } 11689 11690 ps.primaryCpuAbiString = adjustedAbi; 11691 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11692 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11693 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11694 if (DEBUG_ABI_SELECTION) { 11695 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11696 + " (requirer=" 11697 + (requirer != null ? requirer.pkg : "null") 11698 + ", scannedPackage=" 11699 + (scannedPackage != null ? scannedPackage : "null") 11700 + ")"); 11701 } 11702 try { 11703 mInstaller.rmdex(ps.codePathString, 11704 getDexCodeInstructionSet(getPreferredInstructionSet())); 11705 } catch (InstallerException ignored) { 11706 } 11707 } 11708 } 11709 } 11710 } 11711 } 11712 11713 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11714 synchronized (mPackages) { 11715 mResolverReplaced = true; 11716 // Set up information for custom user intent resolution activity. 11717 mResolveActivity.applicationInfo = pkg.applicationInfo; 11718 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11719 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11720 mResolveActivity.processName = pkg.applicationInfo.packageName; 11721 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11722 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11723 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11724 mResolveActivity.theme = 0; 11725 mResolveActivity.exported = true; 11726 mResolveActivity.enabled = true; 11727 mResolveInfo.activityInfo = mResolveActivity; 11728 mResolveInfo.priority = 0; 11729 mResolveInfo.preferredOrder = 0; 11730 mResolveInfo.match = 0; 11731 mResolveComponentName = mCustomResolverComponentName; 11732 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11733 mResolveComponentName); 11734 } 11735 } 11736 11737 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11738 if (installerActivity == null) { 11739 if (DEBUG_EPHEMERAL) { 11740 Slog.d(TAG, "Clear ephemeral installer activity"); 11741 } 11742 mInstantAppInstallerActivity = null; 11743 return; 11744 } 11745 11746 if (DEBUG_EPHEMERAL) { 11747 Slog.d(TAG, "Set ephemeral installer activity: " 11748 + installerActivity.getComponentName()); 11749 } 11750 // Set up information for ephemeral installer activity 11751 mInstantAppInstallerActivity = installerActivity; 11752 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11753 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11754 mInstantAppInstallerActivity.exported = true; 11755 mInstantAppInstallerActivity.enabled = true; 11756 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11757 mInstantAppInstallerInfo.priority = 0; 11758 mInstantAppInstallerInfo.preferredOrder = 1; 11759 mInstantAppInstallerInfo.isDefault = true; 11760 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11761 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11762 } 11763 11764 private static String calculateBundledApkRoot(final String codePathString) { 11765 final File codePath = new File(codePathString); 11766 final File codeRoot; 11767 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11768 codeRoot = Environment.getRootDirectory(); 11769 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11770 codeRoot = Environment.getOemDirectory(); 11771 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11772 codeRoot = Environment.getVendorDirectory(); 11773 } else { 11774 // Unrecognized code path; take its top real segment as the apk root: 11775 // e.g. /something/app/blah.apk => /something 11776 try { 11777 File f = codePath.getCanonicalFile(); 11778 File parent = f.getParentFile(); // non-null because codePath is a file 11779 File tmp; 11780 while ((tmp = parent.getParentFile()) != null) { 11781 f = parent; 11782 parent = tmp; 11783 } 11784 codeRoot = f; 11785 Slog.w(TAG, "Unrecognized code path " 11786 + codePath + " - using " + codeRoot); 11787 } catch (IOException e) { 11788 // Can't canonicalize the code path -- shenanigans? 11789 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11790 return Environment.getRootDirectory().getPath(); 11791 } 11792 } 11793 return codeRoot.getPath(); 11794 } 11795 11796 /** 11797 * Derive and set the location of native libraries for the given package, 11798 * which varies depending on where and how the package was installed. 11799 */ 11800 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11801 final ApplicationInfo info = pkg.applicationInfo; 11802 final String codePath = pkg.codePath; 11803 final File codeFile = new File(codePath); 11804 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11805 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11806 11807 info.nativeLibraryRootDir = null; 11808 info.nativeLibraryRootRequiresIsa = false; 11809 info.nativeLibraryDir = null; 11810 info.secondaryNativeLibraryDir = null; 11811 11812 if (isApkFile(codeFile)) { 11813 // Monolithic install 11814 if (bundledApp) { 11815 // If "/system/lib64/apkname" exists, assume that is the per-package 11816 // native library directory to use; otherwise use "/system/lib/apkname". 11817 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11818 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11819 getPrimaryInstructionSet(info)); 11820 11821 // This is a bundled system app so choose the path based on the ABI. 11822 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11823 // is just the default path. 11824 final String apkName = deriveCodePathName(codePath); 11825 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11826 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11827 apkName).getAbsolutePath(); 11828 11829 if (info.secondaryCpuAbi != null) { 11830 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11831 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11832 secondaryLibDir, apkName).getAbsolutePath(); 11833 } 11834 } else if (asecApp) { 11835 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11836 .getAbsolutePath(); 11837 } else { 11838 final String apkName = deriveCodePathName(codePath); 11839 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11840 .getAbsolutePath(); 11841 } 11842 11843 info.nativeLibraryRootRequiresIsa = false; 11844 info.nativeLibraryDir = info.nativeLibraryRootDir; 11845 } else { 11846 // Cluster install 11847 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11848 info.nativeLibraryRootRequiresIsa = true; 11849 11850 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11851 getPrimaryInstructionSet(info)).getAbsolutePath(); 11852 11853 if (info.secondaryCpuAbi != null) { 11854 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11855 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11856 } 11857 } 11858 } 11859 11860 /** 11861 * Calculate the abis and roots for a bundled app. These can uniquely 11862 * be determined from the contents of the system partition, i.e whether 11863 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11864 * of this information, and instead assume that the system was built 11865 * sensibly. 11866 */ 11867 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11868 PackageSetting pkgSetting) { 11869 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11870 11871 // If "/system/lib64/apkname" exists, assume that is the per-package 11872 // native library directory to use; otherwise use "/system/lib/apkname". 11873 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11874 setBundledAppAbi(pkg, apkRoot, apkName); 11875 // pkgSetting might be null during rescan following uninstall of updates 11876 // to a bundled app, so accommodate that possibility. The settings in 11877 // that case will be established later from the parsed package. 11878 // 11879 // If the settings aren't null, sync them up with what we've just derived. 11880 // note that apkRoot isn't stored in the package settings. 11881 if (pkgSetting != null) { 11882 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11883 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11884 } 11885 } 11886 11887 /** 11888 * Deduces the ABI of a bundled app and sets the relevant fields on the 11889 * parsed pkg object. 11890 * 11891 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11892 * under which system libraries are installed. 11893 * @param apkName the name of the installed package. 11894 */ 11895 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11896 final File codeFile = new File(pkg.codePath); 11897 11898 final boolean has64BitLibs; 11899 final boolean has32BitLibs; 11900 if (isApkFile(codeFile)) { 11901 // Monolithic install 11902 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11903 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11904 } else { 11905 // Cluster install 11906 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11907 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11908 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11909 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11910 has64BitLibs = (new File(rootDir, isa)).exists(); 11911 } else { 11912 has64BitLibs = false; 11913 } 11914 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11915 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11916 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11917 has32BitLibs = (new File(rootDir, isa)).exists(); 11918 } else { 11919 has32BitLibs = false; 11920 } 11921 } 11922 11923 if (has64BitLibs && !has32BitLibs) { 11924 // The package has 64 bit libs, but not 32 bit libs. Its primary 11925 // ABI should be 64 bit. We can safely assume here that the bundled 11926 // native libraries correspond to the most preferred ABI in the list. 11927 11928 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11929 pkg.applicationInfo.secondaryCpuAbi = null; 11930 } else if (has32BitLibs && !has64BitLibs) { 11931 // The package has 32 bit libs but not 64 bit libs. Its primary 11932 // ABI should be 32 bit. 11933 11934 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11935 pkg.applicationInfo.secondaryCpuAbi = null; 11936 } else if (has32BitLibs && has64BitLibs) { 11937 // The application has both 64 and 32 bit bundled libraries. We check 11938 // here that the app declares multiArch support, and warn if it doesn't. 11939 // 11940 // We will be lenient here and record both ABIs. The primary will be the 11941 // ABI that's higher on the list, i.e, a device that's configured to prefer 11942 // 64 bit apps will see a 64 bit primary ABI, 11943 11944 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11945 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11946 } 11947 11948 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11949 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11950 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11951 } else { 11952 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11953 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11954 } 11955 } else { 11956 pkg.applicationInfo.primaryCpuAbi = null; 11957 pkg.applicationInfo.secondaryCpuAbi = null; 11958 } 11959 } 11960 11961 private void killApplication(String pkgName, int appId, String reason) { 11962 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11963 } 11964 11965 private void killApplication(String pkgName, int appId, int userId, String reason) { 11966 // Request the ActivityManager to kill the process(only for existing packages) 11967 // so that we do not end up in a confused state while the user is still using the older 11968 // version of the application while the new one gets installed. 11969 final long token = Binder.clearCallingIdentity(); 11970 try { 11971 IActivityManager am = ActivityManager.getService(); 11972 if (am != null) { 11973 try { 11974 am.killApplication(pkgName, appId, userId, reason); 11975 } catch (RemoteException e) { 11976 } 11977 } 11978 } finally { 11979 Binder.restoreCallingIdentity(token); 11980 } 11981 } 11982 11983 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11984 // Remove the parent package setting 11985 PackageSetting ps = (PackageSetting) pkg.mExtras; 11986 if (ps != null) { 11987 removePackageLI(ps, chatty); 11988 } 11989 // Remove the child package setting 11990 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11991 for (int i = 0; i < childCount; i++) { 11992 PackageParser.Package childPkg = pkg.childPackages.get(i); 11993 ps = (PackageSetting) childPkg.mExtras; 11994 if (ps != null) { 11995 removePackageLI(ps, chatty); 11996 } 11997 } 11998 } 11999 12000 void removePackageLI(PackageSetting ps, boolean chatty) { 12001 if (DEBUG_INSTALL) { 12002 if (chatty) 12003 Log.d(TAG, "Removing package " + ps.name); 12004 } 12005 12006 // writer 12007 synchronized (mPackages) { 12008 mPackages.remove(ps.name); 12009 final PackageParser.Package pkg = ps.pkg; 12010 if (pkg != null) { 12011 cleanPackageDataStructuresLILPw(pkg, chatty); 12012 } 12013 } 12014 } 12015 12016 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 12017 if (DEBUG_INSTALL) { 12018 if (chatty) 12019 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 12020 } 12021 12022 // writer 12023 synchronized (mPackages) { 12024 // Remove the parent package 12025 mPackages.remove(pkg.applicationInfo.packageName); 12026 cleanPackageDataStructuresLILPw(pkg, chatty); 12027 12028 // Remove the child packages 12029 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12030 for (int i = 0; i < childCount; i++) { 12031 PackageParser.Package childPkg = pkg.childPackages.get(i); 12032 mPackages.remove(childPkg.applicationInfo.packageName); 12033 cleanPackageDataStructuresLILPw(childPkg, chatty); 12034 } 12035 } 12036 } 12037 12038 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 12039 int N = pkg.providers.size(); 12040 StringBuilder r = null; 12041 int i; 12042 for (i=0; i<N; i++) { 12043 PackageParser.Provider p = pkg.providers.get(i); 12044 mProviders.removeProvider(p); 12045 if (p.info.authority == null) { 12046 12047 /* There was another ContentProvider with this authority when 12048 * this app was installed so this authority is null, 12049 * Ignore it as we don't have to unregister the provider. 12050 */ 12051 continue; 12052 } 12053 String names[] = p.info.authority.split(";"); 12054 for (int j = 0; j < names.length; j++) { 12055 if (mProvidersByAuthority.get(names[j]) == p) { 12056 mProvidersByAuthority.remove(names[j]); 12057 if (DEBUG_REMOVE) { 12058 if (chatty) 12059 Log.d(TAG, "Unregistered content provider: " + names[j] 12060 + ", className = " + p.info.name + ", isSyncable = " 12061 + p.info.isSyncable); 12062 } 12063 } 12064 } 12065 if (DEBUG_REMOVE && chatty) { 12066 if (r == null) { 12067 r = new StringBuilder(256); 12068 } else { 12069 r.append(' '); 12070 } 12071 r.append(p.info.name); 12072 } 12073 } 12074 if (r != null) { 12075 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 12076 } 12077 12078 N = pkg.services.size(); 12079 r = null; 12080 for (i=0; i<N; i++) { 12081 PackageParser.Service s = pkg.services.get(i); 12082 mServices.removeService(s); 12083 if (chatty) { 12084 if (r == null) { 12085 r = new StringBuilder(256); 12086 } else { 12087 r.append(' '); 12088 } 12089 r.append(s.info.name); 12090 } 12091 } 12092 if (r != null) { 12093 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 12094 } 12095 12096 N = pkg.receivers.size(); 12097 r = null; 12098 for (i=0; i<N; i++) { 12099 PackageParser.Activity a = pkg.receivers.get(i); 12100 mReceivers.removeActivity(a, "receiver"); 12101 if (DEBUG_REMOVE && chatty) { 12102 if (r == null) { 12103 r = new StringBuilder(256); 12104 } else { 12105 r.append(' '); 12106 } 12107 r.append(a.info.name); 12108 } 12109 } 12110 if (r != null) { 12111 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 12112 } 12113 12114 N = pkg.activities.size(); 12115 r = null; 12116 for (i=0; i<N; i++) { 12117 PackageParser.Activity a = pkg.activities.get(i); 12118 mActivities.removeActivity(a, "activity"); 12119 if (DEBUG_REMOVE && chatty) { 12120 if (r == null) { 12121 r = new StringBuilder(256); 12122 } else { 12123 r.append(' '); 12124 } 12125 r.append(a.info.name); 12126 } 12127 } 12128 if (r != null) { 12129 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 12130 } 12131 12132 N = pkg.permissions.size(); 12133 r = null; 12134 for (i=0; i<N; i++) { 12135 PackageParser.Permission p = pkg.permissions.get(i); 12136 BasePermission bp = mSettings.mPermissions.get(p.info.name); 12137 if (bp == null) { 12138 bp = mSettings.mPermissionTrees.get(p.info.name); 12139 } 12140 if (bp != null && bp.perm == p) { 12141 bp.perm = null; 12142 if (DEBUG_REMOVE && chatty) { 12143 if (r == null) { 12144 r = new StringBuilder(256); 12145 } else { 12146 r.append(' '); 12147 } 12148 r.append(p.info.name); 12149 } 12150 } 12151 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 12152 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 12153 if (appOpPkgs != null) { 12154 appOpPkgs.remove(pkg.packageName); 12155 } 12156 } 12157 } 12158 if (r != null) { 12159 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 12160 } 12161 12162 N = pkg.requestedPermissions.size(); 12163 r = null; 12164 for (i=0; i<N; i++) { 12165 String perm = pkg.requestedPermissions.get(i); 12166 BasePermission bp = mSettings.mPermissions.get(perm); 12167 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 12168 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 12169 if (appOpPkgs != null) { 12170 appOpPkgs.remove(pkg.packageName); 12171 if (appOpPkgs.isEmpty()) { 12172 mAppOpPermissionPackages.remove(perm); 12173 } 12174 } 12175 } 12176 } 12177 if (r != null) { 12178 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 12179 } 12180 12181 N = pkg.instrumentation.size(); 12182 r = null; 12183 for (i=0; i<N; i++) { 12184 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12185 mInstrumentation.remove(a.getComponentName()); 12186 if (DEBUG_REMOVE && chatty) { 12187 if (r == null) { 12188 r = new StringBuilder(256); 12189 } else { 12190 r.append(' '); 12191 } 12192 r.append(a.info.name); 12193 } 12194 } 12195 if (r != null) { 12196 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 12197 } 12198 12199 r = null; 12200 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 12201 // Only system apps can hold shared libraries. 12202 if (pkg.libraryNames != null) { 12203 for (i = 0; i < pkg.libraryNames.size(); i++) { 12204 String name = pkg.libraryNames.get(i); 12205 if (removeSharedLibraryLPw(name, 0)) { 12206 if (DEBUG_REMOVE && chatty) { 12207 if (r == null) { 12208 r = new StringBuilder(256); 12209 } else { 12210 r.append(' '); 12211 } 12212 r.append(name); 12213 } 12214 } 12215 } 12216 } 12217 } 12218 12219 r = null; 12220 12221 // Any package can hold static shared libraries. 12222 if (pkg.staticSharedLibName != null) { 12223 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 12224 if (DEBUG_REMOVE && chatty) { 12225 if (r == null) { 12226 r = new StringBuilder(256); 12227 } else { 12228 r.append(' '); 12229 } 12230 r.append(pkg.staticSharedLibName); 12231 } 12232 } 12233 } 12234 12235 if (r != null) { 12236 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12237 } 12238 } 12239 12240 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 12241 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 12242 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 12243 return true; 12244 } 12245 } 12246 return false; 12247 } 12248 12249 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 12250 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 12251 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 12252 12253 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 12254 // Update the parent permissions 12255 updatePermissionsLPw(pkg.packageName, pkg, flags); 12256 // Update the child permissions 12257 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12258 for (int i = 0; i < childCount; i++) { 12259 PackageParser.Package childPkg = pkg.childPackages.get(i); 12260 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 12261 } 12262 } 12263 12264 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 12265 int flags) { 12266 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 12267 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 12268 } 12269 12270 private void updatePermissionsLPw(String changingPkg, 12271 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 12272 // Make sure there are no dangling permission trees. 12273 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 12274 while (it.hasNext()) { 12275 final BasePermission bp = it.next(); 12276 if (bp.packageSetting == null) { 12277 // We may not yet have parsed the package, so just see if 12278 // we still know about its settings. 12279 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 12280 } 12281 if (bp.packageSetting == null) { 12282 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 12283 + " from package " + bp.sourcePackage); 12284 it.remove(); 12285 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 12286 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 12287 Slog.i(TAG, "Removing old permission tree: " + bp.name 12288 + " from package " + bp.sourcePackage); 12289 flags |= UPDATE_PERMISSIONS_ALL; 12290 it.remove(); 12291 } 12292 } 12293 } 12294 12295 // Make sure all dynamic permissions have been assigned to a package, 12296 // and make sure there are no dangling permissions. 12297 it = mSettings.mPermissions.values().iterator(); 12298 while (it.hasNext()) { 12299 final BasePermission bp = it.next(); 12300 if (bp.type == BasePermission.TYPE_DYNAMIC) { 12301 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 12302 + bp.name + " pkg=" + bp.sourcePackage 12303 + " info=" + bp.pendingInfo); 12304 if (bp.packageSetting == null && bp.pendingInfo != null) { 12305 final BasePermission tree = findPermissionTreeLP(bp.name); 12306 if (tree != null && tree.perm != null) { 12307 bp.packageSetting = tree.packageSetting; 12308 bp.perm = new PackageParser.Permission(tree.perm.owner, 12309 new PermissionInfo(bp.pendingInfo)); 12310 bp.perm.info.packageName = tree.perm.info.packageName; 12311 bp.perm.info.name = bp.name; 12312 bp.uid = tree.uid; 12313 } 12314 } 12315 } 12316 if (bp.packageSetting == null) { 12317 // We may not yet have parsed the package, so just see if 12318 // we still know about its settings. 12319 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 12320 } 12321 if (bp.packageSetting == null) { 12322 Slog.w(TAG, "Removing dangling permission: " + bp.name 12323 + " from package " + bp.sourcePackage); 12324 it.remove(); 12325 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 12326 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 12327 Slog.i(TAG, "Removing old permission: " + bp.name 12328 + " from package " + bp.sourcePackage); 12329 flags |= UPDATE_PERMISSIONS_ALL; 12330 it.remove(); 12331 } 12332 } 12333 } 12334 12335 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 12336 // Now update the permissions for all packages, in particular 12337 // replace the granted permissions of the system packages. 12338 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 12339 for (PackageParser.Package pkg : mPackages.values()) { 12340 if (pkg != pkgInfo) { 12341 // Only replace for packages on requested volume 12342 final String volumeUuid = getVolumeUuidForPackage(pkg); 12343 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 12344 && Objects.equals(replaceVolumeUuid, volumeUuid); 12345 grantPermissionsLPw(pkg, replace, changingPkg); 12346 } 12347 } 12348 } 12349 12350 if (pkgInfo != null) { 12351 // Only replace for packages on requested volume 12352 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 12353 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 12354 && Objects.equals(replaceVolumeUuid, volumeUuid); 12355 grantPermissionsLPw(pkgInfo, replace, changingPkg); 12356 } 12357 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12358 } 12359 12360 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 12361 String packageOfInterest) { 12362 // IMPORTANT: There are two types of permissions: install and runtime. 12363 // Install time permissions are granted when the app is installed to 12364 // all device users and users added in the future. Runtime permissions 12365 // are granted at runtime explicitly to specific users. Normal and signature 12366 // protected permissions are install time permissions. Dangerous permissions 12367 // are install permissions if the app's target SDK is Lollipop MR1 or older, 12368 // otherwise they are runtime permissions. This function does not manage 12369 // runtime permissions except for the case an app targeting Lollipop MR1 12370 // being upgraded to target a newer SDK, in which case dangerous permissions 12371 // are transformed from install time to runtime ones. 12372 12373 final PackageSetting ps = (PackageSetting) pkg.mExtras; 12374 if (ps == null) { 12375 return; 12376 } 12377 12378 PermissionsState permissionsState = ps.getPermissionsState(); 12379 PermissionsState origPermissions = permissionsState; 12380 12381 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 12382 12383 boolean runtimePermissionsRevoked = false; 12384 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 12385 12386 boolean changedInstallPermission = false; 12387 12388 if (replace) { 12389 ps.installPermissionsFixed = false; 12390 if (!ps.isSharedUser()) { 12391 origPermissions = new PermissionsState(permissionsState); 12392 permissionsState.reset(); 12393 } else { 12394 // We need to know only about runtime permission changes since the 12395 // calling code always writes the install permissions state but 12396 // the runtime ones are written only if changed. The only cases of 12397 // changed runtime permissions here are promotion of an install to 12398 // runtime and revocation of a runtime from a shared user. 12399 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 12400 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 12401 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 12402 runtimePermissionsRevoked = true; 12403 } 12404 } 12405 } 12406 12407 permissionsState.setGlobalGids(mGlobalGids); 12408 12409 final int N = pkg.requestedPermissions.size(); 12410 for (int i=0; i<N; i++) { 12411 final String name = pkg.requestedPermissions.get(i); 12412 final BasePermission bp = mSettings.mPermissions.get(name); 12413 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 12414 >= Build.VERSION_CODES.M; 12415 12416 if (DEBUG_INSTALL) { 12417 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 12418 } 12419 12420 if (bp == null || bp.packageSetting == null) { 12421 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 12422 if (DEBUG_PERMISSIONS) { 12423 Slog.i(TAG, "Unknown permission " + name 12424 + " in package " + pkg.packageName); 12425 } 12426 } 12427 continue; 12428 } 12429 12430 12431 // Limit ephemeral apps to ephemeral allowed permissions. 12432 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 12433 if (DEBUG_PERMISSIONS) { 12434 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 12435 + pkg.packageName); 12436 } 12437 continue; 12438 } 12439 12440 if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) { 12441 if (DEBUG_PERMISSIONS) { 12442 Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package " 12443 + pkg.packageName); 12444 } 12445 continue; 12446 } 12447 12448 final String perm = bp.name; 12449 boolean allowedSig = false; 12450 int grant = GRANT_DENIED; 12451 12452 // Keep track of app op permissions. 12453 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 12454 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 12455 if (pkgs == null) { 12456 pkgs = new ArraySet<>(); 12457 mAppOpPermissionPackages.put(bp.name, pkgs); 12458 } 12459 pkgs.add(pkg.packageName); 12460 } 12461 12462 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 12463 switch (level) { 12464 case PermissionInfo.PROTECTION_NORMAL: { 12465 // For all apps normal permissions are install time ones. 12466 grant = GRANT_INSTALL; 12467 } break; 12468 12469 case PermissionInfo.PROTECTION_DANGEROUS: { 12470 // If a permission review is required for legacy apps we represent 12471 // their permissions as always granted runtime ones since we need 12472 // to keep the review required permission flag per user while an 12473 // install permission's state is shared across all users. 12474 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 12475 // For legacy apps dangerous permissions are install time ones. 12476 grant = GRANT_INSTALL; 12477 } else if (origPermissions.hasInstallPermission(bp.name)) { 12478 // For legacy apps that became modern, install becomes runtime. 12479 grant = GRANT_UPGRADE; 12480 } else if (mPromoteSystemApps 12481 && isSystemApp(ps) 12482 && mExistingSystemPackages.contains(ps.name)) { 12483 // For legacy system apps, install becomes runtime. 12484 // We cannot check hasInstallPermission() for system apps since those 12485 // permissions were granted implicitly and not persisted pre-M. 12486 grant = GRANT_UPGRADE; 12487 } else { 12488 // For modern apps keep runtime permissions unchanged. 12489 grant = GRANT_RUNTIME; 12490 } 12491 } break; 12492 12493 case PermissionInfo.PROTECTION_SIGNATURE: { 12494 // For all apps signature permissions are install time ones. 12495 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 12496 if (allowedSig) { 12497 grant = GRANT_INSTALL; 12498 } 12499 } break; 12500 } 12501 12502 if (DEBUG_PERMISSIONS) { 12503 Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName); 12504 } 12505 12506 if (grant != GRANT_DENIED) { 12507 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 12508 // If this is an existing, non-system package, then 12509 // we can't add any new permissions to it. 12510 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 12511 // Except... if this is a permission that was added 12512 // to the platform (note: need to only do this when 12513 // updating the platform). 12514 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 12515 grant = GRANT_DENIED; 12516 } 12517 } 12518 } 12519 12520 switch (grant) { 12521 case GRANT_INSTALL: { 12522 // Revoke this as runtime permission to handle the case of 12523 // a runtime permission being downgraded to an install one. 12524 // Also in permission review mode we keep dangerous permissions 12525 // for legacy apps 12526 for (int userId : UserManagerService.getInstance().getUserIds()) { 12527 if (origPermissions.getRuntimePermissionState( 12528 bp.name, userId) != null) { 12529 // Revoke the runtime permission and clear the flags. 12530 origPermissions.revokeRuntimePermission(bp, userId); 12531 origPermissions.updatePermissionFlags(bp, userId, 12532 PackageManager.MASK_PERMISSION_FLAGS, 0); 12533 // If we revoked a permission permission, we have to write. 12534 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12535 changedRuntimePermissionUserIds, userId); 12536 } 12537 } 12538 // Grant an install permission. 12539 if (permissionsState.grantInstallPermission(bp) != 12540 PermissionsState.PERMISSION_OPERATION_FAILURE) { 12541 changedInstallPermission = true; 12542 } 12543 } break; 12544 12545 case GRANT_RUNTIME: { 12546 // Grant previously granted runtime permissions. 12547 for (int userId : UserManagerService.getInstance().getUserIds()) { 12548 PermissionState permissionState = origPermissions 12549 .getRuntimePermissionState(bp.name, userId); 12550 int flags = permissionState != null 12551 ? permissionState.getFlags() : 0; 12552 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 12553 // Don't propagate the permission in a permission review mode if 12554 // the former was revoked, i.e. marked to not propagate on upgrade. 12555 // Note that in a permission review mode install permissions are 12556 // represented as constantly granted runtime ones since we need to 12557 // keep a per user state associated with the permission. Also the 12558 // revoke on upgrade flag is no longer applicable and is reset. 12559 final boolean revokeOnUpgrade = (flags & PackageManager 12560 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 12561 if (revokeOnUpgrade) { 12562 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12563 // Since we changed the flags, we have to write. 12564 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12565 changedRuntimePermissionUserIds, userId); 12566 } 12567 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 12568 if (permissionsState.grantRuntimePermission(bp, userId) == 12569 PermissionsState.PERMISSION_OPERATION_FAILURE) { 12570 // If we cannot put the permission as it was, 12571 // we have to write. 12572 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12573 changedRuntimePermissionUserIds, userId); 12574 } 12575 } 12576 12577 // If the app supports runtime permissions no need for a review. 12578 if (mPermissionReviewRequired 12579 && appSupportsRuntimePermissions 12580 && (flags & PackageManager 12581 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 12582 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 12583 // Since we changed the flags, we have to write. 12584 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12585 changedRuntimePermissionUserIds, userId); 12586 } 12587 } else if (mPermissionReviewRequired 12588 && !appSupportsRuntimePermissions) { 12589 // For legacy apps that need a permission review, every new 12590 // runtime permission is granted but it is pending a review. 12591 // We also need to review only platform defined runtime 12592 // permissions as these are the only ones the platform knows 12593 // how to disable the API to simulate revocation as legacy 12594 // apps don't expect to run with revoked permissions. 12595 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 12596 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 12597 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 12598 // We changed the flags, hence have to write. 12599 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12600 changedRuntimePermissionUserIds, userId); 12601 } 12602 } 12603 if (permissionsState.grantRuntimePermission(bp, userId) 12604 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 12605 // We changed the permission, hence have to write. 12606 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12607 changedRuntimePermissionUserIds, userId); 12608 } 12609 } 12610 // Propagate the permission flags. 12611 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 12612 } 12613 } break; 12614 12615 case GRANT_UPGRADE: { 12616 // Grant runtime permissions for a previously held install permission. 12617 PermissionState permissionState = origPermissions 12618 .getInstallPermissionState(bp.name); 12619 final int flags = permissionState != null ? permissionState.getFlags() : 0; 12620 12621 if (origPermissions.revokeInstallPermission(bp) 12622 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 12623 // We will be transferring the permission flags, so clear them. 12624 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 12625 PackageManager.MASK_PERMISSION_FLAGS, 0); 12626 changedInstallPermission = true; 12627 } 12628 12629 // If the permission is not to be promoted to runtime we ignore it and 12630 // also its other flags as they are not applicable to install permissions. 12631 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 12632 for (int userId : currentUserIds) { 12633 if (permissionsState.grantRuntimePermission(bp, userId) != 12634 PermissionsState.PERMISSION_OPERATION_FAILURE) { 12635 // Transfer the permission flags. 12636 permissionsState.updatePermissionFlags(bp, userId, 12637 flags, flags); 12638 // If we granted the permission, we have to write. 12639 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 12640 changedRuntimePermissionUserIds, userId); 12641 } 12642 } 12643 } 12644 } break; 12645 12646 default: { 12647 if (packageOfInterest == null 12648 || packageOfInterest.equals(pkg.packageName)) { 12649 if (DEBUG_PERMISSIONS) { 12650 Slog.i(TAG, "Not granting permission " + perm 12651 + " to package " + pkg.packageName 12652 + " because it was previously installed without"); 12653 } 12654 } 12655 } break; 12656 } 12657 } else { 12658 if (permissionsState.revokeInstallPermission(bp) != 12659 PermissionsState.PERMISSION_OPERATION_FAILURE) { 12660 // Also drop the permission flags. 12661 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12662 PackageManager.MASK_PERMISSION_FLAGS, 0); 12663 changedInstallPermission = true; 12664 Slog.i(TAG, "Un-granting permission " + perm 12665 + " from package " + pkg.packageName 12666 + " (protectionLevel=" + bp.protectionLevel 12667 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 12668 + ")"); 12669 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 12670 // Don't print warning for app op permissions, since it is fine for them 12671 // not to be granted, there is a UI for the user to decide. 12672 if (DEBUG_PERMISSIONS 12673 && (packageOfInterest == null 12674 || packageOfInterest.equals(pkg.packageName))) { 12675 Slog.i(TAG, "Not granting permission " + perm 12676 + " to package " + pkg.packageName 12677 + " (protectionLevel=" + bp.protectionLevel 12678 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 12679 + ")"); 12680 } 12681 } 12682 } 12683 } 12684 12685 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 12686 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 12687 // This is the first that we have heard about this package, so the 12688 // permissions we have now selected are fixed until explicitly 12689 // changed. 12690 ps.installPermissionsFixed = true; 12691 } 12692 12693 // Persist the runtime permissions state for users with changes. If permissions 12694 // were revoked because no app in the shared user declares them we have to 12695 // write synchronously to avoid losing runtime permissions state. 12696 for (int userId : changedRuntimePermissionUserIds) { 12697 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 12698 } 12699 } 12700 12701 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 12702 boolean allowed = false; 12703 final int NP = PackageParser.NEW_PERMISSIONS.length; 12704 for (int ip=0; ip<NP; ip++) { 12705 final PackageParser.NewPermissionInfo npi 12706 = PackageParser.NEW_PERMISSIONS[ip]; 12707 if (npi.name.equals(perm) 12708 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 12709 allowed = true; 12710 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 12711 + pkg.packageName); 12712 break; 12713 } 12714 } 12715 return allowed; 12716 } 12717 12718 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 12719 BasePermission bp, PermissionsState origPermissions) { 12720 boolean privilegedPermission = (bp.protectionLevel 12721 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 12722 boolean privappPermissionsDisable = 12723 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 12724 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 12725 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 12726 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 12727 && !platformPackage && platformPermission) { 12728 ArraySet<String> wlPermissions = SystemConfig.getInstance() 12729 .getPrivAppPermissions(pkg.packageName); 12730 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 12731 if (!whitelisted) { 12732 Slog.w(TAG, "Privileged permission " + perm + " for package " 12733 + pkg.packageName + " - not in privapp-permissions whitelist"); 12734 // Only report violations for apps on system image 12735 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 12736 if (mPrivappPermissionsViolations == null) { 12737 mPrivappPermissionsViolations = new ArraySet<>(); 12738 } 12739 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 12740 } 12741 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 12742 return false; 12743 } 12744 } 12745 } 12746 boolean allowed = (compareSignatures( 12747 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 12748 == PackageManager.SIGNATURE_MATCH) 12749 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 12750 == PackageManager.SIGNATURE_MATCH); 12751 if (!allowed && privilegedPermission) { 12752 if (isSystemApp(pkg)) { 12753 // For updated system applications, a system permission 12754 // is granted only if it had been defined by the original application. 12755 if (pkg.isUpdatedSystemApp()) { 12756 final PackageSetting sysPs = mSettings 12757 .getDisabledSystemPkgLPr(pkg.packageName); 12758 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 12759 // If the original was granted this permission, we take 12760 // that grant decision as read and propagate it to the 12761 // update. 12762 if (sysPs.isPrivileged()) { 12763 allowed = true; 12764 } 12765 } else { 12766 // The system apk may have been updated with an older 12767 // version of the one on the data partition, but which 12768 // granted a new system permission that it didn't have 12769 // before. In this case we do want to allow the app to 12770 // now get the new permission if the ancestral apk is 12771 // privileged to get it. 12772 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 12773 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 12774 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 12775 allowed = true; 12776 break; 12777 } 12778 } 12779 } 12780 // Also if a privileged parent package on the system image or any of 12781 // its children requested a privileged permission, the updated child 12782 // packages can also get the permission. 12783 if (pkg.parentPackage != null) { 12784 final PackageSetting disabledSysParentPs = mSettings 12785 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 12786 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 12787 && disabledSysParentPs.isPrivileged()) { 12788 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 12789 allowed = true; 12790 } else if (disabledSysParentPs.pkg.childPackages != null) { 12791 final int count = disabledSysParentPs.pkg.childPackages.size(); 12792 for (int i = 0; i < count; i++) { 12793 PackageParser.Package disabledSysChildPkg = 12794 disabledSysParentPs.pkg.childPackages.get(i); 12795 if (isPackageRequestingPermission(disabledSysChildPkg, 12796 perm)) { 12797 allowed = true; 12798 break; 12799 } 12800 } 12801 } 12802 } 12803 } 12804 } 12805 } else { 12806 allowed = isPrivilegedApp(pkg); 12807 } 12808 } 12809 } 12810 if (!allowed) { 12811 if (!allowed && (bp.protectionLevel 12812 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 12813 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 12814 // If this was a previously normal/dangerous permission that got moved 12815 // to a system permission as part of the runtime permission redesign, then 12816 // we still want to blindly grant it to old apps. 12817 allowed = true; 12818 } 12819 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 12820 && pkg.packageName.equals(mRequiredInstallerPackage)) { 12821 // If this permission is to be granted to the system installer and 12822 // this app is an installer, then it gets the permission. 12823 allowed = true; 12824 } 12825 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 12826 && pkg.packageName.equals(mRequiredVerifierPackage)) { 12827 // If this permission is to be granted to the system verifier and 12828 // this app is a verifier, then it gets the permission. 12829 allowed = true; 12830 } 12831 if (!allowed && (bp.protectionLevel 12832 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 12833 && isSystemApp(pkg)) { 12834 // Any pre-installed system app is allowed to get this permission. 12835 allowed = true; 12836 } 12837 if (!allowed && (bp.protectionLevel 12838 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 12839 // For development permissions, a development permission 12840 // is granted only if it was already granted. 12841 allowed = origPermissions.hasInstallPermission(perm); 12842 } 12843 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 12844 && pkg.packageName.equals(mSetupWizardPackage)) { 12845 // If this permission is to be granted to the system setup wizard and 12846 // this app is a setup wizard, then it gets the permission. 12847 allowed = true; 12848 } 12849 } 12850 return allowed; 12851 } 12852 12853 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 12854 final int permCount = pkg.requestedPermissions.size(); 12855 for (int j = 0; j < permCount; j++) { 12856 String requestedPermission = pkg.requestedPermissions.get(j); 12857 if (permission.equals(requestedPermission)) { 12858 return true; 12859 } 12860 } 12861 return false; 12862 } 12863 12864 final class ActivityIntentResolver 12865 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12866 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12867 boolean defaultOnly, int userId) { 12868 if (!sUserManager.exists(userId)) return null; 12869 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12870 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12871 } 12872 12873 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12874 int userId) { 12875 if (!sUserManager.exists(userId)) return null; 12876 mFlags = flags; 12877 return super.queryIntent(intent, resolvedType, 12878 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12879 userId); 12880 } 12881 12882 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12883 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12884 if (!sUserManager.exists(userId)) return null; 12885 if (packageActivities == null) { 12886 return null; 12887 } 12888 mFlags = flags; 12889 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12890 final int N = packageActivities.size(); 12891 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12892 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12893 12894 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12895 for (int i = 0; i < N; ++i) { 12896 intentFilters = packageActivities.get(i).intents; 12897 if (intentFilters != null && intentFilters.size() > 0) { 12898 PackageParser.ActivityIntentInfo[] array = 12899 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12900 intentFilters.toArray(array); 12901 listCut.add(array); 12902 } 12903 } 12904 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12905 } 12906 12907 /** 12908 * Finds a privileged activity that matches the specified activity names. 12909 */ 12910 private PackageParser.Activity findMatchingActivity( 12911 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12912 for (PackageParser.Activity sysActivity : activityList) { 12913 if (sysActivity.info.name.equals(activityInfo.name)) { 12914 return sysActivity; 12915 } 12916 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12917 return sysActivity; 12918 } 12919 if (sysActivity.info.targetActivity != null) { 12920 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12921 return sysActivity; 12922 } 12923 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12924 return sysActivity; 12925 } 12926 } 12927 } 12928 return null; 12929 } 12930 12931 public class IterGenerator<E> { 12932 public Iterator<E> generate(ActivityIntentInfo info) { 12933 return null; 12934 } 12935 } 12936 12937 public class ActionIterGenerator extends IterGenerator<String> { 12938 @Override 12939 public Iterator<String> generate(ActivityIntentInfo info) { 12940 return info.actionsIterator(); 12941 } 12942 } 12943 12944 public class CategoriesIterGenerator extends IterGenerator<String> { 12945 @Override 12946 public Iterator<String> generate(ActivityIntentInfo info) { 12947 return info.categoriesIterator(); 12948 } 12949 } 12950 12951 public class SchemesIterGenerator extends IterGenerator<String> { 12952 @Override 12953 public Iterator<String> generate(ActivityIntentInfo info) { 12954 return info.schemesIterator(); 12955 } 12956 } 12957 12958 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12959 @Override 12960 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12961 return info.authoritiesIterator(); 12962 } 12963 } 12964 12965 /** 12966 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12967 * MODIFIED. Do not pass in a list that should not be changed. 12968 */ 12969 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12970 IterGenerator<T> generator, Iterator<T> searchIterator) { 12971 // loop through the set of actions; every one must be found in the intent filter 12972 while (searchIterator.hasNext()) { 12973 // we must have at least one filter in the list to consider a match 12974 if (intentList.size() == 0) { 12975 break; 12976 } 12977 12978 final T searchAction = searchIterator.next(); 12979 12980 // loop through the set of intent filters 12981 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12982 while (intentIter.hasNext()) { 12983 final ActivityIntentInfo intentInfo = intentIter.next(); 12984 boolean selectionFound = false; 12985 12986 // loop through the intent filter's selection criteria; at least one 12987 // of them must match the searched criteria 12988 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12989 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12990 final T intentSelection = intentSelectionIter.next(); 12991 if (intentSelection != null && intentSelection.equals(searchAction)) { 12992 selectionFound = true; 12993 break; 12994 } 12995 } 12996 12997 // the selection criteria wasn't found in this filter's set; this filter 12998 // is not a potential match 12999 if (!selectionFound) { 13000 intentIter.remove(); 13001 } 13002 } 13003 } 13004 } 13005 13006 private boolean isProtectedAction(ActivityIntentInfo filter) { 13007 final Iterator<String> actionsIter = filter.actionsIterator(); 13008 while (actionsIter != null && actionsIter.hasNext()) { 13009 final String filterAction = actionsIter.next(); 13010 if (PROTECTED_ACTIONS.contains(filterAction)) { 13011 return true; 13012 } 13013 } 13014 return false; 13015 } 13016 13017 /** 13018 * Adjusts the priority of the given intent filter according to policy. 13019 * <p> 13020 * <ul> 13021 * <li>The priority for non privileged applications is capped to '0'</li> 13022 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 13023 * <li>The priority for unbundled updates to privileged applications is capped to the 13024 * priority defined on the system partition</li> 13025 * </ul> 13026 * <p> 13027 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 13028 * allowed to obtain any priority on any action. 13029 */ 13030 private void adjustPriority( 13031 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 13032 // nothing to do; priority is fine as-is 13033 if (intent.getPriority() <= 0) { 13034 return; 13035 } 13036 13037 final ActivityInfo activityInfo = intent.activity.info; 13038 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 13039 13040 final boolean privilegedApp = 13041 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 13042 if (!privilegedApp) { 13043 // non-privileged applications can never define a priority >0 13044 if (DEBUG_FILTERS) { 13045 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 13046 + " package: " + applicationInfo.packageName 13047 + " activity: " + intent.activity.className 13048 + " origPrio: " + intent.getPriority()); 13049 } 13050 intent.setPriority(0); 13051 return; 13052 } 13053 13054 if (systemActivities == null) { 13055 // the system package is not disabled; we're parsing the system partition 13056 if (isProtectedAction(intent)) { 13057 if (mDeferProtectedFilters) { 13058 // We can't deal with these just yet. No component should ever obtain a 13059 // >0 priority for a protected actions, with ONE exception -- the setup 13060 // wizard. The setup wizard, however, cannot be known until we're able to 13061 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 13062 // until all intent filters have been processed. Chicken, meet egg. 13063 // Let the filter temporarily have a high priority and rectify the 13064 // priorities after all system packages have been scanned. 13065 mProtectedFilters.add(intent); 13066 if (DEBUG_FILTERS) { 13067 Slog.i(TAG, "Protected action; save for later;" 13068 + " package: " + applicationInfo.packageName 13069 + " activity: " + intent.activity.className 13070 + " origPrio: " + intent.getPriority()); 13071 } 13072 return; 13073 } else { 13074 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 13075 Slog.i(TAG, "No setup wizard;" 13076 + " All protected intents capped to priority 0"); 13077 } 13078 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 13079 if (DEBUG_FILTERS) { 13080 Slog.i(TAG, "Found setup wizard;" 13081 + " allow priority " + intent.getPriority() + ";" 13082 + " package: " + intent.activity.info.packageName 13083 + " activity: " + intent.activity.className 13084 + " priority: " + intent.getPriority()); 13085 } 13086 // setup wizard gets whatever it wants 13087 return; 13088 } 13089 if (DEBUG_FILTERS) { 13090 Slog.i(TAG, "Protected action; cap priority to 0;" 13091 + " package: " + intent.activity.info.packageName 13092 + " activity: " + intent.activity.className 13093 + " origPrio: " + intent.getPriority()); 13094 } 13095 intent.setPriority(0); 13096 return; 13097 } 13098 } 13099 // privileged apps on the system image get whatever priority they request 13100 return; 13101 } 13102 13103 // privileged app unbundled update ... try to find the same activity 13104 final PackageParser.Activity foundActivity = 13105 findMatchingActivity(systemActivities, activityInfo); 13106 if (foundActivity == null) { 13107 // this is a new activity; it cannot obtain >0 priority 13108 if (DEBUG_FILTERS) { 13109 Slog.i(TAG, "New activity; cap priority to 0;" 13110 + " package: " + applicationInfo.packageName 13111 + " activity: " + intent.activity.className 13112 + " origPrio: " + intent.getPriority()); 13113 } 13114 intent.setPriority(0); 13115 return; 13116 } 13117 13118 // found activity, now check for filter equivalence 13119 13120 // a shallow copy is enough; we modify the list, not its contents 13121 final List<ActivityIntentInfo> intentListCopy = 13122 new ArrayList<>(foundActivity.intents); 13123 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 13124 13125 // find matching action subsets 13126 final Iterator<String> actionsIterator = intent.actionsIterator(); 13127 if (actionsIterator != null) { 13128 getIntentListSubset( 13129 intentListCopy, new ActionIterGenerator(), actionsIterator); 13130 if (intentListCopy.size() == 0) { 13131 // no more intents to match; we're not equivalent 13132 if (DEBUG_FILTERS) { 13133 Slog.i(TAG, "Mismatched action; cap priority to 0;" 13134 + " package: " + applicationInfo.packageName 13135 + " activity: " + intent.activity.className 13136 + " origPrio: " + intent.getPriority()); 13137 } 13138 intent.setPriority(0); 13139 return; 13140 } 13141 } 13142 13143 // find matching category subsets 13144 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 13145 if (categoriesIterator != null) { 13146 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 13147 categoriesIterator); 13148 if (intentListCopy.size() == 0) { 13149 // no more intents to match; we're not equivalent 13150 if (DEBUG_FILTERS) { 13151 Slog.i(TAG, "Mismatched category; cap priority to 0;" 13152 + " package: " + applicationInfo.packageName 13153 + " activity: " + intent.activity.className 13154 + " origPrio: " + intent.getPriority()); 13155 } 13156 intent.setPriority(0); 13157 return; 13158 } 13159 } 13160 13161 // find matching schemes subsets 13162 final Iterator<String> schemesIterator = intent.schemesIterator(); 13163 if (schemesIterator != null) { 13164 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 13165 schemesIterator); 13166 if (intentListCopy.size() == 0) { 13167 // no more intents to match; we're not equivalent 13168 if (DEBUG_FILTERS) { 13169 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 13170 + " package: " + applicationInfo.packageName 13171 + " activity: " + intent.activity.className 13172 + " origPrio: " + intent.getPriority()); 13173 } 13174 intent.setPriority(0); 13175 return; 13176 } 13177 } 13178 13179 // find matching authorities subsets 13180 final Iterator<IntentFilter.AuthorityEntry> 13181 authoritiesIterator = intent.authoritiesIterator(); 13182 if (authoritiesIterator != null) { 13183 getIntentListSubset(intentListCopy, 13184 new AuthoritiesIterGenerator(), 13185 authoritiesIterator); 13186 if (intentListCopy.size() == 0) { 13187 // no more intents to match; we're not equivalent 13188 if (DEBUG_FILTERS) { 13189 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 13190 + " package: " + applicationInfo.packageName 13191 + " activity: " + intent.activity.className 13192 + " origPrio: " + intent.getPriority()); 13193 } 13194 intent.setPriority(0); 13195 return; 13196 } 13197 } 13198 13199 // we found matching filter(s); app gets the max priority of all intents 13200 int cappedPriority = 0; 13201 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 13202 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 13203 } 13204 if (intent.getPriority() > cappedPriority) { 13205 if (DEBUG_FILTERS) { 13206 Slog.i(TAG, "Found matching filter(s);" 13207 + " cap priority to " + cappedPriority + ";" 13208 + " package: " + applicationInfo.packageName 13209 + " activity: " + intent.activity.className 13210 + " origPrio: " + intent.getPriority()); 13211 } 13212 intent.setPriority(cappedPriority); 13213 return; 13214 } 13215 // all this for nothing; the requested priority was <= what was on the system 13216 } 13217 13218 public final void addActivity(PackageParser.Activity a, String type) { 13219 mActivities.put(a.getComponentName(), a); 13220 if (DEBUG_SHOW_INFO) 13221 Log.v( 13222 TAG, " " + type + " " + 13223 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 13224 if (DEBUG_SHOW_INFO) 13225 Log.v(TAG, " Class=" + a.info.name); 13226 final int NI = a.intents.size(); 13227 for (int j=0; j<NI; j++) { 13228 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 13229 if ("activity".equals(type)) { 13230 final PackageSetting ps = 13231 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 13232 final List<PackageParser.Activity> systemActivities = 13233 ps != null && ps.pkg != null ? ps.pkg.activities : null; 13234 adjustPriority(systemActivities, intent); 13235 } 13236 if (DEBUG_SHOW_INFO) { 13237 Log.v(TAG, " IntentFilter:"); 13238 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13239 } 13240 if (!intent.debugCheck()) { 13241 Log.w(TAG, "==> For Activity " + a.info.name); 13242 } 13243 addFilter(intent); 13244 } 13245 } 13246 13247 public final void removeActivity(PackageParser.Activity a, String type) { 13248 mActivities.remove(a.getComponentName()); 13249 if (DEBUG_SHOW_INFO) { 13250 Log.v(TAG, " " + type + " " 13251 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 13252 : a.info.name) + ":"); 13253 Log.v(TAG, " Class=" + a.info.name); 13254 } 13255 final int NI = a.intents.size(); 13256 for (int j=0; j<NI; j++) { 13257 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 13258 if (DEBUG_SHOW_INFO) { 13259 Log.v(TAG, " IntentFilter:"); 13260 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13261 } 13262 removeFilter(intent); 13263 } 13264 } 13265 13266 @Override 13267 protected boolean allowFilterResult( 13268 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 13269 ActivityInfo filterAi = filter.activity.info; 13270 for (int i=dest.size()-1; i>=0; i--) { 13271 ActivityInfo destAi = dest.get(i).activityInfo; 13272 if (destAi.name == filterAi.name 13273 && destAi.packageName == filterAi.packageName) { 13274 return false; 13275 } 13276 } 13277 return true; 13278 } 13279 13280 @Override 13281 protected ActivityIntentInfo[] newArray(int size) { 13282 return new ActivityIntentInfo[size]; 13283 } 13284 13285 @Override 13286 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 13287 if (!sUserManager.exists(userId)) return true; 13288 PackageParser.Package p = filter.activity.owner; 13289 if (p != null) { 13290 PackageSetting ps = (PackageSetting)p.mExtras; 13291 if (ps != null) { 13292 // System apps are never considered stopped for purposes of 13293 // filtering, because there may be no way for the user to 13294 // actually re-launch them. 13295 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 13296 && ps.getStopped(userId); 13297 } 13298 } 13299 return false; 13300 } 13301 13302 @Override 13303 protected boolean isPackageForFilter(String packageName, 13304 PackageParser.ActivityIntentInfo info) { 13305 return packageName.equals(info.activity.owner.packageName); 13306 } 13307 13308 @Override 13309 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 13310 int match, int userId) { 13311 if (!sUserManager.exists(userId)) return null; 13312 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 13313 return null; 13314 } 13315 final PackageParser.Activity activity = info.activity; 13316 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 13317 if (ps == null) { 13318 return null; 13319 } 13320 final PackageUserState userState = ps.readUserState(userId); 13321 ActivityInfo ai = 13322 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 13323 if (ai == null) { 13324 return null; 13325 } 13326 final boolean matchExplicitlyVisibleOnly = 13327 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 13328 final boolean matchVisibleToInstantApp = 13329 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13330 final boolean componentVisible = 13331 matchVisibleToInstantApp 13332 && info.isVisibleToInstantApp() 13333 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 13334 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13335 // throw out filters that aren't visible to ephemeral apps 13336 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 13337 return null; 13338 } 13339 // throw out instant app filters if we're not explicitly requesting them 13340 if (!matchInstantApp && userState.instantApp) { 13341 return null; 13342 } 13343 // throw out instant app filters if updates are available; will trigger 13344 // instant app resolution 13345 if (userState.instantApp && ps.isUpdateAvailable()) { 13346 return null; 13347 } 13348 final ResolveInfo res = new ResolveInfo(); 13349 res.activityInfo = ai; 13350 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 13351 res.filter = info; 13352 } 13353 if (info != null) { 13354 res.handleAllWebDataURI = info.handleAllWebDataURI(); 13355 } 13356 res.priority = info.getPriority(); 13357 res.preferredOrder = activity.owner.mPreferredOrder; 13358 //System.out.println("Result: " + res.activityInfo.className + 13359 // " = " + res.priority); 13360 res.match = match; 13361 res.isDefault = info.hasDefault; 13362 res.labelRes = info.labelRes; 13363 res.nonLocalizedLabel = info.nonLocalizedLabel; 13364 if (userNeedsBadging(userId)) { 13365 res.noResourceId = true; 13366 } else { 13367 res.icon = info.icon; 13368 } 13369 res.iconResourceId = info.icon; 13370 res.system = res.activityInfo.applicationInfo.isSystemApp(); 13371 res.isInstantAppAvailable = userState.instantApp; 13372 return res; 13373 } 13374 13375 @Override 13376 protected void sortResults(List<ResolveInfo> results) { 13377 Collections.sort(results, mResolvePrioritySorter); 13378 } 13379 13380 @Override 13381 protected void dumpFilter(PrintWriter out, String prefix, 13382 PackageParser.ActivityIntentInfo filter) { 13383 out.print(prefix); out.print( 13384 Integer.toHexString(System.identityHashCode(filter.activity))); 13385 out.print(' '); 13386 filter.activity.printComponentShortName(out); 13387 out.print(" filter "); 13388 out.println(Integer.toHexString(System.identityHashCode(filter))); 13389 } 13390 13391 @Override 13392 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 13393 return filter.activity; 13394 } 13395 13396 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13397 PackageParser.Activity activity = (PackageParser.Activity)label; 13398 out.print(prefix); out.print( 13399 Integer.toHexString(System.identityHashCode(activity))); 13400 out.print(' '); 13401 activity.printComponentShortName(out); 13402 if (count > 1) { 13403 out.print(" ("); out.print(count); out.print(" filters)"); 13404 } 13405 out.println(); 13406 } 13407 13408 // Keys are String (activity class name), values are Activity. 13409 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 13410 = new ArrayMap<ComponentName, PackageParser.Activity>(); 13411 private int mFlags; 13412 } 13413 13414 private final class ServiceIntentResolver 13415 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 13416 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 13417 boolean defaultOnly, int userId) { 13418 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 13419 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 13420 } 13421 13422 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 13423 int userId) { 13424 if (!sUserManager.exists(userId)) return null; 13425 mFlags = flags; 13426 return super.queryIntent(intent, resolvedType, 13427 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 13428 userId); 13429 } 13430 13431 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 13432 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 13433 if (!sUserManager.exists(userId)) return null; 13434 if (packageServices == null) { 13435 return null; 13436 } 13437 mFlags = flags; 13438 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 13439 final int N = packageServices.size(); 13440 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 13441 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 13442 13443 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 13444 for (int i = 0; i < N; ++i) { 13445 intentFilters = packageServices.get(i).intents; 13446 if (intentFilters != null && intentFilters.size() > 0) { 13447 PackageParser.ServiceIntentInfo[] array = 13448 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 13449 intentFilters.toArray(array); 13450 listCut.add(array); 13451 } 13452 } 13453 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 13454 } 13455 13456 public final void addService(PackageParser.Service s) { 13457 mServices.put(s.getComponentName(), s); 13458 if (DEBUG_SHOW_INFO) { 13459 Log.v(TAG, " " 13460 + (s.info.nonLocalizedLabel != null 13461 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 13462 Log.v(TAG, " Class=" + s.info.name); 13463 } 13464 final int NI = s.intents.size(); 13465 int j; 13466 for (j=0; j<NI; j++) { 13467 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 13468 if (DEBUG_SHOW_INFO) { 13469 Log.v(TAG, " IntentFilter:"); 13470 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13471 } 13472 if (!intent.debugCheck()) { 13473 Log.w(TAG, "==> For Service " + s.info.name); 13474 } 13475 addFilter(intent); 13476 } 13477 } 13478 13479 public final void removeService(PackageParser.Service s) { 13480 mServices.remove(s.getComponentName()); 13481 if (DEBUG_SHOW_INFO) { 13482 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 13483 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 13484 Log.v(TAG, " Class=" + s.info.name); 13485 } 13486 final int NI = s.intents.size(); 13487 int j; 13488 for (j=0; j<NI; j++) { 13489 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 13490 if (DEBUG_SHOW_INFO) { 13491 Log.v(TAG, " IntentFilter:"); 13492 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13493 } 13494 removeFilter(intent); 13495 } 13496 } 13497 13498 @Override 13499 protected boolean allowFilterResult( 13500 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 13501 ServiceInfo filterSi = filter.service.info; 13502 for (int i=dest.size()-1; i>=0; i--) { 13503 ServiceInfo destAi = dest.get(i).serviceInfo; 13504 if (destAi.name == filterSi.name 13505 && destAi.packageName == filterSi.packageName) { 13506 return false; 13507 } 13508 } 13509 return true; 13510 } 13511 13512 @Override 13513 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 13514 return new PackageParser.ServiceIntentInfo[size]; 13515 } 13516 13517 @Override 13518 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 13519 if (!sUserManager.exists(userId)) return true; 13520 PackageParser.Package p = filter.service.owner; 13521 if (p != null) { 13522 PackageSetting ps = (PackageSetting)p.mExtras; 13523 if (ps != null) { 13524 // System apps are never considered stopped for purposes of 13525 // filtering, because there may be no way for the user to 13526 // actually re-launch them. 13527 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13528 && ps.getStopped(userId); 13529 } 13530 } 13531 return false; 13532 } 13533 13534 @Override 13535 protected boolean isPackageForFilter(String packageName, 13536 PackageParser.ServiceIntentInfo info) { 13537 return packageName.equals(info.service.owner.packageName); 13538 } 13539 13540 @Override 13541 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 13542 int match, int userId) { 13543 if (!sUserManager.exists(userId)) return null; 13544 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 13545 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 13546 return null; 13547 } 13548 final PackageParser.Service service = info.service; 13549 PackageSetting ps = (PackageSetting) service.owner.mExtras; 13550 if (ps == null) { 13551 return null; 13552 } 13553 final PackageUserState userState = ps.readUserState(userId); 13554 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 13555 userState, userId); 13556 if (si == null) { 13557 return null; 13558 } 13559 final boolean matchVisibleToInstantApp = 13560 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13561 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13562 // throw out filters that aren't visible to ephemeral apps 13563 if (matchVisibleToInstantApp 13564 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13565 return null; 13566 } 13567 // throw out ephemeral filters if we're not explicitly requesting them 13568 if (!isInstantApp && userState.instantApp) { 13569 return null; 13570 } 13571 // throw out instant app filters if updates are available; will trigger 13572 // instant app resolution 13573 if (userState.instantApp && ps.isUpdateAvailable()) { 13574 return null; 13575 } 13576 final ResolveInfo res = new ResolveInfo(); 13577 res.serviceInfo = si; 13578 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 13579 res.filter = filter; 13580 } 13581 res.priority = info.getPriority(); 13582 res.preferredOrder = service.owner.mPreferredOrder; 13583 res.match = match; 13584 res.isDefault = info.hasDefault; 13585 res.labelRes = info.labelRes; 13586 res.nonLocalizedLabel = info.nonLocalizedLabel; 13587 res.icon = info.icon; 13588 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 13589 return res; 13590 } 13591 13592 @Override 13593 protected void sortResults(List<ResolveInfo> results) { 13594 Collections.sort(results, mResolvePrioritySorter); 13595 } 13596 13597 @Override 13598 protected void dumpFilter(PrintWriter out, String prefix, 13599 PackageParser.ServiceIntentInfo filter) { 13600 out.print(prefix); out.print( 13601 Integer.toHexString(System.identityHashCode(filter.service))); 13602 out.print(' '); 13603 filter.service.printComponentShortName(out); 13604 out.print(" filter "); 13605 out.println(Integer.toHexString(System.identityHashCode(filter))); 13606 } 13607 13608 @Override 13609 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 13610 return filter.service; 13611 } 13612 13613 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13614 PackageParser.Service service = (PackageParser.Service)label; 13615 out.print(prefix); out.print( 13616 Integer.toHexString(System.identityHashCode(service))); 13617 out.print(' '); 13618 service.printComponentShortName(out); 13619 if (count > 1) { 13620 out.print(" ("); out.print(count); out.print(" filters)"); 13621 } 13622 out.println(); 13623 } 13624 13625 // List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 13626 // final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 13627 // final List<ResolveInfo> retList = Lists.newArrayList(); 13628 // while (i.hasNext()) { 13629 // final ResolveInfo resolveInfo = (ResolveInfo) i; 13630 // if (isEnabledLP(resolveInfo.serviceInfo)) { 13631 // retList.add(resolveInfo); 13632 // } 13633 // } 13634 // return retList; 13635 // } 13636 13637 // Keys are String (activity class name), values are Activity. 13638 private final ArrayMap<ComponentName, PackageParser.Service> mServices 13639 = new ArrayMap<ComponentName, PackageParser.Service>(); 13640 private int mFlags; 13641 } 13642 13643 private final class ProviderIntentResolver 13644 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 13645 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 13646 boolean defaultOnly, int userId) { 13647 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 13648 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 13649 } 13650 13651 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 13652 int userId) { 13653 if (!sUserManager.exists(userId)) 13654 return null; 13655 mFlags = flags; 13656 return super.queryIntent(intent, resolvedType, 13657 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 13658 userId); 13659 } 13660 13661 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 13662 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 13663 if (!sUserManager.exists(userId)) 13664 return null; 13665 if (packageProviders == null) { 13666 return null; 13667 } 13668 mFlags = flags; 13669 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 13670 final int N = packageProviders.size(); 13671 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 13672 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 13673 13674 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 13675 for (int i = 0; i < N; ++i) { 13676 intentFilters = packageProviders.get(i).intents; 13677 if (intentFilters != null && intentFilters.size() > 0) { 13678 PackageParser.ProviderIntentInfo[] array = 13679 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 13680 intentFilters.toArray(array); 13681 listCut.add(array); 13682 } 13683 } 13684 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 13685 } 13686 13687 public final void addProvider(PackageParser.Provider p) { 13688 if (mProviders.containsKey(p.getComponentName())) { 13689 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 13690 return; 13691 } 13692 13693 mProviders.put(p.getComponentName(), p); 13694 if (DEBUG_SHOW_INFO) { 13695 Log.v(TAG, " " 13696 + (p.info.nonLocalizedLabel != null 13697 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13698 Log.v(TAG, " Class=" + p.info.name); 13699 } 13700 final int NI = p.intents.size(); 13701 int j; 13702 for (j = 0; j < NI; j++) { 13703 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13704 if (DEBUG_SHOW_INFO) { 13705 Log.v(TAG, " IntentFilter:"); 13706 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13707 } 13708 if (!intent.debugCheck()) { 13709 Log.w(TAG, "==> For Provider " + p.info.name); 13710 } 13711 addFilter(intent); 13712 } 13713 } 13714 13715 public final void removeProvider(PackageParser.Provider p) { 13716 mProviders.remove(p.getComponentName()); 13717 if (DEBUG_SHOW_INFO) { 13718 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 13719 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13720 Log.v(TAG, " Class=" + p.info.name); 13721 } 13722 final int NI = p.intents.size(); 13723 int j; 13724 for (j = 0; j < NI; j++) { 13725 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13726 if (DEBUG_SHOW_INFO) { 13727 Log.v(TAG, " IntentFilter:"); 13728 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13729 } 13730 removeFilter(intent); 13731 } 13732 } 13733 13734 @Override 13735 protected boolean allowFilterResult( 13736 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 13737 ProviderInfo filterPi = filter.provider.info; 13738 for (int i = dest.size() - 1; i >= 0; i--) { 13739 ProviderInfo destPi = dest.get(i).providerInfo; 13740 if (destPi.name == filterPi.name 13741 && destPi.packageName == filterPi.packageName) { 13742 return false; 13743 } 13744 } 13745 return true; 13746 } 13747 13748 @Override 13749 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 13750 return new PackageParser.ProviderIntentInfo[size]; 13751 } 13752 13753 @Override 13754 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 13755 if (!sUserManager.exists(userId)) 13756 return true; 13757 PackageParser.Package p = filter.provider.owner; 13758 if (p != null) { 13759 PackageSetting ps = (PackageSetting) p.mExtras; 13760 if (ps != null) { 13761 // System apps are never considered stopped for purposes of 13762 // filtering, because there may be no way for the user to 13763 // actually re-launch them. 13764 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13765 && ps.getStopped(userId); 13766 } 13767 } 13768 return false; 13769 } 13770 13771 @Override 13772 protected boolean isPackageForFilter(String packageName, 13773 PackageParser.ProviderIntentInfo info) { 13774 return packageName.equals(info.provider.owner.packageName); 13775 } 13776 13777 @Override 13778 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 13779 int match, int userId) { 13780 if (!sUserManager.exists(userId)) 13781 return null; 13782 final PackageParser.ProviderIntentInfo info = filter; 13783 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 13784 return null; 13785 } 13786 final PackageParser.Provider provider = info.provider; 13787 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 13788 if (ps == null) { 13789 return null; 13790 } 13791 final PackageUserState userState = ps.readUserState(userId); 13792 final boolean matchVisibleToInstantApp = 13793 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13794 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13795 // throw out filters that aren't visible to instant applications 13796 if (matchVisibleToInstantApp 13797 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13798 return null; 13799 } 13800 // throw out instant application filters if we're not explicitly requesting them 13801 if (!isInstantApp && userState.instantApp) { 13802 return null; 13803 } 13804 // throw out instant application filters if updates are available; will trigger 13805 // instant application resolution 13806 if (userState.instantApp && ps.isUpdateAvailable()) { 13807 return null; 13808 } 13809 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13810 userState, userId); 13811 if (pi == null) { 13812 return null; 13813 } 13814 final ResolveInfo res = new ResolveInfo(); 13815 res.providerInfo = pi; 13816 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13817 res.filter = filter; 13818 } 13819 res.priority = info.getPriority(); 13820 res.preferredOrder = provider.owner.mPreferredOrder; 13821 res.match = match; 13822 res.isDefault = info.hasDefault; 13823 res.labelRes = info.labelRes; 13824 res.nonLocalizedLabel = info.nonLocalizedLabel; 13825 res.icon = info.icon; 13826 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13827 return res; 13828 } 13829 13830 @Override 13831 protected void sortResults(List<ResolveInfo> results) { 13832 Collections.sort(results, mResolvePrioritySorter); 13833 } 13834 13835 @Override 13836 protected void dumpFilter(PrintWriter out, String prefix, 13837 PackageParser.ProviderIntentInfo filter) { 13838 out.print(prefix); 13839 out.print( 13840 Integer.toHexString(System.identityHashCode(filter.provider))); 13841 out.print(' '); 13842 filter.provider.printComponentShortName(out); 13843 out.print(" filter "); 13844 out.println(Integer.toHexString(System.identityHashCode(filter))); 13845 } 13846 13847 @Override 13848 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13849 return filter.provider; 13850 } 13851 13852 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13853 PackageParser.Provider provider = (PackageParser.Provider)label; 13854 out.print(prefix); out.print( 13855 Integer.toHexString(System.identityHashCode(provider))); 13856 out.print(' '); 13857 provider.printComponentShortName(out); 13858 if (count > 1) { 13859 out.print(" ("); out.print(count); out.print(" filters)"); 13860 } 13861 out.println(); 13862 } 13863 13864 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13865 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13866 private int mFlags; 13867 } 13868 13869 static final class EphemeralIntentResolver 13870 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 13871 /** 13872 * The result that has the highest defined order. Ordering applies on a 13873 * per-package basis. Mapping is from package name to Pair of order and 13874 * EphemeralResolveInfo. 13875 * <p> 13876 * NOTE: This is implemented as a field variable for convenience and efficiency. 13877 * By having a field variable, we're able to track filter ordering as soon as 13878 * a non-zero order is defined. Otherwise, multiple loops across the result set 13879 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13880 * this needs to be contained entirely within {@link #filterResults}. 13881 */ 13882 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13883 13884 @Override 13885 protected AuxiliaryResolveInfo[] newArray(int size) { 13886 return new AuxiliaryResolveInfo[size]; 13887 } 13888 13889 @Override 13890 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 13891 return true; 13892 } 13893 13894 @Override 13895 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 13896 int userId) { 13897 if (!sUserManager.exists(userId)) { 13898 return null; 13899 } 13900 final String packageName = responseObj.resolveInfo.getPackageName(); 13901 final Integer order = responseObj.getOrder(); 13902 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13903 mOrderResult.get(packageName); 13904 // ordering is enabled and this item's order isn't high enough 13905 if (lastOrderResult != null && lastOrderResult.first >= order) { 13906 return null; 13907 } 13908 final InstantAppResolveInfo res = responseObj.resolveInfo; 13909 if (order > 0) { 13910 // non-zero order, enable ordering 13911 mOrderResult.put(packageName, new Pair<>(order, res)); 13912 } 13913 return responseObj; 13914 } 13915 13916 @Override 13917 protected void filterResults(List<AuxiliaryResolveInfo> results) { 13918 // only do work if ordering is enabled [most of the time it won't be] 13919 if (mOrderResult.size() == 0) { 13920 return; 13921 } 13922 int resultSize = results.size(); 13923 for (int i = 0; i < resultSize; i++) { 13924 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13925 final String packageName = info.getPackageName(); 13926 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13927 if (savedInfo == null) { 13928 // package doesn't having ordering 13929 continue; 13930 } 13931 if (savedInfo.second == info) { 13932 // circled back to the highest ordered item; remove from order list 13933 mOrderResult.remove(savedInfo); 13934 if (mOrderResult.size() == 0) { 13935 // no more ordered items 13936 break; 13937 } 13938 continue; 13939 } 13940 // item has a worse order, remove it from the result list 13941 results.remove(i); 13942 resultSize--; 13943 i--; 13944 } 13945 } 13946 } 13947 13948 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13949 new Comparator<ResolveInfo>() { 13950 public int compare(ResolveInfo r1, ResolveInfo r2) { 13951 int v1 = r1.priority; 13952 int v2 = r2.priority; 13953 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13954 if (v1 != v2) { 13955 return (v1 > v2) ? -1 : 1; 13956 } 13957 v1 = r1.preferredOrder; 13958 v2 = r2.preferredOrder; 13959 if (v1 != v2) { 13960 return (v1 > v2) ? -1 : 1; 13961 } 13962 if (r1.isDefault != r2.isDefault) { 13963 return r1.isDefault ? -1 : 1; 13964 } 13965 v1 = r1.match; 13966 v2 = r2.match; 13967 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13968 if (v1 != v2) { 13969 return (v1 > v2) ? -1 : 1; 13970 } 13971 if (r1.system != r2.system) { 13972 return r1.system ? -1 : 1; 13973 } 13974 if (r1.activityInfo != null) { 13975 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13976 } 13977 if (r1.serviceInfo != null) { 13978 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13979 } 13980 if (r1.providerInfo != null) { 13981 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13982 } 13983 return 0; 13984 } 13985 }; 13986 13987 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13988 new Comparator<ProviderInfo>() { 13989 public int compare(ProviderInfo p1, ProviderInfo p2) { 13990 final int v1 = p1.initOrder; 13991 final int v2 = p2.initOrder; 13992 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13993 } 13994 }; 13995 13996 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13997 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13998 final int[] userIds) { 13999 mHandler.post(new Runnable() { 14000 @Override 14001 public void run() { 14002 try { 14003 final IActivityManager am = ActivityManager.getService(); 14004 if (am == null) return; 14005 final int[] resolvedUserIds; 14006 if (userIds == null) { 14007 resolvedUserIds = am.getRunningUserIds(); 14008 } else { 14009 resolvedUserIds = userIds; 14010 } 14011 for (int id : resolvedUserIds) { 14012 final Intent intent = new Intent(action, 14013 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 14014 if (extras != null) { 14015 intent.putExtras(extras); 14016 } 14017 if (targetPkg != null) { 14018 intent.setPackage(targetPkg); 14019 } 14020 // Modify the UID when posting to other users 14021 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 14022 if (uid > 0 && UserHandle.getUserId(uid) != id) { 14023 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 14024 intent.putExtra(Intent.EXTRA_UID, uid); 14025 } 14026 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 14027 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 14028 if (DEBUG_BROADCASTS) { 14029 RuntimeException here = new RuntimeException("here"); 14030 here.fillInStackTrace(); 14031 Slog.d(TAG, "Sending to user " + id + ": " 14032 + intent.toShortString(false, true, false, false) 14033 + " " + intent.getExtras(), here); 14034 } 14035 am.broadcastIntent(null, intent, null, finishedReceiver, 14036 0, null, null, null, android.app.AppOpsManager.OP_NONE, 14037 null, finishedReceiver != null, false, id); 14038 } 14039 } catch (RemoteException ex) { 14040 } 14041 } 14042 }); 14043 } 14044 14045 /** 14046 * Check if the external storage media is available. This is true if there 14047 * is a mounted external storage medium or if the external storage is 14048 * emulated. 14049 */ 14050 private boolean isExternalMediaAvailable() { 14051 return mMediaMounted || Environment.isExternalStorageEmulated(); 14052 } 14053 14054 @Override 14055 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 14056 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14057 return null; 14058 } 14059 // writer 14060 synchronized (mPackages) { 14061 if (!isExternalMediaAvailable()) { 14062 // If the external storage is no longer mounted at this point, 14063 // the caller may not have been able to delete all of this 14064 // packages files and can not delete any more. Bail. 14065 return null; 14066 } 14067 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 14068 if (lastPackage != null) { 14069 pkgs.remove(lastPackage); 14070 } 14071 if (pkgs.size() > 0) { 14072 return pkgs.get(0); 14073 } 14074 } 14075 return null; 14076 } 14077 14078 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 14079 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 14080 userId, andCode ? 1 : 0, packageName); 14081 if (mSystemReady) { 14082 msg.sendToTarget(); 14083 } else { 14084 if (mPostSystemReadyMessages == null) { 14085 mPostSystemReadyMessages = new ArrayList<>(); 14086 } 14087 mPostSystemReadyMessages.add(msg); 14088 } 14089 } 14090 14091 void startCleaningPackages() { 14092 // reader 14093 if (!isExternalMediaAvailable()) { 14094 return; 14095 } 14096 synchronized (mPackages) { 14097 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 14098 return; 14099 } 14100 } 14101 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 14102 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 14103 IActivityManager am = ActivityManager.getService(); 14104 if (am != null) { 14105 int dcsUid = -1; 14106 synchronized (mPackages) { 14107 if (!mDefaultContainerWhitelisted) { 14108 mDefaultContainerWhitelisted = true; 14109 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 14110 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 14111 } 14112 } 14113 try { 14114 if (dcsUid > 0) { 14115 am.backgroundWhitelistUid(dcsUid); 14116 } 14117 am.startService(null, intent, null, false, mContext.getOpPackageName(), 14118 UserHandle.USER_SYSTEM); 14119 } catch (RemoteException e) { 14120 } 14121 } 14122 } 14123 14124 @Override 14125 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 14126 int installFlags, String installerPackageName, int userId) { 14127 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 14128 14129 final int callingUid = Binder.getCallingUid(); 14130 enforceCrossUserPermission(callingUid, userId, 14131 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 14132 14133 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 14134 try { 14135 if (observer != null) { 14136 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 14137 } 14138 } catch (RemoteException re) { 14139 } 14140 return; 14141 } 14142 14143 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 14144 installFlags |= PackageManager.INSTALL_FROM_ADB; 14145 14146 } else { 14147 // Caller holds INSTALL_PACKAGES permission, so we're less strict 14148 // about installerPackageName. 14149 14150 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 14151 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 14152 } 14153 14154 UserHandle user; 14155 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 14156 user = UserHandle.ALL; 14157 } else { 14158 user = new UserHandle(userId); 14159 } 14160 14161 // Only system components can circumvent runtime permissions when installing. 14162 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 14163 && mContext.checkCallingOrSelfPermission(Manifest.permission 14164 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 14165 throw new SecurityException("You need the " 14166 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 14167 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 14168 } 14169 14170 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 14171 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14172 throw new IllegalArgumentException( 14173 "New installs into ASEC containers no longer supported"); 14174 } 14175 14176 final File originFile = new File(originPath); 14177 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 14178 14179 final Message msg = mHandler.obtainMessage(INIT_COPY); 14180 final VerificationInfo verificationInfo = new VerificationInfo( 14181 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 14182 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 14183 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 14184 null /*packageAbiOverride*/, null /*grantedPermissions*/, 14185 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 14186 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 14187 msg.obj = params; 14188 14189 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 14190 System.identityHashCode(msg.obj)); 14191 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 14192 System.identityHashCode(msg.obj)); 14193 14194 mHandler.sendMessage(msg); 14195 } 14196 14197 14198 /** 14199 * Ensure that the install reason matches what we know about the package installer (e.g. whether 14200 * it is acting on behalf on an enterprise or the user). 14201 * 14202 * Note that the ordering of the conditionals in this method is important. The checks we perform 14203 * are as follows, in this order: 14204 * 14205 * 1) If the install is being performed by a system app, we can trust the app to have set the 14206 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 14207 * what it is. 14208 * 2) If the install is being performed by a device or profile owner app, the install reason 14209 * should be enterprise policy. However, we cannot be sure that the device or profile owner 14210 * set the install reason correctly. If the app targets an older SDK version where install 14211 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 14212 * unset or wrong. Thus, we force the install reason to be enterprise policy. 14213 * 3) In all other cases, the install is being performed by a regular app that is neither part 14214 * of the system nor a device or profile owner. We have no reason to believe that this app is 14215 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 14216 * set to enterprise policy and if so, change it to unknown instead. 14217 */ 14218 private int fixUpInstallReason(String installerPackageName, int installerUid, 14219 int installReason) { 14220 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 14221 == PERMISSION_GRANTED) { 14222 // If the install is being performed by a system app, we trust that app to have set the 14223 // install reason correctly. 14224 return installReason; 14225 } 14226 14227 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14228 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14229 if (dpm != null) { 14230 ComponentName owner = null; 14231 try { 14232 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 14233 if (owner == null) { 14234 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 14235 } 14236 } catch (RemoteException e) { 14237 } 14238 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 14239 // If the install is being performed by a device or profile owner, the install 14240 // reason should be enterprise policy. 14241 return PackageManager.INSTALL_REASON_POLICY; 14242 } 14243 } 14244 14245 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 14246 // If the install is being performed by a regular app (i.e. neither system app nor 14247 // device or profile owner), we have no reason to believe that the app is acting on 14248 // behalf of an enterprise. If the app set the install reason to enterprise policy, 14249 // change it to unknown instead. 14250 return PackageManager.INSTALL_REASON_UNKNOWN; 14251 } 14252 14253 // If the install is being performed by a regular app and the install reason was set to any 14254 // value but enterprise policy, leave the install reason unchanged. 14255 return installReason; 14256 } 14257 14258 void installStage(String packageName, File stagedDir, String stagedCid, 14259 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 14260 String installerPackageName, int installerUid, UserHandle user, 14261 Certificate[][] certificates) { 14262 if (DEBUG_EPHEMERAL) { 14263 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14264 Slog.d(TAG, "Ephemeral install of " + packageName); 14265 } 14266 } 14267 final VerificationInfo verificationInfo = new VerificationInfo( 14268 sessionParams.originatingUri, sessionParams.referrerUri, 14269 sessionParams.originatingUid, installerUid); 14270 14271 final OriginInfo origin; 14272 if (stagedDir != null) { 14273 origin = OriginInfo.fromStagedFile(stagedDir); 14274 } else { 14275 origin = OriginInfo.fromStagedContainer(stagedCid); 14276 } 14277 14278 final Message msg = mHandler.obtainMessage(INIT_COPY); 14279 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 14280 sessionParams.installReason); 14281 final InstallParams params = new InstallParams(origin, null, observer, 14282 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 14283 verificationInfo, user, sessionParams.abiOverride, 14284 sessionParams.grantedRuntimePermissions, certificates, installReason); 14285 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 14286 msg.obj = params; 14287 14288 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 14289 System.identityHashCode(msg.obj)); 14290 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 14291 System.identityHashCode(msg.obj)); 14292 14293 mHandler.sendMessage(msg); 14294 } 14295 14296 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 14297 int userId) { 14298 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 14299 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 14300 14301 // Send a session commit broadcast 14302 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 14303 info.installReason = pkgSetting.getInstallReason(userId); 14304 info.appPackageName = packageName; 14305 sendSessionCommitBroadcast(info, userId); 14306 } 14307 14308 public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) { 14309 if (ArrayUtils.isEmpty(userIds)) { 14310 return; 14311 } 14312 Bundle extras = new Bundle(1); 14313 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 14314 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 14315 14316 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 14317 packageName, extras, 0, null, null, userIds); 14318 if (isSystem) { 14319 mHandler.post(() -> { 14320 for (int userId : userIds) { 14321 sendBootCompletedBroadcastToSystemApp(packageName, userId); 14322 } 14323 } 14324 ); 14325 } 14326 } 14327 14328 /** 14329 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 14330 * automatically without needing an explicit launch. 14331 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 14332 */ 14333 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 14334 // If user is not running, the app didn't miss any broadcast 14335 if (!mUserManagerInternal.isUserRunning(userId)) { 14336 return; 14337 } 14338 final IActivityManager am = ActivityManager.getService(); 14339 try { 14340 // Deliver LOCKED_BOOT_COMPLETED first 14341 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 14342 .setPackage(packageName); 14343 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 14344 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 14345 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 14346 14347 // Deliver BOOT_COMPLETED only if user is unlocked 14348 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 14349 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 14350 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 14351 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 14352 } 14353 } catch (RemoteException e) { 14354 throw e.rethrowFromSystemServer(); 14355 } 14356 } 14357 14358 @Override 14359 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 14360 int userId) { 14361 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 14362 PackageSetting pkgSetting; 14363 final int callingUid = Binder.getCallingUid(); 14364 enforceCrossUserPermission(callingUid, userId, 14365 true /* requireFullPermission */, true /* checkShell */, 14366 "setApplicationHiddenSetting for user " + userId); 14367 14368 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 14369 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 14370 return false; 14371 } 14372 14373 long callingId = Binder.clearCallingIdentity(); 14374 try { 14375 boolean sendAdded = false; 14376 boolean sendRemoved = false; 14377 // writer 14378 synchronized (mPackages) { 14379 pkgSetting = mSettings.mPackages.get(packageName); 14380 if (pkgSetting == null) { 14381 return false; 14382 } 14383 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 14384 return false; 14385 } 14386 // Do not allow "android" is being disabled 14387 if ("android".equals(packageName)) { 14388 Slog.w(TAG, "Cannot hide package: android"); 14389 return false; 14390 } 14391 // Cannot hide static shared libs as they are considered 14392 // a part of the using app (emulating static linking). Also 14393 // static libs are installed always on internal storage. 14394 PackageParser.Package pkg = mPackages.get(packageName); 14395 if (pkg != null && pkg.staticSharedLibName != null) { 14396 Slog.w(TAG, "Cannot hide package: " + packageName 14397 + " providing static shared library: " 14398 + pkg.staticSharedLibName); 14399 return false; 14400 } 14401 // Only allow protected packages to hide themselves. 14402 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 14403 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14404 Slog.w(TAG, "Not hiding protected package: " + packageName); 14405 return false; 14406 } 14407 14408 if (pkgSetting.getHidden(userId) != hidden) { 14409 pkgSetting.setHidden(hidden, userId); 14410 mSettings.writePackageRestrictionsLPr(userId); 14411 if (hidden) { 14412 sendRemoved = true; 14413 } else { 14414 sendAdded = true; 14415 } 14416 } 14417 } 14418 if (sendAdded) { 14419 sendPackageAddedForUser(packageName, pkgSetting, userId); 14420 return true; 14421 } 14422 if (sendRemoved) { 14423 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 14424 "hiding pkg"); 14425 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 14426 return true; 14427 } 14428 } finally { 14429 Binder.restoreCallingIdentity(callingId); 14430 } 14431 return false; 14432 } 14433 14434 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 14435 int userId) { 14436 final PackageRemovedInfo info = new PackageRemovedInfo(this); 14437 info.removedPackage = packageName; 14438 info.installerPackageName = pkgSetting.installerPackageName; 14439 info.removedUsers = new int[] {userId}; 14440 info.broadcastUsers = new int[] {userId}; 14441 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 14442 info.sendPackageRemovedBroadcasts(true /*killApp*/); 14443 } 14444 14445 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 14446 if (pkgList.length > 0) { 14447 Bundle extras = new Bundle(1); 14448 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14449 14450 sendPackageBroadcast( 14451 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 14452 : Intent.ACTION_PACKAGES_UNSUSPENDED, 14453 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 14454 new int[] {userId}); 14455 } 14456 } 14457 14458 /** 14459 * Returns true if application is not found or there was an error. Otherwise it returns 14460 * the hidden state of the package for the given user. 14461 */ 14462 @Override 14463 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 14464 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 14465 final int callingUid = Binder.getCallingUid(); 14466 enforceCrossUserPermission(callingUid, userId, 14467 true /* requireFullPermission */, false /* checkShell */, 14468 "getApplicationHidden for user " + userId); 14469 PackageSetting ps; 14470 long callingId = Binder.clearCallingIdentity(); 14471 try { 14472 // writer 14473 synchronized (mPackages) { 14474 ps = mSettings.mPackages.get(packageName); 14475 if (ps == null) { 14476 return true; 14477 } 14478 if (filterAppAccessLPr(ps, callingUid, userId)) { 14479 return true; 14480 } 14481 return ps.getHidden(userId); 14482 } 14483 } finally { 14484 Binder.restoreCallingIdentity(callingId); 14485 } 14486 } 14487 14488 /** 14489 * @hide 14490 */ 14491 @Override 14492 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 14493 int installReason) { 14494 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 14495 null); 14496 PackageSetting pkgSetting; 14497 final int callingUid = Binder.getCallingUid(); 14498 enforceCrossUserPermission(callingUid, userId, 14499 true /* requireFullPermission */, true /* checkShell */, 14500 "installExistingPackage for user " + userId); 14501 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 14502 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 14503 } 14504 14505 long callingId = Binder.clearCallingIdentity(); 14506 try { 14507 boolean installed = false; 14508 final boolean instantApp = 14509 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14510 final boolean fullApp = 14511 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 14512 14513 // writer 14514 synchronized (mPackages) { 14515 pkgSetting = mSettings.mPackages.get(packageName); 14516 if (pkgSetting == null) { 14517 return PackageManager.INSTALL_FAILED_INVALID_URI; 14518 } 14519 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 14520 // only allow the existing package to be used if it's installed as a full 14521 // application for at least one user 14522 boolean installAllowed = false; 14523 for (int checkUserId : sUserManager.getUserIds()) { 14524 installAllowed = !pkgSetting.getInstantApp(checkUserId); 14525 if (installAllowed) { 14526 break; 14527 } 14528 } 14529 if (!installAllowed) { 14530 return PackageManager.INSTALL_FAILED_INVALID_URI; 14531 } 14532 } 14533 if (!pkgSetting.getInstalled(userId)) { 14534 pkgSetting.setInstalled(true, userId); 14535 pkgSetting.setHidden(false, userId); 14536 pkgSetting.setInstallReason(installReason, userId); 14537 mSettings.writePackageRestrictionsLPr(userId); 14538 mSettings.writeKernelMappingLPr(pkgSetting); 14539 installed = true; 14540 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 14541 // upgrade app from instant to full; we don't allow app downgrade 14542 installed = true; 14543 } 14544 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 14545 } 14546 14547 if (installed) { 14548 if (pkgSetting.pkg != null) { 14549 synchronized (mInstallLock) { 14550 // We don't need to freeze for a brand new install 14551 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 14552 } 14553 } 14554 sendPackageAddedForUser(packageName, pkgSetting, userId); 14555 synchronized (mPackages) { 14556 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 14557 } 14558 } 14559 } finally { 14560 Binder.restoreCallingIdentity(callingId); 14561 } 14562 14563 return PackageManager.INSTALL_SUCCEEDED; 14564 } 14565 14566 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 14567 boolean instantApp, boolean fullApp) { 14568 // no state specified; do nothing 14569 if (!instantApp && !fullApp) { 14570 return; 14571 } 14572 if (userId != UserHandle.USER_ALL) { 14573 if (instantApp && !pkgSetting.getInstantApp(userId)) { 14574 pkgSetting.setInstantApp(true /*instantApp*/, userId); 14575 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 14576 pkgSetting.setInstantApp(false /*instantApp*/, userId); 14577 } 14578 } else { 14579 for (int currentUserId : sUserManager.getUserIds()) { 14580 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 14581 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 14582 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 14583 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 14584 } 14585 } 14586 } 14587 } 14588 14589 boolean isUserRestricted(int userId, String restrictionKey) { 14590 Bundle restrictions = sUserManager.getUserRestrictions(userId); 14591 if (restrictions.getBoolean(restrictionKey, false)) { 14592 Log.w(TAG, "User is restricted: " + restrictionKey); 14593 return true; 14594 } 14595 return false; 14596 } 14597 14598 @Override 14599 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 14600 int userId) { 14601 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 14602 final int callingUid = Binder.getCallingUid(); 14603 enforceCrossUserPermission(callingUid, userId, 14604 true /* requireFullPermission */, true /* checkShell */, 14605 "setPackagesSuspended for user " + userId); 14606 14607 if (ArrayUtils.isEmpty(packageNames)) { 14608 return packageNames; 14609 } 14610 14611 // List of package names for whom the suspended state has changed. 14612 List<String> changedPackages = new ArrayList<>(packageNames.length); 14613 // List of package names for whom the suspended state is not set as requested in this 14614 // method. 14615 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 14616 long callingId = Binder.clearCallingIdentity(); 14617 try { 14618 for (int i = 0; i < packageNames.length; i++) { 14619 String packageName = packageNames[i]; 14620 boolean changed = false; 14621 final int appId; 14622 synchronized (mPackages) { 14623 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 14624 if (pkgSetting == null 14625 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 14626 Slog.w(TAG, "Could not find package setting for package \"" + packageName 14627 + "\". Skipping suspending/un-suspending."); 14628 unactionedPackages.add(packageName); 14629 continue; 14630 } 14631 appId = pkgSetting.appId; 14632 if (pkgSetting.getSuspended(userId) != suspended) { 14633 if (!canSuspendPackageForUserLocked(packageName, userId)) { 14634 unactionedPackages.add(packageName); 14635 continue; 14636 } 14637 pkgSetting.setSuspended(suspended, userId); 14638 mSettings.writePackageRestrictionsLPr(userId); 14639 changed = true; 14640 changedPackages.add(packageName); 14641 } 14642 } 14643 14644 if (changed && suspended) { 14645 killApplication(packageName, UserHandle.getUid(userId, appId), 14646 "suspending package"); 14647 } 14648 } 14649 } finally { 14650 Binder.restoreCallingIdentity(callingId); 14651 } 14652 14653 if (!changedPackages.isEmpty()) { 14654 sendPackagesSuspendedForUser(changedPackages.toArray( 14655 new String[changedPackages.size()]), userId, suspended); 14656 } 14657 14658 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 14659 } 14660 14661 @Override 14662 public boolean isPackageSuspendedForUser(String packageName, int userId) { 14663 final int callingUid = Binder.getCallingUid(); 14664 enforceCrossUserPermission(callingUid, userId, 14665 true /* requireFullPermission */, false /* checkShell */, 14666 "isPackageSuspendedForUser for user " + userId); 14667 synchronized (mPackages) { 14668 final PackageSetting ps = mSettings.mPackages.get(packageName); 14669 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 14670 throw new IllegalArgumentException("Unknown target package: " + packageName); 14671 } 14672 return ps.getSuspended(userId); 14673 } 14674 } 14675 14676 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 14677 if (isPackageDeviceAdmin(packageName, userId)) { 14678 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14679 + "\": has an active device admin"); 14680 return false; 14681 } 14682 14683 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 14684 if (packageName.equals(activeLauncherPackageName)) { 14685 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14686 + "\": contains the active launcher"); 14687 return false; 14688 } 14689 14690 if (packageName.equals(mRequiredInstallerPackage)) { 14691 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14692 + "\": required for package installation"); 14693 return false; 14694 } 14695 14696 if (packageName.equals(mRequiredUninstallerPackage)) { 14697 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14698 + "\": required for package uninstallation"); 14699 return false; 14700 } 14701 14702 if (packageName.equals(mRequiredVerifierPackage)) { 14703 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14704 + "\": required for package verification"); 14705 return false; 14706 } 14707 14708 if (packageName.equals(getDefaultDialerPackageName(userId))) { 14709 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14710 + "\": is the default dialer"); 14711 return false; 14712 } 14713 14714 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14715 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14716 + "\": protected package"); 14717 return false; 14718 } 14719 14720 // Cannot suspend static shared libs as they are considered 14721 // a part of the using app (emulating static linking). Also 14722 // static libs are installed always on internal storage. 14723 PackageParser.Package pkg = mPackages.get(packageName); 14724 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 14725 Slog.w(TAG, "Cannot suspend package: " + packageName 14726 + " providing static shared library: " 14727 + pkg.staticSharedLibName); 14728 return false; 14729 } 14730 14731 return true; 14732 } 14733 14734 private String getActiveLauncherPackageName(int userId) { 14735 Intent intent = new Intent(Intent.ACTION_MAIN); 14736 intent.addCategory(Intent.CATEGORY_HOME); 14737 ResolveInfo resolveInfo = resolveIntent( 14738 intent, 14739 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 14740 PackageManager.MATCH_DEFAULT_ONLY, 14741 userId); 14742 14743 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 14744 } 14745 14746 private String getDefaultDialerPackageName(int userId) { 14747 synchronized (mPackages) { 14748 return mSettings.getDefaultDialerPackageNameLPw(userId); 14749 } 14750 } 14751 14752 @Override 14753 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 14754 mContext.enforceCallingOrSelfPermission( 14755 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14756 "Only package verification agents can verify applications"); 14757 14758 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14759 final PackageVerificationResponse response = new PackageVerificationResponse( 14760 verificationCode, Binder.getCallingUid()); 14761 msg.arg1 = id; 14762 msg.obj = response; 14763 mHandler.sendMessage(msg); 14764 } 14765 14766 @Override 14767 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 14768 long millisecondsToDelay) { 14769 mContext.enforceCallingOrSelfPermission( 14770 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14771 "Only package verification agents can extend verification timeouts"); 14772 14773 final PackageVerificationState state = mPendingVerification.get(id); 14774 final PackageVerificationResponse response = new PackageVerificationResponse( 14775 verificationCodeAtTimeout, Binder.getCallingUid()); 14776 14777 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 14778 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 14779 } 14780 if (millisecondsToDelay < 0) { 14781 millisecondsToDelay = 0; 14782 } 14783 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 14784 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 14785 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 14786 } 14787 14788 if ((state != null) && !state.timeoutExtended()) { 14789 state.extendTimeout(); 14790 14791 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14792 msg.arg1 = id; 14793 msg.obj = response; 14794 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14795 } 14796 } 14797 14798 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14799 int verificationCode, UserHandle user) { 14800 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14801 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14802 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14803 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14804 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14805 14806 mContext.sendBroadcastAsUser(intent, user, 14807 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14808 } 14809 14810 private ComponentName matchComponentForVerifier(String packageName, 14811 List<ResolveInfo> receivers) { 14812 ActivityInfo targetReceiver = null; 14813 14814 final int NR = receivers.size(); 14815 for (int i = 0; i < NR; i++) { 14816 final ResolveInfo info = receivers.get(i); 14817 if (info.activityInfo == null) { 14818 continue; 14819 } 14820 14821 if (packageName.equals(info.activityInfo.packageName)) { 14822 targetReceiver = info.activityInfo; 14823 break; 14824 } 14825 } 14826 14827 if (targetReceiver == null) { 14828 return null; 14829 } 14830 14831 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14832 } 14833 14834 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14835 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14836 if (pkgInfo.verifiers.length == 0) { 14837 return null; 14838 } 14839 14840 final int N = pkgInfo.verifiers.length; 14841 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14842 for (int i = 0; i < N; i++) { 14843 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14844 14845 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14846 receivers); 14847 if (comp == null) { 14848 continue; 14849 } 14850 14851 final int verifierUid = getUidForVerifier(verifierInfo); 14852 if (verifierUid == -1) { 14853 continue; 14854 } 14855 14856 if (DEBUG_VERIFY) { 14857 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14858 + " with the correct signature"); 14859 } 14860 sufficientVerifiers.add(comp); 14861 verificationState.addSufficientVerifier(verifierUid); 14862 } 14863 14864 return sufficientVerifiers; 14865 } 14866 14867 private int getUidForVerifier(VerifierInfo verifierInfo) { 14868 synchronized (mPackages) { 14869 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14870 if (pkg == null) { 14871 return -1; 14872 } else if (pkg.mSignatures.length != 1) { 14873 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14874 + " has more than one signature; ignoring"); 14875 return -1; 14876 } 14877 14878 /* 14879 * If the public key of the package's signature does not match 14880 * our expected public key, then this is a different package and 14881 * we should skip. 14882 */ 14883 14884 final byte[] expectedPublicKey; 14885 try { 14886 final Signature verifierSig = pkg.mSignatures[0]; 14887 final PublicKey publicKey = verifierSig.getPublicKey(); 14888 expectedPublicKey = publicKey.getEncoded(); 14889 } catch (CertificateException e) { 14890 return -1; 14891 } 14892 14893 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14894 14895 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14896 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14897 + " does not have the expected public key; ignoring"); 14898 return -1; 14899 } 14900 14901 return pkg.applicationInfo.uid; 14902 } 14903 } 14904 14905 @Override 14906 public void finishPackageInstall(int token, boolean didLaunch) { 14907 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14908 14909 if (DEBUG_INSTALL) { 14910 Slog.v(TAG, "BM finishing package install for " + token); 14911 } 14912 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14913 14914 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14915 mHandler.sendMessage(msg); 14916 } 14917 14918 /** 14919 * Get the verification agent timeout. Used for both the APK verifier and the 14920 * intent filter verifier. 14921 * 14922 * @return verification timeout in milliseconds 14923 */ 14924 private long getVerificationTimeout() { 14925 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14926 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14927 DEFAULT_VERIFICATION_TIMEOUT); 14928 } 14929 14930 /** 14931 * Get the default verification agent response code. 14932 * 14933 * @return default verification response code 14934 */ 14935 private int getDefaultVerificationResponse(UserHandle user) { 14936 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 14937 return PackageManager.VERIFICATION_REJECT; 14938 } 14939 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14940 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14941 DEFAULT_VERIFICATION_RESPONSE); 14942 } 14943 14944 /** 14945 * Check whether or not package verification has been enabled. 14946 * 14947 * @return true if verification should be performed 14948 */ 14949 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 14950 if (!DEFAULT_VERIFY_ENABLE) { 14951 return false; 14952 } 14953 14954 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14955 14956 // Check if installing from ADB 14957 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14958 // Do not run verification in a test harness environment 14959 if (ActivityManager.isRunningInTestHarness()) { 14960 return false; 14961 } 14962 if (ensureVerifyAppsEnabled) { 14963 return true; 14964 } 14965 // Check if the developer does not want package verification for ADB installs 14966 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14967 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14968 return false; 14969 } 14970 } else { 14971 // only when not installed from ADB, skip verification for instant apps when 14972 // the installer and verifier are the same. 14973 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14974 if (mInstantAppInstallerActivity != null 14975 && mInstantAppInstallerActivity.packageName.equals( 14976 mRequiredVerifierPackage)) { 14977 try { 14978 mContext.getSystemService(AppOpsManager.class) 14979 .checkPackage(installerUid, mRequiredVerifierPackage); 14980 if (DEBUG_VERIFY) { 14981 Slog.i(TAG, "disable verification for instant app"); 14982 } 14983 return false; 14984 } catch (SecurityException ignore) { } 14985 } 14986 } 14987 } 14988 14989 if (ensureVerifyAppsEnabled) { 14990 return true; 14991 } 14992 14993 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14994 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14995 } 14996 14997 @Override 14998 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14999 throws RemoteException { 15000 mContext.enforceCallingOrSelfPermission( 15001 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 15002 "Only intentfilter verification agents can verify applications"); 15003 15004 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 15005 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 15006 Binder.getCallingUid(), verificationCode, failedDomains); 15007 msg.arg1 = id; 15008 msg.obj = response; 15009 mHandler.sendMessage(msg); 15010 } 15011 15012 @Override 15013 public int getIntentVerificationStatus(String packageName, int userId) { 15014 final int callingUid = Binder.getCallingUid(); 15015 if (getInstantAppPackageName(callingUid) != null) { 15016 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 15017 } 15018 synchronized (mPackages) { 15019 final PackageSetting ps = mSettings.mPackages.get(packageName); 15020 if (ps == null 15021 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 15022 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 15023 } 15024 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 15025 } 15026 } 15027 15028 @Override 15029 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 15030 mContext.enforceCallingOrSelfPermission( 15031 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15032 15033 boolean result = false; 15034 synchronized (mPackages) { 15035 final PackageSetting ps = mSettings.mPackages.get(packageName); 15036 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 15037 return false; 15038 } 15039 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 15040 } 15041 if (result) { 15042 scheduleWritePackageRestrictionsLocked(userId); 15043 } 15044 return result; 15045 } 15046 15047 @Override 15048 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 15049 String packageName) { 15050 final int callingUid = Binder.getCallingUid(); 15051 if (getInstantAppPackageName(callingUid) != null) { 15052 return ParceledListSlice.emptyList(); 15053 } 15054 synchronized (mPackages) { 15055 final PackageSetting ps = mSettings.mPackages.get(packageName); 15056 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 15057 return ParceledListSlice.emptyList(); 15058 } 15059 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 15060 } 15061 } 15062 15063 @Override 15064 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 15065 if (TextUtils.isEmpty(packageName)) { 15066 return ParceledListSlice.emptyList(); 15067 } 15068 final int callingUid = Binder.getCallingUid(); 15069 final int callingUserId = UserHandle.getUserId(callingUid); 15070 synchronized (mPackages) { 15071 PackageParser.Package pkg = mPackages.get(packageName); 15072 if (pkg == null || pkg.activities == null) { 15073 return ParceledListSlice.emptyList(); 15074 } 15075 if (pkg.mExtras == null) { 15076 return ParceledListSlice.emptyList(); 15077 } 15078 final PackageSetting ps = (PackageSetting) pkg.mExtras; 15079 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 15080 return ParceledListSlice.emptyList(); 15081 } 15082 final int count = pkg.activities.size(); 15083 ArrayList<IntentFilter> result = new ArrayList<>(); 15084 for (int n=0; n<count; n++) { 15085 PackageParser.Activity activity = pkg.activities.get(n); 15086 if (activity.intents != null && activity.intents.size() > 0) { 15087 result.addAll(activity.intents); 15088 } 15089 } 15090 return new ParceledListSlice<>(result); 15091 } 15092 } 15093 15094 @Override 15095 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 15096 mContext.enforceCallingOrSelfPermission( 15097 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15098 15099 synchronized (mPackages) { 15100 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 15101 if (packageName != null) { 15102 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 15103 packageName, userId); 15104 } 15105 return result; 15106 } 15107 } 15108 15109 @Override 15110 public String getDefaultBrowserPackageName(int userId) { 15111 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 15112 return null; 15113 } 15114 synchronized (mPackages) { 15115 return mSettings.getDefaultBrowserPackageNameLPw(userId); 15116 } 15117 } 15118 15119 /** 15120 * Get the "allow unknown sources" setting. 15121 * 15122 * @return the current "allow unknown sources" setting 15123 */ 15124 private int getUnknownSourcesSettings() { 15125 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 15126 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 15127 -1); 15128 } 15129 15130 @Override 15131 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 15132 final int callingUid = Binder.getCallingUid(); 15133 if (getInstantAppPackageName(callingUid) != null) { 15134 return; 15135 } 15136 // writer 15137 synchronized (mPackages) { 15138 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 15139 if (targetPackageSetting == null 15140 || filterAppAccessLPr( 15141 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 15142 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 15143 } 15144 15145 PackageSetting installerPackageSetting; 15146 if (installerPackageName != null) { 15147 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 15148 if (installerPackageSetting == null) { 15149 throw new IllegalArgumentException("Unknown installer package: " 15150 + installerPackageName); 15151 } 15152 } else { 15153 installerPackageSetting = null; 15154 } 15155 15156 Signature[] callerSignature; 15157 Object obj = mSettings.getUserIdLPr(callingUid); 15158 if (obj != null) { 15159 if (obj instanceof SharedUserSetting) { 15160 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 15161 } else if (obj instanceof PackageSetting) { 15162 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 15163 } else { 15164 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 15165 } 15166 } else { 15167 throw new SecurityException("Unknown calling UID: " + callingUid); 15168 } 15169 15170 // Verify: can't set installerPackageName to a package that is 15171 // not signed with the same cert as the caller. 15172 if (installerPackageSetting != null) { 15173 if (compareSignatures(callerSignature, 15174 installerPackageSetting.signatures.mSignatures) 15175 != PackageManager.SIGNATURE_MATCH) { 15176 throw new SecurityException( 15177 "Caller does not have same cert as new installer package " 15178 + installerPackageName); 15179 } 15180 } 15181 15182 // Verify: if target already has an installer package, it must 15183 // be signed with the same cert as the caller. 15184 if (targetPackageSetting.installerPackageName != null) { 15185 PackageSetting setting = mSettings.mPackages.get( 15186 targetPackageSetting.installerPackageName); 15187 // If the currently set package isn't valid, then it's always 15188 // okay to change it. 15189 if (setting != null) { 15190 if (compareSignatures(callerSignature, 15191 setting.signatures.mSignatures) 15192 != PackageManager.SIGNATURE_MATCH) { 15193 throw new SecurityException( 15194 "Caller does not have same cert as old installer package " 15195 + targetPackageSetting.installerPackageName); 15196 } 15197 } 15198 } 15199 15200 // Okay! 15201 targetPackageSetting.installerPackageName = installerPackageName; 15202 if (installerPackageName != null) { 15203 mSettings.mInstallerPackages.add(installerPackageName); 15204 } 15205 scheduleWriteSettingsLocked(); 15206 } 15207 } 15208 15209 @Override 15210 public void setApplicationCategoryHint(String packageName, int categoryHint, 15211 String callerPackageName) { 15212 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 15213 throw new SecurityException("Instant applications don't have access to this method"); 15214 } 15215 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 15216 callerPackageName); 15217 synchronized (mPackages) { 15218 PackageSetting ps = mSettings.mPackages.get(packageName); 15219 if (ps == null) { 15220 throw new IllegalArgumentException("Unknown target package " + packageName); 15221 } 15222 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 15223 throw new IllegalArgumentException("Unknown target package " + packageName); 15224 } 15225 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 15226 throw new IllegalArgumentException("Calling package " + callerPackageName 15227 + " is not installer for " + packageName); 15228 } 15229 15230 if (ps.categoryHint != categoryHint) { 15231 ps.categoryHint = categoryHint; 15232 scheduleWriteSettingsLocked(); 15233 } 15234 } 15235 } 15236 15237 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 15238 // Queue up an async operation since the package installation may take a little while. 15239 mHandler.post(new Runnable() { 15240 public void run() { 15241 mHandler.removeCallbacks(this); 15242 // Result object to be returned 15243 PackageInstalledInfo res = new PackageInstalledInfo(); 15244 res.setReturnCode(currentStatus); 15245 res.uid = -1; 15246 res.pkg = null; 15247 res.removedInfo = null; 15248 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15249 args.doPreInstall(res.returnCode); 15250 synchronized (mInstallLock) { 15251 installPackageTracedLI(args, res); 15252 } 15253 args.doPostInstall(res.returnCode, res.uid); 15254 } 15255 15256 // A restore should be performed at this point if (a) the install 15257 // succeeded, (b) the operation is not an update, and (c) the new 15258 // package has not opted out of backup participation. 15259 final boolean update = res.removedInfo != null 15260 && res.removedInfo.removedPackage != null; 15261 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 15262 boolean doRestore = !update 15263 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 15264 15265 // Set up the post-install work request bookkeeping. This will be used 15266 // and cleaned up by the post-install event handling regardless of whether 15267 // there's a restore pass performed. Token values are >= 1. 15268 int token; 15269 if (mNextInstallToken < 0) mNextInstallToken = 1; 15270 token = mNextInstallToken++; 15271 15272 PostInstallData data = new PostInstallData(args, res); 15273 mRunningInstalls.put(token, data); 15274 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 15275 15276 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 15277 // Pass responsibility to the Backup Manager. It will perform a 15278 // restore if appropriate, then pass responsibility back to the 15279 // Package Manager to run the post-install observer callbacks 15280 // and broadcasts. 15281 IBackupManager bm = IBackupManager.Stub.asInterface( 15282 ServiceManager.getService(Context.BACKUP_SERVICE)); 15283 if (bm != null) { 15284 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 15285 + " to BM for possible restore"); 15286 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 15287 try { 15288 // TODO: http://b/22388012 15289 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 15290 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 15291 } else { 15292 doRestore = false; 15293 } 15294 } catch (RemoteException e) { 15295 // can't happen; the backup manager is local 15296 } catch (Exception e) { 15297 Slog.e(TAG, "Exception trying to enqueue restore", e); 15298 doRestore = false; 15299 } 15300 } else { 15301 Slog.e(TAG, "Backup Manager not found!"); 15302 doRestore = false; 15303 } 15304 } 15305 15306 if (!doRestore) { 15307 // No restore possible, or the Backup Manager was mysteriously not 15308 // available -- just fire the post-install work request directly. 15309 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 15310 15311 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 15312 15313 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 15314 mHandler.sendMessage(msg); 15315 } 15316 } 15317 }); 15318 } 15319 15320 /** 15321 * Callback from PackageSettings whenever an app is first transitioned out of the 15322 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 15323 * the app was "launched" for a restoreAtInstall operation. Therefore we check 15324 * here whether the app is the target of an ongoing install, and only send the 15325 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 15326 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 15327 * handling. 15328 */ 15329 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 15330 // Serialize this with the rest of the install-process message chain. In the 15331 // restore-at-install case, this Runnable will necessarily run before the 15332 // POST_INSTALL message is processed, so the contents of mRunningInstalls 15333 // are coherent. In the non-restore case, the app has already completed install 15334 // and been launched through some other means, so it is not in a problematic 15335 // state for observers to see the FIRST_LAUNCH signal. 15336 mHandler.post(new Runnable() { 15337 @Override 15338 public void run() { 15339 for (int i = 0; i < mRunningInstalls.size(); i++) { 15340 final PostInstallData data = mRunningInstalls.valueAt(i); 15341 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15342 continue; 15343 } 15344 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 15345 // right package; but is it for the right user? 15346 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 15347 if (userId == data.res.newUsers[uIndex]) { 15348 if (DEBUG_BACKUP) { 15349 Slog.i(TAG, "Package " + pkgName 15350 + " being restored so deferring FIRST_LAUNCH"); 15351 } 15352 return; 15353 } 15354 } 15355 } 15356 } 15357 // didn't find it, so not being restored 15358 if (DEBUG_BACKUP) { 15359 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 15360 } 15361 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 15362 } 15363 }); 15364 } 15365 15366 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 15367 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 15368 installerPkg, null, userIds); 15369 } 15370 15371 private abstract class HandlerParams { 15372 private static final int MAX_RETRIES = 4; 15373 15374 /** 15375 * Number of times startCopy() has been attempted and had a non-fatal 15376 * error. 15377 */ 15378 private int mRetries = 0; 15379 15380 /** User handle for the user requesting the information or installation. */ 15381 private final UserHandle mUser; 15382 String traceMethod; 15383 int traceCookie; 15384 15385 HandlerParams(UserHandle user) { 15386 mUser = user; 15387 } 15388 15389 UserHandle getUser() { 15390 return mUser; 15391 } 15392 15393 HandlerParams setTraceMethod(String traceMethod) { 15394 this.traceMethod = traceMethod; 15395 return this; 15396 } 15397 15398 HandlerParams setTraceCookie(int traceCookie) { 15399 this.traceCookie = traceCookie; 15400 return this; 15401 } 15402 15403 final boolean startCopy() { 15404 boolean res; 15405 try { 15406 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 15407 15408 if (++mRetries > MAX_RETRIES) { 15409 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 15410 mHandler.sendEmptyMessage(MCS_GIVE_UP); 15411 handleServiceError(); 15412 return false; 15413 } else { 15414 handleStartCopy(); 15415 res = true; 15416 } 15417 } catch (RemoteException e) { 15418 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 15419 mHandler.sendEmptyMessage(MCS_RECONNECT); 15420 res = false; 15421 } 15422 handleReturnCode(); 15423 return res; 15424 } 15425 15426 final void serviceError() { 15427 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 15428 handleServiceError(); 15429 handleReturnCode(); 15430 } 15431 15432 abstract void handleStartCopy() throws RemoteException; 15433 abstract void handleServiceError(); 15434 abstract void handleReturnCode(); 15435 } 15436 15437 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 15438 for (File path : paths) { 15439 try { 15440 mcs.clearDirectory(path.getAbsolutePath()); 15441 } catch (RemoteException e) { 15442 } 15443 } 15444 } 15445 15446 static class OriginInfo { 15447 /** 15448 * Location where install is coming from, before it has been 15449 * copied/renamed into place. This could be a single monolithic APK 15450 * file, or a cluster directory. This location may be untrusted. 15451 */ 15452 final File file; 15453 final String cid; 15454 15455 /** 15456 * Flag indicating that {@link #file} or {@link #cid} has already been 15457 * staged, meaning downstream users don't need to defensively copy the 15458 * contents. 15459 */ 15460 final boolean staged; 15461 15462 /** 15463 * Flag indicating that {@link #file} or {@link #cid} is an already 15464 * installed app that is being moved. 15465 */ 15466 final boolean existing; 15467 15468 final String resolvedPath; 15469 final File resolvedFile; 15470 15471 static OriginInfo fromNothing() { 15472 return new OriginInfo(null, null, false, false); 15473 } 15474 15475 static OriginInfo fromUntrustedFile(File file) { 15476 return new OriginInfo(file, null, false, false); 15477 } 15478 15479 static OriginInfo fromExistingFile(File file) { 15480 return new OriginInfo(file, null, false, true); 15481 } 15482 15483 static OriginInfo fromStagedFile(File file) { 15484 return new OriginInfo(file, null, true, false); 15485 } 15486 15487 static OriginInfo fromStagedContainer(String cid) { 15488 return new OriginInfo(null, cid, true, false); 15489 } 15490 15491 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 15492 this.file = file; 15493 this.cid = cid; 15494 this.staged = staged; 15495 this.existing = existing; 15496 15497 if (cid != null) { 15498 resolvedPath = PackageHelper.getSdDir(cid); 15499 resolvedFile = new File(resolvedPath); 15500 } else if (file != null) { 15501 resolvedPath = file.getAbsolutePath(); 15502 resolvedFile = file; 15503 } else { 15504 resolvedPath = null; 15505 resolvedFile = null; 15506 } 15507 } 15508 } 15509 15510 static class MoveInfo { 15511 final int moveId; 15512 final String fromUuid; 15513 final String toUuid; 15514 final String packageName; 15515 final String dataAppName; 15516 final int appId; 15517 final String seinfo; 15518 final int targetSdkVersion; 15519 15520 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 15521 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 15522 this.moveId = moveId; 15523 this.fromUuid = fromUuid; 15524 this.toUuid = toUuid; 15525 this.packageName = packageName; 15526 this.dataAppName = dataAppName; 15527 this.appId = appId; 15528 this.seinfo = seinfo; 15529 this.targetSdkVersion = targetSdkVersion; 15530 } 15531 } 15532 15533 static class VerificationInfo { 15534 /** A constant used to indicate that a uid value is not present. */ 15535 public static final int NO_UID = -1; 15536 15537 /** URI referencing where the package was downloaded from. */ 15538 final Uri originatingUri; 15539 15540 /** HTTP referrer URI associated with the originatingURI. */ 15541 final Uri referrer; 15542 15543 /** UID of the application that the install request originated from. */ 15544 final int originatingUid; 15545 15546 /** UID of application requesting the install */ 15547 final int installerUid; 15548 15549 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 15550 this.originatingUri = originatingUri; 15551 this.referrer = referrer; 15552 this.originatingUid = originatingUid; 15553 this.installerUid = installerUid; 15554 } 15555 } 15556 15557 class InstallParams extends HandlerParams { 15558 final OriginInfo origin; 15559 final MoveInfo move; 15560 final IPackageInstallObserver2 observer; 15561 int installFlags; 15562 final String installerPackageName; 15563 final String volumeUuid; 15564 private InstallArgs mArgs; 15565 private int mRet; 15566 final String packageAbiOverride; 15567 final String[] grantedRuntimePermissions; 15568 final VerificationInfo verificationInfo; 15569 final Certificate[][] certificates; 15570 final int installReason; 15571 15572 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15573 int installFlags, String installerPackageName, String volumeUuid, 15574 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 15575 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 15576 super(user); 15577 this.origin = origin; 15578 this.move = move; 15579 this.observer = observer; 15580 this.installFlags = installFlags; 15581 this.installerPackageName = installerPackageName; 15582 this.volumeUuid = volumeUuid; 15583 this.verificationInfo = verificationInfo; 15584 this.packageAbiOverride = packageAbiOverride; 15585 this.grantedRuntimePermissions = grantedPermissions; 15586 this.certificates = certificates; 15587 this.installReason = installReason; 15588 } 15589 15590 @Override 15591 public String toString() { 15592 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 15593 + " file=" + origin.file + " cid=" + origin.cid + "}"; 15594 } 15595 15596 private int installLocationPolicy(PackageInfoLite pkgLite) { 15597 String packageName = pkgLite.packageName; 15598 int installLocation = pkgLite.installLocation; 15599 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15600 // reader 15601 synchronized (mPackages) { 15602 // Currently installed package which the new package is attempting to replace or 15603 // null if no such package is installed. 15604 PackageParser.Package installedPkg = mPackages.get(packageName); 15605 // Package which currently owns the data which the new package will own if installed. 15606 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 15607 // will be null whereas dataOwnerPkg will contain information about the package 15608 // which was uninstalled while keeping its data. 15609 PackageParser.Package dataOwnerPkg = installedPkg; 15610 if (dataOwnerPkg == null) { 15611 PackageSetting ps = mSettings.mPackages.get(packageName); 15612 if (ps != null) { 15613 dataOwnerPkg = ps.pkg; 15614 } 15615 } 15616 15617 if (dataOwnerPkg != null) { 15618 // If installed, the package will get access to data left on the device by its 15619 // predecessor. As a security measure, this is permited only if this is not a 15620 // version downgrade or if the predecessor package is marked as debuggable and 15621 // a downgrade is explicitly requested. 15622 // 15623 // On debuggable platform builds, downgrades are permitted even for 15624 // non-debuggable packages to make testing easier. Debuggable platform builds do 15625 // not offer security guarantees and thus it's OK to disable some security 15626 // mechanisms to make debugging/testing easier on those builds. However, even on 15627 // debuggable builds downgrades of packages are permitted only if requested via 15628 // installFlags. This is because we aim to keep the behavior of debuggable 15629 // platform builds as close as possible to the behavior of non-debuggable 15630 // platform builds. 15631 final boolean downgradeRequested = 15632 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 15633 final boolean packageDebuggable = 15634 (dataOwnerPkg.applicationInfo.flags 15635 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 15636 final boolean downgradePermitted = 15637 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 15638 if (!downgradePermitted) { 15639 try { 15640 checkDowngrade(dataOwnerPkg, pkgLite); 15641 } catch (PackageManagerException e) { 15642 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 15643 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 15644 } 15645 } 15646 } 15647 15648 if (installedPkg != null) { 15649 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15650 // Check for updated system application. 15651 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15652 if (onSd) { 15653 Slog.w(TAG, "Cannot install update to system app on sdcard"); 15654 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 15655 } 15656 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15657 } else { 15658 if (onSd) { 15659 // Install flag overrides everything. 15660 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15661 } 15662 // If current upgrade specifies particular preference 15663 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 15664 // Application explicitly specified internal. 15665 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15666 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 15667 // App explictly prefers external. Let policy decide 15668 } else { 15669 // Prefer previous location 15670 if (isExternal(installedPkg)) { 15671 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15672 } 15673 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15674 } 15675 } 15676 } else { 15677 // Invalid install. Return error code 15678 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 15679 } 15680 } 15681 } 15682 // All the special cases have been taken care of. 15683 // Return result based on recommended install location. 15684 if (onSd) { 15685 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15686 } 15687 return pkgLite.recommendedInstallLocation; 15688 } 15689 15690 /* 15691 * Invoke remote method to get package information and install 15692 * location values. Override install location based on default 15693 * policy if needed and then create install arguments based 15694 * on the install location. 15695 */ 15696 public void handleStartCopy() throws RemoteException { 15697 int ret = PackageManager.INSTALL_SUCCEEDED; 15698 15699 // If we're already staged, we've firmly committed to an install location 15700 if (origin.staged) { 15701 if (origin.file != null) { 15702 installFlags |= PackageManager.INSTALL_INTERNAL; 15703 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15704 } else if (origin.cid != null) { 15705 installFlags |= PackageManager.INSTALL_EXTERNAL; 15706 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15707 } else { 15708 throw new IllegalStateException("Invalid stage location"); 15709 } 15710 } 15711 15712 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15713 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 15714 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15715 PackageInfoLite pkgLite = null; 15716 15717 if (onInt && onSd) { 15718 // Check if both bits are set. 15719 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 15720 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15721 } else if (onSd && ephemeral) { 15722 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 15723 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15724 } else { 15725 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 15726 packageAbiOverride); 15727 15728 if (DEBUG_EPHEMERAL && ephemeral) { 15729 Slog.v(TAG, "pkgLite for install: " + pkgLite); 15730 } 15731 15732 /* 15733 * If we have too little free space, try to free cache 15734 * before giving up. 15735 */ 15736 if (!origin.staged && pkgLite.recommendedInstallLocation 15737 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15738 // TODO: focus freeing disk space on the target device 15739 final StorageManager storage = StorageManager.from(mContext); 15740 final long lowThreshold = storage.getStorageLowBytes( 15741 Environment.getDataDirectory()); 15742 15743 final long sizeBytes = mContainerService.calculateInstalledSize( 15744 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 15745 15746 try { 15747 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 15748 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 15749 installFlags, packageAbiOverride); 15750 } catch (InstallerException e) { 15751 Slog.w(TAG, "Failed to free cache", e); 15752 } 15753 15754 /* 15755 * The cache free must have deleted the file we 15756 * downloaded to install. 15757 * 15758 * TODO: fix the "freeCache" call to not delete 15759 * the file we care about. 15760 */ 15761 if (pkgLite.recommendedInstallLocation 15762 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15763 pkgLite.recommendedInstallLocation 15764 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 15765 } 15766 } 15767 } 15768 15769 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15770 int loc = pkgLite.recommendedInstallLocation; 15771 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 15772 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15773 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 15774 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 15775 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15776 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15777 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 15778 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 15779 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15780 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 15781 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 15782 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 15783 } else { 15784 // Override with defaults if needed. 15785 loc = installLocationPolicy(pkgLite); 15786 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 15787 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 15788 } else if (!onSd && !onInt) { 15789 // Override install location with flags 15790 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 15791 // Set the flag to install on external media. 15792 installFlags |= PackageManager.INSTALL_EXTERNAL; 15793 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15794 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 15795 if (DEBUG_EPHEMERAL) { 15796 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 15797 } 15798 installFlags |= PackageManager.INSTALL_INSTANT_APP; 15799 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 15800 |PackageManager.INSTALL_INTERNAL); 15801 } else { 15802 // Make sure the flag for installing on external 15803 // media is unset 15804 installFlags |= PackageManager.INSTALL_INTERNAL; 15805 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15806 } 15807 } 15808 } 15809 } 15810 15811 final InstallArgs args = createInstallArgs(this); 15812 mArgs = args; 15813 15814 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15815 // TODO: http://b/22976637 15816 // Apps installed for "all" users use the device owner to verify the app 15817 UserHandle verifierUser = getUser(); 15818 if (verifierUser == UserHandle.ALL) { 15819 verifierUser = UserHandle.SYSTEM; 15820 } 15821 15822 /* 15823 * Determine if we have any installed package verifiers. If we 15824 * do, then we'll defer to them to verify the packages. 15825 */ 15826 final int requiredUid = mRequiredVerifierPackage == null ? -1 15827 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15828 verifierUser.getIdentifier()); 15829 final int installerUid = 15830 verificationInfo == null ? -1 : verificationInfo.installerUid; 15831 if (!origin.existing && requiredUid != -1 15832 && isVerificationEnabled( 15833 verifierUser.getIdentifier(), installFlags, installerUid)) { 15834 final Intent verification = new Intent( 15835 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15836 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15837 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15838 PACKAGE_MIME_TYPE); 15839 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15840 15841 // Query all live verifiers based on current user state 15842 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15843 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 15844 15845 if (DEBUG_VERIFY) { 15846 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15847 + verification.toString() + " with " + pkgLite.verifiers.length 15848 + " optional verifiers"); 15849 } 15850 15851 final int verificationId = mPendingVerificationToken++; 15852 15853 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15854 15855 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15856 installerPackageName); 15857 15858 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15859 installFlags); 15860 15861 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15862 pkgLite.packageName); 15863 15864 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15865 pkgLite.versionCode); 15866 15867 if (verificationInfo != null) { 15868 if (verificationInfo.originatingUri != null) { 15869 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15870 verificationInfo.originatingUri); 15871 } 15872 if (verificationInfo.referrer != null) { 15873 verification.putExtra(Intent.EXTRA_REFERRER, 15874 verificationInfo.referrer); 15875 } 15876 if (verificationInfo.originatingUid >= 0) { 15877 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15878 verificationInfo.originatingUid); 15879 } 15880 if (verificationInfo.installerUid >= 0) { 15881 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15882 verificationInfo.installerUid); 15883 } 15884 } 15885 15886 final PackageVerificationState verificationState = new PackageVerificationState( 15887 requiredUid, args); 15888 15889 mPendingVerification.append(verificationId, verificationState); 15890 15891 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15892 receivers, verificationState); 15893 15894 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15895 final long idleDuration = getVerificationTimeout(); 15896 15897 /* 15898 * If any sufficient verifiers were listed in the package 15899 * manifest, attempt to ask them. 15900 */ 15901 if (sufficientVerifiers != null) { 15902 final int N = sufficientVerifiers.size(); 15903 if (N == 0) { 15904 Slog.i(TAG, "Additional verifiers required, but none installed."); 15905 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15906 } else { 15907 for (int i = 0; i < N; i++) { 15908 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15909 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15910 verifierComponent.getPackageName(), idleDuration, 15911 verifierUser.getIdentifier(), false, "package verifier"); 15912 15913 final Intent sufficientIntent = new Intent(verification); 15914 sufficientIntent.setComponent(verifierComponent); 15915 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15916 } 15917 } 15918 } 15919 15920 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15921 mRequiredVerifierPackage, receivers); 15922 if (ret == PackageManager.INSTALL_SUCCEEDED 15923 && mRequiredVerifierPackage != null) { 15924 Trace.asyncTraceBegin( 15925 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15926 /* 15927 * Send the intent to the required verification agent, 15928 * but only start the verification timeout after the 15929 * target BroadcastReceivers have run. 15930 */ 15931 verification.setComponent(requiredVerifierComponent); 15932 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15933 mRequiredVerifierPackage, idleDuration, 15934 verifierUser.getIdentifier(), false, "package verifier"); 15935 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15936 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15937 new BroadcastReceiver() { 15938 @Override 15939 public void onReceive(Context context, Intent intent) { 15940 final Message msg = mHandler 15941 .obtainMessage(CHECK_PENDING_VERIFICATION); 15942 msg.arg1 = verificationId; 15943 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15944 } 15945 }, null, 0, null, null); 15946 15947 /* 15948 * We don't want the copy to proceed until verification 15949 * succeeds, so null out this field. 15950 */ 15951 mArgs = null; 15952 } 15953 } else { 15954 /* 15955 * No package verification is enabled, so immediately start 15956 * the remote call to initiate copy using temporary file. 15957 */ 15958 ret = args.copyApk(mContainerService, true); 15959 } 15960 } 15961 15962 mRet = ret; 15963 } 15964 15965 @Override 15966 void handleReturnCode() { 15967 // If mArgs is null, then MCS couldn't be reached. When it 15968 // reconnects, it will try again to install. At that point, this 15969 // will succeed. 15970 if (mArgs != null) { 15971 processPendingInstall(mArgs, mRet); 15972 } 15973 } 15974 15975 @Override 15976 void handleServiceError() { 15977 mArgs = createInstallArgs(this); 15978 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15979 } 15980 15981 public boolean isForwardLocked() { 15982 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15983 } 15984 } 15985 15986 /** 15987 * Used during creation of InstallArgs 15988 * 15989 * @param installFlags package installation flags 15990 * @return true if should be installed on external storage 15991 */ 15992 private static boolean installOnExternalAsec(int installFlags) { 15993 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 15994 return false; 15995 } 15996 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 15997 return true; 15998 } 15999 return false; 16000 } 16001 16002 /** 16003 * Used during creation of InstallArgs 16004 * 16005 * @param installFlags package installation flags 16006 * @return true if should be installed as forward locked 16007 */ 16008 private static boolean installForwardLocked(int installFlags) { 16009 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 16010 } 16011 16012 private InstallArgs createInstallArgs(InstallParams params) { 16013 if (params.move != null) { 16014 return new MoveInstallArgs(params); 16015 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 16016 return new AsecInstallArgs(params); 16017 } else { 16018 return new FileInstallArgs(params); 16019 } 16020 } 16021 16022 /** 16023 * Create args that describe an existing installed package. Typically used 16024 * when cleaning up old installs, or used as a move source. 16025 */ 16026 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 16027 String resourcePath, String[] instructionSets) { 16028 final boolean isInAsec; 16029 if (installOnExternalAsec(installFlags)) { 16030 /* Apps on SD card are always in ASEC containers. */ 16031 isInAsec = true; 16032 } else if (installForwardLocked(installFlags) 16033 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 16034 /* 16035 * Forward-locked apps are only in ASEC containers if they're the 16036 * new style 16037 */ 16038 isInAsec = true; 16039 } else { 16040 isInAsec = false; 16041 } 16042 16043 if (isInAsec) { 16044 return new AsecInstallArgs(codePath, instructionSets, 16045 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 16046 } else { 16047 return new FileInstallArgs(codePath, resourcePath, instructionSets); 16048 } 16049 } 16050 16051 static abstract class InstallArgs { 16052 /** @see InstallParams#origin */ 16053 final OriginInfo origin; 16054 /** @see InstallParams#move */ 16055 final MoveInfo move; 16056 16057 final IPackageInstallObserver2 observer; 16058 // Always refers to PackageManager flags only 16059 final int installFlags; 16060 final String installerPackageName; 16061 final String volumeUuid; 16062 final UserHandle user; 16063 final String abiOverride; 16064 final String[] installGrantPermissions; 16065 /** If non-null, drop an async trace when the install completes */ 16066 final String traceMethod; 16067 final int traceCookie; 16068 final Certificate[][] certificates; 16069 final int installReason; 16070 16071 // The list of instruction sets supported by this app. This is currently 16072 // only used during the rmdex() phase to clean up resources. We can get rid of this 16073 // if we move dex files under the common app path. 16074 /* nullable */ String[] instructionSets; 16075 16076 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 16077 int installFlags, String installerPackageName, String volumeUuid, 16078 UserHandle user, String[] instructionSets, 16079 String abiOverride, String[] installGrantPermissions, 16080 String traceMethod, int traceCookie, Certificate[][] certificates, 16081 int installReason) { 16082 this.origin = origin; 16083 this.move = move; 16084 this.installFlags = installFlags; 16085 this.observer = observer; 16086 this.installerPackageName = installerPackageName; 16087 this.volumeUuid = volumeUuid; 16088 this.user = user; 16089 this.instructionSets = instructionSets; 16090 this.abiOverride = abiOverride; 16091 this.installGrantPermissions = installGrantPermissions; 16092 this.traceMethod = traceMethod; 16093 this.traceCookie = traceCookie; 16094 this.certificates = certificates; 16095 this.installReason = installReason; 16096 } 16097 16098 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 16099 abstract int doPreInstall(int status); 16100 16101 /** 16102 * Rename package into final resting place. All paths on the given 16103 * scanned package should be updated to reflect the rename. 16104 */ 16105 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 16106 abstract int doPostInstall(int status, int uid); 16107 16108 /** @see PackageSettingBase#codePathString */ 16109 abstract String getCodePath(); 16110 /** @see PackageSettingBase#resourcePathString */ 16111 abstract String getResourcePath(); 16112 16113 // Need installer lock especially for dex file removal. 16114 abstract void cleanUpResourcesLI(); 16115 abstract boolean doPostDeleteLI(boolean delete); 16116 16117 /** 16118 * Called before the source arguments are copied. This is used mostly 16119 * for MoveParams when it needs to read the source file to put it in the 16120 * destination. 16121 */ 16122 int doPreCopy() { 16123 return PackageManager.INSTALL_SUCCEEDED; 16124 } 16125 16126 /** 16127 * Called after the source arguments are copied. This is used mostly for 16128 * MoveParams when it needs to read the source file to put it in the 16129 * destination. 16130 */ 16131 int doPostCopy(int uid) { 16132 return PackageManager.INSTALL_SUCCEEDED; 16133 } 16134 16135 protected boolean isFwdLocked() { 16136 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 16137 } 16138 16139 protected boolean isExternalAsec() { 16140 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 16141 } 16142 16143 protected boolean isEphemeral() { 16144 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 16145 } 16146 16147 UserHandle getUser() { 16148 return user; 16149 } 16150 } 16151 16152 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 16153 if (!allCodePaths.isEmpty()) { 16154 if (instructionSets == null) { 16155 throw new IllegalStateException("instructionSet == null"); 16156 } 16157 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 16158 for (String codePath : allCodePaths) { 16159 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 16160 try { 16161 mInstaller.rmdex(codePath, dexCodeInstructionSet); 16162 } catch (InstallerException ignored) { 16163 } 16164 } 16165 } 16166 } 16167 } 16168 16169 /** 16170 * Logic to handle installation of non-ASEC applications, including copying 16171 * and renaming logic. 16172 */ 16173 class FileInstallArgs extends InstallArgs { 16174 private File codeFile; 16175 private File resourceFile; 16176 16177 // Example topology: 16178 // /data/app/com.example/base.apk 16179 // /data/app/com.example/split_foo.apk 16180 // /data/app/com.example/lib/arm/libfoo.so 16181 // /data/app/com.example/lib/arm64/libfoo.so 16182 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 16183 16184 /** New install */ 16185 FileInstallArgs(InstallParams params) { 16186 super(params.origin, params.move, params.observer, params.installFlags, 16187 params.installerPackageName, params.volumeUuid, 16188 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 16189 params.grantedRuntimePermissions, 16190 params.traceMethod, params.traceCookie, params.certificates, 16191 params.installReason); 16192 if (isFwdLocked()) { 16193 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 16194 } 16195 } 16196 16197 /** Existing install */ 16198 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 16199 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 16200 null, null, null, 0, null /*certificates*/, 16201 PackageManager.INSTALL_REASON_UNKNOWN); 16202 this.codeFile = (codePath != null) ? new File(codePath) : null; 16203 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 16204 } 16205 16206 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 16207 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 16208 try { 16209 return doCopyApk(imcs, temp); 16210 } finally { 16211 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16212 } 16213 } 16214 16215 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 16216 if (origin.staged) { 16217 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 16218 codeFile = origin.file; 16219 resourceFile = origin.file; 16220 return PackageManager.INSTALL_SUCCEEDED; 16221 } 16222 16223 try { 16224 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 16225 final File tempDir = 16226 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 16227 codeFile = tempDir; 16228 resourceFile = tempDir; 16229 } catch (IOException e) { 16230 Slog.w(TAG, "Failed to create copy file: " + e); 16231 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 16232 } 16233 16234 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 16235 @Override 16236 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 16237 if (!FileUtils.isValidExtFilename(name)) { 16238 throw new IllegalArgumentException("Invalid filename: " + name); 16239 } 16240 try { 16241 final File file = new File(codeFile, name); 16242 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 16243 O_RDWR | O_CREAT, 0644); 16244 Os.chmod(file.getAbsolutePath(), 0644); 16245 return new ParcelFileDescriptor(fd); 16246 } catch (ErrnoException e) { 16247 throw new RemoteException("Failed to open: " + e.getMessage()); 16248 } 16249 } 16250 }; 16251 16252 int ret = PackageManager.INSTALL_SUCCEEDED; 16253 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 16254 if (ret != PackageManager.INSTALL_SUCCEEDED) { 16255 Slog.e(TAG, "Failed to copy package"); 16256 return ret; 16257 } 16258 16259 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 16260 NativeLibraryHelper.Handle handle = null; 16261 try { 16262 handle = NativeLibraryHelper.Handle.create(codeFile); 16263 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 16264 abiOverride); 16265 } catch (IOException e) { 16266 Slog.e(TAG, "Copying native libraries failed", e); 16267 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 16268 } finally { 16269 IoUtils.closeQuietly(handle); 16270 } 16271 16272 return ret; 16273 } 16274 16275 int doPreInstall(int status) { 16276 if (status != PackageManager.INSTALL_SUCCEEDED) { 16277 cleanUp(); 16278 } 16279 return status; 16280 } 16281 16282 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 16283 if (status != PackageManager.INSTALL_SUCCEEDED) { 16284 cleanUp(); 16285 return false; 16286 } 16287 16288 final File targetDir = codeFile.getParentFile(); 16289 final File beforeCodeFile = codeFile; 16290 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 16291 16292 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 16293 try { 16294 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 16295 } catch (ErrnoException e) { 16296 Slog.w(TAG, "Failed to rename", e); 16297 return false; 16298 } 16299 16300 if (!SELinux.restoreconRecursive(afterCodeFile)) { 16301 Slog.w(TAG, "Failed to restorecon"); 16302 return false; 16303 } 16304 16305 // Reflect the rename internally 16306 codeFile = afterCodeFile; 16307 resourceFile = afterCodeFile; 16308 16309 // Reflect the rename in scanned details 16310 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 16311 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 16312 afterCodeFile, pkg.baseCodePath)); 16313 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 16314 afterCodeFile, pkg.splitCodePaths)); 16315 16316 // Reflect the rename in app info 16317 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 16318 pkg.setApplicationInfoCodePath(pkg.codePath); 16319 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 16320 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 16321 pkg.setApplicationInfoResourcePath(pkg.codePath); 16322 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 16323 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 16324 16325 return true; 16326 } 16327 16328 int doPostInstall(int status, int uid) { 16329 if (status != PackageManager.INSTALL_SUCCEEDED) { 16330 cleanUp(); 16331 } 16332 return status; 16333 } 16334 16335 @Override 16336 String getCodePath() { 16337 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 16338 } 16339 16340 @Override 16341 String getResourcePath() { 16342 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 16343 } 16344 16345 private boolean cleanUp() { 16346 if (codeFile == null || !codeFile.exists()) { 16347 return false; 16348 } 16349 16350 removeCodePathLI(codeFile); 16351 16352 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 16353 resourceFile.delete(); 16354 } 16355 16356 return true; 16357 } 16358 16359 void cleanUpResourcesLI() { 16360 // Try enumerating all code paths before deleting 16361 List<String> allCodePaths = Collections.EMPTY_LIST; 16362 if (codeFile != null && codeFile.exists()) { 16363 try { 16364 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 16365 allCodePaths = pkg.getAllCodePaths(); 16366 } catch (PackageParserException e) { 16367 // Ignored; we tried our best 16368 } 16369 } 16370 16371 cleanUp(); 16372 removeDexFiles(allCodePaths, instructionSets); 16373 } 16374 16375 boolean doPostDeleteLI(boolean delete) { 16376 // XXX err, shouldn't we respect the delete flag? 16377 cleanUpResourcesLI(); 16378 return true; 16379 } 16380 } 16381 16382 private boolean isAsecExternal(String cid) { 16383 final String asecPath = PackageHelper.getSdFilesystem(cid); 16384 return !asecPath.startsWith(mAsecInternalPath); 16385 } 16386 16387 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 16388 PackageManagerException { 16389 if (copyRet < 0) { 16390 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 16391 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 16392 throw new PackageManagerException(copyRet, message); 16393 } 16394 } 16395 } 16396 16397 /** 16398 * Extract the StorageManagerService "container ID" from the full code path of an 16399 * .apk. 16400 */ 16401 static String cidFromCodePath(String fullCodePath) { 16402 int eidx = fullCodePath.lastIndexOf("/"); 16403 String subStr1 = fullCodePath.substring(0, eidx); 16404 int sidx = subStr1.lastIndexOf("/"); 16405 return subStr1.substring(sidx+1, eidx); 16406 } 16407 16408 /** 16409 * Logic to handle installation of ASEC applications, including copying and 16410 * renaming logic. 16411 */ 16412 class AsecInstallArgs extends InstallArgs { 16413 static final String RES_FILE_NAME = "pkg.apk"; 16414 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 16415 16416 String cid; 16417 String packagePath; 16418 String resourcePath; 16419 16420 /** New install */ 16421 AsecInstallArgs(InstallParams params) { 16422 super(params.origin, params.move, params.observer, params.installFlags, 16423 params.installerPackageName, params.volumeUuid, 16424 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 16425 params.grantedRuntimePermissions, 16426 params.traceMethod, params.traceCookie, params.certificates, 16427 params.installReason); 16428 } 16429 16430 /** Existing install */ 16431 AsecInstallArgs(String fullCodePath, String[] instructionSets, 16432 boolean isExternal, boolean isForwardLocked) { 16433 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 16434 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 16435 instructionSets, null, null, null, 0, null /*certificates*/, 16436 PackageManager.INSTALL_REASON_UNKNOWN); 16437 // Hackily pretend we're still looking at a full code path 16438 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 16439 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 16440 } 16441 16442 // Extract cid from fullCodePath 16443 int eidx = fullCodePath.lastIndexOf("/"); 16444 String subStr1 = fullCodePath.substring(0, eidx); 16445 int sidx = subStr1.lastIndexOf("/"); 16446 cid = subStr1.substring(sidx+1, eidx); 16447 setMountPath(subStr1); 16448 } 16449 16450 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 16451 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 16452 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 16453 instructionSets, null, null, null, 0, null /*certificates*/, 16454 PackageManager.INSTALL_REASON_UNKNOWN); 16455 this.cid = cid; 16456 setMountPath(PackageHelper.getSdDir(cid)); 16457 } 16458 16459 void createCopyFile() { 16460 cid = mInstallerService.allocateExternalStageCidLegacy(); 16461 } 16462 16463 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 16464 if (origin.staged && origin.cid != null) { 16465 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 16466 cid = origin.cid; 16467 setMountPath(PackageHelper.getSdDir(cid)); 16468 return PackageManager.INSTALL_SUCCEEDED; 16469 } 16470 16471 if (temp) { 16472 createCopyFile(); 16473 } else { 16474 /* 16475 * Pre-emptively destroy the container since it's destroyed if 16476 * copying fails due to it existing anyway. 16477 */ 16478 PackageHelper.destroySdDir(cid); 16479 } 16480 16481 final String newMountPath = imcs.copyPackageToContainer( 16482 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 16483 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 16484 16485 if (newMountPath != null) { 16486 setMountPath(newMountPath); 16487 return PackageManager.INSTALL_SUCCEEDED; 16488 } else { 16489 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16490 } 16491 } 16492 16493 @Override 16494 String getCodePath() { 16495 return packagePath; 16496 } 16497 16498 @Override 16499 String getResourcePath() { 16500 return resourcePath; 16501 } 16502 16503 int doPreInstall(int status) { 16504 if (status != PackageManager.INSTALL_SUCCEEDED) { 16505 // Destroy container 16506 PackageHelper.destroySdDir(cid); 16507 } else { 16508 boolean mounted = PackageHelper.isContainerMounted(cid); 16509 if (!mounted) { 16510 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 16511 Process.SYSTEM_UID); 16512 if (newMountPath != null) { 16513 setMountPath(newMountPath); 16514 } else { 16515 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16516 } 16517 } 16518 } 16519 return status; 16520 } 16521 16522 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 16523 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 16524 String newMountPath = null; 16525 if (PackageHelper.isContainerMounted(cid)) { 16526 // Unmount the container 16527 if (!PackageHelper.unMountSdDir(cid)) { 16528 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 16529 return false; 16530 } 16531 } 16532 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 16533 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 16534 " which might be stale. Will try to clean up."); 16535 // Clean up the stale container and proceed to recreate. 16536 if (!PackageHelper.destroySdDir(newCacheId)) { 16537 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 16538 return false; 16539 } 16540 // Successfully cleaned up stale container. Try to rename again. 16541 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 16542 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 16543 + " inspite of cleaning it up."); 16544 return false; 16545 } 16546 } 16547 if (!PackageHelper.isContainerMounted(newCacheId)) { 16548 Slog.w(TAG, "Mounting container " + newCacheId); 16549 newMountPath = PackageHelper.mountSdDir(newCacheId, 16550 getEncryptKey(), Process.SYSTEM_UID); 16551 } else { 16552 newMountPath = PackageHelper.getSdDir(newCacheId); 16553 } 16554 if (newMountPath == null) { 16555 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 16556 return false; 16557 } 16558 Log.i(TAG, "Succesfully renamed " + cid + 16559 " to " + newCacheId + 16560 " at new path: " + newMountPath); 16561 cid = newCacheId; 16562 16563 final File beforeCodeFile = new File(packagePath); 16564 setMountPath(newMountPath); 16565 final File afterCodeFile = new File(packagePath); 16566 16567 // Reflect the rename in scanned details 16568 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 16569 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 16570 afterCodeFile, pkg.baseCodePath)); 16571 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 16572 afterCodeFile, pkg.splitCodePaths)); 16573 16574 // Reflect the rename in app info 16575 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 16576 pkg.setApplicationInfoCodePath(pkg.codePath); 16577 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 16578 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 16579 pkg.setApplicationInfoResourcePath(pkg.codePath); 16580 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 16581 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 16582 16583 return true; 16584 } 16585 16586 private void setMountPath(String mountPath) { 16587 final File mountFile = new File(mountPath); 16588 16589 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 16590 if (monolithicFile.exists()) { 16591 packagePath = monolithicFile.getAbsolutePath(); 16592 if (isFwdLocked()) { 16593 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 16594 } else { 16595 resourcePath = packagePath; 16596 } 16597 } else { 16598 packagePath = mountFile.getAbsolutePath(); 16599 resourcePath = packagePath; 16600 } 16601 } 16602 16603 int doPostInstall(int status, int uid) { 16604 if (status != PackageManager.INSTALL_SUCCEEDED) { 16605 cleanUp(); 16606 } else { 16607 final int groupOwner; 16608 final String protectedFile; 16609 if (isFwdLocked()) { 16610 groupOwner = UserHandle.getSharedAppGid(uid); 16611 protectedFile = RES_FILE_NAME; 16612 } else { 16613 groupOwner = -1; 16614 protectedFile = null; 16615 } 16616 16617 if (uid < Process.FIRST_APPLICATION_UID 16618 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 16619 Slog.e(TAG, "Failed to finalize " + cid); 16620 PackageHelper.destroySdDir(cid); 16621 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16622 } 16623 16624 boolean mounted = PackageHelper.isContainerMounted(cid); 16625 if (!mounted) { 16626 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 16627 } 16628 } 16629 return status; 16630 } 16631 16632 private void cleanUp() { 16633 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 16634 16635 // Destroy secure container 16636 PackageHelper.destroySdDir(cid); 16637 } 16638 16639 private List<String> getAllCodePaths() { 16640 final File codeFile = new File(getCodePath()); 16641 if (codeFile != null && codeFile.exists()) { 16642 try { 16643 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 16644 return pkg.getAllCodePaths(); 16645 } catch (PackageParserException e) { 16646 // Ignored; we tried our best 16647 } 16648 } 16649 return Collections.EMPTY_LIST; 16650 } 16651 16652 void cleanUpResourcesLI() { 16653 // Enumerate all code paths before deleting 16654 cleanUpResourcesLI(getAllCodePaths()); 16655 } 16656 16657 private void cleanUpResourcesLI(List<String> allCodePaths) { 16658 cleanUp(); 16659 removeDexFiles(allCodePaths, instructionSets); 16660 } 16661 16662 String getPackageName() { 16663 return getAsecPackageName(cid); 16664 } 16665 16666 boolean doPostDeleteLI(boolean delete) { 16667 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 16668 final List<String> allCodePaths = getAllCodePaths(); 16669 boolean mounted = PackageHelper.isContainerMounted(cid); 16670 if (mounted) { 16671 // Unmount first 16672 if (PackageHelper.unMountSdDir(cid)) { 16673 mounted = false; 16674 } 16675 } 16676 if (!mounted && delete) { 16677 cleanUpResourcesLI(allCodePaths); 16678 } 16679 return !mounted; 16680 } 16681 16682 @Override 16683 int doPreCopy() { 16684 if (isFwdLocked()) { 16685 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 16686 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 16687 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16688 } 16689 } 16690 16691 return PackageManager.INSTALL_SUCCEEDED; 16692 } 16693 16694 @Override 16695 int doPostCopy(int uid) { 16696 if (isFwdLocked()) { 16697 if (uid < Process.FIRST_APPLICATION_UID 16698 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 16699 RES_FILE_NAME)) { 16700 Slog.e(TAG, "Failed to finalize " + cid); 16701 PackageHelper.destroySdDir(cid); 16702 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16703 } 16704 } 16705 16706 return PackageManager.INSTALL_SUCCEEDED; 16707 } 16708 } 16709 16710 /** 16711 * Logic to handle movement of existing installed applications. 16712 */ 16713 class MoveInstallArgs extends InstallArgs { 16714 private File codeFile; 16715 private File resourceFile; 16716 16717 /** New install */ 16718 MoveInstallArgs(InstallParams params) { 16719 super(params.origin, params.move, params.observer, params.installFlags, 16720 params.installerPackageName, params.volumeUuid, 16721 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 16722 params.grantedRuntimePermissions, 16723 params.traceMethod, params.traceCookie, params.certificates, 16724 params.installReason); 16725 } 16726 16727 int copyApk(IMediaContainerService imcs, boolean temp) { 16728 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 16729 + move.fromUuid + " to " + move.toUuid); 16730 synchronized (mInstaller) { 16731 try { 16732 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 16733 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 16734 } catch (InstallerException e) { 16735 Slog.w(TAG, "Failed to move app", e); 16736 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 16737 } 16738 } 16739 16740 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 16741 resourceFile = codeFile; 16742 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 16743 16744 return PackageManager.INSTALL_SUCCEEDED; 16745 } 16746 16747 int doPreInstall(int status) { 16748 if (status != PackageManager.INSTALL_SUCCEEDED) { 16749 cleanUp(move.toUuid); 16750 } 16751 return status; 16752 } 16753 16754 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 16755 if (status != PackageManager.INSTALL_SUCCEEDED) { 16756 cleanUp(move.toUuid); 16757 return false; 16758 } 16759 16760 // Reflect the move in app info 16761 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 16762 pkg.setApplicationInfoCodePath(pkg.codePath); 16763 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 16764 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 16765 pkg.setApplicationInfoResourcePath(pkg.codePath); 16766 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 16767 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 16768 16769 return true; 16770 } 16771 16772 int doPostInstall(int status, int uid) { 16773 if (status == PackageManager.INSTALL_SUCCEEDED) { 16774 cleanUp(move.fromUuid); 16775 } else { 16776 cleanUp(move.toUuid); 16777 } 16778 return status; 16779 } 16780 16781 @Override 16782 String getCodePath() { 16783 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 16784 } 16785 16786 @Override 16787 String getResourcePath() { 16788 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 16789 } 16790 16791 private boolean cleanUp(String volumeUuid) { 16792 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 16793 move.dataAppName); 16794 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 16795 final int[] userIds = sUserManager.getUserIds(); 16796 synchronized (mInstallLock) { 16797 // Clean up both app data and code 16798 // All package moves are frozen until finished 16799 for (int userId : userIds) { 16800 try { 16801 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 16802 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 16803 } catch (InstallerException e) { 16804 Slog.w(TAG, String.valueOf(e)); 16805 } 16806 } 16807 removeCodePathLI(codeFile); 16808 } 16809 return true; 16810 } 16811 16812 void cleanUpResourcesLI() { 16813 throw new UnsupportedOperationException(); 16814 } 16815 16816 boolean doPostDeleteLI(boolean delete) { 16817 throw new UnsupportedOperationException(); 16818 } 16819 } 16820 16821 static String getAsecPackageName(String packageCid) { 16822 int idx = packageCid.lastIndexOf("-"); 16823 if (idx == -1) { 16824 return packageCid; 16825 } 16826 return packageCid.substring(0, idx); 16827 } 16828 16829 // Utility method used to create code paths based on package name and available index. 16830 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 16831 String idxStr = ""; 16832 int idx = 1; 16833 // Fall back to default value of idx=1 if prefix is not 16834 // part of oldCodePath 16835 if (oldCodePath != null) { 16836 String subStr = oldCodePath; 16837 // Drop the suffix right away 16838 if (suffix != null && subStr.endsWith(suffix)) { 16839 subStr = subStr.substring(0, subStr.length() - suffix.length()); 16840 } 16841 // If oldCodePath already contains prefix find out the 16842 // ending index to either increment or decrement. 16843 int sidx = subStr.lastIndexOf(prefix); 16844 if (sidx != -1) { 16845 subStr = subStr.substring(sidx + prefix.length()); 16846 if (subStr != null) { 16847 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 16848 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 16849 } 16850 try { 16851 idx = Integer.parseInt(subStr); 16852 if (idx <= 1) { 16853 idx++; 16854 } else { 16855 idx--; 16856 } 16857 } catch(NumberFormatException e) { 16858 } 16859 } 16860 } 16861 } 16862 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 16863 return prefix + idxStr; 16864 } 16865 16866 private File getNextCodePath(File targetDir, String packageName) { 16867 File result; 16868 SecureRandom random = new SecureRandom(); 16869 byte[] bytes = new byte[16]; 16870 do { 16871 random.nextBytes(bytes); 16872 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 16873 result = new File(targetDir, packageName + "-" + suffix); 16874 } while (result.exists()); 16875 return result; 16876 } 16877 16878 // Utility method that returns the relative package path with respect 16879 // to the installation directory. Like say for /data/data/com.test-1.apk 16880 // string com.test-1 is returned. 16881 static String deriveCodePathName(String codePath) { 16882 if (codePath == null) { 16883 return null; 16884 } 16885 final File codeFile = new File(codePath); 16886 final String name = codeFile.getName(); 16887 if (codeFile.isDirectory()) { 16888 return name; 16889 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 16890 final int lastDot = name.lastIndexOf('.'); 16891 return name.substring(0, lastDot); 16892 } else { 16893 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 16894 return null; 16895 } 16896 } 16897 16898 static class PackageInstalledInfo { 16899 String name; 16900 int uid; 16901 // The set of users that originally had this package installed. 16902 int[] origUsers; 16903 // The set of users that now have this package installed. 16904 int[] newUsers; 16905 PackageParser.Package pkg; 16906 int returnCode; 16907 String returnMsg; 16908 PackageRemovedInfo removedInfo; 16909 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 16910 16911 public void setError(int code, String msg) { 16912 setReturnCode(code); 16913 setReturnMessage(msg); 16914 Slog.w(TAG, msg); 16915 } 16916 16917 public void setError(String msg, PackageParserException e) { 16918 setReturnCode(e.error); 16919 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16920 Slog.w(TAG, msg, e); 16921 } 16922 16923 public void setError(String msg, PackageManagerException e) { 16924 returnCode = e.error; 16925 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16926 Slog.w(TAG, msg, e); 16927 } 16928 16929 public void setReturnCode(int returnCode) { 16930 this.returnCode = returnCode; 16931 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16932 for (int i = 0; i < childCount; i++) { 16933 addedChildPackages.valueAt(i).returnCode = returnCode; 16934 } 16935 } 16936 16937 private void setReturnMessage(String returnMsg) { 16938 this.returnMsg = returnMsg; 16939 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16940 for (int i = 0; i < childCount; i++) { 16941 addedChildPackages.valueAt(i).returnMsg = returnMsg; 16942 } 16943 } 16944 16945 // In some error cases we want to convey more info back to the observer 16946 String origPackage; 16947 String origPermission; 16948 } 16949 16950 /* 16951 * Install a non-existing package. 16952 */ 16953 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 16954 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 16955 PackageInstalledInfo res, int installReason) { 16956 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 16957 16958 // Remember this for later, in case we need to rollback this install 16959 String pkgName = pkg.packageName; 16960 16961 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 16962 16963 synchronized(mPackages) { 16964 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 16965 if (renamedPackage != null) { 16966 // A package with the same name is already installed, though 16967 // it has been renamed to an older name. The package we 16968 // are trying to install should be installed as an update to 16969 // the existing one, but that has not been requested, so bail. 16970 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16971 + " without first uninstalling package running as " 16972 + renamedPackage); 16973 return; 16974 } 16975 if (mPackages.containsKey(pkgName)) { 16976 // Don't allow installation over an existing package with the same name. 16977 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16978 + " without first uninstalling."); 16979 return; 16980 } 16981 } 16982 16983 try { 16984 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 16985 System.currentTimeMillis(), user); 16986 16987 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 16988 16989 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16990 prepareAppDataAfterInstallLIF(newPackage); 16991 16992 } else { 16993 // Remove package from internal structures, but keep around any 16994 // data that might have already existed 16995 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 16996 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 16997 } 16998 } catch (PackageManagerException e) { 16999 res.setError("Package couldn't be installed in " + pkg.codePath, e); 17000 } 17001 17002 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17003 } 17004 17005 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 17006 // Can't rotate keys during boot or if sharedUser. 17007 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 17008 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 17009 return false; 17010 } 17011 // app is using upgradeKeySets; make sure all are valid 17012 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17013 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 17014 for (int i = 0; i < upgradeKeySets.length; i++) { 17015 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 17016 Slog.wtf(TAG, "Package " 17017 + (oldPs.name != null ? oldPs.name : "<null>") 17018 + " contains upgrade-key-set reference to unknown key-set: " 17019 + upgradeKeySets[i] 17020 + " reverting to signatures check."); 17021 return false; 17022 } 17023 } 17024 return true; 17025 } 17026 17027 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 17028 // Upgrade keysets are being used. Determine if new package has a superset of the 17029 // required keys. 17030 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 17031 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17032 for (int i = 0; i < upgradeKeySets.length; i++) { 17033 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 17034 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 17035 return true; 17036 } 17037 } 17038 return false; 17039 } 17040 17041 private static void updateDigest(MessageDigest digest, File file) throws IOException { 17042 try (DigestInputStream digestStream = 17043 new DigestInputStream(new FileInputStream(file), digest)) { 17044 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 17045 } 17046 } 17047 17048 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 17049 UserHandle user, String installerPackageName, PackageInstalledInfo res, 17050 int installReason) { 17051 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 17052 17053 final PackageParser.Package oldPackage; 17054 final PackageSetting ps; 17055 final String pkgName = pkg.packageName; 17056 final int[] allUsers; 17057 final int[] installedUsers; 17058 17059 synchronized(mPackages) { 17060 oldPackage = mPackages.get(pkgName); 17061 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 17062 17063 // don't allow upgrade to target a release SDK from a pre-release SDK 17064 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 17065 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 17066 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 17067 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 17068 if (oldTargetsPreRelease 17069 && !newTargetsPreRelease 17070 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 17071 Slog.w(TAG, "Can't install package targeting released sdk"); 17072 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 17073 return; 17074 } 17075 17076 ps = mSettings.mPackages.get(pkgName); 17077 17078 // verify signatures are valid 17079 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 17080 if (!checkUpgradeKeySetLP(ps, pkg)) { 17081 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 17082 "New package not signed by keys specified by upgrade-keysets: " 17083 + pkgName); 17084 return; 17085 } 17086 } else { 17087 // default to original signature matching 17088 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 17089 != PackageManager.SIGNATURE_MATCH) { 17090 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 17091 "New package has a different signature: " + pkgName); 17092 return; 17093 } 17094 } 17095 17096 // don't allow a system upgrade unless the upgrade hash matches 17097 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 17098 byte[] digestBytes = null; 17099 try { 17100 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 17101 updateDigest(digest, new File(pkg.baseCodePath)); 17102 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 17103 for (String path : pkg.splitCodePaths) { 17104 updateDigest(digest, new File(path)); 17105 } 17106 } 17107 digestBytes = digest.digest(); 17108 } catch (NoSuchAlgorithmException | IOException e) { 17109 res.setError(INSTALL_FAILED_INVALID_APK, 17110 "Could not compute hash: " + pkgName); 17111 return; 17112 } 17113 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 17114 res.setError(INSTALL_FAILED_INVALID_APK, 17115 "New package fails restrict-update check: " + pkgName); 17116 return; 17117 } 17118 // retain upgrade restriction 17119 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 17120 } 17121 17122 // Check for shared user id changes 17123 String invalidPackageName = 17124 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 17125 if (invalidPackageName != null) { 17126 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 17127 "Package " + invalidPackageName + " tried to change user " 17128 + oldPackage.mSharedUserId); 17129 return; 17130 } 17131 17132 // In case of rollback, remember per-user/profile install state 17133 allUsers = sUserManager.getUserIds(); 17134 installedUsers = ps.queryInstalledUsers(allUsers, true); 17135 17136 // don't allow an upgrade from full to ephemeral 17137 if (isInstantApp) { 17138 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 17139 for (int currentUser : allUsers) { 17140 if (!ps.getInstantApp(currentUser)) { 17141 // can't downgrade from full to instant 17142 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 17143 + " for user: " + currentUser); 17144 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17145 return; 17146 } 17147 } 17148 } else if (!ps.getInstantApp(user.getIdentifier())) { 17149 // can't downgrade from full to instant 17150 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 17151 + " for user: " + user.getIdentifier()); 17152 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17153 return; 17154 } 17155 } 17156 } 17157 17158 // Update what is removed 17159 res.removedInfo = new PackageRemovedInfo(this); 17160 res.removedInfo.uid = oldPackage.applicationInfo.uid; 17161 res.removedInfo.removedPackage = oldPackage.packageName; 17162 res.removedInfo.installerPackageName = ps.installerPackageName; 17163 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 17164 res.removedInfo.isUpdate = true; 17165 res.removedInfo.origUsers = installedUsers; 17166 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 17167 for (int i = 0; i < installedUsers.length; i++) { 17168 final int userId = installedUsers[i]; 17169 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 17170 } 17171 17172 final int childCount = (oldPackage.childPackages != null) 17173 ? oldPackage.childPackages.size() : 0; 17174 for (int i = 0; i < childCount; i++) { 17175 boolean childPackageUpdated = false; 17176 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 17177 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17178 if (res.addedChildPackages != null) { 17179 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17180 if (childRes != null) { 17181 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 17182 childRes.removedInfo.removedPackage = childPkg.packageName; 17183 if (childPs != null) { 17184 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 17185 } 17186 childRes.removedInfo.isUpdate = true; 17187 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 17188 childPackageUpdated = true; 17189 } 17190 } 17191 if (!childPackageUpdated) { 17192 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 17193 childRemovedRes.removedPackage = childPkg.packageName; 17194 if (childPs != null) { 17195 childRemovedRes.installerPackageName = childPs.installerPackageName; 17196 } 17197 childRemovedRes.isUpdate = false; 17198 childRemovedRes.dataRemoved = true; 17199 synchronized (mPackages) { 17200 if (childPs != null) { 17201 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 17202 } 17203 } 17204 if (res.removedInfo.removedChildPackages == null) { 17205 res.removedInfo.removedChildPackages = new ArrayMap<>(); 17206 } 17207 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 17208 } 17209 } 17210 17211 boolean sysPkg = (isSystemApp(oldPackage)); 17212 if (sysPkg) { 17213 // Set the system/privileged flags as needed 17214 final boolean privileged = 17215 (oldPackage.applicationInfo.privateFlags 17216 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17217 final int systemPolicyFlags = policyFlags 17218 | PackageParser.PARSE_IS_SYSTEM 17219 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 17220 17221 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 17222 user, allUsers, installerPackageName, res, installReason); 17223 } else { 17224 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 17225 user, allUsers, installerPackageName, res, installReason); 17226 } 17227 } 17228 17229 @Override 17230 public List<String> getPreviousCodePaths(String packageName) { 17231 final int callingUid = Binder.getCallingUid(); 17232 final List<String> result = new ArrayList<>(); 17233 if (getInstantAppPackageName(callingUid) != null) { 17234 return result; 17235 } 17236 final PackageSetting ps = mSettings.mPackages.get(packageName); 17237 if (ps != null 17238 && ps.oldCodePaths != null 17239 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 17240 result.addAll(ps.oldCodePaths); 17241 } 17242 return result; 17243 } 17244 17245 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 17246 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 17247 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 17248 int installReason) { 17249 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 17250 + deletedPackage); 17251 17252 String pkgName = deletedPackage.packageName; 17253 boolean deletedPkg = true; 17254 boolean addedPkg = false; 17255 boolean updatedSettings = false; 17256 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 17257 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 17258 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 17259 17260 final long origUpdateTime = (pkg.mExtras != null) 17261 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 17262 17263 // First delete the existing package while retaining the data directory 17264 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 17265 res.removedInfo, true, pkg)) { 17266 // If the existing package wasn't successfully deleted 17267 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 17268 deletedPkg = false; 17269 } else { 17270 // Successfully deleted the old package; proceed with replace. 17271 17272 // If deleted package lived in a container, give users a chance to 17273 // relinquish resources before killing. 17274 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 17275 if (DEBUG_INSTALL) { 17276 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 17277 } 17278 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 17279 final ArrayList<String> pkgList = new ArrayList<String>(1); 17280 pkgList.add(deletedPackage.applicationInfo.packageName); 17281 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 17282 } 17283 17284 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 17285 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17286 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 17287 17288 try { 17289 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 17290 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 17291 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 17292 installReason); 17293 17294 // Update the in-memory copy of the previous code paths. 17295 PackageSetting ps = mSettings.mPackages.get(pkgName); 17296 if (!killApp) { 17297 if (ps.oldCodePaths == null) { 17298 ps.oldCodePaths = new ArraySet<>(); 17299 } 17300 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 17301 if (deletedPackage.splitCodePaths != null) { 17302 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 17303 } 17304 } else { 17305 ps.oldCodePaths = null; 17306 } 17307 if (ps.childPackageNames != null) { 17308 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 17309 final String childPkgName = ps.childPackageNames.get(i); 17310 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 17311 childPs.oldCodePaths = ps.oldCodePaths; 17312 } 17313 } 17314 // set instant app status, but, only if it's explicitly specified 17315 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 17316 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 17317 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 17318 prepareAppDataAfterInstallLIF(newPackage); 17319 addedPkg = true; 17320 mDexManager.notifyPackageUpdated(newPackage.packageName, 17321 newPackage.baseCodePath, newPackage.splitCodePaths); 17322 } catch (PackageManagerException e) { 17323 res.setError("Package couldn't be installed in " + pkg.codePath, e); 17324 } 17325 } 17326 17327 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 17328 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 17329 17330 // Revert all internal state mutations and added folders for the failed install 17331 if (addedPkg) { 17332 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 17333 res.removedInfo, true, null); 17334 } 17335 17336 // Restore the old package 17337 if (deletedPkg) { 17338 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 17339 File restoreFile = new File(deletedPackage.codePath); 17340 // Parse old package 17341 boolean oldExternal = isExternal(deletedPackage); 17342 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 17343 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 17344 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 17345 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 17346 try { 17347 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 17348 null); 17349 } catch (PackageManagerException e) { 17350 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 17351 + e.getMessage()); 17352 return; 17353 } 17354 17355 synchronized (mPackages) { 17356 // Ensure the installer package name up to date 17357 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 17358 17359 // Update permissions for restored package 17360 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 17361 17362 mSettings.writeLPr(); 17363 } 17364 17365 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 17366 } 17367 } else { 17368 synchronized (mPackages) { 17369 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 17370 if (ps != null) { 17371 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 17372 if (res.removedInfo.removedChildPackages != null) { 17373 final int childCount = res.removedInfo.removedChildPackages.size(); 17374 // Iterate in reverse as we may modify the collection 17375 for (int i = childCount - 1; i >= 0; i--) { 17376 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 17377 if (res.addedChildPackages.containsKey(childPackageName)) { 17378 res.removedInfo.removedChildPackages.removeAt(i); 17379 } else { 17380 PackageRemovedInfo childInfo = res.removedInfo 17381 .removedChildPackages.valueAt(i); 17382 childInfo.removedForAllUsers = mPackages.get( 17383 childInfo.removedPackage) == null; 17384 } 17385 } 17386 } 17387 } 17388 } 17389 } 17390 } 17391 17392 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 17393 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 17394 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 17395 int installReason) { 17396 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 17397 + ", old=" + deletedPackage); 17398 17399 final boolean disabledSystem; 17400 17401 // Remove existing system package 17402 removePackageLI(deletedPackage, true); 17403 17404 synchronized (mPackages) { 17405 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 17406 } 17407 if (!disabledSystem) { 17408 // We didn't need to disable the .apk as a current system package, 17409 // which means we are replacing another update that is already 17410 // installed. We need to make sure to delete the older one's .apk. 17411 res.removedInfo.args = createInstallArgsForExisting(0, 17412 deletedPackage.applicationInfo.getCodePath(), 17413 deletedPackage.applicationInfo.getResourcePath(), 17414 getAppDexInstructionSets(deletedPackage.applicationInfo)); 17415 } else { 17416 res.removedInfo.args = null; 17417 } 17418 17419 // Successfully disabled the old package. Now proceed with re-installation 17420 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 17421 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17422 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 17423 17424 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17425 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 17426 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 17427 17428 PackageParser.Package newPackage = null; 17429 try { 17430 // Add the package to the internal data structures 17431 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 17432 17433 // Set the update and install times 17434 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 17435 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 17436 System.currentTimeMillis()); 17437 17438 // Update the package dynamic state if succeeded 17439 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17440 // Now that the install succeeded make sure we remove data 17441 // directories for any child package the update removed. 17442 final int deletedChildCount = (deletedPackage.childPackages != null) 17443 ? deletedPackage.childPackages.size() : 0; 17444 final int newChildCount = (newPackage.childPackages != null) 17445 ? newPackage.childPackages.size() : 0; 17446 for (int i = 0; i < deletedChildCount; i++) { 17447 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 17448 boolean childPackageDeleted = true; 17449 for (int j = 0; j < newChildCount; j++) { 17450 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 17451 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 17452 childPackageDeleted = false; 17453 break; 17454 } 17455 } 17456 if (childPackageDeleted) { 17457 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 17458 deletedChildPkg.packageName); 17459 if (ps != null && res.removedInfo.removedChildPackages != null) { 17460 PackageRemovedInfo removedChildRes = res.removedInfo 17461 .removedChildPackages.get(deletedChildPkg.packageName); 17462 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 17463 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 17464 } 17465 } 17466 } 17467 17468 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 17469 installReason); 17470 prepareAppDataAfterInstallLIF(newPackage); 17471 17472 mDexManager.notifyPackageUpdated(newPackage.packageName, 17473 newPackage.baseCodePath, newPackage.splitCodePaths); 17474 } 17475 } catch (PackageManagerException e) { 17476 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 17477 res.setError("Package couldn't be installed in " + pkg.codePath, e); 17478 } 17479 17480 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 17481 // Re installation failed. Restore old information 17482 // Remove new pkg information 17483 if (newPackage != null) { 17484 removeInstalledPackageLI(newPackage, true); 17485 } 17486 // Add back the old system package 17487 try { 17488 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 17489 } catch (PackageManagerException e) { 17490 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 17491 } 17492 17493 synchronized (mPackages) { 17494 if (disabledSystem) { 17495 enableSystemPackageLPw(deletedPackage); 17496 } 17497 17498 // Ensure the installer package name up to date 17499 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 17500 17501 // Update permissions for restored package 17502 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 17503 17504 mSettings.writeLPr(); 17505 } 17506 17507 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 17508 + " after failed upgrade"); 17509 } 17510 } 17511 17512 /** 17513 * Checks whether the parent or any of the child packages have a change shared 17514 * user. For a package to be a valid update the shred users of the parent and 17515 * the children should match. We may later support changing child shared users. 17516 * @param oldPkg The updated package. 17517 * @param newPkg The update package. 17518 * @return The shared user that change between the versions. 17519 */ 17520 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 17521 PackageParser.Package newPkg) { 17522 // Check parent shared user 17523 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 17524 return newPkg.packageName; 17525 } 17526 // Check child shared users 17527 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 17528 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 17529 for (int i = 0; i < newChildCount; i++) { 17530 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 17531 // If this child was present, did it have the same shared user? 17532 for (int j = 0; j < oldChildCount; j++) { 17533 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 17534 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 17535 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 17536 return newChildPkg.packageName; 17537 } 17538 } 17539 } 17540 return null; 17541 } 17542 17543 private void removeNativeBinariesLI(PackageSetting ps) { 17544 // Remove the lib path for the parent package 17545 if (ps != null) { 17546 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 17547 // Remove the lib path for the child packages 17548 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 17549 for (int i = 0; i < childCount; i++) { 17550 PackageSetting childPs = null; 17551 synchronized (mPackages) { 17552 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 17553 } 17554 if (childPs != null) { 17555 NativeLibraryHelper.removeNativeBinariesLI(childPs 17556 .legacyNativeLibraryPathString); 17557 } 17558 } 17559 } 17560 } 17561 17562 private void enableSystemPackageLPw(PackageParser.Package pkg) { 17563 // Enable the parent package 17564 mSettings.enableSystemPackageLPw(pkg.packageName); 17565 // Enable the child packages 17566 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17567 for (int i = 0; i < childCount; i++) { 17568 PackageParser.Package childPkg = pkg.childPackages.get(i); 17569 mSettings.enableSystemPackageLPw(childPkg.packageName); 17570 } 17571 } 17572 17573 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 17574 PackageParser.Package newPkg) { 17575 // Disable the parent package (parent always replaced) 17576 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 17577 // Disable the child packages 17578 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 17579 for (int i = 0; i < childCount; i++) { 17580 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 17581 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 17582 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 17583 } 17584 return disabled; 17585 } 17586 17587 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 17588 String installerPackageName) { 17589 // Enable the parent package 17590 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 17591 // Enable the child packages 17592 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17593 for (int i = 0; i < childCount; i++) { 17594 PackageParser.Package childPkg = pkg.childPackages.get(i); 17595 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 17596 } 17597 } 17598 17599 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 17600 // Collect all used permissions in the UID 17601 ArraySet<String> usedPermissions = new ArraySet<>(); 17602 final int packageCount = su.packages.size(); 17603 for (int i = 0; i < packageCount; i++) { 17604 PackageSetting ps = su.packages.valueAt(i); 17605 if (ps.pkg == null) { 17606 continue; 17607 } 17608 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 17609 for (int j = 0; j < requestedPermCount; j++) { 17610 String permission = ps.pkg.requestedPermissions.get(j); 17611 BasePermission bp = mSettings.mPermissions.get(permission); 17612 if (bp != null) { 17613 usedPermissions.add(permission); 17614 } 17615 } 17616 } 17617 17618 PermissionsState permissionsState = su.getPermissionsState(); 17619 // Prune install permissions 17620 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 17621 final int installPermCount = installPermStates.size(); 17622 for (int i = installPermCount - 1; i >= 0; i--) { 17623 PermissionState permissionState = installPermStates.get(i); 17624 if (!usedPermissions.contains(permissionState.getName())) { 17625 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 17626 if (bp != null) { 17627 permissionsState.revokeInstallPermission(bp); 17628 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 17629 PackageManager.MASK_PERMISSION_FLAGS, 0); 17630 } 17631 } 17632 } 17633 17634 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 17635 17636 // Prune runtime permissions 17637 for (int userId : allUserIds) { 17638 List<PermissionState> runtimePermStates = permissionsState 17639 .getRuntimePermissionStates(userId); 17640 final int runtimePermCount = runtimePermStates.size(); 17641 for (int i = runtimePermCount - 1; i >= 0; i--) { 17642 PermissionState permissionState = runtimePermStates.get(i); 17643 if (!usedPermissions.contains(permissionState.getName())) { 17644 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 17645 if (bp != null) { 17646 permissionsState.revokeRuntimePermission(bp, userId); 17647 permissionsState.updatePermissionFlags(bp, userId, 17648 PackageManager.MASK_PERMISSION_FLAGS, 0); 17649 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 17650 runtimePermissionChangedUserIds, userId); 17651 } 17652 } 17653 } 17654 } 17655 17656 return runtimePermissionChangedUserIds; 17657 } 17658 17659 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 17660 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 17661 // Update the parent package setting 17662 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 17663 res, user, installReason); 17664 // Update the child packages setting 17665 final int childCount = (newPackage.childPackages != null) 17666 ? newPackage.childPackages.size() : 0; 17667 for (int i = 0; i < childCount; i++) { 17668 PackageParser.Package childPackage = newPackage.childPackages.get(i); 17669 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 17670 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 17671 childRes.origUsers, childRes, user, installReason); 17672 } 17673 } 17674 17675 private void updateSettingsInternalLI(PackageParser.Package newPackage, 17676 String installerPackageName, int[] allUsers, int[] installedForUsers, 17677 PackageInstalledInfo res, UserHandle user, int installReason) { 17678 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 17679 17680 String pkgName = newPackage.packageName; 17681 synchronized (mPackages) { 17682 //write settings. the installStatus will be incomplete at this stage. 17683 //note that the new package setting would have already been 17684 //added to mPackages. It hasn't been persisted yet. 17685 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 17686 // TODO: Remove this write? It's also written at the end of this method 17687 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 17688 mSettings.writeLPr(); 17689 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17690 } 17691 17692 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 17693 synchronized (mPackages) { 17694 updatePermissionsLPw(newPackage.packageName, newPackage, 17695 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 17696 ? UPDATE_PERMISSIONS_ALL : 0)); 17697 // For system-bundled packages, we assume that installing an upgraded version 17698 // of the package implies that the user actually wants to run that new code, 17699 // so we enable the package. 17700 PackageSetting ps = mSettings.mPackages.get(pkgName); 17701 final int userId = user.getIdentifier(); 17702 if (ps != null) { 17703 if (isSystemApp(newPackage)) { 17704 if (DEBUG_INSTALL) { 17705 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 17706 } 17707 // Enable system package for requested users 17708 if (res.origUsers != null) { 17709 for (int origUserId : res.origUsers) { 17710 if (userId == UserHandle.USER_ALL || userId == origUserId) { 17711 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 17712 origUserId, installerPackageName); 17713 } 17714 } 17715 } 17716 // Also convey the prior install/uninstall state 17717 if (allUsers != null && installedForUsers != null) { 17718 for (int currentUserId : allUsers) { 17719 final boolean installed = ArrayUtils.contains( 17720 installedForUsers, currentUserId); 17721 if (DEBUG_INSTALL) { 17722 Slog.d(TAG, " user " + currentUserId + " => " + installed); 17723 } 17724 ps.setInstalled(installed, currentUserId); 17725 } 17726 // these install state changes will be persisted in the 17727 // upcoming call to mSettings.writeLPr(). 17728 } 17729 } 17730 // It's implied that when a user requests installation, they want the app to be 17731 // installed and enabled. 17732 if (userId != UserHandle.USER_ALL) { 17733 ps.setInstalled(true, userId); 17734 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 17735 } 17736 17737 // When replacing an existing package, preserve the original install reason for all 17738 // users that had the package installed before. 17739 final Set<Integer> previousUserIds = new ArraySet<>(); 17740 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 17741 final int installReasonCount = res.removedInfo.installReasons.size(); 17742 for (int i = 0; i < installReasonCount; i++) { 17743 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 17744 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 17745 ps.setInstallReason(previousInstallReason, previousUserId); 17746 previousUserIds.add(previousUserId); 17747 } 17748 } 17749 17750 // Set install reason for users that are having the package newly installed. 17751 if (userId == UserHandle.USER_ALL) { 17752 for (int currentUserId : sUserManager.getUserIds()) { 17753 if (!previousUserIds.contains(currentUserId)) { 17754 ps.setInstallReason(installReason, currentUserId); 17755 } 17756 } 17757 } else if (!previousUserIds.contains(userId)) { 17758 ps.setInstallReason(installReason, userId); 17759 } 17760 mSettings.writeKernelMappingLPr(ps); 17761 } 17762 res.name = pkgName; 17763 res.uid = newPackage.applicationInfo.uid; 17764 res.pkg = newPackage; 17765 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 17766 mSettings.setInstallerPackageName(pkgName, installerPackageName); 17767 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17768 //to update install status 17769 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 17770 mSettings.writeLPr(); 17771 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17772 } 17773 17774 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17775 } 17776 17777 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 17778 try { 17779 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 17780 installPackageLI(args, res); 17781 } finally { 17782 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17783 } 17784 } 17785 17786 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 17787 final int installFlags = args.installFlags; 17788 final String installerPackageName = args.installerPackageName; 17789 final String volumeUuid = args.volumeUuid; 17790 final File tmpPackageFile = new File(args.getCodePath()); 17791 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 17792 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 17793 || (args.volumeUuid != null)); 17794 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 17795 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 17796 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 17797 boolean replace = false; 17798 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 17799 if (args.move != null) { 17800 // moving a complete application; perform an initial scan on the new install location 17801 scanFlags |= SCAN_INITIAL; 17802 } 17803 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 17804 scanFlags |= SCAN_DONT_KILL_APP; 17805 } 17806 if (instantApp) { 17807 scanFlags |= SCAN_AS_INSTANT_APP; 17808 } 17809 if (fullApp) { 17810 scanFlags |= SCAN_AS_FULL_APP; 17811 } 17812 17813 // Result object to be returned 17814 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17815 17816 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 17817 17818 // Sanity check 17819 if (instantApp && (forwardLocked || onExternal)) { 17820 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 17821 + " external=" + onExternal); 17822 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17823 return; 17824 } 17825 17826 // Retrieve PackageSettings and parse package 17827 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 17828 | PackageParser.PARSE_ENFORCE_CODE 17829 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 17830 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 17831 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 17832 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 17833 PackageParser pp = new PackageParser(); 17834 pp.setSeparateProcesses(mSeparateProcesses); 17835 pp.setDisplayMetrics(mMetrics); 17836 pp.setCallback(mPackageParserCallback); 17837 17838 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 17839 final PackageParser.Package pkg; 17840 try { 17841 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 17842 } catch (PackageParserException e) { 17843 res.setError("Failed parse during installPackageLI", e); 17844 return; 17845 } finally { 17846 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17847 } 17848 17849 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 17850 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 17851 Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O"); 17852 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 17853 "Instant app package must target O"); 17854 return; 17855 } 17856 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 17857 Slog.w(TAG, "Instant app package " + pkg.packageName 17858 + " does not target targetSandboxVersion 2"); 17859 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 17860 "Instant app package must use targetSanboxVersion 2"); 17861 return; 17862 } 17863 17864 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17865 // Static shared libraries have synthetic package names 17866 renameStaticSharedLibraryPackage(pkg); 17867 17868 // No static shared libs on external storage 17869 if (onExternal) { 17870 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 17871 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17872 "Packages declaring static-shared libs cannot be updated"); 17873 return; 17874 } 17875 } 17876 17877 // If we are installing a clustered package add results for the children 17878 if (pkg.childPackages != null) { 17879 synchronized (mPackages) { 17880 final int childCount = pkg.childPackages.size(); 17881 for (int i = 0; i < childCount; i++) { 17882 PackageParser.Package childPkg = pkg.childPackages.get(i); 17883 PackageInstalledInfo childRes = new PackageInstalledInfo(); 17884 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17885 childRes.pkg = childPkg; 17886 childRes.name = childPkg.packageName; 17887 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17888 if (childPs != null) { 17889 childRes.origUsers = childPs.queryInstalledUsers( 17890 sUserManager.getUserIds(), true); 17891 } 17892 if ((mPackages.containsKey(childPkg.packageName))) { 17893 childRes.removedInfo = new PackageRemovedInfo(this); 17894 childRes.removedInfo.removedPackage = childPkg.packageName; 17895 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 17896 } 17897 if (res.addedChildPackages == null) { 17898 res.addedChildPackages = new ArrayMap<>(); 17899 } 17900 res.addedChildPackages.put(childPkg.packageName, childRes); 17901 } 17902 } 17903 } 17904 17905 // If package doesn't declare API override, mark that we have an install 17906 // time CPU ABI override. 17907 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 17908 pkg.cpuAbiOverride = args.abiOverride; 17909 } 17910 17911 String pkgName = res.name = pkg.packageName; 17912 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 17913 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 17914 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 17915 return; 17916 } 17917 } 17918 17919 try { 17920 // either use what we've been given or parse directly from the APK 17921 if (args.certificates != null) { 17922 try { 17923 PackageParser.populateCertificates(pkg, args.certificates); 17924 } catch (PackageParserException e) { 17925 // there was something wrong with the certificates we were given; 17926 // try to pull them from the APK 17927 PackageParser.collectCertificates(pkg, parseFlags); 17928 } 17929 } else { 17930 PackageParser.collectCertificates(pkg, parseFlags); 17931 } 17932 } catch (PackageParserException e) { 17933 res.setError("Failed collect during installPackageLI", e); 17934 return; 17935 } 17936 17937 // Get rid of all references to package scan path via parser. 17938 pp = null; 17939 String oldCodePath = null; 17940 boolean systemApp = false; 17941 synchronized (mPackages) { 17942 // Check if installing already existing package 17943 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 17944 String oldName = mSettings.getRenamedPackageLPr(pkgName); 17945 if (pkg.mOriginalPackages != null 17946 && pkg.mOriginalPackages.contains(oldName) 17947 && mPackages.containsKey(oldName)) { 17948 // This package is derived from an original package, 17949 // and this device has been updating from that original 17950 // name. We must continue using the original name, so 17951 // rename the new package here. 17952 pkg.setPackageName(oldName); 17953 pkgName = pkg.packageName; 17954 replace = true; 17955 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 17956 + oldName + " pkgName=" + pkgName); 17957 } else if (mPackages.containsKey(pkgName)) { 17958 // This package, under its official name, already exists 17959 // on the device; we should replace it. 17960 replace = true; 17961 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 17962 } 17963 17964 // Child packages are installed through the parent package 17965 if (pkg.parentPackage != null) { 17966 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17967 "Package " + pkg.packageName + " is child of package " 17968 + pkg.parentPackage.parentPackage + ". Child packages " 17969 + "can be updated only through the parent package."); 17970 return; 17971 } 17972 17973 if (replace) { 17974 // Prevent apps opting out from runtime permissions 17975 PackageParser.Package oldPackage = mPackages.get(pkgName); 17976 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 17977 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 17978 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 17979 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 17980 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 17981 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 17982 + " doesn't support runtime permissions but the old" 17983 + " target SDK " + oldTargetSdk + " does."); 17984 return; 17985 } 17986 // Prevent apps from downgrading their targetSandbox. 17987 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 17988 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 17989 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 17990 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 17991 "Package " + pkg.packageName + " new target sandbox " 17992 + newTargetSandbox + " is incompatible with the previous value of" 17993 + oldTargetSandbox + "."); 17994 return; 17995 } 17996 17997 // Prevent installing of child packages 17998 if (oldPackage.parentPackage != null) { 17999 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 18000 "Package " + pkg.packageName + " is child of package " 18001 + oldPackage.parentPackage + ". Child packages " 18002 + "can be updated only through the parent package."); 18003 return; 18004 } 18005 } 18006 } 18007 18008 PackageSetting ps = mSettings.mPackages.get(pkgName); 18009 if (ps != null) { 18010 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 18011 18012 // Static shared libs have same package with different versions where 18013 // we internally use a synthetic package name to allow multiple versions 18014 // of the same package, therefore we need to compare signatures against 18015 // the package setting for the latest library version. 18016 PackageSetting signatureCheckPs = ps; 18017 if (pkg.applicationInfo.isStaticSharedLibrary()) { 18018 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 18019 if (libraryEntry != null) { 18020 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 18021 } 18022 } 18023 18024 // Quick sanity check that we're signed correctly if updating; 18025 // we'll check this again later when scanning, but we want to 18026 // bail early here before tripping over redefined permissions. 18027 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 18028 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 18029 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 18030 + pkg.packageName + " upgrade keys do not match the " 18031 + "previously installed version"); 18032 return; 18033 } 18034 } else { 18035 try { 18036 verifySignaturesLP(signatureCheckPs, pkg); 18037 } catch (PackageManagerException e) { 18038 res.setError(e.error, e.getMessage()); 18039 return; 18040 } 18041 } 18042 18043 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 18044 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 18045 systemApp = (ps.pkg.applicationInfo.flags & 18046 ApplicationInfo.FLAG_SYSTEM) != 0; 18047 } 18048 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 18049 } 18050 18051 int N = pkg.permissions.size(); 18052 for (int i = N-1; i >= 0; i--) { 18053 PackageParser.Permission perm = pkg.permissions.get(i); 18054 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 18055 18056 // Don't allow anyone but the system to define ephemeral permissions. 18057 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 18058 && !systemApp) { 18059 Slog.w(TAG, "Non-System package " + pkg.packageName 18060 + " attempting to delcare ephemeral permission " 18061 + perm.info.name + "; Removing ephemeral."); 18062 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 18063 } 18064 // Check whether the newly-scanned package wants to define an already-defined perm 18065 if (bp != null) { 18066 // If the defining package is signed with our cert, it's okay. This 18067 // also includes the "updating the same package" case, of course. 18068 // "updating same package" could also involve key-rotation. 18069 final boolean sigsOk; 18070 if (bp.sourcePackage.equals(pkg.packageName) 18071 && (bp.packageSetting instanceof PackageSetting) 18072 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 18073 scanFlags))) { 18074 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 18075 } else { 18076 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 18077 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 18078 } 18079 if (!sigsOk) { 18080 // If the owning package is the system itself, we log but allow 18081 // install to proceed; we fail the install on all other permission 18082 // redefinitions. 18083 if (!bp.sourcePackage.equals("android")) { 18084 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 18085 + pkg.packageName + " attempting to redeclare permission " 18086 + perm.info.name + " already owned by " + bp.sourcePackage); 18087 res.origPermission = perm.info.name; 18088 res.origPackage = bp.sourcePackage; 18089 return; 18090 } else { 18091 Slog.w(TAG, "Package " + pkg.packageName 18092 + " attempting to redeclare system permission " 18093 + perm.info.name + "; ignoring new declaration"); 18094 pkg.permissions.remove(i); 18095 } 18096 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 18097 // Prevent apps to change protection level to dangerous from any other 18098 // type as this would allow a privilege escalation where an app adds a 18099 // normal/signature permission in other app's group and later redefines 18100 // it as dangerous leading to the group auto-grant. 18101 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 18102 == PermissionInfo.PROTECTION_DANGEROUS) { 18103 if (bp != null && !bp.isRuntime()) { 18104 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 18105 + "non-runtime permission " + perm.info.name 18106 + " to runtime; keeping old protection level"); 18107 perm.info.protectionLevel = bp.protectionLevel; 18108 } 18109 } 18110 } 18111 } 18112 } 18113 } 18114 18115 if (systemApp) { 18116 if (onExternal) { 18117 // Abort update; system app can't be replaced with app on sdcard 18118 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 18119 "Cannot install updates to system apps on sdcard"); 18120 return; 18121 } else if (instantApp) { 18122 // Abort update; system app can't be replaced with an instant app 18123 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 18124 "Cannot update a system app with an instant app"); 18125 return; 18126 } 18127 } 18128 18129 if (args.move != null) { 18130 // We did an in-place move, so dex is ready to roll 18131 scanFlags |= SCAN_NO_DEX; 18132 scanFlags |= SCAN_MOVE; 18133 18134 synchronized (mPackages) { 18135 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18136 if (ps == null) { 18137 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 18138 "Missing settings for moved package " + pkgName); 18139 } 18140 18141 // We moved the entire application as-is, so bring over the 18142 // previously derived ABI information. 18143 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 18144 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 18145 } 18146 18147 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 18148 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 18149 scanFlags |= SCAN_NO_DEX; 18150 18151 try { 18152 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 18153 args.abiOverride : pkg.cpuAbiOverride); 18154 final boolean extractNativeLibs = !pkg.isLibrary(); 18155 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 18156 extractNativeLibs, mAppLib32InstallDir); 18157 } catch (PackageManagerException pme) { 18158 Slog.e(TAG, "Error deriving application ABI", pme); 18159 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 18160 return; 18161 } 18162 18163 // Shared libraries for the package need to be updated. 18164 synchronized (mPackages) { 18165 try { 18166 updateSharedLibrariesLPr(pkg, null); 18167 } catch (PackageManagerException e) { 18168 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18169 } 18170 } 18171 18172 // dexopt can take some time to complete, so, for instant apps, we skip this 18173 // step during installation. Instead, we'll take extra time the first time the 18174 // instant app starts. It's preferred to do it this way to provide continuous 18175 // progress to the user instead of mysteriously blocking somewhere in the 18176 // middle of running an instant app. The default behaviour can be overridden 18177 // via gservices. 18178 if (!instantApp || Global.getInt( 18179 mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) { 18180 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 18181 // Do not run PackageDexOptimizer through the local performDexOpt 18182 // method because `pkg` may not be in `mPackages` yet. 18183 // 18184 // Also, don't fail application installs if the dexopt step fails. 18185 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 18186 null /* instructionSets */, false /* checkProfiles */, 18187 getCompilerFilterForReason(REASON_INSTALL), 18188 getOrCreateCompilerPackageStats(pkg), 18189 mDexManager.isUsedByOtherApps(pkg.packageName)); 18190 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 18191 } 18192 18193 // Notify BackgroundDexOptService that the package has been changed. 18194 // If this is an update of a package which used to fail to compile, 18195 // BDOS will remove it from its blacklist. 18196 // TODO: Layering violation 18197 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 18198 } 18199 18200 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 18201 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 18202 return; 18203 } 18204 18205 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 18206 18207 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 18208 "installPackageLI")) { 18209 if (replace) { 18210 if (pkg.applicationInfo.isStaticSharedLibrary()) { 18211 // Static libs have a synthetic package name containing the version 18212 // and cannot be updated as an update would get a new package name, 18213 // unless this is the exact same version code which is useful for 18214 // development. 18215 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 18216 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 18217 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 18218 + "static-shared libs cannot be updated"); 18219 return; 18220 } 18221 } 18222 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 18223 installerPackageName, res, args.installReason); 18224 } else { 18225 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 18226 args.user, installerPackageName, volumeUuid, res, args.installReason); 18227 } 18228 } 18229 18230 synchronized (mPackages) { 18231 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18232 if (ps != null) { 18233 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 18234 ps.setUpdateAvailable(false /*updateAvailable*/); 18235 } 18236 18237 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18238 for (int i = 0; i < childCount; i++) { 18239 PackageParser.Package childPkg = pkg.childPackages.get(i); 18240 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 18241 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 18242 if (childPs != null) { 18243 childRes.newUsers = childPs.queryInstalledUsers( 18244 sUserManager.getUserIds(), true); 18245 } 18246 } 18247 18248 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 18249 updateSequenceNumberLP(ps, res.newUsers); 18250 updateInstantAppInstallerLocked(pkgName); 18251 } 18252 } 18253 } 18254 18255 private void startIntentFilterVerifications(int userId, boolean replacing, 18256 PackageParser.Package pkg) { 18257 if (mIntentFilterVerifierComponent == null) { 18258 Slog.w(TAG, "No IntentFilter verification will not be done as " 18259 + "there is no IntentFilterVerifier available!"); 18260 return; 18261 } 18262 18263 final int verifierUid = getPackageUid( 18264 mIntentFilterVerifierComponent.getPackageName(), 18265 MATCH_DEBUG_TRIAGED_MISSING, 18266 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 18267 18268 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 18269 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 18270 mHandler.sendMessage(msg); 18271 18272 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18273 for (int i = 0; i < childCount; i++) { 18274 PackageParser.Package childPkg = pkg.childPackages.get(i); 18275 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 18276 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 18277 mHandler.sendMessage(msg); 18278 } 18279 } 18280 18281 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 18282 PackageParser.Package pkg) { 18283 int size = pkg.activities.size(); 18284 if (size == 0) { 18285 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 18286 "No activity, so no need to verify any IntentFilter!"); 18287 return; 18288 } 18289 18290 final boolean hasDomainURLs = hasDomainURLs(pkg); 18291 if (!hasDomainURLs) { 18292 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 18293 "No domain URLs, so no need to verify any IntentFilter!"); 18294 return; 18295 } 18296 18297 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 18298 + " if any IntentFilter from the " + size 18299 + " Activities needs verification ..."); 18300 18301 int count = 0; 18302 final String packageName = pkg.packageName; 18303 18304 synchronized (mPackages) { 18305 // If this is a new install and we see that we've already run verification for this 18306 // package, we have nothing to do: it means the state was restored from backup. 18307 if (!replacing) { 18308 IntentFilterVerificationInfo ivi = 18309 mSettings.getIntentFilterVerificationLPr(packageName); 18310 if (ivi != null) { 18311 if (DEBUG_DOMAIN_VERIFICATION) { 18312 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 18313 + ivi.getStatusString()); 18314 } 18315 return; 18316 } 18317 } 18318 18319 // If any filters need to be verified, then all need to be. 18320 boolean needToVerify = false; 18321 for (PackageParser.Activity a : pkg.activities) { 18322 for (ActivityIntentInfo filter : a.intents) { 18323 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 18324 if (DEBUG_DOMAIN_VERIFICATION) { 18325 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 18326 } 18327 needToVerify = true; 18328 break; 18329 } 18330 } 18331 } 18332 18333 if (needToVerify) { 18334 final int verificationId = mIntentFilterVerificationToken++; 18335 for (PackageParser.Activity a : pkg.activities) { 18336 for (ActivityIntentInfo filter : a.intents) { 18337 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 18338 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 18339 "Verification needed for IntentFilter:" + filter.toString()); 18340 mIntentFilterVerifier.addOneIntentFilterVerification( 18341 verifierUid, userId, verificationId, filter, packageName); 18342 count++; 18343 } 18344 } 18345 } 18346 } 18347 } 18348 18349 if (count > 0) { 18350 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 18351 + " IntentFilter verification" + (count > 1 ? "s" : "") 18352 + " for userId:" + userId); 18353 mIntentFilterVerifier.startVerifications(userId); 18354 } else { 18355 if (DEBUG_DOMAIN_VERIFICATION) { 18356 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 18357 } 18358 } 18359 } 18360 18361 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 18362 final ComponentName cn = filter.activity.getComponentName(); 18363 final String packageName = cn.getPackageName(); 18364 18365 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 18366 packageName); 18367 if (ivi == null) { 18368 return true; 18369 } 18370 int status = ivi.getStatus(); 18371 switch (status) { 18372 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 18373 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 18374 return true; 18375 18376 default: 18377 // Nothing to do 18378 return false; 18379 } 18380 } 18381 18382 private static boolean isMultiArch(ApplicationInfo info) { 18383 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 18384 } 18385 18386 private static boolean isExternal(PackageParser.Package pkg) { 18387 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 18388 } 18389 18390 private static boolean isExternal(PackageSetting ps) { 18391 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 18392 } 18393 18394 private static boolean isSystemApp(PackageParser.Package pkg) { 18395 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 18396 } 18397 18398 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 18399 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 18400 } 18401 18402 private static boolean hasDomainURLs(PackageParser.Package pkg) { 18403 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 18404 } 18405 18406 private static boolean isSystemApp(PackageSetting ps) { 18407 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 18408 } 18409 18410 private static boolean isUpdatedSystemApp(PackageSetting ps) { 18411 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 18412 } 18413 18414 private int packageFlagsToInstallFlags(PackageSetting ps) { 18415 int installFlags = 0; 18416 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 18417 // This existing package was an external ASEC install when we have 18418 // the external flag without a UUID 18419 installFlags |= PackageManager.INSTALL_EXTERNAL; 18420 } 18421 if (ps.isForwardLocked()) { 18422 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 18423 } 18424 return installFlags; 18425 } 18426 18427 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 18428 if (isExternal(pkg)) { 18429 if (TextUtils.isEmpty(pkg.volumeUuid)) { 18430 return StorageManager.UUID_PRIMARY_PHYSICAL; 18431 } else { 18432 return pkg.volumeUuid; 18433 } 18434 } else { 18435 return StorageManager.UUID_PRIVATE_INTERNAL; 18436 } 18437 } 18438 18439 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 18440 if (isExternal(pkg)) { 18441 if (TextUtils.isEmpty(pkg.volumeUuid)) { 18442 return mSettings.getExternalVersion(); 18443 } else { 18444 return mSettings.findOrCreateVersion(pkg.volumeUuid); 18445 } 18446 } else { 18447 return mSettings.getInternalVersion(); 18448 } 18449 } 18450 18451 private void deleteTempPackageFiles() { 18452 final FilenameFilter filter = new FilenameFilter() { 18453 public boolean accept(File dir, String name) { 18454 return name.startsWith("vmdl") && name.endsWith(".tmp"); 18455 } 18456 }; 18457 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 18458 file.delete(); 18459 } 18460 } 18461 18462 @Override 18463 public void deletePackageAsUser(String packageName, int versionCode, 18464 IPackageDeleteObserver observer, int userId, int flags) { 18465 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 18466 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 18467 } 18468 18469 @Override 18470 public void deletePackageVersioned(VersionedPackage versionedPackage, 18471 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 18472 final int callingUid = Binder.getCallingUid(); 18473 mContext.enforceCallingOrSelfPermission( 18474 android.Manifest.permission.DELETE_PACKAGES, null); 18475 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 18476 Preconditions.checkNotNull(versionedPackage); 18477 Preconditions.checkNotNull(observer); 18478 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 18479 PackageManager.VERSION_CODE_HIGHEST, 18480 Integer.MAX_VALUE, "versionCode must be >= -1"); 18481 18482 final String packageName = versionedPackage.getPackageName(); 18483 final int versionCode = versionedPackage.getVersionCode(); 18484 final String internalPackageName; 18485 synchronized (mPackages) { 18486 // Normalize package name to handle renamed packages and static libs 18487 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 18488 versionedPackage.getVersionCode()); 18489 } 18490 18491 final int uid = Binder.getCallingUid(); 18492 if (!isOrphaned(internalPackageName) 18493 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 18494 try { 18495 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 18496 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 18497 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 18498 observer.onUserActionRequired(intent); 18499 } catch (RemoteException re) { 18500 } 18501 return; 18502 } 18503 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 18504 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 18505 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 18506 mContext.enforceCallingOrSelfPermission( 18507 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 18508 "deletePackage for user " + userId); 18509 } 18510 18511 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 18512 try { 18513 observer.onPackageDeleted(packageName, 18514 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 18515 } catch (RemoteException re) { 18516 } 18517 return; 18518 } 18519 18520 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 18521 try { 18522 observer.onPackageDeleted(packageName, 18523 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 18524 } catch (RemoteException re) { 18525 } 18526 return; 18527 } 18528 18529 if (DEBUG_REMOVE) { 18530 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 18531 + " deleteAllUsers: " + deleteAllUsers + " version=" 18532 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 18533 ? "VERSION_CODE_HIGHEST" : versionCode)); 18534 } 18535 // Queue up an async operation since the package deletion may take a little while. 18536 mHandler.post(new Runnable() { 18537 public void run() { 18538 mHandler.removeCallbacks(this); 18539 int returnCode; 18540 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 18541 boolean doDeletePackage = true; 18542 if (ps != null) { 18543 final boolean targetIsInstantApp = 18544 ps.getInstantApp(UserHandle.getUserId(callingUid)); 18545 doDeletePackage = !targetIsInstantApp 18546 || canViewInstantApps; 18547 } 18548 if (doDeletePackage) { 18549 if (!deleteAllUsers) { 18550 returnCode = deletePackageX(internalPackageName, versionCode, 18551 userId, deleteFlags); 18552 } else { 18553 int[] blockUninstallUserIds = getBlockUninstallForUsers( 18554 internalPackageName, users); 18555 // If nobody is blocking uninstall, proceed with delete for all users 18556 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 18557 returnCode = deletePackageX(internalPackageName, versionCode, 18558 userId, deleteFlags); 18559 } else { 18560 // Otherwise uninstall individually for users with blockUninstalls=false 18561 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 18562 for (int userId : users) { 18563 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 18564 returnCode = deletePackageX(internalPackageName, versionCode, 18565 userId, userFlags); 18566 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 18567 Slog.w(TAG, "Package delete failed for user " + userId 18568 + ", returnCode " + returnCode); 18569 } 18570 } 18571 } 18572 // The app has only been marked uninstalled for certain users. 18573 // We still need to report that delete was blocked 18574 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 18575 } 18576 } 18577 } else { 18578 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18579 } 18580 try { 18581 observer.onPackageDeleted(packageName, returnCode, null); 18582 } catch (RemoteException e) { 18583 Log.i(TAG, "Observer no longer exists."); 18584 } //end catch 18585 } //end run 18586 }); 18587 } 18588 18589 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 18590 if (pkg.staticSharedLibName != null) { 18591 return pkg.manifestPackageName; 18592 } 18593 return pkg.packageName; 18594 } 18595 18596 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 18597 // Handle renamed packages 18598 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 18599 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 18600 18601 // Is this a static library? 18602 SparseArray<SharedLibraryEntry> versionedLib = 18603 mStaticLibsByDeclaringPackage.get(packageName); 18604 if (versionedLib == null || versionedLib.size() <= 0) { 18605 return packageName; 18606 } 18607 18608 // Figure out which lib versions the caller can see 18609 SparseIntArray versionsCallerCanSee = null; 18610 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 18611 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 18612 && callingAppId != Process.ROOT_UID) { 18613 versionsCallerCanSee = new SparseIntArray(); 18614 String libName = versionedLib.valueAt(0).info.getName(); 18615 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 18616 if (uidPackages != null) { 18617 for (String uidPackage : uidPackages) { 18618 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 18619 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 18620 if (libIdx >= 0) { 18621 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 18622 versionsCallerCanSee.append(libVersion, libVersion); 18623 } 18624 } 18625 } 18626 } 18627 18628 // Caller can see nothing - done 18629 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 18630 return packageName; 18631 } 18632 18633 // Find the version the caller can see and the app version code 18634 SharedLibraryEntry highestVersion = null; 18635 final int versionCount = versionedLib.size(); 18636 for (int i = 0; i < versionCount; i++) { 18637 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 18638 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 18639 libEntry.info.getVersion()) < 0) { 18640 continue; 18641 } 18642 final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode(); 18643 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 18644 if (libVersionCode == versionCode) { 18645 return libEntry.apk; 18646 } 18647 } else if (highestVersion == null) { 18648 highestVersion = libEntry; 18649 } else if (libVersionCode > highestVersion.info 18650 .getDeclaringPackage().getVersionCode()) { 18651 highestVersion = libEntry; 18652 } 18653 } 18654 18655 if (highestVersion != null) { 18656 return highestVersion.apk; 18657 } 18658 18659 return packageName; 18660 } 18661 18662 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 18663 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 18664 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 18665 return true; 18666 } 18667 final int callingUserId = UserHandle.getUserId(callingUid); 18668 // If the caller installed the pkgName, then allow it to silently uninstall. 18669 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 18670 return true; 18671 } 18672 18673 // Allow package verifier to silently uninstall. 18674 if (mRequiredVerifierPackage != null && 18675 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 18676 return true; 18677 } 18678 18679 // Allow package uninstaller to silently uninstall. 18680 if (mRequiredUninstallerPackage != null && 18681 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 18682 return true; 18683 } 18684 18685 // Allow storage manager to silently uninstall. 18686 if (mStorageManagerPackage != null && 18687 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 18688 return true; 18689 } 18690 return false; 18691 } 18692 18693 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 18694 int[] result = EMPTY_INT_ARRAY; 18695 for (int userId : userIds) { 18696 if (getBlockUninstallForUser(packageName, userId)) { 18697 result = ArrayUtils.appendInt(result, userId); 18698 } 18699 } 18700 return result; 18701 } 18702 18703 @Override 18704 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 18705 final int callingUid = Binder.getCallingUid(); 18706 if (getInstantAppPackageName(callingUid) != null 18707 && !isCallerSameApp(packageName, callingUid)) { 18708 return false; 18709 } 18710 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 18711 } 18712 18713 private boolean isPackageDeviceAdmin(String packageName, int userId) { 18714 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 18715 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 18716 try { 18717 if (dpm != null) { 18718 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 18719 /* callingUserOnly =*/ false); 18720 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 18721 : deviceOwnerComponentName.getPackageName(); 18722 // Does the package contains the device owner? 18723 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 18724 // this check is probably not needed, since DO should be registered as a device 18725 // admin on some user too. (Original bug for this: b/17657954) 18726 if (packageName.equals(deviceOwnerPackageName)) { 18727 return true; 18728 } 18729 // Does it contain a device admin for any user? 18730 int[] users; 18731 if (userId == UserHandle.USER_ALL) { 18732 users = sUserManager.getUserIds(); 18733 } else { 18734 users = new int[]{userId}; 18735 } 18736 for (int i = 0; i < users.length; ++i) { 18737 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 18738 return true; 18739 } 18740 } 18741 } 18742 } catch (RemoteException e) { 18743 } 18744 return false; 18745 } 18746 18747 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 18748 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 18749 } 18750 18751 /** 18752 * This method is an internal method that could be get invoked either 18753 * to delete an installed package or to clean up a failed installation. 18754 * After deleting an installed package, a broadcast is sent to notify any 18755 * listeners that the package has been removed. For cleaning up a failed 18756 * installation, the broadcast is not necessary since the package's 18757 * installation wouldn't have sent the initial broadcast either 18758 * The key steps in deleting a package are 18759 * deleting the package information in internal structures like mPackages, 18760 * deleting the packages base directories through installd 18761 * updating mSettings to reflect current status 18762 * persisting settings for later use 18763 * sending a broadcast if necessary 18764 */ 18765 int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 18766 final PackageRemovedInfo info = new PackageRemovedInfo(this); 18767 final boolean res; 18768 18769 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 18770 ? UserHandle.USER_ALL : userId; 18771 18772 if (isPackageDeviceAdmin(packageName, removeUser)) { 18773 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 18774 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 18775 } 18776 18777 PackageSetting uninstalledPs = null; 18778 PackageParser.Package pkg = null; 18779 18780 // for the uninstall-updates case and restricted profiles, remember the per- 18781 // user handle installed state 18782 int[] allUsers; 18783 synchronized (mPackages) { 18784 uninstalledPs = mSettings.mPackages.get(packageName); 18785 if (uninstalledPs == null) { 18786 Slog.w(TAG, "Not removing non-existent package " + packageName); 18787 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18788 } 18789 18790 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 18791 && uninstalledPs.versionCode != versionCode) { 18792 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 18793 + uninstalledPs.versionCode + " != " + versionCode); 18794 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18795 } 18796 18797 // Static shared libs can be declared by any package, so let us not 18798 // allow removing a package if it provides a lib others depend on. 18799 pkg = mPackages.get(packageName); 18800 18801 allUsers = sUserManager.getUserIds(); 18802 18803 if (pkg != null && pkg.staticSharedLibName != null) { 18804 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 18805 pkg.staticSharedLibVersion); 18806 if (libEntry != null) { 18807 for (int currUserId : allUsers) { 18808 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 18809 continue; 18810 } 18811 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 18812 libEntry.info, 0, currUserId); 18813 if (!ArrayUtils.isEmpty(libClientPackages)) { 18814 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 18815 + " hosting lib " + libEntry.info.getName() + " version " 18816 + libEntry.info.getVersion() + " used by " + libClientPackages 18817 + " for user " + currUserId); 18818 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 18819 } 18820 } 18821 } 18822 } 18823 18824 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 18825 } 18826 18827 final int freezeUser; 18828 if (isUpdatedSystemApp(uninstalledPs) 18829 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 18830 // We're downgrading a system app, which will apply to all users, so 18831 // freeze them all during the downgrade 18832 freezeUser = UserHandle.USER_ALL; 18833 } else { 18834 freezeUser = removeUser; 18835 } 18836 18837 synchronized (mInstallLock) { 18838 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 18839 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 18840 deleteFlags, "deletePackageX")) { 18841 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 18842 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 18843 } 18844 synchronized (mPackages) { 18845 if (res) { 18846 if (pkg != null) { 18847 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 18848 } 18849 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 18850 updateInstantAppInstallerLocked(packageName); 18851 } 18852 } 18853 } 18854 18855 if (res) { 18856 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 18857 info.sendPackageRemovedBroadcasts(killApp); 18858 info.sendSystemPackageUpdatedBroadcasts(); 18859 info.sendSystemPackageAppearedBroadcasts(); 18860 } 18861 // Force a gc here. 18862 Runtime.getRuntime().gc(); 18863 // Delete the resources here after sending the broadcast to let 18864 // other processes clean up before deleting resources. 18865 if (info.args != null) { 18866 synchronized (mInstallLock) { 18867 info.args.doPostDeleteLI(true); 18868 } 18869 } 18870 18871 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18872 } 18873 18874 static class PackageRemovedInfo { 18875 final PackageSender packageSender; 18876 String removedPackage; 18877 String installerPackageName; 18878 int uid = -1; 18879 int removedAppId = -1; 18880 int[] origUsers; 18881 int[] removedUsers = null; 18882 int[] broadcastUsers = null; 18883 SparseArray<Integer> installReasons; 18884 boolean isRemovedPackageSystemUpdate = false; 18885 boolean isUpdate; 18886 boolean dataRemoved; 18887 boolean removedForAllUsers; 18888 boolean isStaticSharedLib; 18889 // Clean up resources deleted packages. 18890 InstallArgs args = null; 18891 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 18892 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 18893 18894 PackageRemovedInfo(PackageSender packageSender) { 18895 this.packageSender = packageSender; 18896 } 18897 18898 void sendPackageRemovedBroadcasts(boolean killApp) { 18899 sendPackageRemovedBroadcastInternal(killApp); 18900 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 18901 for (int i = 0; i < childCount; i++) { 18902 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18903 childInfo.sendPackageRemovedBroadcastInternal(killApp); 18904 } 18905 } 18906 18907 void sendSystemPackageUpdatedBroadcasts() { 18908 if (isRemovedPackageSystemUpdate) { 18909 sendSystemPackageUpdatedBroadcastsInternal(); 18910 final int childCount = (removedChildPackages != null) 18911 ? removedChildPackages.size() : 0; 18912 for (int i = 0; i < childCount; i++) { 18913 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18914 if (childInfo.isRemovedPackageSystemUpdate) { 18915 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 18916 } 18917 } 18918 } 18919 } 18920 18921 void sendSystemPackageAppearedBroadcasts() { 18922 final int packageCount = (appearedChildPackages != null) 18923 ? appearedChildPackages.size() : 0; 18924 for (int i = 0; i < packageCount; i++) { 18925 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 18926 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 18927 true, UserHandle.getAppId(installedInfo.uid), 18928 installedInfo.newUsers); 18929 } 18930 } 18931 18932 private void sendSystemPackageUpdatedBroadcastsInternal() { 18933 Bundle extras = new Bundle(2); 18934 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18935 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18936 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18937 removedPackage, extras, 0, null /*targetPackage*/, null, null); 18938 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18939 removedPackage, extras, 0, null /*targetPackage*/, null, null); 18940 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 18941 null, null, 0, removedPackage, null, null); 18942 if (installerPackageName != null) { 18943 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18944 removedPackage, extras, 0 /*flags*/, 18945 installerPackageName, null, null); 18946 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18947 removedPackage, extras, 0 /*flags*/, 18948 installerPackageName, null, null); 18949 } 18950 } 18951 18952 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 18953 // Don't send static shared library removal broadcasts as these 18954 // libs are visible only the the apps that depend on them an one 18955 // cannot remove the library if it has a dependency. 18956 if (isStaticSharedLib) { 18957 return; 18958 } 18959 Bundle extras = new Bundle(2); 18960 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18961 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 18962 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 18963 if (isUpdate || isRemovedPackageSystemUpdate) { 18964 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18965 } 18966 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18967 if (removedPackage != null) { 18968 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18969 removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers); 18970 if (installerPackageName != null) { 18971 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18972 removedPackage, extras, 0 /*flags*/, 18973 installerPackageName, null, broadcastUsers); 18974 } 18975 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18976 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18977 removedPackage, extras, 18978 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18979 null, null, broadcastUsers); 18980 } 18981 } 18982 if (removedAppId >= 0) { 18983 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 18984 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers); 18985 } 18986 } 18987 18988 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18989 removedUsers = userIds; 18990 if (removedUsers == null) { 18991 broadcastUsers = null; 18992 return; 18993 } 18994 18995 broadcastUsers = EMPTY_INT_ARRAY; 18996 for (int i = userIds.length - 1; i >= 0; --i) { 18997 final int userId = userIds[i]; 18998 if (deletedPackageSetting.getInstantApp(userId)) { 18999 continue; 19000 } 19001 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 19002 } 19003 } 19004 } 19005 19006 /* 19007 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 19008 * flag is not set, the data directory is removed as well. 19009 * make sure this flag is set for partially installed apps. If not its meaningless to 19010 * delete a partially installed application. 19011 */ 19012 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 19013 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 19014 String packageName = ps.name; 19015 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 19016 // Retrieve object to delete permissions for shared user later on 19017 final PackageParser.Package deletedPkg; 19018 final PackageSetting deletedPs; 19019 // reader 19020 synchronized (mPackages) { 19021 deletedPkg = mPackages.get(packageName); 19022 deletedPs = mSettings.mPackages.get(packageName); 19023 if (outInfo != null) { 19024 outInfo.removedPackage = packageName; 19025 outInfo.installerPackageName = ps.installerPackageName; 19026 outInfo.isStaticSharedLib = deletedPkg != null 19027 && deletedPkg.staticSharedLibName != null; 19028 outInfo.populateUsers(deletedPs == null ? null 19029 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 19030 } 19031 } 19032 19033 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 19034 19035 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 19036 final PackageParser.Package resolvedPkg; 19037 if (deletedPkg != null) { 19038 resolvedPkg = deletedPkg; 19039 } else { 19040 // We don't have a parsed package when it lives on an ejected 19041 // adopted storage device, so fake something together 19042 resolvedPkg = new PackageParser.Package(ps.name); 19043 resolvedPkg.setVolumeUuid(ps.volumeUuid); 19044 } 19045 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 19046 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19047 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 19048 if (outInfo != null) { 19049 outInfo.dataRemoved = true; 19050 } 19051 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 19052 } 19053 19054 int removedAppId = -1; 19055 19056 // writer 19057 synchronized (mPackages) { 19058 boolean installedStateChanged = false; 19059 if (deletedPs != null) { 19060 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 19061 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 19062 clearDefaultBrowserIfNeeded(packageName); 19063 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 19064 removedAppId = mSettings.removePackageLPw(packageName); 19065 if (outInfo != null) { 19066 outInfo.removedAppId = removedAppId; 19067 } 19068 updatePermissionsLPw(deletedPs.name, null, 0); 19069 if (deletedPs.sharedUser != null) { 19070 // Remove permissions associated with package. Since runtime 19071 // permissions are per user we have to kill the removed package 19072 // or packages running under the shared user of the removed 19073 // package if revoking the permissions requested only by the removed 19074 // package is successful and this causes a change in gids. 19075 for (int userId : UserManagerService.getInstance().getUserIds()) { 19076 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 19077 userId); 19078 if (userIdToKill == UserHandle.USER_ALL 19079 || userIdToKill >= UserHandle.USER_SYSTEM) { 19080 // If gids changed for this user, kill all affected packages. 19081 mHandler.post(new Runnable() { 19082 @Override 19083 public void run() { 19084 // This has to happen with no lock held. 19085 killApplication(deletedPs.name, deletedPs.appId, 19086 KILL_APP_REASON_GIDS_CHANGED); 19087 } 19088 }); 19089 break; 19090 } 19091 } 19092 } 19093 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 19094 } 19095 // make sure to preserve per-user disabled state if this removal was just 19096 // a downgrade of a system app to the factory package 19097 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 19098 if (DEBUG_REMOVE) { 19099 Slog.d(TAG, "Propagating install state across downgrade"); 19100 } 19101 for (int userId : allUserHandles) { 19102 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 19103 if (DEBUG_REMOVE) { 19104 Slog.d(TAG, " user " + userId + " => " + installed); 19105 } 19106 if (installed != ps.getInstalled(userId)) { 19107 installedStateChanged = true; 19108 } 19109 ps.setInstalled(installed, userId); 19110 } 19111 } 19112 } 19113 // can downgrade to reader 19114 if (writeSettings) { 19115 // Save settings now 19116 mSettings.writeLPr(); 19117 } 19118 if (installedStateChanged) { 19119 mSettings.writeKernelMappingLPr(ps); 19120 } 19121 } 19122 if (removedAppId != -1) { 19123 // A user ID was deleted here. Go through all users and remove it 19124 // from KeyStore. 19125 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 19126 } 19127 } 19128 19129 static boolean locationIsPrivileged(File path) { 19130 try { 19131 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 19132 .getCanonicalPath(); 19133 return path.getCanonicalPath().startsWith(privilegedAppDir); 19134 } catch (IOException e) { 19135 Slog.e(TAG, "Unable to access code path " + path); 19136 } 19137 return false; 19138 } 19139 19140 /* 19141 * Tries to delete system package. 19142 */ 19143 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 19144 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 19145 boolean writeSettings) { 19146 if (deletedPs.parentPackageName != null) { 19147 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 19148 return false; 19149 } 19150 19151 final boolean applyUserRestrictions 19152 = (allUserHandles != null) && (outInfo.origUsers != null); 19153 final PackageSetting disabledPs; 19154 // Confirm if the system package has been updated 19155 // An updated system app can be deleted. This will also have to restore 19156 // the system pkg from system partition 19157 // reader 19158 synchronized (mPackages) { 19159 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 19160 } 19161 19162 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 19163 + " disabledPs=" + disabledPs); 19164 19165 if (disabledPs == null) { 19166 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 19167 return false; 19168 } else if (DEBUG_REMOVE) { 19169 Slog.d(TAG, "Deleting system pkg from data partition"); 19170 } 19171 19172 if (DEBUG_REMOVE) { 19173 if (applyUserRestrictions) { 19174 Slog.d(TAG, "Remembering install states:"); 19175 for (int userId : allUserHandles) { 19176 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 19177 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 19178 } 19179 } 19180 } 19181 19182 // Delete the updated package 19183 outInfo.isRemovedPackageSystemUpdate = true; 19184 if (outInfo.removedChildPackages != null) { 19185 final int childCount = (deletedPs.childPackageNames != null) 19186 ? deletedPs.childPackageNames.size() : 0; 19187 for (int i = 0; i < childCount; i++) { 19188 String childPackageName = deletedPs.childPackageNames.get(i); 19189 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 19190 .contains(childPackageName)) { 19191 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 19192 childPackageName); 19193 if (childInfo != null) { 19194 childInfo.isRemovedPackageSystemUpdate = true; 19195 } 19196 } 19197 } 19198 } 19199 19200 if (disabledPs.versionCode < deletedPs.versionCode) { 19201 // Delete data for downgrades 19202 flags &= ~PackageManager.DELETE_KEEP_DATA; 19203 } else { 19204 // Preserve data by setting flag 19205 flags |= PackageManager.DELETE_KEEP_DATA; 19206 } 19207 19208 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 19209 outInfo, writeSettings, disabledPs.pkg); 19210 if (!ret) { 19211 return false; 19212 } 19213 19214 // writer 19215 synchronized (mPackages) { 19216 // Reinstate the old system package 19217 enableSystemPackageLPw(disabledPs.pkg); 19218 // Remove any native libraries from the upgraded package. 19219 removeNativeBinariesLI(deletedPs); 19220 } 19221 19222 // Install the system package 19223 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 19224 int parseFlags = mDefParseFlags 19225 | PackageParser.PARSE_MUST_BE_APK 19226 | PackageParser.PARSE_IS_SYSTEM 19227 | PackageParser.PARSE_IS_SYSTEM_DIR; 19228 if (locationIsPrivileged(disabledPs.codePath)) { 19229 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 19230 } 19231 19232 final PackageParser.Package newPkg; 19233 try { 19234 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 19235 0 /* currentTime */, null); 19236 } catch (PackageManagerException e) { 19237 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 19238 + e.getMessage()); 19239 return false; 19240 } 19241 19242 try { 19243 // update shared libraries for the newly re-installed system package 19244 updateSharedLibrariesLPr(newPkg, null); 19245 } catch (PackageManagerException e) { 19246 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 19247 } 19248 19249 prepareAppDataAfterInstallLIF(newPkg); 19250 19251 // writer 19252 synchronized (mPackages) { 19253 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 19254 19255 // Propagate the permissions state as we do not want to drop on the floor 19256 // runtime permissions. The update permissions method below will take 19257 // care of removing obsolete permissions and grant install permissions. 19258 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 19259 updatePermissionsLPw(newPkg.packageName, newPkg, 19260 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 19261 19262 if (applyUserRestrictions) { 19263 boolean installedStateChanged = false; 19264 if (DEBUG_REMOVE) { 19265 Slog.d(TAG, "Propagating install state across reinstall"); 19266 } 19267 for (int userId : allUserHandles) { 19268 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 19269 if (DEBUG_REMOVE) { 19270 Slog.d(TAG, " user " + userId + " => " + installed); 19271 } 19272 if (installed != ps.getInstalled(userId)) { 19273 installedStateChanged = true; 19274 } 19275 ps.setInstalled(installed, userId); 19276 19277 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19278 } 19279 // Regardless of writeSettings we need to ensure that this restriction 19280 // state propagation is persisted 19281 mSettings.writeAllUsersPackageRestrictionsLPr(); 19282 if (installedStateChanged) { 19283 mSettings.writeKernelMappingLPr(ps); 19284 } 19285 } 19286 // can downgrade to reader here 19287 if (writeSettings) { 19288 mSettings.writeLPr(); 19289 } 19290 } 19291 return true; 19292 } 19293 19294 private boolean deleteInstalledPackageLIF(PackageSetting ps, 19295 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 19296 PackageRemovedInfo outInfo, boolean writeSettings, 19297 PackageParser.Package replacingPackage) { 19298 synchronized (mPackages) { 19299 if (outInfo != null) { 19300 outInfo.uid = ps.appId; 19301 } 19302 19303 if (outInfo != null && outInfo.removedChildPackages != null) { 19304 final int childCount = (ps.childPackageNames != null) 19305 ? ps.childPackageNames.size() : 0; 19306 for (int i = 0; i < childCount; i++) { 19307 String childPackageName = ps.childPackageNames.get(i); 19308 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 19309 if (childPs == null) { 19310 return false; 19311 } 19312 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 19313 childPackageName); 19314 if (childInfo != null) { 19315 childInfo.uid = childPs.appId; 19316 } 19317 } 19318 } 19319 } 19320 19321 // Delete package data from internal structures and also remove data if flag is set 19322 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 19323 19324 // Delete the child packages data 19325 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 19326 for (int i = 0; i < childCount; i++) { 19327 PackageSetting childPs; 19328 synchronized (mPackages) { 19329 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 19330 } 19331 if (childPs != null) { 19332 PackageRemovedInfo childOutInfo = (outInfo != null 19333 && outInfo.removedChildPackages != null) 19334 ? outInfo.removedChildPackages.get(childPs.name) : null; 19335 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 19336 && (replacingPackage != null 19337 && !replacingPackage.hasChildPackage(childPs.name)) 19338 ? flags & ~DELETE_KEEP_DATA : flags; 19339 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 19340 deleteFlags, writeSettings); 19341 } 19342 } 19343 19344 // Delete application code and resources only for parent packages 19345 if (ps.parentPackageName == null) { 19346 if (deleteCodeAndResources && (outInfo != null)) { 19347 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 19348 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 19349 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 19350 } 19351 } 19352 19353 return true; 19354 } 19355 19356 @Override 19357 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 19358 int userId) { 19359 mContext.enforceCallingOrSelfPermission( 19360 android.Manifest.permission.DELETE_PACKAGES, null); 19361 synchronized (mPackages) { 19362 // Cannot block uninstall of static shared libs as they are 19363 // considered a part of the using app (emulating static linking). 19364 // Also static libs are installed always on internal storage. 19365 PackageParser.Package pkg = mPackages.get(packageName); 19366 if (pkg != null && pkg.staticSharedLibName != null) { 19367 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 19368 + " providing static shared library: " + pkg.staticSharedLibName); 19369 return false; 19370 } 19371 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 19372 mSettings.writePackageRestrictionsLPr(userId); 19373 } 19374 return true; 19375 } 19376 19377 @Override 19378 public boolean getBlockUninstallForUser(String packageName, int userId) { 19379 synchronized (mPackages) { 19380 final PackageSetting ps = mSettings.mPackages.get(packageName); 19381 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 19382 return false; 19383 } 19384 return mSettings.getBlockUninstallLPr(userId, packageName); 19385 } 19386 } 19387 19388 @Override 19389 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 19390 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 19391 synchronized (mPackages) { 19392 PackageSetting ps = mSettings.mPackages.get(packageName); 19393 if (ps == null) { 19394 Log.w(TAG, "Package doesn't exist: " + packageName); 19395 return false; 19396 } 19397 if (systemUserApp) { 19398 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 19399 } else { 19400 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 19401 } 19402 mSettings.writeLPr(); 19403 } 19404 return true; 19405 } 19406 19407 /* 19408 * This method handles package deletion in general 19409 */ 19410 private boolean deletePackageLIF(String packageName, UserHandle user, 19411 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 19412 PackageRemovedInfo outInfo, boolean writeSettings, 19413 PackageParser.Package replacingPackage) { 19414 if (packageName == null) { 19415 Slog.w(TAG, "Attempt to delete null packageName."); 19416 return false; 19417 } 19418 19419 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 19420 19421 PackageSetting ps; 19422 synchronized (mPackages) { 19423 ps = mSettings.mPackages.get(packageName); 19424 if (ps == null) { 19425 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 19426 return false; 19427 } 19428 19429 if (ps.parentPackageName != null && (!isSystemApp(ps) 19430 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 19431 if (DEBUG_REMOVE) { 19432 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 19433 + ((user == null) ? UserHandle.USER_ALL : user)); 19434 } 19435 final int removedUserId = (user != null) ? user.getIdentifier() 19436 : UserHandle.USER_ALL; 19437 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 19438 return false; 19439 } 19440 markPackageUninstalledForUserLPw(ps, user); 19441 scheduleWritePackageRestrictionsLocked(user); 19442 return true; 19443 } 19444 } 19445 19446 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 19447 && user.getIdentifier() != UserHandle.USER_ALL)) { 19448 // The caller is asking that the package only be deleted for a single 19449 // user. To do this, we just mark its uninstalled state and delete 19450 // its data. If this is a system app, we only allow this to happen if 19451 // they have set the special DELETE_SYSTEM_APP which requests different 19452 // semantics than normal for uninstalling system apps. 19453 markPackageUninstalledForUserLPw(ps, user); 19454 19455 if (!isSystemApp(ps)) { 19456 // Do not uninstall the APK if an app should be cached 19457 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 19458 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 19459 // Other user still have this package installed, so all 19460 // we need to do is clear this user's data and save that 19461 // it is uninstalled. 19462 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 19463 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 19464 return false; 19465 } 19466 scheduleWritePackageRestrictionsLocked(user); 19467 return true; 19468 } else { 19469 // We need to set it back to 'installed' so the uninstall 19470 // broadcasts will be sent correctly. 19471 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 19472 ps.setInstalled(true, user.getIdentifier()); 19473 mSettings.writeKernelMappingLPr(ps); 19474 } 19475 } else { 19476 // This is a system app, so we assume that the 19477 // other users still have this package installed, so all 19478 // we need to do is clear this user's data and save that 19479 // it is uninstalled. 19480 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 19481 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 19482 return false; 19483 } 19484 scheduleWritePackageRestrictionsLocked(user); 19485 return true; 19486 } 19487 } 19488 19489 // If we are deleting a composite package for all users, keep track 19490 // of result for each child. 19491 if (ps.childPackageNames != null && outInfo != null) { 19492 synchronized (mPackages) { 19493 final int childCount = ps.childPackageNames.size(); 19494 outInfo.removedChildPackages = new ArrayMap<>(childCount); 19495 for (int i = 0; i < childCount; i++) { 19496 String childPackageName = ps.childPackageNames.get(i); 19497 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 19498 childInfo.removedPackage = childPackageName; 19499 childInfo.installerPackageName = ps.installerPackageName; 19500 outInfo.removedChildPackages.put(childPackageName, childInfo); 19501 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 19502 if (childPs != null) { 19503 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 19504 } 19505 } 19506 } 19507 } 19508 19509 boolean ret = false; 19510 if (isSystemApp(ps)) { 19511 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 19512 // When an updated system application is deleted we delete the existing resources 19513 // as well and fall back to existing code in system partition 19514 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 19515 } else { 19516 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 19517 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 19518 outInfo, writeSettings, replacingPackage); 19519 } 19520 19521 // Take a note whether we deleted the package for all users 19522 if (outInfo != null) { 19523 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 19524 if (outInfo.removedChildPackages != null) { 19525 synchronized (mPackages) { 19526 final int childCount = outInfo.removedChildPackages.size(); 19527 for (int i = 0; i < childCount; i++) { 19528 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 19529 if (childInfo != null) { 19530 childInfo.removedForAllUsers = mPackages.get( 19531 childInfo.removedPackage) == null; 19532 } 19533 } 19534 } 19535 } 19536 // If we uninstalled an update to a system app there may be some 19537 // child packages that appeared as they are declared in the system 19538 // app but were not declared in the update. 19539 if (isSystemApp(ps)) { 19540 synchronized (mPackages) { 19541 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 19542 final int childCount = (updatedPs.childPackageNames != null) 19543 ? updatedPs.childPackageNames.size() : 0; 19544 for (int i = 0; i < childCount; i++) { 19545 String childPackageName = updatedPs.childPackageNames.get(i); 19546 if (outInfo.removedChildPackages == null 19547 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 19548 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 19549 if (childPs == null) { 19550 continue; 19551 } 19552 PackageInstalledInfo installRes = new PackageInstalledInfo(); 19553 installRes.name = childPackageName; 19554 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 19555 installRes.pkg = mPackages.get(childPackageName); 19556 installRes.uid = childPs.pkg.applicationInfo.uid; 19557 if (outInfo.appearedChildPackages == null) { 19558 outInfo.appearedChildPackages = new ArrayMap<>(); 19559 } 19560 outInfo.appearedChildPackages.put(childPackageName, installRes); 19561 } 19562 } 19563 } 19564 } 19565 } 19566 19567 return ret; 19568 } 19569 19570 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 19571 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 19572 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 19573 for (int nextUserId : userIds) { 19574 if (DEBUG_REMOVE) { 19575 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 19576 } 19577 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 19578 false /*installed*/, 19579 true /*stopped*/, 19580 true /*notLaunched*/, 19581 false /*hidden*/, 19582 false /*suspended*/, 19583 false /*instantApp*/, 19584 null /*lastDisableAppCaller*/, 19585 null /*enabledComponents*/, 19586 null /*disabledComponents*/, 19587 ps.readUserState(nextUserId).domainVerificationStatus, 19588 0, PackageManager.INSTALL_REASON_UNKNOWN); 19589 } 19590 mSettings.writeKernelMappingLPr(ps); 19591 } 19592 19593 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 19594 PackageRemovedInfo outInfo) { 19595 final PackageParser.Package pkg; 19596 synchronized (mPackages) { 19597 pkg = mPackages.get(ps.name); 19598 } 19599 19600 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 19601 : new int[] {userId}; 19602 for (int nextUserId : userIds) { 19603 if (DEBUG_REMOVE) { 19604 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 19605 + nextUserId); 19606 } 19607 19608 destroyAppDataLIF(pkg, userId, 19609 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19610 destroyAppProfilesLIF(pkg, userId); 19611 clearDefaultBrowserIfNeededForUser(ps.name, userId); 19612 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 19613 schedulePackageCleaning(ps.name, nextUserId, false); 19614 synchronized (mPackages) { 19615 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 19616 scheduleWritePackageRestrictionsLocked(nextUserId); 19617 } 19618 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 19619 } 19620 } 19621 19622 if (outInfo != null) { 19623 outInfo.removedPackage = ps.name; 19624 outInfo.installerPackageName = ps.installerPackageName; 19625 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 19626 outInfo.removedAppId = ps.appId; 19627 outInfo.removedUsers = userIds; 19628 outInfo.broadcastUsers = userIds; 19629 } 19630 19631 return true; 19632 } 19633 19634 private final class ClearStorageConnection implements ServiceConnection { 19635 IMediaContainerService mContainerService; 19636 19637 @Override 19638 public void onServiceConnected(ComponentName name, IBinder service) { 19639 synchronized (this) { 19640 mContainerService = IMediaContainerService.Stub 19641 .asInterface(Binder.allowBlocking(service)); 19642 notifyAll(); 19643 } 19644 } 19645 19646 @Override 19647 public void onServiceDisconnected(ComponentName name) { 19648 } 19649 } 19650 19651 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 19652 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 19653 19654 final boolean mounted; 19655 if (Environment.isExternalStorageEmulated()) { 19656 mounted = true; 19657 } else { 19658 final String status = Environment.getExternalStorageState(); 19659 19660 mounted = status.equals(Environment.MEDIA_MOUNTED) 19661 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 19662 } 19663 19664 if (!mounted) { 19665 return; 19666 } 19667 19668 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 19669 int[] users; 19670 if (userId == UserHandle.USER_ALL) { 19671 users = sUserManager.getUserIds(); 19672 } else { 19673 users = new int[] { userId }; 19674 } 19675 final ClearStorageConnection conn = new ClearStorageConnection(); 19676 if (mContext.bindServiceAsUser( 19677 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 19678 try { 19679 for (int curUser : users) { 19680 long timeout = SystemClock.uptimeMillis() + 5000; 19681 synchronized (conn) { 19682 long now; 19683 while (conn.mContainerService == null && 19684 (now = SystemClock.uptimeMillis()) < timeout) { 19685 try { 19686 conn.wait(timeout - now); 19687 } catch (InterruptedException e) { 19688 } 19689 } 19690 } 19691 if (conn.mContainerService == null) { 19692 return; 19693 } 19694 19695 final UserEnvironment userEnv = new UserEnvironment(curUser); 19696 clearDirectory(conn.mContainerService, 19697 userEnv.buildExternalStorageAppCacheDirs(packageName)); 19698 if (allData) { 19699 clearDirectory(conn.mContainerService, 19700 userEnv.buildExternalStorageAppDataDirs(packageName)); 19701 clearDirectory(conn.mContainerService, 19702 userEnv.buildExternalStorageAppMediaDirs(packageName)); 19703 } 19704 } 19705 } finally { 19706 mContext.unbindService(conn); 19707 } 19708 } 19709 } 19710 19711 @Override 19712 public void clearApplicationProfileData(String packageName) { 19713 enforceSystemOrRoot("Only the system can clear all profile data"); 19714 19715 final PackageParser.Package pkg; 19716 synchronized (mPackages) { 19717 pkg = mPackages.get(packageName); 19718 } 19719 19720 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 19721 synchronized (mInstallLock) { 19722 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 19723 } 19724 } 19725 } 19726 19727 @Override 19728 public void clearApplicationUserData(final String packageName, 19729 final IPackageDataObserver observer, final int userId) { 19730 mContext.enforceCallingOrSelfPermission( 19731 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 19732 19733 final int callingUid = Binder.getCallingUid(); 19734 enforceCrossUserPermission(callingUid, userId, 19735 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 19736 19737 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19738 if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) { 19739 return; 19740 } 19741 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 19742 throw new SecurityException("Cannot clear data for a protected package: " 19743 + packageName); 19744 } 19745 // Queue up an async operation since the package deletion may take a little while. 19746 mHandler.post(new Runnable() { 19747 public void run() { 19748 mHandler.removeCallbacks(this); 19749 final boolean succeeded; 19750 try (PackageFreezer freezer = freezePackage(packageName, 19751 "clearApplicationUserData")) { 19752 synchronized (mInstallLock) { 19753 succeeded = clearApplicationUserDataLIF(packageName, userId); 19754 } 19755 clearExternalStorageDataSync(packageName, userId, true); 19756 synchronized (mPackages) { 19757 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 19758 packageName, userId); 19759 } 19760 } 19761 if (succeeded) { 19762 // invoke DeviceStorageMonitor's update method to clear any notifications 19763 DeviceStorageMonitorInternal dsm = LocalServices 19764 .getService(DeviceStorageMonitorInternal.class); 19765 if (dsm != null) { 19766 dsm.checkMemory(); 19767 } 19768 } 19769 if(observer != null) { 19770 try { 19771 observer.onRemoveCompleted(packageName, succeeded); 19772 } catch (RemoteException e) { 19773 Log.i(TAG, "Observer no longer exists."); 19774 } 19775 } //end if observer 19776 } //end run 19777 }); 19778 } 19779 19780 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 19781 if (packageName == null) { 19782 Slog.w(TAG, "Attempt to delete null packageName."); 19783 return false; 19784 } 19785 19786 // Try finding details about the requested package 19787 PackageParser.Package pkg; 19788 synchronized (mPackages) { 19789 pkg = mPackages.get(packageName); 19790 if (pkg == null) { 19791 final PackageSetting ps = mSettings.mPackages.get(packageName); 19792 if (ps != null) { 19793 pkg = ps.pkg; 19794 } 19795 } 19796 19797 if (pkg == null) { 19798 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 19799 return false; 19800 } 19801 19802 PackageSetting ps = (PackageSetting) pkg.mExtras; 19803 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19804 } 19805 19806 clearAppDataLIF(pkg, userId, 19807 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19808 19809 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19810 removeKeystoreDataIfNeeded(userId, appId); 19811 19812 UserManagerInternal umInternal = getUserManagerInternal(); 19813 final int flags; 19814 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 19815 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19816 } else if (umInternal.isUserRunning(userId)) { 19817 flags = StorageManager.FLAG_STORAGE_DE; 19818 } else { 19819 flags = 0; 19820 } 19821 prepareAppDataContentsLIF(pkg, userId, flags); 19822 19823 return true; 19824 } 19825 19826 /** 19827 * Reverts user permission state changes (permissions and flags) in 19828 * all packages for a given user. 19829 * 19830 * @param userId The device user for which to do a reset. 19831 */ 19832 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 19833 final int packageCount = mPackages.size(); 19834 for (int i = 0; i < packageCount; i++) { 19835 PackageParser.Package pkg = mPackages.valueAt(i); 19836 PackageSetting ps = (PackageSetting) pkg.mExtras; 19837 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19838 } 19839 } 19840 19841 private void resetNetworkPolicies(int userId) { 19842 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 19843 } 19844 19845 /** 19846 * Reverts user permission state changes (permissions and flags). 19847 * 19848 * @param ps The package for which to reset. 19849 * @param userId The device user for which to do a reset. 19850 */ 19851 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 19852 final PackageSetting ps, final int userId) { 19853 if (ps.pkg == null) { 19854 return; 19855 } 19856 19857 // These are flags that can change base on user actions. 19858 final int userSettableMask = FLAG_PERMISSION_USER_SET 19859 | FLAG_PERMISSION_USER_FIXED 19860 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 19861 | FLAG_PERMISSION_REVIEW_REQUIRED; 19862 19863 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 19864 | FLAG_PERMISSION_POLICY_FIXED; 19865 19866 boolean writeInstallPermissions = false; 19867 boolean writeRuntimePermissions = false; 19868 19869 final int permissionCount = ps.pkg.requestedPermissions.size(); 19870 for (int i = 0; i < permissionCount; i++) { 19871 String permission = ps.pkg.requestedPermissions.get(i); 19872 19873 BasePermission bp = mSettings.mPermissions.get(permission); 19874 if (bp == null) { 19875 continue; 19876 } 19877 19878 // If shared user we just reset the state to which only this app contributed. 19879 if (ps.sharedUser != null) { 19880 boolean used = false; 19881 final int packageCount = ps.sharedUser.packages.size(); 19882 for (int j = 0; j < packageCount; j++) { 19883 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 19884 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 19885 && pkg.pkg.requestedPermissions.contains(permission)) { 19886 used = true; 19887 break; 19888 } 19889 } 19890 if (used) { 19891 continue; 19892 } 19893 } 19894 19895 PermissionsState permissionsState = ps.getPermissionsState(); 19896 19897 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 19898 19899 // Always clear the user settable flags. 19900 final boolean hasInstallState = permissionsState.getInstallPermissionState( 19901 bp.name) != null; 19902 // If permission review is enabled and this is a legacy app, mark the 19903 // permission as requiring a review as this is the initial state. 19904 int flags = 0; 19905 if (mPermissionReviewRequired 19906 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 19907 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 19908 } 19909 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 19910 if (hasInstallState) { 19911 writeInstallPermissions = true; 19912 } else { 19913 writeRuntimePermissions = true; 19914 } 19915 } 19916 19917 // Below is only runtime permission handling. 19918 if (!bp.isRuntime()) { 19919 continue; 19920 } 19921 19922 // Never clobber system or policy. 19923 if ((oldFlags & policyOrSystemFlags) != 0) { 19924 continue; 19925 } 19926 19927 // If this permission was granted by default, make sure it is. 19928 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19929 if (permissionsState.grantRuntimePermission(bp, userId) 19930 != PERMISSION_OPERATION_FAILURE) { 19931 writeRuntimePermissions = true; 19932 } 19933 // If permission review is enabled the permissions for a legacy apps 19934 // are represented as constantly granted runtime ones, so don't revoke. 19935 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19936 // Otherwise, reset the permission. 19937 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 19938 switch (revokeResult) { 19939 case PERMISSION_OPERATION_SUCCESS: 19940 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 19941 writeRuntimePermissions = true; 19942 final int appId = ps.appId; 19943 mHandler.post(new Runnable() { 19944 @Override 19945 public void run() { 19946 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 19947 } 19948 }); 19949 } break; 19950 } 19951 } 19952 } 19953 19954 // Synchronously write as we are taking permissions away. 19955 if (writeRuntimePermissions) { 19956 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 19957 } 19958 19959 // Synchronously write as we are taking permissions away. 19960 if (writeInstallPermissions) { 19961 mSettings.writeLPr(); 19962 } 19963 } 19964 19965 /** 19966 * Remove entries from the keystore daemon. Will only remove it if the 19967 * {@code appId} is valid. 19968 */ 19969 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19970 if (appId < 0) { 19971 return; 19972 } 19973 19974 final KeyStore keyStore = KeyStore.getInstance(); 19975 if (keyStore != null) { 19976 if (userId == UserHandle.USER_ALL) { 19977 for (final int individual : sUserManager.getUserIds()) { 19978 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19979 } 19980 } else { 19981 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19982 } 19983 } else { 19984 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19985 } 19986 } 19987 19988 @Override 19989 public void deleteApplicationCacheFiles(final String packageName, 19990 final IPackageDataObserver observer) { 19991 final int userId = UserHandle.getCallingUserId(); 19992 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19993 } 19994 19995 @Override 19996 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19997 final IPackageDataObserver observer) { 19998 final int callingUid = Binder.getCallingUid(); 19999 mContext.enforceCallingOrSelfPermission( 20000 android.Manifest.permission.DELETE_CACHE_FILES, null); 20001 enforceCrossUserPermission(callingUid, userId, 20002 /* requireFullPermission= */ true, /* checkShell= */ false, 20003 "delete application cache files"); 20004 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 20005 android.Manifest.permission.ACCESS_INSTANT_APPS); 20006 20007 final PackageParser.Package pkg; 20008 synchronized (mPackages) { 20009 pkg = mPackages.get(packageName); 20010 } 20011 20012 // Queue up an async operation since the package deletion may take a little while. 20013 mHandler.post(new Runnable() { 20014 public void run() { 20015 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 20016 boolean doClearData = true; 20017 if (ps != null) { 20018 final boolean targetIsInstantApp = 20019 ps.getInstantApp(UserHandle.getUserId(callingUid)); 20020 doClearData = !targetIsInstantApp 20021 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 20022 } 20023 if (doClearData) { 20024 synchronized (mInstallLock) { 20025 final int flags = StorageManager.FLAG_STORAGE_DE 20026 | StorageManager.FLAG_STORAGE_CE; 20027 // We're only clearing cache files, so we don't care if the 20028 // app is unfrozen and still able to run 20029 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 20030 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20031 } 20032 clearExternalStorageDataSync(packageName, userId, false); 20033 } 20034 if (observer != null) { 20035 try { 20036 observer.onRemoveCompleted(packageName, true); 20037 } catch (RemoteException e) { 20038 Log.i(TAG, "Observer no longer exists."); 20039 } 20040 } 20041 } 20042 }); 20043 } 20044 20045 @Override 20046 public void getPackageSizeInfo(final String packageName, int userHandle, 20047 final IPackageStatsObserver observer) { 20048 throw new UnsupportedOperationException( 20049 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 20050 } 20051 20052 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 20053 final PackageSetting ps; 20054 synchronized (mPackages) { 20055 ps = mSettings.mPackages.get(packageName); 20056 if (ps == null) { 20057 Slog.w(TAG, "Failed to find settings for " + packageName); 20058 return false; 20059 } 20060 } 20061 20062 final String[] packageNames = { packageName }; 20063 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 20064 final String[] codePaths = { ps.codePathString }; 20065 20066 try { 20067 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 20068 ps.appId, ceDataInodes, codePaths, stats); 20069 20070 // For now, ignore code size of packages on system partition 20071 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 20072 stats.codeSize = 0; 20073 } 20074 20075 // External clients expect these to be tracked separately 20076 stats.dataSize -= stats.cacheSize; 20077 20078 } catch (InstallerException e) { 20079 Slog.w(TAG, String.valueOf(e)); 20080 return false; 20081 } 20082 20083 return true; 20084 } 20085 20086 private int getUidTargetSdkVersionLockedLPr(int uid) { 20087 Object obj = mSettings.getUserIdLPr(uid); 20088 if (obj instanceof SharedUserSetting) { 20089 final SharedUserSetting sus = (SharedUserSetting) obj; 20090 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 20091 final Iterator<PackageSetting> it = sus.packages.iterator(); 20092 while (it.hasNext()) { 20093 final PackageSetting ps = it.next(); 20094 if (ps.pkg != null) { 20095 int v = ps.pkg.applicationInfo.targetSdkVersion; 20096 if (v < vers) vers = v; 20097 } 20098 } 20099 return vers; 20100 } else if (obj instanceof PackageSetting) { 20101 final PackageSetting ps = (PackageSetting) obj; 20102 if (ps.pkg != null) { 20103 return ps.pkg.applicationInfo.targetSdkVersion; 20104 } 20105 } 20106 return Build.VERSION_CODES.CUR_DEVELOPMENT; 20107 } 20108 20109 @Override 20110 public void addPreferredActivity(IntentFilter filter, int match, 20111 ComponentName[] set, ComponentName activity, int userId) { 20112 addPreferredActivityInternal(filter, match, set, activity, true, userId, 20113 "Adding preferred"); 20114 } 20115 20116 private void addPreferredActivityInternal(IntentFilter filter, int match, 20117 ComponentName[] set, ComponentName activity, boolean always, int userId, 20118 String opname) { 20119 // writer 20120 int callingUid = Binder.getCallingUid(); 20121 enforceCrossUserPermission(callingUid, userId, 20122 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 20123 if (filter.countActions() == 0) { 20124 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 20125 return; 20126 } 20127 synchronized (mPackages) { 20128 if (mContext.checkCallingOrSelfPermission( 20129 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 20130 != PackageManager.PERMISSION_GRANTED) { 20131 if (getUidTargetSdkVersionLockedLPr(callingUid) 20132 < Build.VERSION_CODES.FROYO) { 20133 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 20134 + callingUid); 20135 return; 20136 } 20137 mContext.enforceCallingOrSelfPermission( 20138 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20139 } 20140 20141 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 20142 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 20143 + userId + ":"); 20144 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20145 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 20146 scheduleWritePackageRestrictionsLocked(userId); 20147 postPreferredActivityChangedBroadcast(userId); 20148 } 20149 } 20150 20151 private void postPreferredActivityChangedBroadcast(int userId) { 20152 mHandler.post(() -> { 20153 final IActivityManager am = ActivityManager.getService(); 20154 if (am == null) { 20155 return; 20156 } 20157 20158 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 20159 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 20160 try { 20161 am.broadcastIntent(null, intent, null, null, 20162 0, null, null, null, android.app.AppOpsManager.OP_NONE, 20163 null, false, false, userId); 20164 } catch (RemoteException e) { 20165 } 20166 }); 20167 } 20168 20169 @Override 20170 public void replacePreferredActivity(IntentFilter filter, int match, 20171 ComponentName[] set, ComponentName activity, int userId) { 20172 if (filter.countActions() != 1) { 20173 throw new IllegalArgumentException( 20174 "replacePreferredActivity expects filter to have only 1 action."); 20175 } 20176 if (filter.countDataAuthorities() != 0 20177 || filter.countDataPaths() != 0 20178 || filter.countDataSchemes() > 1 20179 || filter.countDataTypes() != 0) { 20180 throw new IllegalArgumentException( 20181 "replacePreferredActivity expects filter to have no data authorities, " + 20182 "paths, or types; and at most one scheme."); 20183 } 20184 20185 final int callingUid = Binder.getCallingUid(); 20186 enforceCrossUserPermission(callingUid, userId, 20187 true /* requireFullPermission */, false /* checkShell */, 20188 "replace preferred activity"); 20189 synchronized (mPackages) { 20190 if (mContext.checkCallingOrSelfPermission( 20191 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 20192 != PackageManager.PERMISSION_GRANTED) { 20193 if (getUidTargetSdkVersionLockedLPr(callingUid) 20194 < Build.VERSION_CODES.FROYO) { 20195 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 20196 + Binder.getCallingUid()); 20197 return; 20198 } 20199 mContext.enforceCallingOrSelfPermission( 20200 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20201 } 20202 20203 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 20204 if (pir != null) { 20205 // Get all of the existing entries that exactly match this filter. 20206 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 20207 if (existing != null && existing.size() == 1) { 20208 PreferredActivity cur = existing.get(0); 20209 if (DEBUG_PREFERRED) { 20210 Slog.i(TAG, "Checking replace of preferred:"); 20211 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20212 if (!cur.mPref.mAlways) { 20213 Slog.i(TAG, " -- CUR; not mAlways!"); 20214 } else { 20215 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 20216 Slog.i(TAG, " -- CUR: mSet=" 20217 + Arrays.toString(cur.mPref.mSetComponents)); 20218 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 20219 Slog.i(TAG, " -- NEW: mMatch=" 20220 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 20221 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 20222 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 20223 } 20224 } 20225 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 20226 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 20227 && cur.mPref.sameSet(set)) { 20228 // Setting the preferred activity to what it happens to be already 20229 if (DEBUG_PREFERRED) { 20230 Slog.i(TAG, "Replacing with same preferred activity " 20231 + cur.mPref.mShortComponent + " for user " 20232 + userId + ":"); 20233 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20234 } 20235 return; 20236 } 20237 } 20238 20239 if (existing != null) { 20240 if (DEBUG_PREFERRED) { 20241 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 20242 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20243 } 20244 for (int i = 0; i < existing.size(); i++) { 20245 PreferredActivity pa = existing.get(i); 20246 if (DEBUG_PREFERRED) { 20247 Slog.i(TAG, "Removing existing preferred activity " 20248 + pa.mPref.mComponent + ":"); 20249 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 20250 } 20251 pir.removeFilter(pa); 20252 } 20253 } 20254 } 20255 addPreferredActivityInternal(filter, match, set, activity, true, userId, 20256 "Replacing preferred"); 20257 } 20258 } 20259 20260 @Override 20261 public void clearPackagePreferredActivities(String packageName) { 20262 final int callingUid = Binder.getCallingUid(); 20263 if (getInstantAppPackageName(callingUid) != null) { 20264 return; 20265 } 20266 // writer 20267 synchronized (mPackages) { 20268 PackageParser.Package pkg = mPackages.get(packageName); 20269 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 20270 if (mContext.checkCallingOrSelfPermission( 20271 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 20272 != PackageManager.PERMISSION_GRANTED) { 20273 if (getUidTargetSdkVersionLockedLPr(callingUid) 20274 < Build.VERSION_CODES.FROYO) { 20275 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 20276 + callingUid); 20277 return; 20278 } 20279 mContext.enforceCallingOrSelfPermission( 20280 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20281 } 20282 } 20283 final PackageSetting ps = mSettings.getPackageLPr(packageName); 20284 if (ps != null 20285 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20286 return; 20287 } 20288 int user = UserHandle.getCallingUserId(); 20289 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 20290 scheduleWritePackageRestrictionsLocked(user); 20291 } 20292 } 20293 } 20294 20295 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 20296 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 20297 ArrayList<PreferredActivity> removed = null; 20298 boolean changed = false; 20299 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20300 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 20301 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20302 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 20303 continue; 20304 } 20305 Iterator<PreferredActivity> it = pir.filterIterator(); 20306 while (it.hasNext()) { 20307 PreferredActivity pa = it.next(); 20308 // Mark entry for removal only if it matches the package name 20309 // and the entry is of type "always". 20310 if (packageName == null || 20311 (pa.mPref.mComponent.getPackageName().equals(packageName) 20312 && pa.mPref.mAlways)) { 20313 if (removed == null) { 20314 removed = new ArrayList<PreferredActivity>(); 20315 } 20316 removed.add(pa); 20317 } 20318 } 20319 if (removed != null) { 20320 for (int j=0; j<removed.size(); j++) { 20321 PreferredActivity pa = removed.get(j); 20322 pir.removeFilter(pa); 20323 } 20324 changed = true; 20325 } 20326 } 20327 if (changed) { 20328 postPreferredActivityChangedBroadcast(userId); 20329 } 20330 return changed; 20331 } 20332 20333 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 20334 private void clearIntentFilterVerificationsLPw(int userId) { 20335 final int packageCount = mPackages.size(); 20336 for (int i = 0; i < packageCount; i++) { 20337 PackageParser.Package pkg = mPackages.valueAt(i); 20338 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 20339 } 20340 } 20341 20342 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 20343 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 20344 if (userId == UserHandle.USER_ALL) { 20345 if (mSettings.removeIntentFilterVerificationLPw(packageName, 20346 sUserManager.getUserIds())) { 20347 for (int oneUserId : sUserManager.getUserIds()) { 20348 scheduleWritePackageRestrictionsLocked(oneUserId); 20349 } 20350 } 20351 } else { 20352 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 20353 scheduleWritePackageRestrictionsLocked(userId); 20354 } 20355 } 20356 } 20357 20358 /** Clears state for all users, and touches intent filter verification policy */ 20359 void clearDefaultBrowserIfNeeded(String packageName) { 20360 for (int oneUserId : sUserManager.getUserIds()) { 20361 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 20362 } 20363 } 20364 20365 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 20366 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 20367 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 20368 if (packageName.equals(defaultBrowserPackageName)) { 20369 setDefaultBrowserPackageName(null, userId); 20370 } 20371 } 20372 } 20373 20374 @Override 20375 public void resetApplicationPreferences(int userId) { 20376 mContext.enforceCallingOrSelfPermission( 20377 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20378 final long identity = Binder.clearCallingIdentity(); 20379 // writer 20380 try { 20381 synchronized (mPackages) { 20382 clearPackagePreferredActivitiesLPw(null, userId); 20383 mSettings.applyDefaultPreferredAppsLPw(this, userId); 20384 // TODO: We have to reset the default SMS and Phone. This requires 20385 // significant refactoring to keep all default apps in the package 20386 // manager (cleaner but more work) or have the services provide 20387 // callbacks to the package manager to request a default app reset. 20388 applyFactoryDefaultBrowserLPw(userId); 20389 clearIntentFilterVerificationsLPw(userId); 20390 primeDomainVerificationsLPw(userId); 20391 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 20392 scheduleWritePackageRestrictionsLocked(userId); 20393 } 20394 resetNetworkPolicies(userId); 20395 } finally { 20396 Binder.restoreCallingIdentity(identity); 20397 } 20398 } 20399 20400 @Override 20401 public int getPreferredActivities(List<IntentFilter> outFilters, 20402 List<ComponentName> outActivities, String packageName) { 20403 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20404 return 0; 20405 } 20406 int num = 0; 20407 final int userId = UserHandle.getCallingUserId(); 20408 // reader 20409 synchronized (mPackages) { 20410 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 20411 if (pir != null) { 20412 final Iterator<PreferredActivity> it = pir.filterIterator(); 20413 while (it.hasNext()) { 20414 final PreferredActivity pa = it.next(); 20415 if (packageName == null 20416 || (pa.mPref.mComponent.getPackageName().equals(packageName) 20417 && pa.mPref.mAlways)) { 20418 if (outFilters != null) { 20419 outFilters.add(new IntentFilter(pa)); 20420 } 20421 if (outActivities != null) { 20422 outActivities.add(pa.mPref.mComponent); 20423 } 20424 } 20425 } 20426 } 20427 } 20428 20429 return num; 20430 } 20431 20432 @Override 20433 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 20434 int userId) { 20435 int callingUid = Binder.getCallingUid(); 20436 if (callingUid != Process.SYSTEM_UID) { 20437 throw new SecurityException( 20438 "addPersistentPreferredActivity can only be run by the system"); 20439 } 20440 if (filter.countActions() == 0) { 20441 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 20442 return; 20443 } 20444 synchronized (mPackages) { 20445 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 20446 ":"); 20447 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20448 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 20449 new PersistentPreferredActivity(filter, activity)); 20450 scheduleWritePackageRestrictionsLocked(userId); 20451 postPreferredActivityChangedBroadcast(userId); 20452 } 20453 } 20454 20455 @Override 20456 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 20457 int callingUid = Binder.getCallingUid(); 20458 if (callingUid != Process.SYSTEM_UID) { 20459 throw new SecurityException( 20460 "clearPackagePersistentPreferredActivities can only be run by the system"); 20461 } 20462 ArrayList<PersistentPreferredActivity> removed = null; 20463 boolean changed = false; 20464 synchronized (mPackages) { 20465 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 20466 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 20467 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 20468 .valueAt(i); 20469 if (userId != thisUserId) { 20470 continue; 20471 } 20472 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 20473 while (it.hasNext()) { 20474 PersistentPreferredActivity ppa = it.next(); 20475 // Mark entry for removal only if it matches the package name. 20476 if (ppa.mComponent.getPackageName().equals(packageName)) { 20477 if (removed == null) { 20478 removed = new ArrayList<PersistentPreferredActivity>(); 20479 } 20480 removed.add(ppa); 20481 } 20482 } 20483 if (removed != null) { 20484 for (int j=0; j<removed.size(); j++) { 20485 PersistentPreferredActivity ppa = removed.get(j); 20486 ppir.removeFilter(ppa); 20487 } 20488 changed = true; 20489 } 20490 } 20491 20492 if (changed) { 20493 scheduleWritePackageRestrictionsLocked(userId); 20494 postPreferredActivityChangedBroadcast(userId); 20495 } 20496 } 20497 } 20498 20499 /** 20500 * Common machinery for picking apart a restored XML blob and passing 20501 * it to a caller-supplied functor to be applied to the running system. 20502 */ 20503 private void restoreFromXml(XmlPullParser parser, int userId, 20504 String expectedStartTag, BlobXmlRestorer functor) 20505 throws IOException, XmlPullParserException { 20506 int type; 20507 while ((type = parser.next()) != XmlPullParser.START_TAG 20508 && type != XmlPullParser.END_DOCUMENT) { 20509 } 20510 if (type != XmlPullParser.START_TAG) { 20511 // oops didn't find a start tag?! 20512 if (DEBUG_BACKUP) { 20513 Slog.e(TAG, "Didn't find start tag during restore"); 20514 } 20515 return; 20516 } 20517 Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 20518 // this is supposed to be TAG_PREFERRED_BACKUP 20519 if (!expectedStartTag.equals(parser.getName())) { 20520 if (DEBUG_BACKUP) { 20521 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 20522 } 20523 return; 20524 } 20525 20526 // skip interfering stuff, then we're aligned with the backing implementation 20527 while ((type = parser.next()) == XmlPullParser.TEXT) { } 20528 Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 20529 functor.apply(parser, userId); 20530 } 20531 20532 private interface BlobXmlRestorer { 20533 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 20534 } 20535 20536 /** 20537 * Non-Binder method, support for the backup/restore mechanism: write the 20538 * full set of preferred activities in its canonical XML format. Returns the 20539 * XML output as a byte array, or null if there is none. 20540 */ 20541 @Override 20542 public byte[] getPreferredActivityBackup(int userId) { 20543 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20544 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 20545 } 20546 20547 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20548 try { 20549 final XmlSerializer serializer = new FastXmlSerializer(); 20550 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20551 serializer.startDocument(null, true); 20552 serializer.startTag(null, TAG_PREFERRED_BACKUP); 20553 20554 synchronized (mPackages) { 20555 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 20556 } 20557 20558 serializer.endTag(null, TAG_PREFERRED_BACKUP); 20559 serializer.endDocument(); 20560 serializer.flush(); 20561 } catch (Exception e) { 20562 if (DEBUG_BACKUP) { 20563 Slog.e(TAG, "Unable to write preferred activities for backup", e); 20564 } 20565 return null; 20566 } 20567 20568 return dataStream.toByteArray(); 20569 } 20570 20571 @Override 20572 public void restorePreferredActivities(byte[] backup, int userId) { 20573 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20574 throw new SecurityException("Only the system may call restorePreferredActivities()"); 20575 } 20576 20577 try { 20578 final XmlPullParser parser = Xml.newPullParser(); 20579 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20580 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 20581 new BlobXmlRestorer() { 20582 @Override 20583 public void apply(XmlPullParser parser, int userId) 20584 throws XmlPullParserException, IOException { 20585 synchronized (mPackages) { 20586 mSettings.readPreferredActivitiesLPw(parser, userId); 20587 } 20588 } 20589 } ); 20590 } catch (Exception e) { 20591 if (DEBUG_BACKUP) { 20592 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20593 } 20594 } 20595 } 20596 20597 /** 20598 * Non-Binder method, support for the backup/restore mechanism: write the 20599 * default browser (etc) settings in its canonical XML format. Returns the default 20600 * browser XML representation as a byte array, or null if there is none. 20601 */ 20602 @Override 20603 public byte[] getDefaultAppsBackup(int userId) { 20604 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20605 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 20606 } 20607 20608 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20609 try { 20610 final XmlSerializer serializer = new FastXmlSerializer(); 20611 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20612 serializer.startDocument(null, true); 20613 serializer.startTag(null, TAG_DEFAULT_APPS); 20614 20615 synchronized (mPackages) { 20616 mSettings.writeDefaultAppsLPr(serializer, userId); 20617 } 20618 20619 serializer.endTag(null, TAG_DEFAULT_APPS); 20620 serializer.endDocument(); 20621 serializer.flush(); 20622 } catch (Exception e) { 20623 if (DEBUG_BACKUP) { 20624 Slog.e(TAG, "Unable to write default apps for backup", e); 20625 } 20626 return null; 20627 } 20628 20629 return dataStream.toByteArray(); 20630 } 20631 20632 @Override 20633 public void restoreDefaultApps(byte[] backup, int userId) { 20634 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20635 throw new SecurityException("Only the system may call restoreDefaultApps()"); 20636 } 20637 20638 try { 20639 final XmlPullParser parser = Xml.newPullParser(); 20640 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20641 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 20642 new BlobXmlRestorer() { 20643 @Override 20644 public void apply(XmlPullParser parser, int userId) 20645 throws XmlPullParserException, IOException { 20646 synchronized (mPackages) { 20647 mSettings.readDefaultAppsLPw(parser, userId); 20648 } 20649 } 20650 } ); 20651 } catch (Exception e) { 20652 if (DEBUG_BACKUP) { 20653 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 20654 } 20655 } 20656 } 20657 20658 @Override 20659 public byte[] getIntentFilterVerificationBackup(int userId) { 20660 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20661 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 20662 } 20663 20664 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20665 try { 20666 final XmlSerializer serializer = new FastXmlSerializer(); 20667 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20668 serializer.startDocument(null, true); 20669 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 20670 20671 synchronized (mPackages) { 20672 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 20673 } 20674 20675 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 20676 serializer.endDocument(); 20677 serializer.flush(); 20678 } catch (Exception e) { 20679 if (DEBUG_BACKUP) { 20680 Slog.e(TAG, "Unable to write default apps for backup", e); 20681 } 20682 return null; 20683 } 20684 20685 return dataStream.toByteArray(); 20686 } 20687 20688 @Override 20689 public void restoreIntentFilterVerification(byte[] backup, int userId) { 20690 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20691 throw new SecurityException("Only the system may call restorePreferredActivities()"); 20692 } 20693 20694 try { 20695 final XmlPullParser parser = Xml.newPullParser(); 20696 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20697 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 20698 new BlobXmlRestorer() { 20699 @Override 20700 public void apply(XmlPullParser parser, int userId) 20701 throws XmlPullParserException, IOException { 20702 synchronized (mPackages) { 20703 mSettings.readAllDomainVerificationsLPr(parser, userId); 20704 mSettings.writeLPr(); 20705 } 20706 } 20707 } ); 20708 } catch (Exception e) { 20709 if (DEBUG_BACKUP) { 20710 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20711 } 20712 } 20713 } 20714 20715 @Override 20716 public byte[] getPermissionGrantBackup(int userId) { 20717 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20718 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 20719 } 20720 20721 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20722 try { 20723 final XmlSerializer serializer = new FastXmlSerializer(); 20724 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20725 serializer.startDocument(null, true); 20726 serializer.startTag(null, TAG_PERMISSION_BACKUP); 20727 20728 synchronized (mPackages) { 20729 serializeRuntimePermissionGrantsLPr(serializer, userId); 20730 } 20731 20732 serializer.endTag(null, TAG_PERMISSION_BACKUP); 20733 serializer.endDocument(); 20734 serializer.flush(); 20735 } catch (Exception e) { 20736 if (DEBUG_BACKUP) { 20737 Slog.e(TAG, "Unable to write default apps for backup", e); 20738 } 20739 return null; 20740 } 20741 20742 return dataStream.toByteArray(); 20743 } 20744 20745 @Override 20746 public void restorePermissionGrants(byte[] backup, int userId) { 20747 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20748 throw new SecurityException("Only the system may call restorePermissionGrants()"); 20749 } 20750 20751 try { 20752 final XmlPullParser parser = Xml.newPullParser(); 20753 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20754 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 20755 new BlobXmlRestorer() { 20756 @Override 20757 public void apply(XmlPullParser parser, int userId) 20758 throws XmlPullParserException, IOException { 20759 synchronized (mPackages) { 20760 processRestoredPermissionGrantsLPr(parser, userId); 20761 } 20762 } 20763 } ); 20764 } catch (Exception e) { 20765 if (DEBUG_BACKUP) { 20766 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20767 } 20768 } 20769 } 20770 20771 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 20772 throws IOException { 20773 serializer.startTag(null, TAG_ALL_GRANTS); 20774 20775 final int N = mSettings.mPackages.size(); 20776 for (int i = 0; i < N; i++) { 20777 final PackageSetting ps = mSettings.mPackages.valueAt(i); 20778 boolean pkgGrantsKnown = false; 20779 20780 PermissionsState packagePerms = ps.getPermissionsState(); 20781 20782 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 20783 final int grantFlags = state.getFlags(); 20784 // only look at grants that are not system/policy fixed 20785 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 20786 final boolean isGranted = state.isGranted(); 20787 // And only back up the user-twiddled state bits 20788 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 20789 final String packageName = mSettings.mPackages.keyAt(i); 20790 if (!pkgGrantsKnown) { 20791 serializer.startTag(null, TAG_GRANT); 20792 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 20793 pkgGrantsKnown = true; 20794 } 20795 20796 final boolean userSet = 20797 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 20798 final boolean userFixed = 20799 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 20800 final boolean revoke = 20801 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 20802 20803 serializer.startTag(null, TAG_PERMISSION); 20804 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 20805 if (isGranted) { 20806 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 20807 } 20808 if (userSet) { 20809 serializer.attribute(null, ATTR_USER_SET, "true"); 20810 } 20811 if (userFixed) { 20812 serializer.attribute(null, ATTR_USER_FIXED, "true"); 20813 } 20814 if (revoke) { 20815 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 20816 } 20817 serializer.endTag(null, TAG_PERMISSION); 20818 } 20819 } 20820 } 20821 20822 if (pkgGrantsKnown) { 20823 serializer.endTag(null, TAG_GRANT); 20824 } 20825 } 20826 20827 serializer.endTag(null, TAG_ALL_GRANTS); 20828 } 20829 20830 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 20831 throws XmlPullParserException, IOException { 20832 String pkgName = null; 20833 int outerDepth = parser.getDepth(); 20834 int type; 20835 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 20836 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 20837 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 20838 continue; 20839 } 20840 20841 final String tagName = parser.getName(); 20842 if (tagName.equals(TAG_GRANT)) { 20843 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 20844 if (DEBUG_BACKUP) { 20845 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 20846 } 20847 } else if (tagName.equals(TAG_PERMISSION)) { 20848 20849 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 20850 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 20851 20852 int newFlagSet = 0; 20853 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 20854 newFlagSet |= FLAG_PERMISSION_USER_SET; 20855 } 20856 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 20857 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 20858 } 20859 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 20860 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 20861 } 20862 if (DEBUG_BACKUP) { 20863 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 20864 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 20865 } 20866 final PackageSetting ps = mSettings.mPackages.get(pkgName); 20867 if (ps != null) { 20868 // Already installed so we apply the grant immediately 20869 if (DEBUG_BACKUP) { 20870 Slog.v(TAG, " + already installed; applying"); 20871 } 20872 PermissionsState perms = ps.getPermissionsState(); 20873 BasePermission bp = mSettings.mPermissions.get(permName); 20874 if (bp != null) { 20875 if (isGranted) { 20876 perms.grantRuntimePermission(bp, userId); 20877 } 20878 if (newFlagSet != 0) { 20879 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 20880 } 20881 } 20882 } else { 20883 // Need to wait for post-restore install to apply the grant 20884 if (DEBUG_BACKUP) { 20885 Slog.v(TAG, " - not yet installed; saving for later"); 20886 } 20887 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 20888 isGranted, newFlagSet, userId); 20889 } 20890 } else { 20891 PackageManagerService.reportSettingsProblem(Log.WARN, 20892 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 20893 XmlUtils.skipCurrentTag(parser); 20894 } 20895 } 20896 20897 scheduleWriteSettingsLocked(); 20898 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 20899 } 20900 20901 @Override 20902 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20903 int sourceUserId, int targetUserId, int flags) { 20904 mContext.enforceCallingOrSelfPermission( 20905 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20906 int callingUid = Binder.getCallingUid(); 20907 enforceOwnerRights(ownerPackage, callingUid); 20908 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20909 if (intentFilter.countActions() == 0) { 20910 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20911 return; 20912 } 20913 synchronized (mPackages) { 20914 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20915 ownerPackage, targetUserId, flags); 20916 CrossProfileIntentResolver resolver = 20917 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20918 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20919 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20920 if (existing != null) { 20921 int size = existing.size(); 20922 for (int i = 0; i < size; i++) { 20923 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20924 return; 20925 } 20926 } 20927 } 20928 resolver.addFilter(newFilter); 20929 scheduleWritePackageRestrictionsLocked(sourceUserId); 20930 } 20931 } 20932 20933 @Override 20934 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20935 mContext.enforceCallingOrSelfPermission( 20936 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20937 final int callingUid = Binder.getCallingUid(); 20938 enforceOwnerRights(ownerPackage, callingUid); 20939 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20940 synchronized (mPackages) { 20941 CrossProfileIntentResolver resolver = 20942 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20943 ArraySet<CrossProfileIntentFilter> set = 20944 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 20945 for (CrossProfileIntentFilter filter : set) { 20946 if (filter.getOwnerPackage().equals(ownerPackage)) { 20947 resolver.removeFilter(filter); 20948 } 20949 } 20950 scheduleWritePackageRestrictionsLocked(sourceUserId); 20951 } 20952 } 20953 20954 // Enforcing that callingUid is owning pkg on userId 20955 private void enforceOwnerRights(String pkg, int callingUid) { 20956 // The system owns everything. 20957 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20958 return; 20959 } 20960 final int callingUserId = UserHandle.getUserId(callingUid); 20961 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20962 if (pi == null) { 20963 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20964 + callingUserId); 20965 } 20966 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20967 throw new SecurityException("Calling uid " + callingUid 20968 + " does not own package " + pkg); 20969 } 20970 } 20971 20972 @Override 20973 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20974 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20975 return null; 20976 } 20977 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20978 } 20979 20980 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 20981 UserManagerService ums = UserManagerService.getInstance(); 20982 if (ums != null) { 20983 final UserInfo parent = ums.getProfileParent(userId); 20984 final int launcherUid = (parent != null) ? parent.id : userId; 20985 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 20986 if (launcherComponent != null) { 20987 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20988 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20989 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20990 .setPackage(launcherComponent.getPackageName()); 20991 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 20992 } 20993 } 20994 } 20995 20996 /** 20997 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20998 * then reports the most likely home activity or null if there are more than one. 20999 */ 21000 private ComponentName getDefaultHomeActivity(int userId) { 21001 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 21002 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 21003 if (cn != null) { 21004 return cn; 21005 } 21006 21007 // Find the launcher with the highest priority and return that component if there are no 21008 // other home activity with the same priority. 21009 int lastPriority = Integer.MIN_VALUE; 21010 ComponentName lastComponent = null; 21011 final int size = allHomeCandidates.size(); 21012 for (int i = 0; i < size; i++) { 21013 final ResolveInfo ri = allHomeCandidates.get(i); 21014 if (ri.priority > lastPriority) { 21015 lastComponent = ri.activityInfo.getComponentName(); 21016 lastPriority = ri.priority; 21017 } else if (ri.priority == lastPriority) { 21018 // Two components found with same priority. 21019 lastComponent = null; 21020 } 21021 } 21022 return lastComponent; 21023 } 21024 21025 private Intent getHomeIntent() { 21026 Intent intent = new Intent(Intent.ACTION_MAIN); 21027 intent.addCategory(Intent.CATEGORY_HOME); 21028 intent.addCategory(Intent.CATEGORY_DEFAULT); 21029 return intent; 21030 } 21031 21032 private IntentFilter getHomeFilter() { 21033 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 21034 filter.addCategory(Intent.CATEGORY_HOME); 21035 filter.addCategory(Intent.CATEGORY_DEFAULT); 21036 return filter; 21037 } 21038 21039 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21040 int userId) { 21041 Intent intent = getHomeIntent(); 21042 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 21043 PackageManager.GET_META_DATA, userId); 21044 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 21045 true, false, false, userId); 21046 21047 allHomeCandidates.clear(); 21048 if (list != null) { 21049 for (ResolveInfo ri : list) { 21050 allHomeCandidates.add(ri); 21051 } 21052 } 21053 return (preferred == null || preferred.activityInfo == null) 21054 ? null 21055 : new ComponentName(preferred.activityInfo.packageName, 21056 preferred.activityInfo.name); 21057 } 21058 21059 @Override 21060 public void setHomeActivity(ComponentName comp, int userId) { 21061 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 21062 return; 21063 } 21064 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 21065 getHomeActivitiesAsUser(homeActivities, userId); 21066 21067 boolean found = false; 21068 21069 final int size = homeActivities.size(); 21070 final ComponentName[] set = new ComponentName[size]; 21071 for (int i = 0; i < size; i++) { 21072 final ResolveInfo candidate = homeActivities.get(i); 21073 final ActivityInfo info = candidate.activityInfo; 21074 final ComponentName activityName = new ComponentName(info.packageName, info.name); 21075 set[i] = activityName; 21076 if (!found && activityName.equals(comp)) { 21077 found = true; 21078 } 21079 } 21080 if (!found) { 21081 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 21082 + userId); 21083 } 21084 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 21085 set, comp, userId); 21086 } 21087 21088 private @Nullable String getSetupWizardPackageName() { 21089 final Intent intent = new Intent(Intent.ACTION_MAIN); 21090 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 21091 21092 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 21093 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 21094 | MATCH_DISABLED_COMPONENTS, 21095 UserHandle.myUserId()); 21096 if (matches.size() == 1) { 21097 return matches.get(0).getComponentInfo().packageName; 21098 } else { 21099 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 21100 + ": matches=" + matches); 21101 return null; 21102 } 21103 } 21104 21105 private @Nullable String getStorageManagerPackageName() { 21106 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 21107 21108 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 21109 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 21110 | MATCH_DISABLED_COMPONENTS, 21111 UserHandle.myUserId()); 21112 if (matches.size() == 1) { 21113 return matches.get(0).getComponentInfo().packageName; 21114 } else { 21115 Slog.e(TAG, "There should probably be exactly one storage manager; found " 21116 + matches.size() + ": matches=" + matches); 21117 return null; 21118 } 21119 } 21120 21121 @Override 21122 public void setApplicationEnabledSetting(String appPackageName, 21123 int newState, int flags, int userId, String callingPackage) { 21124 if (!sUserManager.exists(userId)) return; 21125 if (callingPackage == null) { 21126 callingPackage = Integer.toString(Binder.getCallingUid()); 21127 } 21128 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 21129 } 21130 21131 @Override 21132 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 21133 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 21134 synchronized (mPackages) { 21135 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 21136 if (pkgSetting != null) { 21137 pkgSetting.setUpdateAvailable(updateAvailable); 21138 } 21139 } 21140 } 21141 21142 @Override 21143 public void setComponentEnabledSetting(ComponentName componentName, 21144 int newState, int flags, int userId) { 21145 if (!sUserManager.exists(userId)) return; 21146 setEnabledSetting(componentName.getPackageName(), 21147 componentName.getClassName(), newState, flags, userId, null); 21148 } 21149 21150 private void setEnabledSetting(final String packageName, String className, int newState, 21151 final int flags, int userId, String callingPackage) { 21152 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 21153 || newState == COMPONENT_ENABLED_STATE_ENABLED 21154 || newState == COMPONENT_ENABLED_STATE_DISABLED 21155 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 21156 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 21157 throw new IllegalArgumentException("Invalid new component state: " 21158 + newState); 21159 } 21160 PackageSetting pkgSetting; 21161 final int callingUid = Binder.getCallingUid(); 21162 final int permission; 21163 if (callingUid == Process.SYSTEM_UID) { 21164 permission = PackageManager.PERMISSION_GRANTED; 21165 } else { 21166 permission = mContext.checkCallingOrSelfPermission( 21167 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 21168 } 21169 enforceCrossUserPermission(callingUid, userId, 21170 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 21171 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 21172 boolean sendNow = false; 21173 boolean isApp = (className == null); 21174 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 21175 String componentName = isApp ? packageName : className; 21176 int packageUid = -1; 21177 ArrayList<String> components; 21178 21179 // reader 21180 synchronized (mPackages) { 21181 pkgSetting = mSettings.mPackages.get(packageName); 21182 if (pkgSetting == null) { 21183 if (!isCallerInstantApp) { 21184 if (className == null) { 21185 throw new IllegalArgumentException("Unknown package: " + packageName); 21186 } 21187 throw new IllegalArgumentException( 21188 "Unknown component: " + packageName + "/" + className); 21189 } else { 21190 // throw SecurityException to prevent leaking package information 21191 throw new SecurityException( 21192 "Attempt to change component state; " 21193 + "pid=" + Binder.getCallingPid() 21194 + ", uid=" + callingUid 21195 + (className == null 21196 ? ", package=" + packageName 21197 : ", component=" + packageName + "/" + className)); 21198 } 21199 } 21200 } 21201 21202 // Limit who can change which apps 21203 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 21204 // Don't allow apps that don't have permission to modify other apps 21205 if (!allowedByPermission 21206 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 21207 throw new SecurityException( 21208 "Attempt to change component state; " 21209 + "pid=" + Binder.getCallingPid() 21210 + ", uid=" + callingUid 21211 + (className == null 21212 ? ", package=" + packageName 21213 : ", component=" + packageName + "/" + className)); 21214 } 21215 // Don't allow changing protected packages. 21216 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 21217 throw new SecurityException("Cannot disable a protected package: " + packageName); 21218 } 21219 } 21220 21221 synchronized (mPackages) { 21222 if (callingUid == Process.SHELL_UID 21223 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 21224 // Shell can only change whole packages between ENABLED and DISABLED_USER states 21225 // unless it is a test package. 21226 int oldState = pkgSetting.getEnabled(userId); 21227 if (className == null 21228 && 21229 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 21230 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 21231 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 21232 && 21233 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 21234 || newState == COMPONENT_ENABLED_STATE_DEFAULT 21235 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 21236 // ok 21237 } else { 21238 throw new SecurityException( 21239 "Shell cannot change component state for " + packageName + "/" 21240 + className + " to " + newState); 21241 } 21242 } 21243 if (className == null) { 21244 // We're dealing with an application/package level state change 21245 if (pkgSetting.getEnabled(userId) == newState) { 21246 // Nothing to do 21247 return; 21248 } 21249 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 21250 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 21251 // Don't care about who enables an app. 21252 callingPackage = null; 21253 } 21254 pkgSetting.setEnabled(newState, userId, callingPackage); 21255 // pkgSetting.pkg.mSetEnabled = newState; 21256 } else { 21257 // We're dealing with a component level state change 21258 // First, verify that this is a valid class name. 21259 PackageParser.Package pkg = pkgSetting.pkg; 21260 if (pkg == null || !pkg.hasComponentClassName(className)) { 21261 if (pkg != null && 21262 pkg.applicationInfo.targetSdkVersion >= 21263 Build.VERSION_CODES.JELLY_BEAN) { 21264 throw new IllegalArgumentException("Component class " + className 21265 + " does not exist in " + packageName); 21266 } else { 21267 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 21268 + className + " does not exist in " + packageName); 21269 } 21270 } 21271 switch (newState) { 21272 case COMPONENT_ENABLED_STATE_ENABLED: 21273 if (!pkgSetting.enableComponentLPw(className, userId)) { 21274 return; 21275 } 21276 break; 21277 case COMPONENT_ENABLED_STATE_DISABLED: 21278 if (!pkgSetting.disableComponentLPw(className, userId)) { 21279 return; 21280 } 21281 break; 21282 case COMPONENT_ENABLED_STATE_DEFAULT: 21283 if (!pkgSetting.restoreComponentLPw(className, userId)) { 21284 return; 21285 } 21286 break; 21287 default: 21288 Slog.e(TAG, "Invalid new component state: " + newState); 21289 return; 21290 } 21291 } 21292 scheduleWritePackageRestrictionsLocked(userId); 21293 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 21294 final long callingId = Binder.clearCallingIdentity(); 21295 try { 21296 updateInstantAppInstallerLocked(packageName); 21297 } finally { 21298 Binder.restoreCallingIdentity(callingId); 21299 } 21300 components = mPendingBroadcasts.get(userId, packageName); 21301 final boolean newPackage = components == null; 21302 if (newPackage) { 21303 components = new ArrayList<String>(); 21304 } 21305 if (!components.contains(componentName)) { 21306 components.add(componentName); 21307 } 21308 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 21309 sendNow = true; 21310 // Purge entry from pending broadcast list if another one exists already 21311 // since we are sending one right away. 21312 mPendingBroadcasts.remove(userId, packageName); 21313 } else { 21314 if (newPackage) { 21315 mPendingBroadcasts.put(userId, packageName, components); 21316 } 21317 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 21318 // Schedule a message 21319 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 21320 } 21321 } 21322 } 21323 21324 long callingId = Binder.clearCallingIdentity(); 21325 try { 21326 if (sendNow) { 21327 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 21328 sendPackageChangedBroadcast(packageName, 21329 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 21330 } 21331 } finally { 21332 Binder.restoreCallingIdentity(callingId); 21333 } 21334 } 21335 21336 @Override 21337 public void flushPackageRestrictionsAsUser(int userId) { 21338 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 21339 return; 21340 } 21341 if (!sUserManager.exists(userId)) { 21342 return; 21343 } 21344 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 21345 false /* checkShell */, "flushPackageRestrictions"); 21346 synchronized (mPackages) { 21347 mSettings.writePackageRestrictionsLPr(userId); 21348 mDirtyUsers.remove(userId); 21349 if (mDirtyUsers.isEmpty()) { 21350 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 21351 } 21352 } 21353 } 21354 21355 private void sendPackageChangedBroadcast(String packageName, 21356 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 21357 if (DEBUG_INSTALL) 21358 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 21359 + componentNames); 21360 Bundle extras = new Bundle(4); 21361 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 21362 String nameList[] = new String[componentNames.size()]; 21363 componentNames.toArray(nameList); 21364 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 21365 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 21366 extras.putInt(Intent.EXTRA_UID, packageUid); 21367 // If this is not reporting a change of the overall package, then only send it 21368 // to registered receivers. We don't want to launch a swath of apps for every 21369 // little component state change. 21370 final int flags = !componentNames.contains(packageName) 21371 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 21372 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 21373 new int[] {UserHandle.getUserId(packageUid)}); 21374 } 21375 21376 @Override 21377 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 21378 if (!sUserManager.exists(userId)) return; 21379 final int callingUid = Binder.getCallingUid(); 21380 if (getInstantAppPackageName(callingUid) != null) { 21381 return; 21382 } 21383 final int permission = mContext.checkCallingOrSelfPermission( 21384 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 21385 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 21386 enforceCrossUserPermission(callingUid, userId, 21387 true /* requireFullPermission */, true /* checkShell */, "stop package"); 21388 // writer 21389 synchronized (mPackages) { 21390 final PackageSetting ps = mSettings.mPackages.get(packageName); 21391 if (!filterAppAccessLPr(ps, callingUid, userId) 21392 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 21393 allowedByPermission, callingUid, userId)) { 21394 scheduleWritePackageRestrictionsLocked(userId); 21395 } 21396 } 21397 } 21398 21399 @Override 21400 public String getInstallerPackageName(String packageName) { 21401 final int callingUid = Binder.getCallingUid(); 21402 if (getInstantAppPackageName(callingUid) != null) { 21403 return null; 21404 } 21405 // reader 21406 synchronized (mPackages) { 21407 final PackageSetting ps = mSettings.mPackages.get(packageName); 21408 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 21409 return null; 21410 } 21411 return mSettings.getInstallerPackageNameLPr(packageName); 21412 } 21413 } 21414 21415 public boolean isOrphaned(String packageName) { 21416 // reader 21417 synchronized (mPackages) { 21418 return mSettings.isOrphaned(packageName); 21419 } 21420 } 21421 21422 @Override 21423 public int getApplicationEnabledSetting(String packageName, int userId) { 21424 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 21425 int callingUid = Binder.getCallingUid(); 21426 enforceCrossUserPermission(callingUid, userId, 21427 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 21428 // reader 21429 synchronized (mPackages) { 21430 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 21431 return COMPONENT_ENABLED_STATE_DISABLED; 21432 } 21433 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 21434 } 21435 } 21436 21437 @Override 21438 public int getComponentEnabledSetting(ComponentName component, int userId) { 21439 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 21440 int callingUid = Binder.getCallingUid(); 21441 enforceCrossUserPermission(callingUid, userId, 21442 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 21443 synchronized (mPackages) { 21444 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 21445 component, TYPE_UNKNOWN, userId)) { 21446 return COMPONENT_ENABLED_STATE_DISABLED; 21447 } 21448 return mSettings.getComponentEnabledSettingLPr(component, userId); 21449 } 21450 } 21451 21452 @Override 21453 public void enterSafeMode() { 21454 enforceSystemOrRoot("Only the system can request entering safe mode"); 21455 21456 if (!mSystemReady) { 21457 mSafeMode = true; 21458 } 21459 } 21460 21461 @Override 21462 public void systemReady() { 21463 enforceSystemOrRoot("Only the system can claim the system is ready"); 21464 21465 mSystemReady = true; 21466 final ContentResolver resolver = mContext.getContentResolver(); 21467 ContentObserver co = new ContentObserver(mHandler) { 21468 @Override 21469 public void onChange(boolean selfChange) { 21470 mEphemeralAppsDisabled = 21471 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 21472 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 21473 } 21474 }; 21475 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 21476 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 21477 false, co, UserHandle.USER_SYSTEM); 21478 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 21479 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 21480 co.onChange(true); 21481 21482 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 21483 // disabled after already being started. 21484 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 21485 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 21486 21487 // Read the compatibilty setting when the system is ready. 21488 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 21489 mContext.getContentResolver(), 21490 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 21491 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 21492 if (DEBUG_SETTINGS) { 21493 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 21494 } 21495 21496 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 21497 21498 synchronized (mPackages) { 21499 // Verify that all of the preferred activity components actually 21500 // exist. It is possible for applications to be updated and at 21501 // that point remove a previously declared activity component that 21502 // had been set as a preferred activity. We try to clean this up 21503 // the next time we encounter that preferred activity, but it is 21504 // possible for the user flow to never be able to return to that 21505 // situation so here we do a sanity check to make sure we haven't 21506 // left any junk around. 21507 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 21508 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21509 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21510 removed.clear(); 21511 for (PreferredActivity pa : pir.filterSet()) { 21512 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 21513 removed.add(pa); 21514 } 21515 } 21516 if (removed.size() > 0) { 21517 for (int r=0; r<removed.size(); r++) { 21518 PreferredActivity pa = removed.get(r); 21519 Slog.w(TAG, "Removing dangling preferred activity: " 21520 + pa.mPref.mComponent); 21521 pir.removeFilter(pa); 21522 } 21523 mSettings.writePackageRestrictionsLPr( 21524 mSettings.mPreferredActivities.keyAt(i)); 21525 } 21526 } 21527 21528 for (int userId : UserManagerService.getInstance().getUserIds()) { 21529 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 21530 grantPermissionsUserIds = ArrayUtils.appendInt( 21531 grantPermissionsUserIds, userId); 21532 } 21533 } 21534 } 21535 sUserManager.systemReady(); 21536 21537 // If we upgraded grant all default permissions before kicking off. 21538 for (int userId : grantPermissionsUserIds) { 21539 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 21540 } 21541 21542 // If we did not grant default permissions, we preload from this the 21543 // default permission exceptions lazily to ensure we don't hit the 21544 // disk on a new user creation. 21545 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 21546 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 21547 } 21548 21549 // Kick off any messages waiting for system ready 21550 if (mPostSystemReadyMessages != null) { 21551 for (Message msg : mPostSystemReadyMessages) { 21552 msg.sendToTarget(); 21553 } 21554 mPostSystemReadyMessages = null; 21555 } 21556 21557 // Watch for external volumes that come and go over time 21558 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21559 storage.registerListener(mStorageListener); 21560 21561 mInstallerService.systemReady(); 21562 mPackageDexOptimizer.systemReady(); 21563 21564 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 21565 StorageManagerInternal.class); 21566 StorageManagerInternal.addExternalStoragePolicy( 21567 new StorageManagerInternal.ExternalStorageMountPolicy() { 21568 @Override 21569 public int getMountMode(int uid, String packageName) { 21570 if (Process.isIsolated(uid)) { 21571 return Zygote.MOUNT_EXTERNAL_NONE; 21572 } 21573 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 21574 return Zygote.MOUNT_EXTERNAL_DEFAULT; 21575 } 21576 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 21577 return Zygote.MOUNT_EXTERNAL_DEFAULT; 21578 } 21579 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 21580 return Zygote.MOUNT_EXTERNAL_READ; 21581 } 21582 return Zygote.MOUNT_EXTERNAL_WRITE; 21583 } 21584 21585 @Override 21586 public boolean hasExternalStorage(int uid, String packageName) { 21587 return true; 21588 } 21589 }); 21590 21591 // Now that we're mostly running, clean up stale users and apps 21592 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 21593 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 21594 21595 if (mPrivappPermissionsViolations != null) { 21596 Slog.wtf(TAG,"Signature|privileged permissions not in " 21597 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 21598 mPrivappPermissionsViolations = null; 21599 } 21600 } 21601 21602 public void waitForAppDataPrepared() { 21603 if (mPrepareAppDataFuture == null) { 21604 return; 21605 } 21606 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 21607 mPrepareAppDataFuture = null; 21608 } 21609 21610 @Override 21611 public boolean isSafeMode() { 21612 // allow instant applications 21613 return mSafeMode; 21614 } 21615 21616 @Override 21617 public boolean hasSystemUidErrors() { 21618 // allow instant applications 21619 return mHasSystemUidErrors; 21620 } 21621 21622 static String arrayToString(int[] array) { 21623 StringBuffer buf = new StringBuffer(128); 21624 buf.append('['); 21625 if (array != null) { 21626 for (int i=0; i<array.length; i++) { 21627 if (i > 0) buf.append(", "); 21628 buf.append(array[i]); 21629 } 21630 } 21631 buf.append(']'); 21632 return buf.toString(); 21633 } 21634 21635 static class DumpState { 21636 public static final int DUMP_LIBS = 1 << 0; 21637 public static final int DUMP_FEATURES = 1 << 1; 21638 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 21639 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 21640 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 21641 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 21642 public static final int DUMP_PERMISSIONS = 1 << 6; 21643 public static final int DUMP_PACKAGES = 1 << 7; 21644 public static final int DUMP_SHARED_USERS = 1 << 8; 21645 public static final int DUMP_MESSAGES = 1 << 9; 21646 public static final int DUMP_PROVIDERS = 1 << 10; 21647 public static final int DUMP_VERIFIERS = 1 << 11; 21648 public static final int DUMP_PREFERRED = 1 << 12; 21649 public static final int DUMP_PREFERRED_XML = 1 << 13; 21650 public static final int DUMP_KEYSETS = 1 << 14; 21651 public static final int DUMP_VERSION = 1 << 15; 21652 public static final int DUMP_INSTALLS = 1 << 16; 21653 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 21654 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 21655 public static final int DUMP_FROZEN = 1 << 19; 21656 public static final int DUMP_DEXOPT = 1 << 20; 21657 public static final int DUMP_COMPILER_STATS = 1 << 21; 21658 public static final int DUMP_CHANGES = 1 << 22; 21659 21660 public static final int OPTION_SHOW_FILTERS = 1 << 0; 21661 21662 private int mTypes; 21663 21664 private int mOptions; 21665 21666 private boolean mTitlePrinted; 21667 21668 private SharedUserSetting mSharedUser; 21669 21670 public boolean isDumping(int type) { 21671 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 21672 return true; 21673 } 21674 21675 return (mTypes & type) != 0; 21676 } 21677 21678 public void setDump(int type) { 21679 mTypes |= type; 21680 } 21681 21682 public boolean isOptionEnabled(int option) { 21683 return (mOptions & option) != 0; 21684 } 21685 21686 public void setOptionEnabled(int option) { 21687 mOptions |= option; 21688 } 21689 21690 public boolean onTitlePrinted() { 21691 final boolean printed = mTitlePrinted; 21692 mTitlePrinted = true; 21693 return printed; 21694 } 21695 21696 public boolean getTitlePrinted() { 21697 return mTitlePrinted; 21698 } 21699 21700 public void setTitlePrinted(boolean enabled) { 21701 mTitlePrinted = enabled; 21702 } 21703 21704 public SharedUserSetting getSharedUser() { 21705 return mSharedUser; 21706 } 21707 21708 public void setSharedUser(SharedUserSetting user) { 21709 mSharedUser = user; 21710 } 21711 } 21712 21713 @Override 21714 public void onShellCommand(FileDescriptor in, FileDescriptor out, 21715 FileDescriptor err, String[] args, ShellCallback callback, 21716 ResultReceiver resultReceiver) { 21717 (new PackageManagerShellCommand(this)).exec( 21718 this, in, out, err, args, callback, resultReceiver); 21719 } 21720 21721 @Override 21722 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 21723 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 21724 21725 DumpState dumpState = new DumpState(); 21726 boolean fullPreferred = false; 21727 boolean checkin = false; 21728 21729 String packageName = null; 21730 ArraySet<String> permissionNames = null; 21731 21732 int opti = 0; 21733 while (opti < args.length) { 21734 String opt = args[opti]; 21735 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 21736 break; 21737 } 21738 opti++; 21739 21740 if ("-a".equals(opt)) { 21741 // Right now we only know how to print all. 21742 } else if ("-h".equals(opt)) { 21743 pw.println("Package manager dump options:"); 21744 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 21745 pw.println(" --checkin: dump for a checkin"); 21746 pw.println(" -f: print details of intent filters"); 21747 pw.println(" -h: print this help"); 21748 pw.println(" cmd may be one of:"); 21749 pw.println(" l[ibraries]: list known shared libraries"); 21750 pw.println(" f[eatures]: list device features"); 21751 pw.println(" k[eysets]: print known keysets"); 21752 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 21753 pw.println(" perm[issions]: dump permissions"); 21754 pw.println(" permission [name ...]: dump declaration and use of given permission"); 21755 pw.println(" pref[erred]: print preferred package settings"); 21756 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 21757 pw.println(" prov[iders]: dump content providers"); 21758 pw.println(" p[ackages]: dump installed packages"); 21759 pw.println(" s[hared-users]: dump shared user IDs"); 21760 pw.println(" m[essages]: print collected runtime messages"); 21761 pw.println(" v[erifiers]: print package verifier info"); 21762 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 21763 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 21764 pw.println(" version: print database version info"); 21765 pw.println(" write: write current settings now"); 21766 pw.println(" installs: details about install sessions"); 21767 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 21768 pw.println(" dexopt: dump dexopt state"); 21769 pw.println(" compiler-stats: dump compiler statistics"); 21770 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 21771 pw.println(" <package.name>: info about given package"); 21772 return; 21773 } else if ("--checkin".equals(opt)) { 21774 checkin = true; 21775 } else if ("-f".equals(opt)) { 21776 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21777 } else if ("--proto".equals(opt)) { 21778 dumpProto(fd); 21779 return; 21780 } else { 21781 pw.println("Unknown argument: " + opt + "; use -h for help"); 21782 } 21783 } 21784 21785 // Is the caller requesting to dump a particular piece of data? 21786 if (opti < args.length) { 21787 String cmd = args[opti]; 21788 opti++; 21789 // Is this a package name? 21790 if ("android".equals(cmd) || cmd.contains(".")) { 21791 packageName = cmd; 21792 // When dumping a single package, we always dump all of its 21793 // filter information since the amount of data will be reasonable. 21794 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21795 } else if ("check-permission".equals(cmd)) { 21796 if (opti >= args.length) { 21797 pw.println("Error: check-permission missing permission argument"); 21798 return; 21799 } 21800 String perm = args[opti]; 21801 opti++; 21802 if (opti >= args.length) { 21803 pw.println("Error: check-permission missing package argument"); 21804 return; 21805 } 21806 21807 String pkg = args[opti]; 21808 opti++; 21809 int user = UserHandle.getUserId(Binder.getCallingUid()); 21810 if (opti < args.length) { 21811 try { 21812 user = Integer.parseInt(args[opti]); 21813 } catch (NumberFormatException e) { 21814 pw.println("Error: check-permission user argument is not a number: " 21815 + args[opti]); 21816 return; 21817 } 21818 } 21819 21820 // Normalize package name to handle renamed packages and static libs 21821 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 21822 21823 pw.println(checkPermission(perm, pkg, user)); 21824 return; 21825 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 21826 dumpState.setDump(DumpState.DUMP_LIBS); 21827 } else if ("f".equals(cmd) || "features".equals(cmd)) { 21828 dumpState.setDump(DumpState.DUMP_FEATURES); 21829 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 21830 if (opti >= args.length) { 21831 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 21832 | DumpState.DUMP_SERVICE_RESOLVERS 21833 | DumpState.DUMP_RECEIVER_RESOLVERS 21834 | DumpState.DUMP_CONTENT_RESOLVERS); 21835 } else { 21836 while (opti < args.length) { 21837 String name = args[opti]; 21838 if ("a".equals(name) || "activity".equals(name)) { 21839 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 21840 } else if ("s".equals(name) || "service".equals(name)) { 21841 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 21842 } else if ("r".equals(name) || "receiver".equals(name)) { 21843 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 21844 } else if ("c".equals(name) || "content".equals(name)) { 21845 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 21846 } else { 21847 pw.println("Error: unknown resolver table type: " + name); 21848 return; 21849 } 21850 opti++; 21851 } 21852 } 21853 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 21854 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 21855 } else if ("permission".equals(cmd)) { 21856 if (opti >= args.length) { 21857 pw.println("Error: permission requires permission name"); 21858 return; 21859 } 21860 permissionNames = new ArraySet<>(); 21861 while (opti < args.length) { 21862 permissionNames.add(args[opti]); 21863 opti++; 21864 } 21865 dumpState.setDump(DumpState.DUMP_PERMISSIONS 21866 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 21867 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 21868 dumpState.setDump(DumpState.DUMP_PREFERRED); 21869 } else if ("preferred-xml".equals(cmd)) { 21870 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 21871 if (opti < args.length && "--full".equals(args[opti])) { 21872 fullPreferred = true; 21873 opti++; 21874 } 21875 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 21876 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 21877 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 21878 dumpState.setDump(DumpState.DUMP_PACKAGES); 21879 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 21880 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 21881 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 21882 dumpState.setDump(DumpState.DUMP_PROVIDERS); 21883 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 21884 dumpState.setDump(DumpState.DUMP_MESSAGES); 21885 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 21886 dumpState.setDump(DumpState.DUMP_VERIFIERS); 21887 } else if ("i".equals(cmd) || "ifv".equals(cmd) 21888 || "intent-filter-verifiers".equals(cmd)) { 21889 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 21890 } else if ("version".equals(cmd)) { 21891 dumpState.setDump(DumpState.DUMP_VERSION); 21892 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 21893 dumpState.setDump(DumpState.DUMP_KEYSETS); 21894 } else if ("installs".equals(cmd)) { 21895 dumpState.setDump(DumpState.DUMP_INSTALLS); 21896 } else if ("frozen".equals(cmd)) { 21897 dumpState.setDump(DumpState.DUMP_FROZEN); 21898 } else if ("dexopt".equals(cmd)) { 21899 dumpState.setDump(DumpState.DUMP_DEXOPT); 21900 } else if ("compiler-stats".equals(cmd)) { 21901 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 21902 } else if ("changes".equals(cmd)) { 21903 dumpState.setDump(DumpState.DUMP_CHANGES); 21904 } else if ("write".equals(cmd)) { 21905 synchronized (mPackages) { 21906 mSettings.writeLPr(); 21907 pw.println("Settings written."); 21908 return; 21909 } 21910 } 21911 } 21912 21913 if (checkin) { 21914 pw.println("vers,1"); 21915 } 21916 21917 // reader 21918 synchronized (mPackages) { 21919 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 21920 if (!checkin) { 21921 if (dumpState.onTitlePrinted()) 21922 pw.println(); 21923 pw.println("Database versions:"); 21924 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 21925 } 21926 } 21927 21928 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 21929 if (!checkin) { 21930 if (dumpState.onTitlePrinted()) 21931 pw.println(); 21932 pw.println("Verifiers:"); 21933 pw.print(" Required: "); 21934 pw.print(mRequiredVerifierPackage); 21935 pw.print(" (uid="); 21936 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21937 UserHandle.USER_SYSTEM)); 21938 pw.println(")"); 21939 } else if (mRequiredVerifierPackage != null) { 21940 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 21941 pw.print(","); 21942 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21943 UserHandle.USER_SYSTEM)); 21944 } 21945 } 21946 21947 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 21948 packageName == null) { 21949 if (mIntentFilterVerifierComponent != null) { 21950 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21951 if (!checkin) { 21952 if (dumpState.onTitlePrinted()) 21953 pw.println(); 21954 pw.println("Intent Filter Verifier:"); 21955 pw.print(" Using: "); 21956 pw.print(verifierPackageName); 21957 pw.print(" (uid="); 21958 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21959 UserHandle.USER_SYSTEM)); 21960 pw.println(")"); 21961 } else if (verifierPackageName != null) { 21962 pw.print("ifv,"); pw.print(verifierPackageName); 21963 pw.print(","); 21964 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21965 UserHandle.USER_SYSTEM)); 21966 } 21967 } else { 21968 pw.println(); 21969 pw.println("No Intent Filter Verifier available!"); 21970 } 21971 } 21972 21973 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21974 boolean printedHeader = false; 21975 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21976 while (it.hasNext()) { 21977 String libName = it.next(); 21978 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21979 if (versionedLib == null) { 21980 continue; 21981 } 21982 final int versionCount = versionedLib.size(); 21983 for (int i = 0; i < versionCount; i++) { 21984 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21985 if (!checkin) { 21986 if (!printedHeader) { 21987 if (dumpState.onTitlePrinted()) 21988 pw.println(); 21989 pw.println("Libraries:"); 21990 printedHeader = true; 21991 } 21992 pw.print(" "); 21993 } else { 21994 pw.print("lib,"); 21995 } 21996 pw.print(libEntry.info.getName()); 21997 if (libEntry.info.isStatic()) { 21998 pw.print(" version=" + libEntry.info.getVersion()); 21999 } 22000 if (!checkin) { 22001 pw.print(" -> "); 22002 } 22003 if (libEntry.path != null) { 22004 pw.print(" (jar) "); 22005 pw.print(libEntry.path); 22006 } else { 22007 pw.print(" (apk) "); 22008 pw.print(libEntry.apk); 22009 } 22010 pw.println(); 22011 } 22012 } 22013 } 22014 22015 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 22016 if (dumpState.onTitlePrinted()) 22017 pw.println(); 22018 if (!checkin) { 22019 pw.println("Features:"); 22020 } 22021 22022 synchronized (mAvailableFeatures) { 22023 for (FeatureInfo feat : mAvailableFeatures.values()) { 22024 if (checkin) { 22025 pw.print("feat,"); 22026 pw.print(feat.name); 22027 pw.print(","); 22028 pw.println(feat.version); 22029 } else { 22030 pw.print(" "); 22031 pw.print(feat.name); 22032 if (feat.version > 0) { 22033 pw.print(" version="); 22034 pw.print(feat.version); 22035 } 22036 pw.println(); 22037 } 22038 } 22039 } 22040 } 22041 22042 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 22043 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 22044 : "Activity Resolver Table:", " ", packageName, 22045 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 22046 dumpState.setTitlePrinted(true); 22047 } 22048 } 22049 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 22050 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 22051 : "Receiver Resolver Table:", " ", packageName, 22052 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 22053 dumpState.setTitlePrinted(true); 22054 } 22055 } 22056 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 22057 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 22058 : "Service Resolver Table:", " ", packageName, 22059 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 22060 dumpState.setTitlePrinted(true); 22061 } 22062 } 22063 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 22064 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 22065 : "Provider Resolver Table:", " ", packageName, 22066 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 22067 dumpState.setTitlePrinted(true); 22068 } 22069 } 22070 22071 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 22072 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 22073 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 22074 int user = mSettings.mPreferredActivities.keyAt(i); 22075 if (pir.dump(pw, 22076 dumpState.getTitlePrinted() 22077 ? "\nPreferred Activities User " + user + ":" 22078 : "Preferred Activities User " + user + ":", " ", 22079 packageName, true, false)) { 22080 dumpState.setTitlePrinted(true); 22081 } 22082 } 22083 } 22084 22085 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 22086 pw.flush(); 22087 FileOutputStream fout = new FileOutputStream(fd); 22088 BufferedOutputStream str = new BufferedOutputStream(fout); 22089 XmlSerializer serializer = new FastXmlSerializer(); 22090 try { 22091 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 22092 serializer.startDocument(null, true); 22093 serializer.setFeature( 22094 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 22095 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 22096 serializer.endDocument(); 22097 serializer.flush(); 22098 } catch (IllegalArgumentException e) { 22099 pw.println("Failed writing: " + e); 22100 } catch (IllegalStateException e) { 22101 pw.println("Failed writing: " + e); 22102 } catch (IOException e) { 22103 pw.println("Failed writing: " + e); 22104 } 22105 } 22106 22107 if (!checkin 22108 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 22109 && packageName == null) { 22110 pw.println(); 22111 int count = mSettings.mPackages.size(); 22112 if (count == 0) { 22113 pw.println("No applications!"); 22114 pw.println(); 22115 } else { 22116 final String prefix = " "; 22117 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 22118 if (allPackageSettings.size() == 0) { 22119 pw.println("No domain preferred apps!"); 22120 pw.println(); 22121 } else { 22122 pw.println("App verification status:"); 22123 pw.println(); 22124 count = 0; 22125 for (PackageSetting ps : allPackageSettings) { 22126 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 22127 if (ivi == null || ivi.getPackageName() == null) continue; 22128 pw.println(prefix + "Package: " + ivi.getPackageName()); 22129 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 22130 pw.println(prefix + "Status: " + ivi.getStatusString()); 22131 pw.println(); 22132 count++; 22133 } 22134 if (count == 0) { 22135 pw.println(prefix + "No app verification established."); 22136 pw.println(); 22137 } 22138 for (int userId : sUserManager.getUserIds()) { 22139 pw.println("App linkages for user " + userId + ":"); 22140 pw.println(); 22141 count = 0; 22142 for (PackageSetting ps : allPackageSettings) { 22143 final long status = ps.getDomainVerificationStatusForUser(userId); 22144 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 22145 && !DEBUG_DOMAIN_VERIFICATION) { 22146 continue; 22147 } 22148 pw.println(prefix + "Package: " + ps.name); 22149 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 22150 String statusStr = IntentFilterVerificationInfo. 22151 getStatusStringFromValue(status); 22152 pw.println(prefix + "Status: " + statusStr); 22153 pw.println(); 22154 count++; 22155 } 22156 if (count == 0) { 22157 pw.println(prefix + "No configured app linkages."); 22158 pw.println(); 22159 } 22160 } 22161 } 22162 } 22163 } 22164 22165 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 22166 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 22167 if (packageName == null && permissionNames == null) { 22168 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 22169 if (iperm == 0) { 22170 if (dumpState.onTitlePrinted()) 22171 pw.println(); 22172 pw.println("AppOp Permissions:"); 22173 } 22174 pw.print(" AppOp Permission "); 22175 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 22176 pw.println(":"); 22177 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 22178 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 22179 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 22180 } 22181 } 22182 } 22183 } 22184 22185 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 22186 boolean printedSomething = false; 22187 for (PackageParser.Provider p : mProviders.mProviders.values()) { 22188 if (packageName != null && !packageName.equals(p.info.packageName)) { 22189 continue; 22190 } 22191 if (!printedSomething) { 22192 if (dumpState.onTitlePrinted()) 22193 pw.println(); 22194 pw.println("Registered ContentProviders:"); 22195 printedSomething = true; 22196 } 22197 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 22198 pw.print(" "); pw.println(p.toString()); 22199 } 22200 printedSomething = false; 22201 for (Map.Entry<String, PackageParser.Provider> entry : 22202 mProvidersByAuthority.entrySet()) { 22203 PackageParser.Provider p = entry.getValue(); 22204 if (packageName != null && !packageName.equals(p.info.packageName)) { 22205 continue; 22206 } 22207 if (!printedSomething) { 22208 if (dumpState.onTitlePrinted()) 22209 pw.println(); 22210 pw.println("ContentProvider Authorities:"); 22211 printedSomething = true; 22212 } 22213 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 22214 pw.print(" "); pw.println(p.toString()); 22215 if (p.info != null && p.info.applicationInfo != null) { 22216 final String appInfo = p.info.applicationInfo.toString(); 22217 pw.print(" applicationInfo="); pw.println(appInfo); 22218 } 22219 } 22220 } 22221 22222 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 22223 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 22224 } 22225 22226 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 22227 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 22228 } 22229 22230 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 22231 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 22232 } 22233 22234 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 22235 if (dumpState.onTitlePrinted()) pw.println(); 22236 pw.println("Package Changes:"); 22237 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 22238 final int K = mChangedPackages.size(); 22239 for (int i = 0; i < K; i++) { 22240 final SparseArray<String> changes = mChangedPackages.valueAt(i); 22241 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 22242 final int N = changes.size(); 22243 if (N == 0) { 22244 pw.print(" "); pw.println("No packages changed"); 22245 } else { 22246 for (int j = 0; j < N; j++) { 22247 final String pkgName = changes.valueAt(j); 22248 final int sequenceNumber = changes.keyAt(j); 22249 pw.print(" "); 22250 pw.print("seq="); 22251 pw.print(sequenceNumber); 22252 pw.print(", package="); 22253 pw.println(pkgName); 22254 } 22255 } 22256 } 22257 } 22258 22259 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 22260 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 22261 } 22262 22263 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 22264 // XXX should handle packageName != null by dumping only install data that 22265 // the given package is involved with. 22266 if (dumpState.onTitlePrinted()) pw.println(); 22267 22268 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 22269 ipw.println(); 22270 ipw.println("Frozen packages:"); 22271 ipw.increaseIndent(); 22272 if (mFrozenPackages.size() == 0) { 22273 ipw.println("(none)"); 22274 } else { 22275 for (int i = 0; i < mFrozenPackages.size(); i++) { 22276 ipw.println(mFrozenPackages.valueAt(i)); 22277 } 22278 } 22279 ipw.decreaseIndent(); 22280 } 22281 22282 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 22283 if (dumpState.onTitlePrinted()) pw.println(); 22284 dumpDexoptStateLPr(pw, packageName); 22285 } 22286 22287 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 22288 if (dumpState.onTitlePrinted()) pw.println(); 22289 dumpCompilerStatsLPr(pw, packageName); 22290 } 22291 22292 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 22293 if (dumpState.onTitlePrinted()) pw.println(); 22294 mSettings.dumpReadMessagesLPr(pw, dumpState); 22295 22296 pw.println(); 22297 pw.println("Package warning messages:"); 22298 BufferedReader in = null; 22299 String line = null; 22300 try { 22301 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 22302 while ((line = in.readLine()) != null) { 22303 if (line.contains("ignored: updated version")) continue; 22304 pw.println(line); 22305 } 22306 } catch (IOException ignored) { 22307 } finally { 22308 IoUtils.closeQuietly(in); 22309 } 22310 } 22311 22312 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 22313 BufferedReader in = null; 22314 String line = null; 22315 try { 22316 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 22317 while ((line = in.readLine()) != null) { 22318 if (line.contains("ignored: updated version")) continue; 22319 pw.print("msg,"); 22320 pw.println(line); 22321 } 22322 } catch (IOException ignored) { 22323 } finally { 22324 IoUtils.closeQuietly(in); 22325 } 22326 } 22327 } 22328 22329 // PackageInstaller should be called outside of mPackages lock 22330 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 22331 // XXX should handle packageName != null by dumping only install data that 22332 // the given package is involved with. 22333 if (dumpState.onTitlePrinted()) pw.println(); 22334 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 22335 } 22336 } 22337 22338 private void dumpProto(FileDescriptor fd) { 22339 final ProtoOutputStream proto = new ProtoOutputStream(fd); 22340 22341 synchronized (mPackages) { 22342 final long requiredVerifierPackageToken = 22343 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 22344 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 22345 proto.write( 22346 PackageServiceDumpProto.PackageShortProto.UID, 22347 getPackageUid( 22348 mRequiredVerifierPackage, 22349 MATCH_DEBUG_TRIAGED_MISSING, 22350 UserHandle.USER_SYSTEM)); 22351 proto.end(requiredVerifierPackageToken); 22352 22353 if (mIntentFilterVerifierComponent != null) { 22354 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 22355 final long verifierPackageToken = 22356 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 22357 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 22358 proto.write( 22359 PackageServiceDumpProto.PackageShortProto.UID, 22360 getPackageUid( 22361 verifierPackageName, 22362 MATCH_DEBUG_TRIAGED_MISSING, 22363 UserHandle.USER_SYSTEM)); 22364 proto.end(verifierPackageToken); 22365 } 22366 22367 dumpSharedLibrariesProto(proto); 22368 dumpFeaturesProto(proto); 22369 mSettings.dumpPackagesProto(proto); 22370 mSettings.dumpSharedUsersProto(proto); 22371 dumpMessagesProto(proto); 22372 } 22373 proto.flush(); 22374 } 22375 22376 private void dumpMessagesProto(ProtoOutputStream proto) { 22377 BufferedReader in = null; 22378 String line = null; 22379 try { 22380 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 22381 while ((line = in.readLine()) != null) { 22382 if (line.contains("ignored: updated version")) continue; 22383 proto.write(PackageServiceDumpProto.MESSAGES, line); 22384 } 22385 } catch (IOException ignored) { 22386 } finally { 22387 IoUtils.closeQuietly(in); 22388 } 22389 } 22390 22391 private void dumpFeaturesProto(ProtoOutputStream proto) { 22392 synchronized (mAvailableFeatures) { 22393 final int count = mAvailableFeatures.size(); 22394 for (int i = 0; i < count; i++) { 22395 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 22396 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 22397 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 22398 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 22399 proto.end(featureToken); 22400 } 22401 } 22402 } 22403 22404 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 22405 final int count = mSharedLibraries.size(); 22406 for (int i = 0; i < count; i++) { 22407 final String libName = mSharedLibraries.keyAt(i); 22408 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 22409 if (versionedLib == null) { 22410 continue; 22411 } 22412 final int versionCount = versionedLib.size(); 22413 for (int j = 0; j < versionCount; j++) { 22414 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 22415 final long sharedLibraryToken = 22416 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 22417 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 22418 final boolean isJar = (libEntry.path != null); 22419 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 22420 if (isJar) { 22421 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 22422 } else { 22423 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 22424 } 22425 proto.end(sharedLibraryToken); 22426 } 22427 } 22428 } 22429 22430 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 22431 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 22432 ipw.println(); 22433 ipw.println("Dexopt state:"); 22434 ipw.increaseIndent(); 22435 Collection<PackageParser.Package> packages = null; 22436 if (packageName != null) { 22437 PackageParser.Package targetPackage = mPackages.get(packageName); 22438 if (targetPackage != null) { 22439 packages = Collections.singletonList(targetPackage); 22440 } else { 22441 ipw.println("Unable to find package: " + packageName); 22442 return; 22443 } 22444 } else { 22445 packages = mPackages.values(); 22446 } 22447 22448 for (PackageParser.Package pkg : packages) { 22449 ipw.println("[" + pkg.packageName + "]"); 22450 ipw.increaseIndent(); 22451 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 22452 ipw.decreaseIndent(); 22453 } 22454 } 22455 22456 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 22457 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 22458 ipw.println(); 22459 ipw.println("Compiler stats:"); 22460 ipw.increaseIndent(); 22461 Collection<PackageParser.Package> packages = null; 22462 if (packageName != null) { 22463 PackageParser.Package targetPackage = mPackages.get(packageName); 22464 if (targetPackage != null) { 22465 packages = Collections.singletonList(targetPackage); 22466 } else { 22467 ipw.println("Unable to find package: " + packageName); 22468 return; 22469 } 22470 } else { 22471 packages = mPackages.values(); 22472 } 22473 22474 for (PackageParser.Package pkg : packages) { 22475 ipw.println("[" + pkg.packageName + "]"); 22476 ipw.increaseIndent(); 22477 22478 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 22479 if (stats == null) { 22480 ipw.println("(No recorded stats)"); 22481 } else { 22482 stats.dump(ipw); 22483 } 22484 ipw.decreaseIndent(); 22485 } 22486 } 22487 22488 private String dumpDomainString(String packageName) { 22489 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 22490 .getList(); 22491 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 22492 22493 ArraySet<String> result = new ArraySet<>(); 22494 if (iviList.size() > 0) { 22495 for (IntentFilterVerificationInfo ivi : iviList) { 22496 for (String host : ivi.getDomains()) { 22497 result.add(host); 22498 } 22499 } 22500 } 22501 if (filters != null && filters.size() > 0) { 22502 for (IntentFilter filter : filters) { 22503 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 22504 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 22505 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 22506 result.addAll(filter.getHostsList()); 22507 } 22508 } 22509 } 22510 22511 StringBuilder sb = new StringBuilder(result.size() * 16); 22512 for (String domain : result) { 22513 if (sb.length() > 0) sb.append(" "); 22514 sb.append(domain); 22515 } 22516 return sb.toString(); 22517 } 22518 22519 // ------- apps on sdcard specific code ------- 22520 static final boolean DEBUG_SD_INSTALL = false; 22521 22522 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 22523 22524 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 22525 22526 private boolean mMediaMounted = false; 22527 22528 static String getEncryptKey() { 22529 try { 22530 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 22531 SD_ENCRYPTION_KEYSTORE_NAME); 22532 if (sdEncKey == null) { 22533 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 22534 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 22535 if (sdEncKey == null) { 22536 Slog.e(TAG, "Failed to create encryption keys"); 22537 return null; 22538 } 22539 } 22540 return sdEncKey; 22541 } catch (NoSuchAlgorithmException nsae) { 22542 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 22543 return null; 22544 } catch (IOException ioe) { 22545 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 22546 return null; 22547 } 22548 } 22549 22550 /* 22551 * Update media status on PackageManager. 22552 */ 22553 @Override 22554 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 22555 enforceSystemOrRoot("Media status can only be updated by the system"); 22556 // reader; this apparently protects mMediaMounted, but should probably 22557 // be a different lock in that case. 22558 synchronized (mPackages) { 22559 Log.i(TAG, "Updating external media status from " 22560 + (mMediaMounted ? "mounted" : "unmounted") + " to " 22561 + (mediaStatus ? "mounted" : "unmounted")); 22562 if (DEBUG_SD_INSTALL) 22563 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 22564 + ", mMediaMounted=" + mMediaMounted); 22565 if (mediaStatus == mMediaMounted) { 22566 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 22567 : 0, -1); 22568 mHandler.sendMessage(msg); 22569 return; 22570 } 22571 mMediaMounted = mediaStatus; 22572 } 22573 // Queue up an async operation since the package installation may take a 22574 // little while. 22575 mHandler.post(new Runnable() { 22576 public void run() { 22577 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 22578 } 22579 }); 22580 } 22581 22582 /** 22583 * Called by StorageManagerService when the initial ASECs to scan are available. 22584 * Should block until all the ASEC containers are finished being scanned. 22585 */ 22586 public void scanAvailableAsecs() { 22587 updateExternalMediaStatusInner(true, false, false); 22588 } 22589 22590 /* 22591 * Collect information of applications on external media, map them against 22592 * existing containers and update information based on current mount status. 22593 * Please note that we always have to report status if reportStatus has been 22594 * set to true especially when unloading packages. 22595 */ 22596 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 22597 boolean externalStorage) { 22598 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 22599 int[] uidArr = EmptyArray.INT; 22600 22601 final String[] list = PackageHelper.getSecureContainerList(); 22602 if (ArrayUtils.isEmpty(list)) { 22603 Log.i(TAG, "No secure containers found"); 22604 } else { 22605 // Process list of secure containers and categorize them 22606 // as active or stale based on their package internal state. 22607 22608 // reader 22609 synchronized (mPackages) { 22610 for (String cid : list) { 22611 // Leave stages untouched for now; installer service owns them 22612 if (PackageInstallerService.isStageName(cid)) continue; 22613 22614 if (DEBUG_SD_INSTALL) 22615 Log.i(TAG, "Processing container " + cid); 22616 String pkgName = getAsecPackageName(cid); 22617 if (pkgName == null) { 22618 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 22619 continue; 22620 } 22621 if (DEBUG_SD_INSTALL) 22622 Log.i(TAG, "Looking for pkg : " + pkgName); 22623 22624 final PackageSetting ps = mSettings.mPackages.get(pkgName); 22625 if (ps == null) { 22626 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 22627 continue; 22628 } 22629 22630 /* 22631 * Skip packages that are not external if we're unmounting 22632 * external storage. 22633 */ 22634 if (externalStorage && !isMounted && !isExternal(ps)) { 22635 continue; 22636 } 22637 22638 final AsecInstallArgs args = new AsecInstallArgs(cid, 22639 getAppDexInstructionSets(ps), ps.isForwardLocked()); 22640 // The package status is changed only if the code path 22641 // matches between settings and the container id. 22642 if (ps.codePathString != null 22643 && ps.codePathString.startsWith(args.getCodePath())) { 22644 if (DEBUG_SD_INSTALL) { 22645 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 22646 + " at code path: " + ps.codePathString); 22647 } 22648 22649 // We do have a valid package installed on sdcard 22650 processCids.put(args, ps.codePathString); 22651 final int uid = ps.appId; 22652 if (uid != -1) { 22653 uidArr = ArrayUtils.appendInt(uidArr, uid); 22654 } 22655 } else { 22656 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 22657 + ps.codePathString); 22658 } 22659 } 22660 } 22661 22662 Arrays.sort(uidArr); 22663 } 22664 22665 // Process packages with valid entries. 22666 if (isMounted) { 22667 if (DEBUG_SD_INSTALL) 22668 Log.i(TAG, "Loading packages"); 22669 loadMediaPackages(processCids, uidArr, externalStorage); 22670 startCleaningPackages(); 22671 mInstallerService.onSecureContainersAvailable(); 22672 } else { 22673 if (DEBUG_SD_INSTALL) 22674 Log.i(TAG, "Unloading packages"); 22675 unloadMediaPackages(processCids, uidArr, reportStatus); 22676 } 22677 } 22678 22679 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 22680 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 22681 final int size = infos.size(); 22682 final String[] packageNames = new String[size]; 22683 final int[] packageUids = new int[size]; 22684 for (int i = 0; i < size; i++) { 22685 final ApplicationInfo info = infos.get(i); 22686 packageNames[i] = info.packageName; 22687 packageUids[i] = info.uid; 22688 } 22689 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 22690 finishedReceiver); 22691 } 22692 22693 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 22694 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 22695 sendResourcesChangedBroadcast(mediaStatus, replacing, 22696 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 22697 } 22698 22699 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 22700 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 22701 int size = pkgList.length; 22702 if (size > 0) { 22703 // Send broadcasts here 22704 Bundle extras = new Bundle(); 22705 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 22706 if (uidArr != null) { 22707 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 22708 } 22709 if (replacing) { 22710 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 22711 } 22712 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 22713 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 22714 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 22715 } 22716 } 22717 22718 /* 22719 * Look at potentially valid container ids from processCids If package 22720 * information doesn't match the one on record or package scanning fails, 22721 * the cid is added to list of removeCids. We currently don't delete stale 22722 * containers. 22723 */ 22724 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 22725 boolean externalStorage) { 22726 ArrayList<String> pkgList = new ArrayList<String>(); 22727 Set<AsecInstallArgs> keys = processCids.keySet(); 22728 22729 for (AsecInstallArgs args : keys) { 22730 String codePath = processCids.get(args); 22731 if (DEBUG_SD_INSTALL) 22732 Log.i(TAG, "Loading container : " + args.cid); 22733 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 22734 try { 22735 // Make sure there are no container errors first. 22736 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 22737 Slog.e(TAG, "Failed to mount cid : " + args.cid 22738 + " when installing from sdcard"); 22739 continue; 22740 } 22741 // Check code path here. 22742 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 22743 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 22744 + " does not match one in settings " + codePath); 22745 continue; 22746 } 22747 // Parse package 22748 int parseFlags = mDefParseFlags; 22749 if (args.isExternalAsec()) { 22750 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 22751 } 22752 if (args.isFwdLocked()) { 22753 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 22754 } 22755 22756 synchronized (mInstallLock) { 22757 PackageParser.Package pkg = null; 22758 try { 22759 // Sadly we don't know the package name yet to freeze it 22760 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 22761 SCAN_IGNORE_FROZEN, 0, null); 22762 } catch (PackageManagerException e) { 22763 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 22764 } 22765 // Scan the package 22766 if (pkg != null) { 22767 /* 22768 * TODO why is the lock being held? doPostInstall is 22769 * called in other places without the lock. This needs 22770 * to be straightened out. 22771 */ 22772 // writer 22773 synchronized (mPackages) { 22774 retCode = PackageManager.INSTALL_SUCCEEDED; 22775 pkgList.add(pkg.packageName); 22776 // Post process args 22777 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 22778 pkg.applicationInfo.uid); 22779 } 22780 } else { 22781 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 22782 } 22783 } 22784 22785 } finally { 22786 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 22787 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 22788 } 22789 } 22790 } 22791 // writer 22792 synchronized (mPackages) { 22793 // If the platform SDK has changed since the last time we booted, 22794 // we need to re-grant app permission to catch any new ones that 22795 // appear. This is really a hack, and means that apps can in some 22796 // cases get permissions that the user didn't initially explicitly 22797 // allow... it would be nice to have some better way to handle 22798 // this situation. 22799 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 22800 : mSettings.getInternalVersion(); 22801 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 22802 : StorageManager.UUID_PRIVATE_INTERNAL; 22803 22804 int updateFlags = UPDATE_PERMISSIONS_ALL; 22805 if (ver.sdkVersion != mSdkVersion) { 22806 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 22807 + mSdkVersion + "; regranting permissions for external"); 22808 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 22809 } 22810 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 22811 22812 // Yay, everything is now upgraded 22813 ver.forceCurrent(); 22814 22815 // can downgrade to reader 22816 // Persist settings 22817 mSettings.writeLPr(); 22818 } 22819 // Send a broadcast to let everyone know we are done processing 22820 if (pkgList.size() > 0) { 22821 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 22822 } 22823 } 22824 22825 /* 22826 * Utility method to unload a list of specified containers 22827 */ 22828 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 22829 // Just unmount all valid containers. 22830 for (AsecInstallArgs arg : cidArgs) { 22831 synchronized (mInstallLock) { 22832 arg.doPostDeleteLI(false); 22833 } 22834 } 22835 } 22836 22837 /* 22838 * Unload packages mounted on external media. This involves deleting package 22839 * data from internal structures, sending broadcasts about disabled packages, 22840 * gc'ing to free up references, unmounting all secure containers 22841 * corresponding to packages on external media, and posting a 22842 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 22843 * that we always have to post this message if status has been requested no 22844 * matter what. 22845 */ 22846 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 22847 final boolean reportStatus) { 22848 if (DEBUG_SD_INSTALL) 22849 Log.i(TAG, "unloading media packages"); 22850 ArrayList<String> pkgList = new ArrayList<String>(); 22851 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 22852 final Set<AsecInstallArgs> keys = processCids.keySet(); 22853 for (AsecInstallArgs args : keys) { 22854 String pkgName = args.getPackageName(); 22855 if (DEBUG_SD_INSTALL) 22856 Log.i(TAG, "Trying to unload pkg : " + pkgName); 22857 // Delete package internally 22858 PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 22859 synchronized (mInstallLock) { 22860 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 22861 final boolean res; 22862 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 22863 "unloadMediaPackages")) { 22864 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 22865 null); 22866 } 22867 if (res) { 22868 pkgList.add(pkgName); 22869 } else { 22870 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 22871 failedList.add(args); 22872 } 22873 } 22874 } 22875 22876 // reader 22877 synchronized (mPackages) { 22878 // We didn't update the settings after removing each package; 22879 // write them now for all packages. 22880 mSettings.writeLPr(); 22881 } 22882 22883 // We have to absolutely send UPDATED_MEDIA_STATUS only 22884 // after confirming that all the receivers processed the ordered 22885 // broadcast when packages get disabled, force a gc to clean things up. 22886 // and unload all the containers. 22887 if (pkgList.size() > 0) { 22888 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 22889 new IIntentReceiver.Stub() { 22890 public void performReceive(Intent intent, int resultCode, String data, 22891 Bundle extras, boolean ordered, boolean sticky, 22892 int sendingUser) throws RemoteException { 22893 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 22894 reportStatus ? 1 : 0, 1, keys); 22895 mHandler.sendMessage(msg); 22896 } 22897 }); 22898 } else { 22899 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 22900 keys); 22901 mHandler.sendMessage(msg); 22902 } 22903 } 22904 22905 private void loadPrivatePackages(final VolumeInfo vol) { 22906 mHandler.post(new Runnable() { 22907 @Override 22908 public void run() { 22909 loadPrivatePackagesInner(vol); 22910 } 22911 }); 22912 } 22913 22914 private void loadPrivatePackagesInner(VolumeInfo vol) { 22915 final String volumeUuid = vol.fsUuid; 22916 if (TextUtils.isEmpty(volumeUuid)) { 22917 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 22918 return; 22919 } 22920 22921 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 22922 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 22923 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 22924 22925 final VersionInfo ver; 22926 final List<PackageSetting> packages; 22927 synchronized (mPackages) { 22928 ver = mSettings.findOrCreateVersion(volumeUuid); 22929 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22930 } 22931 22932 for (PackageSetting ps : packages) { 22933 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 22934 synchronized (mInstallLock) { 22935 final PackageParser.Package pkg; 22936 try { 22937 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 22938 loaded.add(pkg.applicationInfo); 22939 22940 } catch (PackageManagerException e) { 22941 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 22942 } 22943 22944 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 22945 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 22946 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 22947 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 22948 } 22949 } 22950 } 22951 22952 // Reconcile app data for all started/unlocked users 22953 final StorageManager sm = mContext.getSystemService(StorageManager.class); 22954 final UserManager um = mContext.getSystemService(UserManager.class); 22955 UserManagerInternal umInternal = getUserManagerInternal(); 22956 for (UserInfo user : um.getUsers()) { 22957 final int flags; 22958 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22959 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22960 } else if (umInternal.isUserRunning(user.id)) { 22961 flags = StorageManager.FLAG_STORAGE_DE; 22962 } else { 22963 continue; 22964 } 22965 22966 try { 22967 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 22968 synchronized (mInstallLock) { 22969 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 22970 } 22971 } catch (IllegalStateException e) { 22972 // Device was probably ejected, and we'll process that event momentarily 22973 Slog.w(TAG, "Failed to prepare storage: " + e); 22974 } 22975 } 22976 22977 synchronized (mPackages) { 22978 int updateFlags = UPDATE_PERMISSIONS_ALL; 22979 if (ver.sdkVersion != mSdkVersion) { 22980 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 22981 + mSdkVersion + "; regranting permissions for " + volumeUuid); 22982 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 22983 } 22984 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 22985 22986 // Yay, everything is now upgraded 22987 ver.forceCurrent(); 22988 22989 mSettings.writeLPr(); 22990 } 22991 22992 for (PackageFreezer freezer : freezers) { 22993 freezer.close(); 22994 } 22995 22996 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 22997 sendResourcesChangedBroadcast(true, false, loaded, null); 22998 } 22999 23000 private void unloadPrivatePackages(final VolumeInfo vol) { 23001 mHandler.post(new Runnable() { 23002 @Override 23003 public void run() { 23004 unloadPrivatePackagesInner(vol); 23005 } 23006 }); 23007 } 23008 23009 private void unloadPrivatePackagesInner(VolumeInfo vol) { 23010 final String volumeUuid = vol.fsUuid; 23011 if (TextUtils.isEmpty(volumeUuid)) { 23012 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 23013 return; 23014 } 23015 23016 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 23017 synchronized (mInstallLock) { 23018 synchronized (mPackages) { 23019 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 23020 for (PackageSetting ps : packages) { 23021 if (ps.pkg == null) continue; 23022 23023 final ApplicationInfo info = ps.pkg.applicationInfo; 23024 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 23025 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 23026 23027 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 23028 "unloadPrivatePackagesInner")) { 23029 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 23030 false, null)) { 23031 unloaded.add(info); 23032 } else { 23033 Slog.w(TAG, "Failed to unload " + ps.codePath); 23034 } 23035 } 23036 23037 // Try very hard to release any references to this package 23038 // so we don't risk the system server being killed due to 23039 // open FDs 23040 AttributeCache.instance().removePackage(ps.name); 23041 } 23042 23043 mSettings.writeLPr(); 23044 } 23045 } 23046 23047 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 23048 sendResourcesChangedBroadcast(false, false, unloaded, null); 23049 23050 // Try very hard to release any references to this path so we don't risk 23051 // the system server being killed due to open FDs 23052 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 23053 23054 for (int i = 0; i < 3; i++) { 23055 System.gc(); 23056 System.runFinalization(); 23057 } 23058 } 23059 23060 private void assertPackageKnown(String volumeUuid, String packageName) 23061 throws PackageManagerException { 23062 synchronized (mPackages) { 23063 // Normalize package name to handle renamed packages 23064 packageName = normalizePackageNameLPr(packageName); 23065 23066 final PackageSetting ps = mSettings.mPackages.get(packageName); 23067 if (ps == null) { 23068 throw new PackageManagerException("Package " + packageName + " is unknown"); 23069 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 23070 throw new PackageManagerException( 23071 "Package " + packageName + " found on unknown volume " + volumeUuid 23072 + "; expected volume " + ps.volumeUuid); 23073 } 23074 } 23075 } 23076 23077 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 23078 throws PackageManagerException { 23079 synchronized (mPackages) { 23080 // Normalize package name to handle renamed packages 23081 packageName = normalizePackageNameLPr(packageName); 23082 23083 final PackageSetting ps = mSettings.mPackages.get(packageName); 23084 if (ps == null) { 23085 throw new PackageManagerException("Package " + packageName + " is unknown"); 23086 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 23087 throw new PackageManagerException( 23088 "Package " + packageName + " found on unknown volume " + volumeUuid 23089 + "; expected volume " + ps.volumeUuid); 23090 } else if (!ps.getInstalled(userId)) { 23091 throw new PackageManagerException( 23092 "Package " + packageName + " not installed for user " + userId); 23093 } 23094 } 23095 } 23096 23097 private List<String> collectAbsoluteCodePaths() { 23098 synchronized (mPackages) { 23099 List<String> codePaths = new ArrayList<>(); 23100 final int packageCount = mSettings.mPackages.size(); 23101 for (int i = 0; i < packageCount; i++) { 23102 final PackageSetting ps = mSettings.mPackages.valueAt(i); 23103 codePaths.add(ps.codePath.getAbsolutePath()); 23104 } 23105 return codePaths; 23106 } 23107 } 23108 23109 /** 23110 * Examine all apps present on given mounted volume, and destroy apps that 23111 * aren't expected, either due to uninstallation or reinstallation on 23112 * another volume. 23113 */ 23114 private void reconcileApps(String volumeUuid) { 23115 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 23116 List<File> filesToDelete = null; 23117 23118 final File[] files = FileUtils.listFilesOrEmpty( 23119 Environment.getDataAppDirectory(volumeUuid)); 23120 for (File file : files) { 23121 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 23122 && !PackageInstallerService.isStageName(file.getName()); 23123 if (!isPackage) { 23124 // Ignore entries which are not packages 23125 continue; 23126 } 23127 23128 String absolutePath = file.getAbsolutePath(); 23129 23130 boolean pathValid = false; 23131 final int absoluteCodePathCount = absoluteCodePaths.size(); 23132 for (int i = 0; i < absoluteCodePathCount; i++) { 23133 String absoluteCodePath = absoluteCodePaths.get(i); 23134 if (absolutePath.startsWith(absoluteCodePath)) { 23135 pathValid = true; 23136 break; 23137 } 23138 } 23139 23140 if (!pathValid) { 23141 if (filesToDelete == null) { 23142 filesToDelete = new ArrayList<>(); 23143 } 23144 filesToDelete.add(file); 23145 } 23146 } 23147 23148 if (filesToDelete != null) { 23149 final int fileToDeleteCount = filesToDelete.size(); 23150 for (int i = 0; i < fileToDeleteCount; i++) { 23151 File fileToDelete = filesToDelete.get(i); 23152 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 23153 synchronized (mInstallLock) { 23154 removeCodePathLI(fileToDelete); 23155 } 23156 } 23157 } 23158 } 23159 23160 /** 23161 * Reconcile all app data for the given user. 23162 * <p> 23163 * Verifies that directories exist and that ownership and labeling is 23164 * correct for all installed apps on all mounted volumes. 23165 */ 23166 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 23167 final StorageManager storage = mContext.getSystemService(StorageManager.class); 23168 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 23169 final String volumeUuid = vol.getFsUuid(); 23170 synchronized (mInstallLock) { 23171 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 23172 } 23173 } 23174 } 23175 23176 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 23177 boolean migrateAppData) { 23178 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 23179 } 23180 23181 /** 23182 * Reconcile all app data on given mounted volume. 23183 * <p> 23184 * Destroys app data that isn't expected, either due to uninstallation or 23185 * reinstallation on another volume. 23186 * <p> 23187 * Verifies that directories exist and that ownership and labeling is 23188 * correct for all installed apps. 23189 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 23190 */ 23191 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 23192 boolean migrateAppData, boolean onlyCoreApps) { 23193 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 23194 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 23195 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 23196 23197 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 23198 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 23199 23200 // First look for stale data that doesn't belong, and check if things 23201 // have changed since we did our last restorecon 23202 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 23203 if (StorageManager.isFileEncryptedNativeOrEmulated() 23204 && !StorageManager.isUserKeyUnlocked(userId)) { 23205 throw new RuntimeException( 23206 "Yikes, someone asked us to reconcile CE storage while " + userId 23207 + " was still locked; this would have caused massive data loss!"); 23208 } 23209 23210 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 23211 for (File file : files) { 23212 final String packageName = file.getName(); 23213 try { 23214 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 23215 } catch (PackageManagerException e) { 23216 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 23217 try { 23218 mInstaller.destroyAppData(volumeUuid, packageName, userId, 23219 StorageManager.FLAG_STORAGE_CE, 0); 23220 } catch (InstallerException e2) { 23221 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 23222 } 23223 } 23224 } 23225 } 23226 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 23227 final File[] files = FileUtils.listFilesOrEmpty(deDir); 23228 for (File file : files) { 23229 final String packageName = file.getName(); 23230 try { 23231 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 23232 } catch (PackageManagerException e) { 23233 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 23234 try { 23235 mInstaller.destroyAppData(volumeUuid, packageName, userId, 23236 StorageManager.FLAG_STORAGE_DE, 0); 23237 } catch (InstallerException e2) { 23238 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 23239 } 23240 } 23241 } 23242 } 23243 23244 // Ensure that data directories are ready to roll for all packages 23245 // installed for this volume and user 23246 final List<PackageSetting> packages; 23247 synchronized (mPackages) { 23248 packages = mSettings.getVolumePackagesLPr(volumeUuid); 23249 } 23250 int preparedCount = 0; 23251 for (PackageSetting ps : packages) { 23252 final String packageName = ps.name; 23253 if (ps.pkg == null) { 23254 Slog.w(TAG, "Odd, missing scanned package " + packageName); 23255 // TODO: might be due to legacy ASEC apps; we should circle back 23256 // and reconcile again once they're scanned 23257 continue; 23258 } 23259 // Skip non-core apps if requested 23260 if (onlyCoreApps && !ps.pkg.coreApp) { 23261 result.add(packageName); 23262 continue; 23263 } 23264 23265 if (ps.getInstalled(userId)) { 23266 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 23267 preparedCount++; 23268 } 23269 } 23270 23271 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 23272 return result; 23273 } 23274 23275 /** 23276 * Prepare app data for the given app just after it was installed or 23277 * upgraded. This method carefully only touches users that it's installed 23278 * for, and it forces a restorecon to handle any seinfo changes. 23279 * <p> 23280 * Verifies that directories exist and that ownership and labeling is 23281 * correct for all installed apps. If there is an ownership mismatch, it 23282 * will try recovering system apps by wiping data; third-party app data is 23283 * left intact. 23284 * <p> 23285 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 23286 */ 23287 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 23288 final PackageSetting ps; 23289 synchronized (mPackages) { 23290 ps = mSettings.mPackages.get(pkg.packageName); 23291 mSettings.writeKernelMappingLPr(ps); 23292 } 23293 23294 final UserManager um = mContext.getSystemService(UserManager.class); 23295 UserManagerInternal umInternal = getUserManagerInternal(); 23296 for (UserInfo user : um.getUsers()) { 23297 final int flags; 23298 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 23299 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 23300 } else if (umInternal.isUserRunning(user.id)) { 23301 flags = StorageManager.FLAG_STORAGE_DE; 23302 } else { 23303 continue; 23304 } 23305 23306 if (ps.getInstalled(user.id)) { 23307 // TODO: when user data is locked, mark that we're still dirty 23308 prepareAppDataLIF(pkg, user.id, flags); 23309 } 23310 } 23311 } 23312 23313 /** 23314 * Prepare app data for the given app. 23315 * <p> 23316 * Verifies that directories exist and that ownership and labeling is 23317 * correct for all installed apps. If there is an ownership mismatch, this 23318 * will try recovering system apps by wiping data; third-party app data is 23319 * left intact. 23320 */ 23321 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 23322 if (pkg == null) { 23323 Slog.wtf(TAG, "Package was null!", new Throwable()); 23324 return; 23325 } 23326 prepareAppDataLeafLIF(pkg, userId, flags); 23327 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 23328 for (int i = 0; i < childCount; i++) { 23329 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 23330 } 23331 } 23332 23333 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 23334 boolean maybeMigrateAppData) { 23335 prepareAppDataLIF(pkg, userId, flags); 23336 23337 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 23338 // We may have just shuffled around app data directories, so 23339 // prepare them one more time 23340 prepareAppDataLIF(pkg, userId, flags); 23341 } 23342 } 23343 23344 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 23345 if (DEBUG_APP_DATA) { 23346 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 23347 + Integer.toHexString(flags)); 23348 } 23349 23350 final String volumeUuid = pkg.volumeUuid; 23351 final String packageName = pkg.packageName; 23352 final ApplicationInfo app = pkg.applicationInfo; 23353 final int appId = UserHandle.getAppId(app.uid); 23354 23355 Preconditions.checkNotNull(app.seInfo); 23356 23357 long ceDataInode = -1; 23358 try { 23359 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 23360 appId, app.seInfo, app.targetSdkVersion); 23361 } catch (InstallerException e) { 23362 if (app.isSystemApp()) { 23363 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 23364 + ", but trying to recover: " + e); 23365 destroyAppDataLeafLIF(pkg, userId, flags); 23366 try { 23367 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 23368 appId, app.seInfo, app.targetSdkVersion); 23369 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 23370 } catch (InstallerException e2) { 23371 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 23372 } 23373 } else { 23374 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 23375 } 23376 } 23377 23378 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 23379 // TODO: mark this structure as dirty so we persist it! 23380 synchronized (mPackages) { 23381 final PackageSetting ps = mSettings.mPackages.get(packageName); 23382 if (ps != null) { 23383 ps.setCeDataInode(ceDataInode, userId); 23384 } 23385 } 23386 } 23387 23388 prepareAppDataContentsLeafLIF(pkg, userId, flags); 23389 } 23390 23391 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 23392 if (pkg == null) { 23393 Slog.wtf(TAG, "Package was null!", new Throwable()); 23394 return; 23395 } 23396 prepareAppDataContentsLeafLIF(pkg, userId, flags); 23397 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 23398 for (int i = 0; i < childCount; i++) { 23399 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 23400 } 23401 } 23402 23403 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 23404 final String volumeUuid = pkg.volumeUuid; 23405 final String packageName = pkg.packageName; 23406 final ApplicationInfo app = pkg.applicationInfo; 23407 23408 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 23409 // Create a native library symlink only if we have native libraries 23410 // and if the native libraries are 32 bit libraries. We do not provide 23411 // this symlink for 64 bit libraries. 23412 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 23413 final String nativeLibPath = app.nativeLibraryDir; 23414 try { 23415 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 23416 nativeLibPath, userId); 23417 } catch (InstallerException e) { 23418 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 23419 } 23420 } 23421 } 23422 } 23423 23424 /** 23425 * For system apps on non-FBE devices, this method migrates any existing 23426 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 23427 * requested by the app. 23428 */ 23429 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 23430 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 23431 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 23432 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 23433 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 23434 try { 23435 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 23436 storageTarget); 23437 } catch (InstallerException e) { 23438 logCriticalInfo(Log.WARN, 23439 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 23440 } 23441 return true; 23442 } else { 23443 return false; 23444 } 23445 } 23446 23447 public PackageFreezer freezePackage(String packageName, String killReason) { 23448 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 23449 } 23450 23451 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 23452 return new PackageFreezer(packageName, userId, killReason); 23453 } 23454 23455 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 23456 String killReason) { 23457 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 23458 } 23459 23460 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 23461 String killReason) { 23462 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 23463 return new PackageFreezer(); 23464 } else { 23465 return freezePackage(packageName, userId, killReason); 23466 } 23467 } 23468 23469 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 23470 String killReason) { 23471 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 23472 } 23473 23474 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 23475 String killReason) { 23476 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 23477 return new PackageFreezer(); 23478 } else { 23479 return freezePackage(packageName, userId, killReason); 23480 } 23481 } 23482 23483 /** 23484 * Class that freezes and kills the given package upon creation, and 23485 * unfreezes it upon closing. This is typically used when doing surgery on 23486 * app code/data to prevent the app from running while you're working. 23487 */ 23488 private class PackageFreezer implements AutoCloseable { 23489 private final String mPackageName; 23490 private final PackageFreezer[] mChildren; 23491 23492 private final boolean mWeFroze; 23493 23494 private final AtomicBoolean mClosed = new AtomicBoolean(); 23495 private final CloseGuard mCloseGuard = CloseGuard.get(); 23496 23497 /** 23498 * Create and return a stub freezer that doesn't actually do anything, 23499 * typically used when someone requested 23500 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 23501 * {@link PackageManager#DELETE_DONT_KILL_APP}. 23502 */ 23503 public PackageFreezer() { 23504 mPackageName = null; 23505 mChildren = null; 23506 mWeFroze = false; 23507 mCloseGuard.open("close"); 23508 } 23509 23510 public PackageFreezer(String packageName, int userId, String killReason) { 23511 synchronized (mPackages) { 23512 mPackageName = packageName; 23513 mWeFroze = mFrozenPackages.add(mPackageName); 23514 23515 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 23516 if (ps != null) { 23517 killApplication(ps.name, ps.appId, userId, killReason); 23518 } 23519 23520 final PackageParser.Package p = mPackages.get(packageName); 23521 if (p != null && p.childPackages != null) { 23522 final int N = p.childPackages.size(); 23523 mChildren = new PackageFreezer[N]; 23524 for (int i = 0; i < N; i++) { 23525 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 23526 userId, killReason); 23527 } 23528 } else { 23529 mChildren = null; 23530 } 23531 } 23532 mCloseGuard.open("close"); 23533 } 23534 23535 @Override 23536 protected void finalize() throws Throwable { 23537 try { 23538 mCloseGuard.warnIfOpen(); 23539 close(); 23540 } finally { 23541 super.finalize(); 23542 } 23543 } 23544 23545 @Override 23546 public void close() { 23547 mCloseGuard.close(); 23548 if (mClosed.compareAndSet(false, true)) { 23549 synchronized (mPackages) { 23550 if (mWeFroze) { 23551 mFrozenPackages.remove(mPackageName); 23552 } 23553 23554 if (mChildren != null) { 23555 for (PackageFreezer freezer : mChildren) { 23556 freezer.close(); 23557 } 23558 } 23559 } 23560 } 23561 } 23562 } 23563 23564 /** 23565 * Verify that given package is currently frozen. 23566 */ 23567 private void checkPackageFrozen(String packageName) { 23568 synchronized (mPackages) { 23569 if (!mFrozenPackages.contains(packageName)) { 23570 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 23571 } 23572 } 23573 } 23574 23575 @Override 23576 public int movePackage(final String packageName, final String volumeUuid) { 23577 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 23578 23579 final int callingUid = Binder.getCallingUid(); 23580 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 23581 final int moveId = mNextMoveId.getAndIncrement(); 23582 mHandler.post(new Runnable() { 23583 @Override 23584 public void run() { 23585 try { 23586 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 23587 } catch (PackageManagerException e) { 23588 Slog.w(TAG, "Failed to move " + packageName, e); 23589 mMoveCallbacks.notifyStatusChanged(moveId, 23590 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 23591 } 23592 } 23593 }); 23594 return moveId; 23595 } 23596 23597 private void movePackageInternal(final String packageName, final String volumeUuid, 23598 final int moveId, final int callingUid, UserHandle user) 23599 throws PackageManagerException { 23600 final StorageManager storage = mContext.getSystemService(StorageManager.class); 23601 final PackageManager pm = mContext.getPackageManager(); 23602 23603 final boolean currentAsec; 23604 final String currentVolumeUuid; 23605 final File codeFile; 23606 final String installerPackageName; 23607 final String packageAbiOverride; 23608 final int appId; 23609 final String seinfo; 23610 final String label; 23611 final int targetSdkVersion; 23612 final PackageFreezer freezer; 23613 final int[] installedUserIds; 23614 23615 // reader 23616 synchronized (mPackages) { 23617 final PackageParser.Package pkg = mPackages.get(packageName); 23618 final PackageSetting ps = mSettings.mPackages.get(packageName); 23619 if (pkg == null 23620 || ps == null 23621 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 23622 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 23623 } 23624 if (pkg.applicationInfo.isSystemApp()) { 23625 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 23626 "Cannot move system application"); 23627 } 23628 23629 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 23630 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 23631 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 23632 if (isInternalStorage && !allow3rdPartyOnInternal) { 23633 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 23634 "3rd party apps are not allowed on internal storage"); 23635 } 23636 23637 if (pkg.applicationInfo.isExternalAsec()) { 23638 currentAsec = true; 23639 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 23640 } else if (pkg.applicationInfo.isForwardLocked()) { 23641 currentAsec = true; 23642 currentVolumeUuid = "forward_locked"; 23643 } else { 23644 currentAsec = false; 23645 currentVolumeUuid = ps.volumeUuid; 23646 23647 final File probe = new File(pkg.codePath); 23648 final File probeOat = new File(probe, "oat"); 23649 if (!probe.isDirectory() || !probeOat.isDirectory()) { 23650 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23651 "Move only supported for modern cluster style installs"); 23652 } 23653 } 23654 23655 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 23656 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23657 "Package already moved to " + volumeUuid); 23658 } 23659 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 23660 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 23661 "Device admin cannot be moved"); 23662 } 23663 23664 if (mFrozenPackages.contains(packageName)) { 23665 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 23666 "Failed to move already frozen package"); 23667 } 23668 23669 codeFile = new File(pkg.codePath); 23670 installerPackageName = ps.installerPackageName; 23671 packageAbiOverride = ps.cpuAbiOverrideString; 23672 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 23673 seinfo = pkg.applicationInfo.seInfo; 23674 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 23675 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 23676 freezer = freezePackage(packageName, "movePackageInternal"); 23677 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 23678 } 23679 23680 final Bundle extras = new Bundle(); 23681 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 23682 extras.putString(Intent.EXTRA_TITLE, label); 23683 mMoveCallbacks.notifyCreated(moveId, extras); 23684 23685 int installFlags; 23686 final boolean moveCompleteApp; 23687 final File measurePath; 23688 23689 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 23690 installFlags = INSTALL_INTERNAL; 23691 moveCompleteApp = !currentAsec; 23692 measurePath = Environment.getDataAppDirectory(volumeUuid); 23693 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 23694 installFlags = INSTALL_EXTERNAL; 23695 moveCompleteApp = false; 23696 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 23697 } else { 23698 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 23699 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 23700 || !volume.isMountedWritable()) { 23701 freezer.close(); 23702 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23703 "Move location not mounted private volume"); 23704 } 23705 23706 Preconditions.checkState(!currentAsec); 23707 23708 installFlags = INSTALL_INTERNAL; 23709 moveCompleteApp = true; 23710 measurePath = Environment.getDataAppDirectory(volumeUuid); 23711 } 23712 23713 final PackageStats stats = new PackageStats(null, -1); 23714 synchronized (mInstaller) { 23715 for (int userId : installedUserIds) { 23716 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 23717 freezer.close(); 23718 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23719 "Failed to measure package size"); 23720 } 23721 } 23722 } 23723 23724 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 23725 + stats.dataSize); 23726 23727 final long startFreeBytes = measurePath.getUsableSpace(); 23728 final long sizeBytes; 23729 if (moveCompleteApp) { 23730 sizeBytes = stats.codeSize + stats.dataSize; 23731 } else { 23732 sizeBytes = stats.codeSize; 23733 } 23734 23735 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 23736 freezer.close(); 23737 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23738 "Not enough free space to move"); 23739 } 23740 23741 mMoveCallbacks.notifyStatusChanged(moveId, 10); 23742 23743 final CountDownLatch installedLatch = new CountDownLatch(1); 23744 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 23745 @Override 23746 public void onUserActionRequired(Intent intent) throws RemoteException { 23747 throw new IllegalStateException(); 23748 } 23749 23750 @Override 23751 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 23752 Bundle extras) throws RemoteException { 23753 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 23754 + PackageManager.installStatusToString(returnCode, msg)); 23755 23756 installedLatch.countDown(); 23757 freezer.close(); 23758 23759 final int status = PackageManager.installStatusToPublicStatus(returnCode); 23760 switch (status) { 23761 case PackageInstaller.STATUS_SUCCESS: 23762 mMoveCallbacks.notifyStatusChanged(moveId, 23763 PackageManager.MOVE_SUCCEEDED); 23764 break; 23765 case PackageInstaller.STATUS_FAILURE_STORAGE: 23766 mMoveCallbacks.notifyStatusChanged(moveId, 23767 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 23768 break; 23769 default: 23770 mMoveCallbacks.notifyStatusChanged(moveId, 23771 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 23772 break; 23773 } 23774 } 23775 }; 23776 23777 final MoveInfo move; 23778 if (moveCompleteApp) { 23779 // Kick off a thread to report progress estimates 23780 new Thread() { 23781 @Override 23782 public void run() { 23783 while (true) { 23784 try { 23785 if (installedLatch.await(1, TimeUnit.SECONDS)) { 23786 break; 23787 } 23788 } catch (InterruptedException ignored) { 23789 } 23790 23791 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 23792 final int progress = 10 + (int) MathUtils.constrain( 23793 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 23794 mMoveCallbacks.notifyStatusChanged(moveId, progress); 23795 } 23796 } 23797 }.start(); 23798 23799 final String dataAppName = codeFile.getName(); 23800 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 23801 dataAppName, appId, seinfo, targetSdkVersion); 23802 } else { 23803 move = null; 23804 } 23805 23806 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 23807 23808 final Message msg = mHandler.obtainMessage(INIT_COPY); 23809 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 23810 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 23811 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 23812 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 23813 PackageManager.INSTALL_REASON_UNKNOWN); 23814 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 23815 msg.obj = params; 23816 23817 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 23818 System.identityHashCode(msg.obj)); 23819 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 23820 System.identityHashCode(msg.obj)); 23821 23822 mHandler.sendMessage(msg); 23823 } 23824 23825 @Override 23826 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 23827 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 23828 23829 final int realMoveId = mNextMoveId.getAndIncrement(); 23830 final Bundle extras = new Bundle(); 23831 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 23832 mMoveCallbacks.notifyCreated(realMoveId, extras); 23833 23834 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 23835 @Override 23836 public void onCreated(int moveId, Bundle extras) { 23837 // Ignored 23838 } 23839 23840 @Override 23841 public void onStatusChanged(int moveId, int status, long estMillis) { 23842 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 23843 } 23844 }; 23845 23846 final StorageManager storage = mContext.getSystemService(StorageManager.class); 23847 storage.setPrimaryStorageUuid(volumeUuid, callback); 23848 return realMoveId; 23849 } 23850 23851 @Override 23852 public int getMoveStatus(int moveId) { 23853 mContext.enforceCallingOrSelfPermission( 23854 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 23855 return mMoveCallbacks.mLastStatus.get(moveId); 23856 } 23857 23858 @Override 23859 public void registerMoveCallback(IPackageMoveObserver callback) { 23860 mContext.enforceCallingOrSelfPermission( 23861 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 23862 mMoveCallbacks.register(callback); 23863 } 23864 23865 @Override 23866 public void unregisterMoveCallback(IPackageMoveObserver callback) { 23867 mContext.enforceCallingOrSelfPermission( 23868 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 23869 mMoveCallbacks.unregister(callback); 23870 } 23871 23872 @Override 23873 public boolean setInstallLocation(int loc) { 23874 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 23875 null); 23876 if (getInstallLocation() == loc) { 23877 return true; 23878 } 23879 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 23880 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 23881 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 23882 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 23883 return true; 23884 } 23885 return false; 23886 } 23887 23888 @Override 23889 public int getInstallLocation() { 23890 // allow instant app access 23891 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 23892 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 23893 PackageHelper.APP_INSTALL_AUTO); 23894 } 23895 23896 /** Called by UserManagerService */ 23897 void cleanUpUser(UserManagerService userManager, int userHandle) { 23898 synchronized (mPackages) { 23899 mDirtyUsers.remove(userHandle); 23900 mUserNeedsBadging.delete(userHandle); 23901 mSettings.removeUserLPw(userHandle); 23902 mPendingBroadcasts.remove(userHandle); 23903 mInstantAppRegistry.onUserRemovedLPw(userHandle); 23904 removeUnusedPackagesLPw(userManager, userHandle); 23905 } 23906 } 23907 23908 /** 23909 * We're removing userHandle and would like to remove any downloaded packages 23910 * that are no longer in use by any other user. 23911 * @param userHandle the user being removed 23912 */ 23913 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 23914 final boolean DEBUG_CLEAN_APKS = false; 23915 int [] users = userManager.getUserIds(); 23916 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 23917 while (psit.hasNext()) { 23918 PackageSetting ps = psit.next(); 23919 if (ps.pkg == null) { 23920 continue; 23921 } 23922 final String packageName = ps.pkg.packageName; 23923 // Skip over if system app 23924 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23925 continue; 23926 } 23927 if (DEBUG_CLEAN_APKS) { 23928 Slog.i(TAG, "Checking package " + packageName); 23929 } 23930 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 23931 if (keep) { 23932 if (DEBUG_CLEAN_APKS) { 23933 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 23934 } 23935 } else { 23936 for (int i = 0; i < users.length; i++) { 23937 if (users[i] != userHandle && ps.getInstalled(users[i])) { 23938 keep = true; 23939 if (DEBUG_CLEAN_APKS) { 23940 Slog.i(TAG, " Keeping package " + packageName + " for user " 23941 + users[i]); 23942 } 23943 break; 23944 } 23945 } 23946 } 23947 if (!keep) { 23948 if (DEBUG_CLEAN_APKS) { 23949 Slog.i(TAG, " Removing package " + packageName); 23950 } 23951 mHandler.post(new Runnable() { 23952 public void run() { 23953 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23954 userHandle, 0); 23955 } //end run 23956 }); 23957 } 23958 } 23959 } 23960 23961 /** Called by UserManagerService */ 23962 void createNewUser(int userId, String[] disallowedPackages) { 23963 synchronized (mInstallLock) { 23964 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 23965 } 23966 synchronized (mPackages) { 23967 scheduleWritePackageRestrictionsLocked(userId); 23968 scheduleWritePackageListLocked(userId); 23969 applyFactoryDefaultBrowserLPw(userId); 23970 primeDomainVerificationsLPw(userId); 23971 } 23972 } 23973 23974 void onNewUserCreated(final int userId) { 23975 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 23976 // If permission review for legacy apps is required, we represent 23977 // dagerous permissions for such apps as always granted runtime 23978 // permissions to keep per user flag state whether review is needed. 23979 // Hence, if a new user is added we have to propagate dangerous 23980 // permission grants for these legacy apps. 23981 if (mPermissionReviewRequired) { 23982 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 23983 | UPDATE_PERMISSIONS_REPLACE_ALL); 23984 } 23985 } 23986 23987 @Override 23988 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 23989 mContext.enforceCallingOrSelfPermission( 23990 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 23991 "Only package verification agents can read the verifier device identity"); 23992 23993 synchronized (mPackages) { 23994 return mSettings.getVerifierDeviceIdentityLPw(); 23995 } 23996 } 23997 23998 @Override 23999 public void setPermissionEnforced(String permission, boolean enforced) { 24000 // TODO: Now that we no longer change GID for storage, this should to away. 24001 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 24002 "setPermissionEnforced"); 24003 if (READ_EXTERNAL_STORAGE.equals(permission)) { 24004 synchronized (mPackages) { 24005 if (mSettings.mReadExternalStorageEnforced == null 24006 || mSettings.mReadExternalStorageEnforced != enforced) { 24007 mSettings.mReadExternalStorageEnforced = enforced; 24008 mSettings.writeLPr(); 24009 } 24010 } 24011 // kill any non-foreground processes so we restart them and 24012 // grant/revoke the GID. 24013 final IActivityManager am = ActivityManager.getService(); 24014 if (am != null) { 24015 final long token = Binder.clearCallingIdentity(); 24016 try { 24017 am.killProcessesBelowForeground("setPermissionEnforcement"); 24018 } catch (RemoteException e) { 24019 } finally { 24020 Binder.restoreCallingIdentity(token); 24021 } 24022 } 24023 } else { 24024 throw new IllegalArgumentException("No selective enforcement for " + permission); 24025 } 24026 } 24027 24028 @Override 24029 @Deprecated 24030 public boolean isPermissionEnforced(String permission) { 24031 // allow instant applications 24032 return true; 24033 } 24034 24035 @Override 24036 public boolean isStorageLow() { 24037 // allow instant applications 24038 final long token = Binder.clearCallingIdentity(); 24039 try { 24040 final DeviceStorageMonitorInternal 24041 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 24042 if (dsm != null) { 24043 return dsm.isMemoryLow(); 24044 } else { 24045 return false; 24046 } 24047 } finally { 24048 Binder.restoreCallingIdentity(token); 24049 } 24050 } 24051 24052 @Override 24053 public IPackageInstaller getPackageInstaller() { 24054 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24055 return null; 24056 } 24057 return mInstallerService; 24058 } 24059 24060 private boolean userNeedsBadging(int userId) { 24061 int index = mUserNeedsBadging.indexOfKey(userId); 24062 if (index < 0) { 24063 final UserInfo userInfo; 24064 final long token = Binder.clearCallingIdentity(); 24065 try { 24066 userInfo = sUserManager.getUserInfo(userId); 24067 } finally { 24068 Binder.restoreCallingIdentity(token); 24069 } 24070 final boolean b; 24071 if (userInfo != null && userInfo.isManagedProfile()) { 24072 b = true; 24073 } else { 24074 b = false; 24075 } 24076 mUserNeedsBadging.put(userId, b); 24077 return b; 24078 } 24079 return mUserNeedsBadging.valueAt(index); 24080 } 24081 24082 @Override 24083 public KeySet getKeySetByAlias(String packageName, String alias) { 24084 if (packageName == null || alias == null) { 24085 return null; 24086 } 24087 synchronized(mPackages) { 24088 final PackageParser.Package pkg = mPackages.get(packageName); 24089 if (pkg == null) { 24090 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 24091 throw new IllegalArgumentException("Unknown package: " + packageName); 24092 } 24093 final PackageSetting ps = (PackageSetting) pkg.mExtras; 24094 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 24095 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 24096 throw new IllegalArgumentException("Unknown package: " + packageName); 24097 } 24098 KeySetManagerService ksms = mSettings.mKeySetManagerService; 24099 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 24100 } 24101 } 24102 24103 @Override 24104 public KeySet getSigningKeySet(String packageName) { 24105 if (packageName == null) { 24106 return null; 24107 } 24108 synchronized(mPackages) { 24109 final int callingUid = Binder.getCallingUid(); 24110 final int callingUserId = UserHandle.getUserId(callingUid); 24111 final PackageParser.Package pkg = mPackages.get(packageName); 24112 if (pkg == null) { 24113 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 24114 throw new IllegalArgumentException("Unknown package: " + packageName); 24115 } 24116 final PackageSetting ps = (PackageSetting) pkg.mExtras; 24117 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 24118 // filter and pretend the package doesn't exist 24119 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 24120 + ", uid:" + callingUid); 24121 throw new IllegalArgumentException("Unknown package: " + packageName); 24122 } 24123 if (pkg.applicationInfo.uid != callingUid 24124 && Process.SYSTEM_UID != callingUid) { 24125 throw new SecurityException("May not access signing KeySet of other apps."); 24126 } 24127 KeySetManagerService ksms = mSettings.mKeySetManagerService; 24128 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 24129 } 24130 } 24131 24132 @Override 24133 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 24134 final int callingUid = Binder.getCallingUid(); 24135 if (getInstantAppPackageName(callingUid) != null) { 24136 return false; 24137 } 24138 if (packageName == null || ks == null) { 24139 return false; 24140 } 24141 synchronized(mPackages) { 24142 final PackageParser.Package pkg = mPackages.get(packageName); 24143 if (pkg == null 24144 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 24145 UserHandle.getUserId(callingUid))) { 24146 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 24147 throw new IllegalArgumentException("Unknown package: " + packageName); 24148 } 24149 IBinder ksh = ks.getToken(); 24150 if (ksh instanceof KeySetHandle) { 24151 KeySetManagerService ksms = mSettings.mKeySetManagerService; 24152 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 24153 } 24154 return false; 24155 } 24156 } 24157 24158 @Override 24159 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 24160 final int callingUid = Binder.getCallingUid(); 24161 if (getInstantAppPackageName(callingUid) != null) { 24162 return false; 24163 } 24164 if (packageName == null || ks == null) { 24165 return false; 24166 } 24167 synchronized(mPackages) { 24168 final PackageParser.Package pkg = mPackages.get(packageName); 24169 if (pkg == null 24170 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 24171 UserHandle.getUserId(callingUid))) { 24172 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 24173 throw new IllegalArgumentException("Unknown package: " + packageName); 24174 } 24175 IBinder ksh = ks.getToken(); 24176 if (ksh instanceof KeySetHandle) { 24177 KeySetManagerService ksms = mSettings.mKeySetManagerService; 24178 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 24179 } 24180 return false; 24181 } 24182 } 24183 24184 private void deletePackageIfUnusedLPr(final String packageName) { 24185 PackageSetting ps = mSettings.mPackages.get(packageName); 24186 if (ps == null) { 24187 return; 24188 } 24189 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 24190 // TODO Implement atomic delete if package is unused 24191 // It is currently possible that the package will be deleted even if it is installed 24192 // after this method returns. 24193 mHandler.post(new Runnable() { 24194 public void run() { 24195 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 24196 0, PackageManager.DELETE_ALL_USERS); 24197 } 24198 }); 24199 } 24200 } 24201 24202 /** 24203 * Check and throw if the given before/after packages would be considered a 24204 * downgrade. 24205 */ 24206 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 24207 throws PackageManagerException { 24208 if (after.versionCode < before.mVersionCode) { 24209 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 24210 "Update version code " + after.versionCode + " is older than current " 24211 + before.mVersionCode); 24212 } else if (after.versionCode == before.mVersionCode) { 24213 if (after.baseRevisionCode < before.baseRevisionCode) { 24214 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 24215 "Update base revision code " + after.baseRevisionCode 24216 + " is older than current " + before.baseRevisionCode); 24217 } 24218 24219 if (!ArrayUtils.isEmpty(after.splitNames)) { 24220 for (int i = 0; i < after.splitNames.length; i++) { 24221 final String splitName = after.splitNames[i]; 24222 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 24223 if (j != -1) { 24224 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 24225 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 24226 "Update split " + splitName + " revision code " 24227 + after.splitRevisionCodes[i] + " is older than current " 24228 + before.splitRevisionCodes[j]); 24229 } 24230 } 24231 } 24232 } 24233 } 24234 } 24235 24236 private static class MoveCallbacks extends Handler { 24237 private static final int MSG_CREATED = 1; 24238 private static final int MSG_STATUS_CHANGED = 2; 24239 24240 private final RemoteCallbackList<IPackageMoveObserver> 24241 mCallbacks = new RemoteCallbackList<>(); 24242 24243 private final SparseIntArray mLastStatus = new SparseIntArray(); 24244 24245 public MoveCallbacks(Looper looper) { 24246 super(looper); 24247 } 24248 24249 public void register(IPackageMoveObserver callback) { 24250 mCallbacks.register(callback); 24251 } 24252 24253 public void unregister(IPackageMoveObserver callback) { 24254 mCallbacks.unregister(callback); 24255 } 24256 24257 @Override 24258 public void handleMessage(Message msg) { 24259 final SomeArgs args = (SomeArgs) msg.obj; 24260 final int n = mCallbacks.beginBroadcast(); 24261 for (int i = 0; i < n; i++) { 24262 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 24263 try { 24264 invokeCallback(callback, msg.what, args); 24265 } catch (RemoteException ignored) { 24266 } 24267 } 24268 mCallbacks.finishBroadcast(); 24269 args.recycle(); 24270 } 24271 24272 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 24273 throws RemoteException { 24274 switch (what) { 24275 case MSG_CREATED: { 24276 callback.onCreated(args.argi1, (Bundle) args.arg2); 24277 break; 24278 } 24279 case MSG_STATUS_CHANGED: { 24280 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 24281 break; 24282 } 24283 } 24284 } 24285 24286 private void notifyCreated(int moveId, Bundle extras) { 24287 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 24288 24289 final SomeArgs args = SomeArgs.obtain(); 24290 args.argi1 = moveId; 24291 args.arg2 = extras; 24292 obtainMessage(MSG_CREATED, args).sendToTarget(); 24293 } 24294 24295 private void notifyStatusChanged(int moveId, int status) { 24296 notifyStatusChanged(moveId, status, -1); 24297 } 24298 24299 private void notifyStatusChanged(int moveId, int status, long estMillis) { 24300 Slog.v(TAG, "Move " + moveId + " status " + status); 24301 24302 final SomeArgs args = SomeArgs.obtain(); 24303 args.argi1 = moveId; 24304 args.argi2 = status; 24305 args.arg3 = estMillis; 24306 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 24307 24308 synchronized (mLastStatus) { 24309 mLastStatus.put(moveId, status); 24310 } 24311 } 24312 } 24313 24314 private final static class OnPermissionChangeListeners extends Handler { 24315 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 24316 24317 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 24318 new RemoteCallbackList<>(); 24319 24320 public OnPermissionChangeListeners(Looper looper) { 24321 super(looper); 24322 } 24323 24324 @Override 24325 public void handleMessage(Message msg) { 24326 switch (msg.what) { 24327 case MSG_ON_PERMISSIONS_CHANGED: { 24328 final int uid = msg.arg1; 24329 handleOnPermissionsChanged(uid); 24330 } break; 24331 } 24332 } 24333 24334 public void addListenerLocked(IOnPermissionsChangeListener listener) { 24335 mPermissionListeners.register(listener); 24336 24337 } 24338 24339 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 24340 mPermissionListeners.unregister(listener); 24341 } 24342 24343 public void onPermissionsChanged(int uid) { 24344 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 24345 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 24346 } 24347 } 24348 24349 private void handleOnPermissionsChanged(int uid) { 24350 final int count = mPermissionListeners.beginBroadcast(); 24351 try { 24352 for (int i = 0; i < count; i++) { 24353 IOnPermissionsChangeListener callback = mPermissionListeners 24354 .getBroadcastItem(i); 24355 try { 24356 callback.onPermissionsChanged(uid); 24357 } catch (RemoteException e) { 24358 Log.e(TAG, "Permission listener is dead", e); 24359 } 24360 } 24361 } finally { 24362 mPermissionListeners.finishBroadcast(); 24363 } 24364 } 24365 } 24366 24367 private class PackageManagerInternalImpl extends PackageManagerInternal { 24368 @Override 24369 public void setLocationPackagesProvider(PackagesProvider provider) { 24370 synchronized (mPackages) { 24371 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 24372 } 24373 } 24374 24375 @Override 24376 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 24377 synchronized (mPackages) { 24378 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 24379 } 24380 } 24381 24382 @Override 24383 public void setSmsAppPackagesProvider(PackagesProvider provider) { 24384 synchronized (mPackages) { 24385 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 24386 } 24387 } 24388 24389 @Override 24390 public void setDialerAppPackagesProvider(PackagesProvider provider) { 24391 synchronized (mPackages) { 24392 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 24393 } 24394 } 24395 24396 @Override 24397 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 24398 synchronized (mPackages) { 24399 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 24400 } 24401 } 24402 24403 @Override 24404 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 24405 synchronized (mPackages) { 24406 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 24407 } 24408 } 24409 24410 @Override 24411 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 24412 synchronized (mPackages) { 24413 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 24414 packageName, userId); 24415 } 24416 } 24417 24418 @Override 24419 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 24420 synchronized (mPackages) { 24421 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 24422 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 24423 packageName, userId); 24424 } 24425 } 24426 24427 @Override 24428 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 24429 synchronized (mPackages) { 24430 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 24431 packageName, userId); 24432 } 24433 } 24434 24435 @Override 24436 public void setKeepUninstalledPackages(final List<String> packageList) { 24437 Preconditions.checkNotNull(packageList); 24438 List<String> removedFromList = null; 24439 synchronized (mPackages) { 24440 if (mKeepUninstalledPackages != null) { 24441 final int packagesCount = mKeepUninstalledPackages.size(); 24442 for (int i = 0; i < packagesCount; i++) { 24443 String oldPackage = mKeepUninstalledPackages.get(i); 24444 if (packageList != null && packageList.contains(oldPackage)) { 24445 continue; 24446 } 24447 if (removedFromList == null) { 24448 removedFromList = new ArrayList<>(); 24449 } 24450 removedFromList.add(oldPackage); 24451 } 24452 } 24453 mKeepUninstalledPackages = new ArrayList<>(packageList); 24454 if (removedFromList != null) { 24455 final int removedCount = removedFromList.size(); 24456 for (int i = 0; i < removedCount; i++) { 24457 deletePackageIfUnusedLPr(removedFromList.get(i)); 24458 } 24459 } 24460 } 24461 } 24462 24463 @Override 24464 public boolean isPermissionsReviewRequired(String packageName, int userId) { 24465 synchronized (mPackages) { 24466 // If we do not support permission review, done. 24467 if (!mPermissionReviewRequired) { 24468 return false; 24469 } 24470 24471 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 24472 if (packageSetting == null) { 24473 return false; 24474 } 24475 24476 // Permission review applies only to apps not supporting the new permission model. 24477 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 24478 return false; 24479 } 24480 24481 // Legacy apps have the permission and get user consent on launch. 24482 PermissionsState permissionsState = packageSetting.getPermissionsState(); 24483 return permissionsState.isPermissionReviewRequired(userId); 24484 } 24485 } 24486 24487 @Override 24488 public PackageInfo getPackageInfo( 24489 String packageName, int flags, int filterCallingUid, int userId) { 24490 return PackageManagerService.this 24491 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 24492 flags, filterCallingUid, userId); 24493 } 24494 24495 @Override 24496 public ApplicationInfo getApplicationInfo( 24497 String packageName, int flags, int filterCallingUid, int userId) { 24498 return PackageManagerService.this 24499 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 24500 } 24501 24502 @Override 24503 public ActivityInfo getActivityInfo( 24504 ComponentName component, int flags, int filterCallingUid, int userId) { 24505 return PackageManagerService.this 24506 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 24507 } 24508 24509 @Override 24510 public List<ResolveInfo> queryIntentActivities( 24511 Intent intent, int flags, int filterCallingUid, int userId) { 24512 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 24513 return PackageManagerService.this 24514 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 24515 userId, false /*resolveForStart*/); 24516 } 24517 24518 @Override 24519 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 24520 int userId) { 24521 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 24522 } 24523 24524 @Override 24525 public void setDeviceAndProfileOwnerPackages( 24526 int deviceOwnerUserId, String deviceOwnerPackage, 24527 SparseArray<String> profileOwnerPackages) { 24528 mProtectedPackages.setDeviceAndProfileOwnerPackages( 24529 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 24530 } 24531 24532 @Override 24533 public boolean isPackageDataProtected(int userId, String packageName) { 24534 return mProtectedPackages.isPackageDataProtected(userId, packageName); 24535 } 24536 24537 @Override 24538 public boolean isPackageEphemeral(int userId, String packageName) { 24539 synchronized (mPackages) { 24540 final PackageSetting ps = mSettings.mPackages.get(packageName); 24541 return ps != null ? ps.getInstantApp(userId) : false; 24542 } 24543 } 24544 24545 @Override 24546 public boolean wasPackageEverLaunched(String packageName, int userId) { 24547 synchronized (mPackages) { 24548 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 24549 } 24550 } 24551 24552 @Override 24553 public void grantRuntimePermission(String packageName, String name, int userId, 24554 boolean overridePolicy) { 24555 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 24556 overridePolicy); 24557 } 24558 24559 @Override 24560 public void revokeRuntimePermission(String packageName, String name, int userId, 24561 boolean overridePolicy) { 24562 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 24563 overridePolicy); 24564 } 24565 24566 @Override 24567 public String getNameForUid(int uid) { 24568 return PackageManagerService.this.getNameForUid(uid); 24569 } 24570 24571 @Override 24572 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 24573 Intent origIntent, String resolvedType, String callingPackage, 24574 Bundle verificationBundle, int userId) { 24575 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 24576 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 24577 userId); 24578 } 24579 24580 @Override 24581 public void grantEphemeralAccess(int userId, Intent intent, 24582 int targetAppId, int ephemeralAppId) { 24583 synchronized (mPackages) { 24584 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 24585 targetAppId, ephemeralAppId); 24586 } 24587 } 24588 24589 @Override 24590 public boolean isInstantAppInstallerComponent(ComponentName component) { 24591 synchronized (mPackages) { 24592 return mInstantAppInstallerActivity != null 24593 && mInstantAppInstallerActivity.getComponentName().equals(component); 24594 } 24595 } 24596 24597 @Override 24598 public void pruneInstantApps() { 24599 mInstantAppRegistry.pruneInstantApps(); 24600 } 24601 24602 @Override 24603 public String getSetupWizardPackageName() { 24604 return mSetupWizardPackage; 24605 } 24606 24607 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 24608 if (policy != null) { 24609 mExternalSourcesPolicy = policy; 24610 } 24611 } 24612 24613 @Override 24614 public boolean isPackagePersistent(String packageName) { 24615 synchronized (mPackages) { 24616 PackageParser.Package pkg = mPackages.get(packageName); 24617 return pkg != null 24618 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 24619 | ApplicationInfo.FLAG_PERSISTENT)) == 24620 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 24621 : false; 24622 } 24623 } 24624 24625 @Override 24626 public List<PackageInfo> getOverlayPackages(int userId) { 24627 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 24628 synchronized (mPackages) { 24629 for (PackageParser.Package p : mPackages.values()) { 24630 if (p.mOverlayTarget != null) { 24631 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 24632 if (pkg != null) { 24633 overlayPackages.add(pkg); 24634 } 24635 } 24636 } 24637 } 24638 return overlayPackages; 24639 } 24640 24641 @Override 24642 public List<String> getTargetPackageNames(int userId) { 24643 List<String> targetPackages = new ArrayList<>(); 24644 synchronized (mPackages) { 24645 for (PackageParser.Package p : mPackages.values()) { 24646 if (p.mOverlayTarget == null) { 24647 targetPackages.add(p.packageName); 24648 } 24649 } 24650 } 24651 return targetPackages; 24652 } 24653 24654 @Override 24655 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 24656 @Nullable List<String> overlayPackageNames) { 24657 synchronized (mPackages) { 24658 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 24659 Slog.e(TAG, "failed to find package " + targetPackageName); 24660 return false; 24661 } 24662 ArrayList<String> overlayPaths = null; 24663 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 24664 final int N = overlayPackageNames.size(); 24665 overlayPaths = new ArrayList<>(N); 24666 for (int i = 0; i < N; i++) { 24667 final String packageName = overlayPackageNames.get(i); 24668 final PackageParser.Package pkg = mPackages.get(packageName); 24669 if (pkg == null) { 24670 Slog.e(TAG, "failed to find package " + packageName); 24671 return false; 24672 } 24673 overlayPaths.add(pkg.baseCodePath); 24674 } 24675 } 24676 24677 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 24678 ps.setOverlayPaths(overlayPaths, userId); 24679 return true; 24680 } 24681 } 24682 24683 @Override 24684 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 24685 int flags, int userId) { 24686 return resolveIntentInternal( 24687 intent, resolvedType, flags, userId, true /*resolveForStart*/); 24688 } 24689 24690 @Override 24691 public ResolveInfo resolveService(Intent intent, String resolvedType, 24692 int flags, int userId, int callingUid) { 24693 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 24694 } 24695 24696 @Override 24697 public void addIsolatedUid(int isolatedUid, int ownerUid) { 24698 synchronized (mPackages) { 24699 mIsolatedOwners.put(isolatedUid, ownerUid); 24700 } 24701 } 24702 24703 @Override 24704 public void removeIsolatedUid(int isolatedUid) { 24705 synchronized (mPackages) { 24706 mIsolatedOwners.delete(isolatedUid); 24707 } 24708 } 24709 24710 @Override 24711 public int getUidTargetSdkVersion(int uid) { 24712 synchronized (mPackages) { 24713 return getUidTargetSdkVersionLockedLPr(uid); 24714 } 24715 } 24716 24717 @Override 24718 public boolean canAccessInstantApps(int callingUid, int userId) { 24719 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 24720 } 24721 } 24722 24723 @Override 24724 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 24725 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 24726 synchronized (mPackages) { 24727 final long identity = Binder.clearCallingIdentity(); 24728 try { 24729 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 24730 packageNames, userId); 24731 } finally { 24732 Binder.restoreCallingIdentity(identity); 24733 } 24734 } 24735 } 24736 24737 @Override 24738 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 24739 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 24740 synchronized (mPackages) { 24741 final long identity = Binder.clearCallingIdentity(); 24742 try { 24743 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 24744 packageNames, userId); 24745 } finally { 24746 Binder.restoreCallingIdentity(identity); 24747 } 24748 } 24749 } 24750 24751 private static void enforceSystemOrPhoneCaller(String tag) { 24752 int callingUid = Binder.getCallingUid(); 24753 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 24754 throw new SecurityException( 24755 "Cannot call " + tag + " from UID " + callingUid); 24756 } 24757 } 24758 24759 boolean isHistoricalPackageUsageAvailable() { 24760 return mPackageUsage.isHistoricalPackageUsageAvailable(); 24761 } 24762 24763 /** 24764 * Return a <b>copy</b> of the collection of packages known to the package manager. 24765 * @return A copy of the values of mPackages. 24766 */ 24767 Collection<PackageParser.Package> getPackages() { 24768 synchronized (mPackages) { 24769 return new ArrayList<>(mPackages.values()); 24770 } 24771 } 24772 24773 /** 24774 * Logs process start information (including base APK hash) to the security log. 24775 * @hide 24776 */ 24777 @Override 24778 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 24779 String apkFile, int pid) { 24780 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24781 return; 24782 } 24783 if (!SecurityLog.isLoggingEnabled()) { 24784 return; 24785 } 24786 Bundle data = new Bundle(); 24787 data.putLong("startTimestamp", System.currentTimeMillis()); 24788 data.putString("processName", processName); 24789 data.putInt("uid", uid); 24790 data.putString("seinfo", seinfo); 24791 data.putString("apkFile", apkFile); 24792 data.putInt("pid", pid); 24793 Message msg = mProcessLoggingHandler.obtainMessage( 24794 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 24795 msg.setData(data); 24796 mProcessLoggingHandler.sendMessage(msg); 24797 } 24798 24799 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 24800 return mCompilerStats.getPackageStats(pkgName); 24801 } 24802 24803 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 24804 return getOrCreateCompilerPackageStats(pkg.packageName); 24805 } 24806 24807 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 24808 return mCompilerStats.getOrCreatePackageStats(pkgName); 24809 } 24810 24811 public void deleteCompilerPackageStats(String pkgName) { 24812 mCompilerStats.deletePackageStats(pkgName); 24813 } 24814 24815 @Override 24816 public int getInstallReason(String packageName, int userId) { 24817 final int callingUid = Binder.getCallingUid(); 24818 enforceCrossUserPermission(callingUid, userId, 24819 true /* requireFullPermission */, false /* checkShell */, 24820 "get install reason"); 24821 synchronized (mPackages) { 24822 final PackageSetting ps = mSettings.mPackages.get(packageName); 24823 if (filterAppAccessLPr(ps, callingUid, userId)) { 24824 return PackageManager.INSTALL_REASON_UNKNOWN; 24825 } 24826 if (ps != null) { 24827 return ps.getInstallReason(userId); 24828 } 24829 } 24830 return PackageManager.INSTALL_REASON_UNKNOWN; 24831 } 24832 24833 @Override 24834 public boolean canRequestPackageInstalls(String packageName, int userId) { 24835 return canRequestPackageInstallsInternal(packageName, 0, userId, 24836 true /* throwIfPermNotDeclared*/); 24837 } 24838 24839 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 24840 boolean throwIfPermNotDeclared) { 24841 int callingUid = Binder.getCallingUid(); 24842 int uid = getPackageUid(packageName, 0, userId); 24843 if (callingUid != uid && callingUid != Process.ROOT_UID 24844 && callingUid != Process.SYSTEM_UID) { 24845 throw new SecurityException( 24846 "Caller uid " + callingUid + " does not own package " + packageName); 24847 } 24848 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 24849 if (info == null) { 24850 return false; 24851 } 24852 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 24853 return false; 24854 } 24855 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 24856 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 24857 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 24858 if (throwIfPermNotDeclared) { 24859 throw new SecurityException("Need to declare " + appOpPermission 24860 + " to call this api"); 24861 } else { 24862 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 24863 return false; 24864 } 24865 } 24866 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 24867 return false; 24868 } 24869 if (mExternalSourcesPolicy != null) { 24870 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 24871 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 24872 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 24873 } 24874 } 24875 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 24876 } 24877 24878 @Override 24879 public ComponentName getInstantAppResolverSettingsComponent() { 24880 return mInstantAppResolverSettingsComponent; 24881 } 24882 24883 @Override 24884 public ComponentName getInstantAppInstallerComponent() { 24885 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24886 return null; 24887 } 24888 return mInstantAppInstallerActivity == null 24889 ? null : mInstantAppInstallerActivity.getComponentName(); 24890 } 24891 24892 @Override 24893 public String getInstantAppAndroidId(String packageName, int userId) { 24894 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 24895 "getInstantAppAndroidId"); 24896 enforceCrossUserPermission(Binder.getCallingUid(), userId, 24897 true /* requireFullPermission */, false /* checkShell */, 24898 "getInstantAppAndroidId"); 24899 // Make sure the target is an Instant App. 24900 if (!isInstantApp(packageName, userId)) { 24901 return null; 24902 } 24903 synchronized (mPackages) { 24904 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 24905 } 24906 } 24907 } 24908 24909 interface PackageSender { 24910 void sendPackageBroadcast(final String action, final String pkg, 24911 final Bundle extras, final int flags, final String targetPkg, 24912 final IIntentReceiver finishedReceiver, final int[] userIds); 24913 void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 24914 int appId, int... userIds); 24915 } 24916