1 /* 2 * Copyright (C) 2020 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 package com.android.server.am; 17 18 import static android.Manifest.permission.GET_ANY_PROVIDER_TYPE; 19 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_GET_PROVIDER; 20 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_REMOVE_PROVIDER; 21 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_PROVIDER; 22 import static android.content.ContentProvider.isAuthorityRedirectedForCloneProfile; 23 import static android.os.Process.PROC_CHAR; 24 import static android.os.Process.PROC_OUT_LONG; 25 import static android.os.Process.PROC_PARENS; 26 import static android.os.Process.PROC_SPACE_TERM; 27 import static android.os.Process.SYSTEM_UID; 28 29 import static com.android.internal.util.FrameworkStatsLog.GET_TYPE_ACCESSED_WITHOUT_PERMISSION; 30 import static com.android.internal.util.FrameworkStatsLog.GET_TYPE_ACCESSED_WITHOUT_PERMISSION__LOCATION__AM_FRAMEWORK_PERMISSION; 31 import static com.android.internal.util.FrameworkStatsLog.PROVIDER_ACQUISITION_EVENT_REPORTED; 32 import static com.android.internal.util.FrameworkStatsLog.PROVIDER_ACQUISITION_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_NORMAL; 33 import static com.android.internal.util.FrameworkStatsLog.PROVIDER_ACQUISITION_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_STOPPED; 34 import static com.android.internal.util.FrameworkStatsLog.PROVIDER_ACQUISITION_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD; 35 import static com.android.internal.util.FrameworkStatsLog.PROVIDER_ACQUISITION_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM; 36 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU; 37 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESSES; 38 import static com.android.server.am.ActivityManagerService.TAG_MU; 39 import static com.android.server.am.Flags.serviceBindingOomAdjPolicy; 40 41 import android.annotation.Nullable; 42 import android.annotation.UserIdInt; 43 import android.app.ActivityManager; 44 import android.app.ActivityManagerInternal; 45 import android.app.AppGlobals; 46 import android.app.AppOpsManager; 47 import android.app.ApplicationExitInfo; 48 import android.app.ContentProviderHolder; 49 import android.app.IApplicationThread; 50 import android.app.usage.UsageEvents.Event; 51 import android.content.AttributionSource; 52 import android.content.ComponentName; 53 import android.content.ContentProvider; 54 import android.content.ContentResolver; 55 import android.content.Context; 56 import android.content.IContentProvider; 57 import android.content.Intent; 58 import android.content.pm.ApplicationInfo; 59 import android.content.pm.PackageInfo; 60 import android.content.pm.PackageManager; 61 import android.content.pm.PathPermission; 62 import android.content.pm.ProviderInfo; 63 import android.content.pm.UserInfo; 64 import android.content.pm.UserProperties; 65 import android.database.ContentObserver; 66 import android.net.Uri; 67 import android.os.Binder; 68 import android.os.Build; 69 import android.os.Bundle; 70 import android.os.Debug; 71 import android.os.IBinder; 72 import android.os.Message; 73 import android.os.Process; 74 import android.os.RemoteCallback; 75 import android.os.RemoteException; 76 import android.os.SystemClock; 77 import android.os.Trace; 78 import android.os.UserHandle; 79 import android.provider.Settings; 80 import android.text.TextUtils; 81 import android.util.ArrayMap; 82 import android.util.Log; 83 import android.util.Slog; 84 import android.util.SparseArray; 85 86 import com.android.internal.annotations.GuardedBy; 87 import com.android.internal.os.BackgroundThread; 88 import com.android.internal.os.TimeoutRecord; 89 import com.android.internal.util.ArrayUtils; 90 import com.android.internal.util.FrameworkStatsLog; 91 import com.android.server.LocalManagerRegistry; 92 import com.android.server.LocalServices; 93 import com.android.server.crashrecovery.CrashRecoveryAdaptor; 94 import com.android.server.pm.UserManagerInternal; 95 import com.android.server.pm.pkg.AndroidPackage; 96 import com.android.server.sdksandbox.SdkSandboxManagerLocal; 97 98 import java.io.FileDescriptor; 99 import java.io.PrintWriter; 100 import java.util.ArrayList; 101 import java.util.HashMap; 102 import java.util.List; 103 import java.util.Map; 104 import java.util.Objects; 105 106 /** 107 * Activity manager code dealing with content providers. 108 */ 109 public class ContentProviderHelper { 110 private static final String TAG = "ContentProviderHelper"; 111 112 private final ActivityManagerService mService; 113 114 /** 115 * List of content providers who have clients waiting for them. The 116 * application is currently being launched and the provider will be 117 * removed from this list once it is published. 118 */ 119 private final ArrayList<ContentProviderRecord> mLaunchingProviders = new ArrayList<>(); 120 private final ProviderMap mProviderMap; 121 private boolean mSystemProvidersInstalled; 122 123 private final Map<String, Boolean> mCloneProfileAuthorityRedirectionCache = new HashMap<>(); 124 ContentProviderHelper(ActivityManagerService service, boolean createProviderMap)125 ContentProviderHelper(ActivityManagerService service, boolean createProviderMap) { 126 mService = service; 127 mProviderMap = createProviderMap ? new ProviderMap(mService) : null; 128 } 129 getProviderMap()130 ProviderMap getProviderMap() { 131 return mProviderMap; 132 } 133 getContentProvider(IApplicationThread caller, String callingPackage, String name, int userId, boolean stable)134 ContentProviderHolder getContentProvider(IApplicationThread caller, String callingPackage, 135 String name, int userId, boolean stable) { 136 mService.enforceNotIsolatedCaller("getContentProvider"); 137 if (caller == null) { 138 String msg = "null IApplicationThread when getting content provider " + name; 139 Slog.w(TAG, msg); 140 throw new SecurityException(msg); 141 } 142 // The incoming user check is now handled in checkContentProviderPermissionLocked() to deal 143 // with cross-user grant. 144 final int callingUid = Binder.getCallingUid(); 145 if (callingPackage != null && mService.mAppOpsService.checkPackage( 146 callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) { 147 throw new SecurityException("Given calling package " + callingPackage 148 + " does not match caller's uid " + callingUid); 149 } 150 return getContentProviderImpl(caller, name, null, callingUid, callingPackage, 151 null, stable, userId); 152 } 153 getContentProviderExternal( String name, int userId, IBinder token, String tag)154 ContentProviderHolder getContentProviderExternal( 155 String name, int userId, IBinder token, String tag) { 156 mService.enforceCallingPermission( 157 android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 158 "Do not have permission in call getContentProviderExternal()"); 159 userId = mService.mUserController.handleIncomingUser( 160 Binder.getCallingPid(), Binder.getCallingUid(), userId, 161 false, ActivityManagerInternal.ALLOW_FULL_ONLY, "getContentProvider", null); 162 return getContentProviderExternalUnchecked(name, token, Binder.getCallingUid(), 163 tag != null ? tag : "*external*", userId); 164 } 165 getContentProviderExternalUnchecked(String name, IBinder token, int callingUid, String callingTag, int userId)166 ContentProviderHolder getContentProviderExternalUnchecked(String name, 167 IBinder token, int callingUid, String callingTag, int userId) { 168 return getContentProviderImpl(null, name, token, callingUid, null, callingTag, 169 true, userId); 170 } 171 getContentProviderImpl(IApplicationThread caller, String name, IBinder token, int callingUid, String callingPackage, String callingTag, boolean stable, int userId)172 private ContentProviderHolder getContentProviderImpl(IApplicationThread caller, 173 String name, IBinder token, int callingUid, String callingPackage, String callingTag, 174 boolean stable, int userId) { 175 ContentProviderRecord cpr = null; 176 ContentProviderConnection conn = null; 177 ProviderInfo cpi = null; 178 boolean providerRunning = false; 179 final int expectedUserId = userId; 180 synchronized (mService) { 181 long startTime = SystemClock.uptimeMillis(); 182 long startTimeNs = SystemClock.uptimeNanos(); 183 184 ProcessRecord r = null; 185 if (caller != null) { 186 r = mService.getRecordForAppLOSP(caller); 187 if (r == null) { 188 throw new SecurityException("Unable to find app for caller " + caller 189 + " (pid=" + Binder.getCallingPid() + ") when getting content provider " 190 + name); 191 } 192 } 193 194 boolean checkCrossUser = true; 195 196 checkTime(startTime, "getContentProviderImpl: getProviderByName"); 197 198 UserManagerInternal umInternal = LocalServices.getService(UserManagerInternal.class); 199 200 /* 201 For clone user profile and allowed authority, skipping finding provider and redirecting 202 it to owner profile. Ideally clone profile should not have MediaProvider instance 203 installed and mProviderMap would not have entry for clone user. This is just fallback 204 check to ensure even if MediaProvider is installed in Clone Profile, it should not be 205 used and redirect to owner user's MediaProvider. 206 */ 207 //todo(b/236121588) MediaProvider should not be installed in clone profile. 208 final UserProperties userProps = umInternal.getUserProperties(userId); 209 final boolean isMediaSharedWithParent = 210 userProps != null && userProps.isMediaSharedWithParent(); 211 if (!isAuthorityRedirectedForCloneProfileCached(name) || !isMediaSharedWithParent) { 212 // First check if this content provider has been published... 213 cpr = mProviderMap.getProviderByName(name, userId); 214 // In case we are on media authority and callingUid is cloned app asking to access 215 // the contentProvider of user 0 by specifying content as 216 // content://<parent-id>@media/external/file, we skip checkUser. 217 if (isAuthorityRedirectedForCloneProfileCached(name)) { 218 final int callingUserId = UserHandle.getUserId(callingUid); 219 final UserProperties userPropsCallingUser = 220 umInternal.getUserProperties(callingUserId); 221 final boolean isMediaSharedWithParentForCallingUser = 222 userPropsCallingUser != null 223 && userPropsCallingUser.isMediaSharedWithParent(); 224 if (isMediaSharedWithParentForCallingUser 225 && umInternal.getProfileParentId(callingUserId) == userId) { 226 checkCrossUser = false; 227 } 228 } 229 } 230 // If that didn't work, check if it exists for user 0 and then 231 // verify that it's a singleton provider before using it. 232 if (cpr == null && userId != UserHandle.USER_SYSTEM) { 233 cpr = mProviderMap.getProviderByName(name, UserHandle.USER_SYSTEM); 234 if (cpr != null) { 235 cpi = cpr.info; 236 237 if (mService.isSingleton( 238 cpi.processName, cpi.applicationInfo, cpi.name, cpi.flags) 239 && mService.isValidSingletonCall( 240 r == null ? callingUid : r.uid, cpi.applicationInfo.uid)) { 241 userId = UserHandle.USER_SYSTEM; 242 checkCrossUser = false; 243 } else if (isAuthorityRedirectedForCloneProfileCached(name)) { 244 if (isMediaSharedWithParent) { 245 userId = umInternal.getProfileParentId(userId); 246 checkCrossUser = false; 247 } 248 } else { 249 cpr = null; 250 cpi = null; 251 } 252 } 253 } 254 255 ProcessRecord dyingProc = null; 256 if (cpr != null && cpr.proc != null) { 257 providerRunning = !cpr.proc.isKilled(); 258 259 // Note if killedByAm is also set, this means the provider process has just been 260 // killed by AM (in ProcessRecord.kill()), but appDiedLocked() hasn't been called 261 // yet. So we need to call appDiedLocked() here and let it clean up. 262 // (See the commit message on I2c4ba1e87c2d47f2013befff10c49b3dc337a9a7 to see 263 // how to test this case.) 264 if (cpr.proc.isKilled() && cpr.proc.isKilledByAm()) { 265 Slog.wtf(TAG, cpr.proc.toString() + " was killed by AM but isn't really dead"); 266 // Now we are going to wait for the death before starting the new process. 267 dyingProc = cpr.proc; 268 } 269 } 270 271 final int callingProcessState = r != null 272 ? r.mState.getCurProcState() : ActivityManager.PROCESS_STATE_UNKNOWN; 273 274 if (providerRunning) { 275 cpi = cpr.info; 276 277 278 if (r != null && cpr.canRunHere(r)) { 279 checkAssociationAndPermissionLocked(r, cpi, callingUid, userId, checkCrossUser, 280 cpr.name.flattenToShortString(), startTime); 281 282 // This provider has been published or is in the process 283 // of being published... but it is also allowed to run 284 // in the caller's process, so don't make a connection 285 // and just let the caller instantiate its own instance. 286 ContentProviderHolder holder = cpr.newHolder(null, true); 287 // don't give caller the provider object, it needs to make its own. 288 holder.provider = null; 289 FrameworkStatsLog.write( 290 PROVIDER_ACQUISITION_EVENT_REPORTED, 291 r.uid, callingUid, 292 PROVIDER_ACQUISITION_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM, 293 PROVIDER_ACQUISITION_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_NORMAL, 294 cpi.packageName, callingPackage, 295 callingProcessState, callingProcessState, 296 false, 0L); 297 return holder; 298 } 299 300 // Don't expose providers between normal apps and instant apps; enforce limited 301 // package visibility (introduced in Android 11); etc. 302 try { 303 if (AppGlobals.getPackageManager() 304 .resolveContentProvider(name, /*flags=*/ 0, userId) == null) { 305 return null; 306 } 307 } catch (RemoteException e) { 308 } 309 310 checkAssociationAndPermissionLocked(r, cpi, callingUid, userId, checkCrossUser, 311 cpr.name.flattenToShortString(), startTime); 312 313 final int providerProcessState = cpr.proc.mState.getCurProcState(); 314 315 final long origId = Binder.clearCallingIdentity(); 316 try { 317 checkTime(startTime, "getContentProviderImpl: incProviderCountLocked"); 318 319 // Return the provider instance right away since it already exists. 320 conn = incProviderCountLocked(r, cpr, token, callingUid, callingPackage, 321 callingTag, stable, true, startTime, mService.mProcessList, 322 expectedUserId); 323 324 checkTime(startTime, "getContentProviderImpl: before updateOomAdj"); 325 final int verifiedAdj = cpr.proc.mState.getVerifiedAdj(); 326 boolean success = !serviceBindingOomAdjPolicy() 327 || mService.mOomAdjuster.evaluateProviderConnectionAdd(r, cpr.proc) 328 ? mService.mProcessStateController.runUpdate(cpr.proc, 329 OOM_ADJ_REASON_GET_PROVIDER) 330 : true; 331 // XXX things have changed so updateOomAdjLocked doesn't actually tell us 332 // if the process has been successfully adjusted. So to reduce races with 333 // it, we will check whether the process still exists. Note that this doesn't 334 // completely get rid of races with LMK killing the process, but should make 335 // them much smaller. 336 if (success && verifiedAdj != cpr.proc.mState.getSetAdj() 337 && !isProcessAliveLocked(cpr.proc)) { 338 success = false; 339 } 340 maybeUpdateProviderUsageStatsLocked(r, cpr.info.packageName, name); 341 checkTime(startTime, "getContentProviderImpl: after updateOomAdj"); 342 if (ActivityManagerDebugConfig.DEBUG_PROVIDER) { 343 Slog.i(TAG, "Adjust success: " + success); 344 } 345 // NOTE: there is still a race here where a signal could be 346 // pending on the process even though we managed to update its 347 // adj level. Not sure what to do about this, but at least 348 // the race is now smaller. 349 if (!success) { 350 // Uh oh... it looks like the provider's process 351 // has been killed on us. We need to wait for a new 352 // process to be started, and make sure its death 353 // doesn't kill our process. 354 Slog.wtf(TAG, "Existing provider " + cpr.name.flattenToShortString() 355 + " is crashing; detaching " + r); 356 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable, 357 false, false); 358 if (!lastRef) { 359 // This wasn't the last ref our process had on 360 // the provider... we will be killed during cleaning up, bail. 361 return null; 362 } 363 // We'll just start a new process to host the content provider 364 providerRunning = false; 365 conn = null; 366 dyingProc = cpr.proc; 367 } else { 368 cpr.proc.mState.setVerifiedAdj(cpr.proc.mState.getSetAdj()); 369 FrameworkStatsLog.write( 370 PROVIDER_ACQUISITION_EVENT_REPORTED, 371 cpr.proc.uid, callingUid, 372 PROVIDER_ACQUISITION_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM, 373 PROVIDER_ACQUISITION_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_NORMAL, 374 cpi.packageName, callingPackage, 375 callingProcessState, providerProcessState, false, 0L); 376 } 377 } finally { 378 Binder.restoreCallingIdentity(origId); 379 } 380 } 381 382 if (!providerRunning) { 383 try { 384 checkTime(startTime, "getContentProviderImpl: before resolveContentProvider"); 385 cpi = AppGlobals.getPackageManager().resolveContentProvider(name, 386 ActivityManagerService.STOCK_PM_FLAGS 387 | PackageManager.GET_URI_PERMISSION_PATTERNS, 388 userId); 389 checkTime(startTime, "getContentProviderImpl: after resolveContentProvider"); 390 } catch (RemoteException ex) { 391 } 392 if (cpi == null) { 393 return null; 394 } 395 // If the provider is a singleton AND 396 // (it's a call within the same user || the provider is a privileged app) 397 // Then allow connecting to the singleton provider 398 boolean singleton = mService.isSingleton( 399 cpi.processName, cpi.applicationInfo, cpi.name, cpi.flags) 400 && mService.isValidSingletonCall( 401 r == null ? callingUid : r.uid, cpi.applicationInfo.uid); 402 if (singleton) { 403 userId = UserHandle.USER_SYSTEM; 404 } 405 cpi.applicationInfo = mService.getAppInfoForUser(cpi.applicationInfo, userId); 406 checkTime(startTime, "getContentProviderImpl: got app info for user"); 407 408 checkAssociationAndPermissionLocked(r, cpi, callingUid, userId, !singleton, 409 name, startTime); 410 411 if (!mService.mProcessesReady && !cpi.processName.equals("system")) { 412 // If this content provider does not run in the system 413 // process, and the system is not yet ready to run other 414 // processes, then fail fast instead of hanging. 415 throw new IllegalArgumentException( 416 "Attempt to launch content provider before system ready"); 417 } 418 419 // If system providers are not installed yet we aggressively crash to avoid 420 // creating multiple instance of these providers and then bad things happen! 421 synchronized (this) { 422 if (!mSystemProvidersInstalled && cpi.applicationInfo.isSystemApp() 423 && "system".equals(cpi.processName)) { 424 throw new IllegalStateException("Cannot access system provider: '" 425 + cpi.authority + "' before system providers are installed!"); 426 } 427 } 428 429 // Make sure that the user who owns this provider is running. If not, 430 // we don't want to allow it to run. 431 if (!mService.mUserController.isUserRunning(userId, 0)) { 432 Slog.w(TAG, "Unable to launch app " 433 + cpi.applicationInfo.packageName + "/" + cpi.applicationInfo.uid 434 + " for provider " + name + ": user " + userId + " is stopped"); 435 return null; 436 } 437 438 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 439 checkTime(startTime, "getContentProviderImpl: before getProviderByClass"); 440 cpr = mProviderMap.getProviderByClass(comp, userId); 441 checkTime(startTime, "getContentProviderImpl: after getProviderByClass"); 442 443 // The old stable connection's client should be killed during proc cleaning up, 444 // so do not re-use the old ContentProviderRecord, otherwise the new clients 445 // could get killed unexpectedly. Meanwhile, we should retrieve the latest 446 // application info from package manager instead of reusing the info from 447 // the dying one, as the package could have been updated. 448 boolean firstClass = cpr == null || (dyingProc == cpr.proc && dyingProc != null); 449 if (firstClass) { 450 final long ident = Binder.clearCallingIdentity(); 451 452 // If permissions need a review before any of the app components can run, 453 // we return no provider and launch a review activity if the calling app 454 // is in the foreground. 455 if (!requestTargetProviderPermissionsReviewIfNeededLocked( 456 cpi, r, userId, mService.mContext)) { 457 return null; 458 } 459 460 try { 461 checkTime(startTime, "getContentProviderImpl: before getApplicationInfo"); 462 ApplicationInfo ai = AppGlobals.getPackageManager().getApplicationInfo( 463 cpi.applicationInfo.packageName, 464 ActivityManagerService.STOCK_PM_FLAGS, userId); 465 checkTime(startTime, "getContentProviderImpl: after getApplicationInfo"); 466 if (ai == null) { 467 Slog.w(TAG, "No package info for content provider " + cpi.name); 468 return null; 469 } 470 ai = mService.getAppInfoForUser(ai, userId); 471 cpr = new ContentProviderRecord(mService, cpi, ai, comp, singleton); 472 } catch (RemoteException ex) { 473 // pm is in same process, this will never happen. 474 } finally { 475 Binder.restoreCallingIdentity(ident); 476 } 477 } 478 479 checkTime(startTime, "getContentProviderImpl: now have ContentProviderRecord"); 480 481 if (r != null && cpr.canRunHere(r)) { 482 // If this is a multiprocess provider, then just return its 483 // info and allow the caller to instantiate it. Only do 484 // this if the provider is the same user as the caller's 485 // process, or can run as root (so can be in any process). 486 return cpr.newHolder(null, true); 487 } 488 489 if (ActivityManagerDebugConfig.DEBUG_PROVIDER) { 490 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + (r != null ? r.uid : null) 491 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name 492 + " callers=" + Debug.getCallers(6)); 493 } 494 495 // This is single process, and our app is now connecting to it. 496 // See if we are already in the process of launching this provider. 497 final int numLaunchingProviders = mLaunchingProviders.size(); 498 int i; 499 for (i = 0; i < numLaunchingProviders; i++) { 500 if (mLaunchingProviders.get(i) == cpr) { 501 break; 502 } 503 } 504 505 // If the provider is not already being launched, then get it started. 506 if (i >= numLaunchingProviders) { 507 final long origId = Binder.clearCallingIdentity(); 508 509 try { 510 if (!TextUtils.equals(cpr.appInfo.packageName, callingPackage)) { 511 // Report component used since a content provider is being bound. 512 mService.mUsageStatsService.reportEvent( 513 cpr.appInfo.packageName, userId, Event.APP_COMPONENT_USED); 514 } 515 516 try { 517 checkTime(startTime, 518 "getContentProviderImpl: before set stopped state"); 519 mService.mPackageManagerInt.notifyComponentUsed( 520 cpr.appInfo.packageName, userId, callingPackage, 521 cpr.toString()); 522 checkTime(startTime, "getContentProviderImpl: after set stopped state"); 523 } catch (IllegalArgumentException e) { 524 Slog.w(TAG, "Failed trying to unstop package " 525 + cpr.appInfo.packageName + ": " + e); 526 } 527 528 // Use existing process if already started 529 checkTime(startTime, "getContentProviderImpl: looking for process record"); 530 ProcessRecord proc = mService.getProcessRecordLocked( 531 cpi.processName, cpr.appInfo.uid); 532 IApplicationThread thread; 533 if (proc != null && (thread = proc.getThread()) != null 534 && !proc.isKilled()) { 535 if (ActivityManagerDebugConfig.DEBUG_PROVIDER) { 536 Slog.d(TAG, "Installing in existing process " + proc); 537 } 538 if (mService.mProcessStateController.addPublishedProvider(proc, 539 cpi.name, cpr)) { 540 checkTime(startTime, "getContentProviderImpl: scheduling install"); 541 mService.mOomAdjuster.unfreezeTemporarily(proc, 542 CachedAppOptimizer.UNFREEZE_REASON_GET_PROVIDER); 543 try { 544 thread.scheduleInstallProvider(cpi); 545 } catch (RemoteException e) { 546 } 547 } 548 FrameworkStatsLog.write( 549 PROVIDER_ACQUISITION_EVENT_REPORTED, 550 proc.uid, callingUid, 551 PROVIDER_ACQUISITION_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM, 552 PROVIDER_ACQUISITION_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_NORMAL, 553 cpi.packageName, callingPackage, 554 callingProcessState, proc.mState.getCurProcState(), 555 false, 0L); 556 } else { 557 final boolean stopped = cpr.appInfo.isStopped(); 558 final int packageState = stopped 559 ? PROVIDER_ACQUISITION_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_STOPPED 560 : PROVIDER_ACQUISITION_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_NORMAL; 561 final boolean firstLaunch = cpr.appInfo.isNotLaunched(); 562 checkTime(startTime, "getContentProviderImpl: before start process"); 563 proc = mService.startProcessLocked( 564 cpi.processName, cpr.appInfo, false, 0, 565 new HostingRecord(HostingRecord.HOSTING_TYPE_CONTENT_PROVIDER, 566 new ComponentName( 567 cpi.applicationInfo.packageName, cpi.name)), 568 Process.ZYGOTE_POLICY_FLAG_EMPTY, false, false); 569 checkTime(startTime, "getContentProviderImpl: after start process"); 570 if (proc == null) { 571 Slog.w(TAG, "Unable to launch app " 572 + cpi.applicationInfo.packageName + "/" 573 + cpi.applicationInfo.uid + " for provider " + name 574 + ": process is bad"); 575 return null; 576 } 577 if (DEBUG_PROCESSES) { 578 Slog.d(TAG, "Logging provider access for " + cpi.packageName 579 + ", stopped=" + stopped + ", firstLaunch=" + firstLaunch); 580 } 581 FrameworkStatsLog.write( 582 PROVIDER_ACQUISITION_EVENT_REPORTED, 583 proc.uid, callingUid, 584 PROVIDER_ACQUISITION_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD, 585 packageState, cpi.packageName, callingPackage, 586 callingProcessState, ActivityManager.PROCESS_STATE_NONEXISTENT, 587 firstLaunch, 588 0L /* TODO: stoppedDuration */); 589 mService.mProcessList.getAppStartInfoTracker() 590 .handleProcessContentProviderStart(startTimeNs, proc); 591 } 592 cpr.launchingApp = proc; 593 mLaunchingProviders.add(cpr); 594 } finally { 595 Binder.restoreCallingIdentity(origId); 596 } 597 } 598 599 checkTime(startTime, "getContentProviderImpl: updating data structures"); 600 601 // Make sure the provider is published (the same provider class 602 // may be published under multiple names). 603 if (firstClass) { 604 mProviderMap.putProviderByClass(comp, cpr); 605 } 606 607 mProviderMap.putProviderByName(name, cpr); 608 conn = incProviderCountLocked(r, cpr, token, callingUid, callingPackage, callingTag, 609 stable, false, startTime, mService.mProcessList, expectedUserId); 610 if (conn != null) { 611 conn.waiting = true; 612 } 613 } 614 checkTime(startTime, "getContentProviderImpl: done!"); 615 616 mService.grantImplicitAccess(userId, null, callingUid, 617 UserHandle.getAppId(cpi.applicationInfo.uid)); 618 619 if (caller != null) { 620 // The client will be waiting, and we'll notify it when the provider is ready. 621 synchronized (cpr) { 622 if (cpr.provider == null) { 623 if (cpr.launchingApp == null) { 624 Slog.w(TAG, "Unable to launch app " 625 + cpi.applicationInfo.packageName + "/" 626 + cpi.applicationInfo.uid + " for provider " 627 + name + ": launching app became null"); 628 EventLogTags.writeAmProviderLostProcess( 629 UserHandle.getUserId(cpi.applicationInfo.uid), 630 cpi.applicationInfo.packageName, 631 cpi.applicationInfo.uid, name); 632 return null; 633 } 634 635 if (conn != null) { 636 conn.waiting = true; 637 } 638 Message msg = mService.mHandler.obtainMessage( 639 ActivityManagerService.WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG); 640 msg.obj = cpr; 641 mService.mHandler.sendMessageDelayed(msg, 642 ContentResolver.CONTENT_PROVIDER_READY_TIMEOUT_MILLIS); 643 } 644 } 645 // Return a holder instance even if we are waiting for the publishing of the 646 // provider, client will check for the holder.provider to see if it needs to wait 647 // for it. 648 return cpr.newHolder(conn, false); 649 } 650 } 651 652 // Because of the provider's external client (i.e., SHELL), we'll have to wait right here. 653 // Wait for the provider to be published... 654 final long timeout = 655 SystemClock.uptimeMillis() + ContentResolver.CONTENT_PROVIDER_READY_TIMEOUT_MILLIS; 656 boolean timedOut = false; 657 synchronized (cpr) { 658 while (cpr.provider == null) { 659 if (cpr.launchingApp == null) { 660 Slog.w(TAG, "Unable to launch app " 661 + cpi.applicationInfo.packageName + "/" + cpi.applicationInfo.uid 662 + " for provider " + name + ": launching app became null"); 663 EventLogTags.writeAmProviderLostProcess( 664 UserHandle.getUserId(cpi.applicationInfo.uid), 665 cpi.applicationInfo.packageName, cpi.applicationInfo.uid, name); 666 return null; 667 } 668 try { 669 final long wait = Math.max(0L, timeout - SystemClock.uptimeMillis()); 670 if (DEBUG_MU) { 671 Slog.v(TAG_MU, "Waiting to start provider " + cpr 672 + " launchingApp=" + cpr.launchingApp + " for " + wait + " ms"); 673 } 674 if (conn != null) { 675 conn.waiting = true; 676 } 677 if (wait > 0) { 678 cpr.wait(wait); 679 } 680 if (cpr.provider == null) { 681 timedOut = true; 682 break; 683 } 684 } catch (InterruptedException ex) { 685 } finally { 686 if (conn != null) { 687 conn.waiting = false; 688 } 689 } 690 } 691 } 692 if (timedOut) { 693 // Note we do it after releasing the lock. 694 String callerName = "unknown"; 695 if (caller != null) { 696 synchronized (mService.mProcLock) { 697 final ProcessRecord record = 698 mService.mProcessList.getLRURecordForAppLOSP(caller); 699 if (record != null) { 700 callerName = record.processName; 701 } 702 } 703 } 704 705 Slog.wtf(TAG, "Timeout waiting for provider " 706 + cpi.applicationInfo.packageName + "/" + cpi.applicationInfo.uid 707 + " for provider " + name + " providerRunning=" + providerRunning 708 + " caller=" + callerName + "/" + Binder.getCallingUid()); 709 return null; 710 } 711 return cpr.newHolder(conn, false); 712 } 713 checkAssociationAndPermissionLocked(ProcessRecord callingApp, ProviderInfo cpi, int callingUid, int userId, boolean checkUser, String cprName, long startTime)714 private void checkAssociationAndPermissionLocked(ProcessRecord callingApp, ProviderInfo cpi, 715 int callingUid, int userId, boolean checkUser, String cprName, long startTime) { 716 String msg; 717 if ((msg = checkContentProviderAssociation(callingApp, callingUid, cpi)) != null) { 718 throw new SecurityException("Content provider lookup " + cprName 719 + " failed: association not allowed with package " + msg); 720 } 721 checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission"); 722 if ((msg = checkContentProviderPermission( 723 cpi, Binder.getCallingPid(), Binder.getCallingUid(), userId, checkUser, 724 callingApp != null ? callingApp.toString() : null)) 725 != null) { 726 throw new SecurityException(msg); 727 } 728 checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission"); 729 } 730 publishContentProviders(IApplicationThread caller, List<ContentProviderHolder> providers)731 void publishContentProviders(IApplicationThread caller, List<ContentProviderHolder> providers) { 732 if (providers == null) { 733 return; 734 } 735 736 mService.enforceNotIsolatedOrSdkSandboxCaller("publishContentProviders"); 737 synchronized (mService) { 738 final ProcessRecord r = mService.getRecordForAppLOSP(caller); 739 if (DEBUG_MU) { 740 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid); 741 } 742 if (r == null) { 743 throw new SecurityException("Unable to find app for caller " + caller 744 + " (pid=" + Binder.getCallingPid() 745 + ") when publishing content providers"); 746 } 747 748 final long origId = Binder.clearCallingIdentity(); 749 boolean providersPublished = false; 750 for (int i = 0, size = providers.size(); i < size; i++) { 751 ContentProviderHolder src = providers.get(i); 752 if (src == null || src.info == null || src.provider == null) { 753 continue; 754 } 755 ContentProviderRecord dst = r.mProviders.getProvider(src.info.name); 756 if (dst == null) { 757 continue; 758 } 759 if (DEBUG_MU) { 760 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid); 761 } 762 providersPublished = true; 763 764 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name); 765 mProviderMap.putProviderByClass(comp, dst); 766 String[] names = dst.info.authority.split(";"); 767 for (int j = 0; j < names.length; j++) { 768 mProviderMap.putProviderByName(names[j], dst); 769 } 770 771 boolean wasInLaunchingProviders = false; 772 for (int j = 0, numLaunching = mLaunchingProviders.size(); j < numLaunching; j++) { 773 if (mLaunchingProviders.get(j) == dst) { 774 mLaunchingProviders.remove(j); 775 wasInLaunchingProviders = true; 776 j--; 777 numLaunching--; 778 } 779 } 780 if (wasInLaunchingProviders) { 781 mService.mHandler.removeMessages( 782 ActivityManagerService.WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG, dst); 783 mService.mHandler.removeMessages( 784 ActivityManagerService.CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, r); 785 } 786 // Make sure the package is associated with the process. 787 // XXX We shouldn't need to do this, since we have added the package 788 // when we generated the providers in generateApplicationProvidersLocked(). 789 // But for some reason in some cases we get here with the package no longer 790 // added... for now just patch it in to make things happy. 791 r.addPackage(dst.info.applicationInfo.packageName, 792 dst.info.applicationInfo.longVersionCode, mService.mProcessStats); 793 synchronized (dst) { 794 dst.provider = src.provider; 795 dst.setProcess(r); 796 dst.notifyAll(); 797 dst.onProviderPublishStatusLocked(true); 798 } 799 dst.mRestartCount = 0; 800 if (hasProviderConnectionLocked(r)) { 801 r.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_PROVIDER); 802 } 803 } 804 805 // update the app's oom adj value and each provider's usage stats 806 if (providersPublished) { 807 mService.updateOomAdjLocked(r, OOM_ADJ_REASON_GET_PROVIDER); 808 for (int i = 0, size = providers.size(); i < size; i++) { 809 ContentProviderHolder src = providers.get(i); 810 if (src == null || src.info == null || src.provider == null) { 811 continue; 812 } 813 maybeUpdateProviderUsageStatsLocked(r, 814 src.info.packageName, src.info.authority); 815 } 816 } 817 818 Binder.restoreCallingIdentity(origId); 819 } 820 } 821 822 /** 823 * Drop a content provider from a ProcessRecord's bookkeeping 824 */ removeContentProvider(IBinder connection, boolean stable)825 void removeContentProvider(IBinder connection, boolean stable) { 826 mService.enforceNotIsolatedCaller("removeContentProvider"); 827 final long ident = Binder.clearCallingIdentity(); 828 try { 829 ContentProviderConnection conn; 830 try { 831 conn = (ContentProviderConnection) connection; 832 } catch (ClassCastException e) { 833 String msg = "removeContentProvider: " + connection 834 + " not a ContentProviderConnection"; 835 Slog.w(TAG, msg); 836 throw new IllegalArgumentException(msg); 837 } 838 if (conn == null) { 839 throw new NullPointerException("connection is null"); 840 } 841 ActivityManagerService.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, 842 "removeContentProvider: ", 843 (conn.provider != null && conn.provider.info != null 844 ? conn.provider.info.authority : "")); 845 try { 846 synchronized (mService) { 847 decProviderCountLocked(conn, null, null, stable, true, true); 848 } 849 } finally { 850 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 851 } 852 } finally { 853 Binder.restoreCallingIdentity(ident); 854 } 855 } 856 removeContentProviderExternalAsUser(String name, IBinder token, int userId)857 void removeContentProviderExternalAsUser(String name, IBinder token, int userId) { 858 mService.enforceCallingPermission( 859 android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 860 "Do not have permission in call removeContentProviderExternal()"); 861 final long ident = Binder.clearCallingIdentity(); 862 try { 863 removeContentProviderExternalUnchecked(name, token, userId); 864 } finally { 865 Binder.restoreCallingIdentity(ident); 866 } 867 } 868 removeContentProviderExternalUnchecked(String name, IBinder token, int userId)869 void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) { 870 synchronized (mService) { 871 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId); 872 if (cpr == null) { 873 //remove from mProvidersByClass 874 if (ActivityManagerDebugConfig.DEBUG_ALL) { 875 Slog.v(TAG, name + " content provider not found in providers list"); 876 } 877 return; 878 } 879 880 // update content provider record entry info 881 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name); 882 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId); 883 if (localCpr.hasExternalProcessHandles()) { 884 if (mService.mProcessStateController.removeExternalProviderClient(localCpr, 885 token)) { 886 mService.updateOomAdjLocked(localCpr.proc, OOM_ADJ_REASON_REMOVE_PROVIDER); 887 } else { 888 Slog.e(TAG, "Attempt to remove content provider " + localCpr 889 + " with no external reference for token: " + token + "."); 890 } 891 } else { 892 Slog.e(TAG, "Attempt to remove content provider: " + localCpr 893 + " with no external references."); 894 } 895 } 896 } 897 refContentProvider(IBinder connection, int stable, int unstable)898 boolean refContentProvider(IBinder connection, int stable, int unstable) { 899 ContentProviderConnection conn; 900 try { 901 conn = (ContentProviderConnection) connection; 902 } catch (ClassCastException e) { 903 String msg = "refContentProvider: " + connection + " not a ContentProviderConnection"; 904 Slog.w(TAG, msg); 905 throw new IllegalArgumentException(msg); 906 } 907 if (conn == null) { 908 throw new NullPointerException("connection is null"); 909 } 910 911 ActivityManagerService.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "refContentProvider: ", 912 (conn.provider != null && conn.provider.info != null 913 ? conn.provider.info.authority : "")); 914 try { 915 conn.adjustCounts(stable, unstable); 916 return !conn.dead; 917 } finally { 918 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 919 } 920 } 921 unstableProviderDied(IBinder connection)922 void unstableProviderDied(IBinder connection) { 923 ContentProviderConnection conn; 924 try { 925 conn = (ContentProviderConnection) connection; 926 } catch (ClassCastException e) { 927 String msg = "refContentProvider: " + connection + " not a ContentProviderConnection"; 928 Slog.w(TAG, msg); 929 throw new IllegalArgumentException(msg); 930 } 931 if (conn == null) { 932 throw new NullPointerException("connection is null"); 933 } 934 935 ActivityManagerService.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, 936 "unstableProviderDied: ", 937 (conn.provider != null && conn.provider.info != null 938 ? conn.provider.info.authority : "")); 939 940 try { 941 // Safely retrieve the content provider associated with the connection. 942 IContentProvider provider; 943 synchronized (mService) { 944 provider = conn.provider.provider; 945 } 946 947 if (provider == null) { 948 // Um, yeah, we're way ahead of you. 949 return; 950 } 951 952 // Make sure the caller is being honest with us. 953 if (provider.asBinder().pingBinder()) { 954 // Er, no, still looks good to us. 955 synchronized (mService) { 956 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid() 957 + " says " + conn + " died, but we don't agree"); 958 return; 959 } 960 } 961 962 // Well look at that! It's dead! 963 synchronized (mService) { 964 if (conn.provider.provider != provider) { 965 // But something changed... good enough. 966 return; 967 } 968 969 ProcessRecord proc = conn.provider.proc; 970 if (proc == null || proc.getThread() == null) { 971 // Seems like the process is already cleaned up. 972 return; 973 } 974 975 // As far as we're concerned, this is just like receiving a 976 // death notification... just a bit prematurely. 977 mService.reportUidInfoMessageLocked(TAG, "Process " + proc.processName 978 + " (pid " + proc.getPid() + ") early provider death", 979 proc.info.uid); 980 final long token = Binder.clearCallingIdentity(); 981 try { 982 mService.appDiedLocked(proc, "unstable content provider"); 983 } finally { 984 Binder.restoreCallingIdentity(token); 985 } 986 } 987 } finally { 988 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 989 } 990 } 991 appNotRespondingViaProvider(IBinder connection)992 void appNotRespondingViaProvider(IBinder connection) { 993 mService.enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS, 994 "appNotRespondingViaProvider()"); 995 996 final ContentProviderConnection conn = (ContentProviderConnection) connection; 997 if (conn == null) { 998 Slog.w(TAG, "ContentProviderConnection is null"); 999 return; 1000 } 1001 1002 ActivityManagerService.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, 1003 "appNotRespondingViaProvider: ", 1004 (conn.provider != null && conn.provider.info != null 1005 ? conn.provider.info.authority : "")); 1006 try { 1007 final ProcessRecord host = conn.provider.proc; 1008 if (host == null) { 1009 Slog.w(TAG, "Failed to find hosting ProcessRecord"); 1010 return; 1011 } 1012 1013 TimeoutRecord timeoutRecord = TimeoutRecord.forContentProvider( 1014 "ContentProvider not responding"); 1015 mService.mAnrHelper.appNotResponding(host, timeoutRecord); 1016 } finally { 1017 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 1018 } 1019 } 1020 1021 /** 1022 * Filters calls to getType based on permission. If the caller has required permission, 1023 * then it returns the contentProvider#getType. 1024 * Else, it returns the contentProvider#getTypeAnonymous, which does not 1025 * reveal any internal information which should be protected by any permission. 1026 */ getMimeTypeFilterAsync(Uri uri, int userId, RemoteCallback resultCallback)1027 void getMimeTypeFilterAsync(Uri uri, int userId, RemoteCallback resultCallback) { 1028 mService.enforceNotIsolatedCaller("getProviderMimeTypeAsync"); 1029 final String name = uri.getAuthority(); 1030 final int callingUid = Binder.getCallingUid(); 1031 final int callingPid = Binder.getCallingPid(); 1032 final int safeUserId = mService.mUserController.unsafeConvertIncomingUser(userId); 1033 final long ident = canClearIdentity(callingPid, callingUid, safeUserId) 1034 ? Binder.clearCallingIdentity() : 0; 1035 final ContentProviderHolder holder; 1036 try { 1037 holder = getContentProviderExternalUnchecked(name, null /* token */, callingUid, 1038 "*getmimetype*", safeUserId); 1039 } finally { 1040 if (ident != 0) { 1041 Binder.restoreCallingIdentity(ident); 1042 } 1043 } 1044 1045 try { 1046 if (isHolderVisibleToCaller(holder, callingUid, safeUserId)) { 1047 if (checkGetAnyTypePermission(callingUid, callingPid)) { 1048 final AttributionSource attributionSource = 1049 new AttributionSource.Builder(callingUid).build(); 1050 holder.provider.getTypeAsync(attributionSource, 1051 uri, new RemoteCallback(result -> { 1052 final long identity = Binder.clearCallingIdentity(); 1053 try { 1054 removeContentProviderExternalUnchecked(name, null, safeUserId); 1055 } finally { 1056 Binder.restoreCallingIdentity(identity); 1057 } 1058 resultCallback.sendResult(result); 1059 })); 1060 } else { 1061 holder.provider.getTypeAnonymousAsync(uri, new RemoteCallback(result -> { 1062 final long identity = Binder.clearCallingIdentity(); 1063 try { 1064 removeContentProviderExternalUnchecked(name, null, safeUserId); 1065 } finally { 1066 Binder.restoreCallingIdentity(identity); 1067 } 1068 resultCallback.sendResult(result); 1069 final String type = result.getPairValue(); 1070 if (type != null) { 1071 logGetTypeData(callingUid, uri, type); 1072 } 1073 })); 1074 } 1075 } else { 1076 resultCallback.sendResult(Bundle.EMPTY); 1077 } 1078 } catch (RemoteException e) { 1079 Log.w(TAG, "Content provider dead retrieving " + uri, e); 1080 resultCallback.sendResult(Bundle.EMPTY); 1081 } 1082 } 1083 checkGetAnyTypePermission(int callingUid, int callingPid)1084 private boolean checkGetAnyTypePermission(int callingUid, int callingPid) { 1085 if (mService.checkPermission(GET_ANY_PROVIDER_TYPE, callingPid, callingUid) 1086 == PackageManager.PERMISSION_GRANTED) { 1087 return true; 1088 } 1089 return false; 1090 } 1091 1092 // Utility function to log the getTypeData calls logGetTypeData(int callingUid, Uri uri, String type)1093 private void logGetTypeData(int callingUid, Uri uri, String type) { 1094 FrameworkStatsLog.write(GET_TYPE_ACCESSED_WITHOUT_PERMISSION, 1095 GET_TYPE_ACCESSED_WITHOUT_PERMISSION__LOCATION__AM_FRAMEWORK_PERMISSION, 1096 callingUid, uri.getAuthority(), type); 1097 } 1098 canClearIdentity(int callingPid, int callingUid, int userId)1099 private boolean canClearIdentity(int callingPid, int callingUid, int userId) { 1100 if (UserHandle.getUserId(callingUid) == userId) { 1101 return true; 1102 } 1103 return ActivityManagerService.checkComponentPermission( 1104 android.Manifest.permission.INTERACT_ACROSS_USERS, callingPid, 1105 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED 1106 || ActivityManagerService.checkComponentPermission( 1107 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, callingPid, 1108 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED; 1109 } 1110 isHolderVisibleToCaller(@ullable ContentProviderHolder holder, int callingUid, @UserIdInt int userId)1111 private boolean isHolderVisibleToCaller(@Nullable ContentProviderHolder holder, int callingUid, 1112 @UserIdInt int userId) { 1113 if (holder == null || holder.info == null) { 1114 return false; 1115 } 1116 1117 if (isAuthorityRedirectedForCloneProfileCached(holder.info.authority) 1118 && resolveParentUserIdForCloneProfile(userId) != userId) { 1119 // Since clone profile shares certain providers with its parent and the access is 1120 // re-directed as well, the holder may not actually be installed on the clone profile. 1121 return !mService.getPackageManagerInternal().filterAppAccess(holder.info.packageName, 1122 callingUid, userId, false /* filterUninstalled */); 1123 } 1124 1125 return !mService.getPackageManagerInternal().filterAppAccess(holder.info.packageName, 1126 callingUid, userId); 1127 } 1128 resolveParentUserIdForCloneProfile(@serIdInt int userId)1129 private static @UserIdInt int resolveParentUserIdForCloneProfile(@UserIdInt int userId) { 1130 final UserManagerInternal umInternal = LocalServices.getService(UserManagerInternal.class); 1131 final UserInfo userInfo = umInternal.getUserInfo(userId); 1132 1133 if (userInfo == null || !userInfo.isCloneProfile()) { 1134 return userId; 1135 } 1136 1137 return umInternal.getProfileParentId(userId); 1138 } 1139 1140 /** 1141 * Check if the calling UID has a possible chance at accessing the provider 1142 * at the given authority and user. 1143 */ checkContentProviderAccess(String authority, int userId)1144 String checkContentProviderAccess(String authority, int userId) { 1145 boolean checkUser = true; 1146 if (userId == UserHandle.USER_ALL) { 1147 mService.mContext.enforceCallingOrSelfPermission( 1148 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, TAG); 1149 userId = UserHandle.getCallingUserId(); 1150 } 1151 1152 if (isAuthorityRedirectedForCloneProfileCached(authority)) { 1153 UserManagerInternal umInternal = LocalServices.getService(UserManagerInternal.class); 1154 UserInfo userInfo = umInternal.getUserInfo(userId); 1155 1156 if (userInfo != null && userInfo.isCloneProfile()) { 1157 userId = umInternal.getProfileParentId(userId); 1158 checkUser = false; 1159 } 1160 } 1161 1162 ProviderInfo cpi = null; 1163 try { 1164 cpi = AppGlobals.getPackageManager().resolveContentProvider(authority, 1165 ActivityManagerService.STOCK_PM_FLAGS 1166 | PackageManager.GET_URI_PERMISSION_PATTERNS 1167 | PackageManager.MATCH_DISABLED_COMPONENTS 1168 | PackageManager.MATCH_DIRECT_BOOT_AWARE 1169 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 1170 userId); 1171 } catch (RemoteException ignored) { 1172 } 1173 if (cpi == null) { 1174 return "Failed to find provider " + authority + " for user " + userId 1175 + "; expected to find a valid ContentProvider for this authority"; 1176 } 1177 1178 final int callingPid = Binder.getCallingPid(); 1179 ProcessRecord r; 1180 final String appName; 1181 synchronized (mService.mPidsSelfLocked) { 1182 r = mService.mPidsSelfLocked.get(callingPid); 1183 if (r == null) { 1184 return "Failed to find PID " + callingPid; 1185 } 1186 appName = r.toString(); 1187 } 1188 1189 return checkContentProviderPermission(cpi, callingPid, Binder.getCallingUid(), 1190 userId, checkUser, appName); 1191 } 1192 checkContentProviderUriPermission(Uri uri, int userId, int callingUid, int modeFlags)1193 int checkContentProviderUriPermission(Uri uri, int userId, int callingUid, int modeFlags) { 1194 if (Thread.holdsLock(mService.mActivityTaskManager.getGlobalLock())) { 1195 Slog.wtf(TAG, new IllegalStateException("Unable to check Uri permission" 1196 + " because caller is holding WM lock; assuming permission denied")); 1197 return PackageManager.PERMISSION_DENIED; 1198 } 1199 1200 final String name = uri.getAuthority(); 1201 final long ident = Binder.clearCallingIdentity(); 1202 ContentProviderHolder holder = null; 1203 try { 1204 holder = getContentProviderExternalUnchecked(name, null, callingUid, 1205 "*checkContentProviderUriPermission*", userId); 1206 if (holder != null) { 1207 1208 final AndroidPackage androidPackage = mService.getPackageManagerInternal() 1209 .getPackage(Binder.getCallingUid()); 1210 if (androidPackage == null) { 1211 return PackageManager.PERMISSION_DENIED; 1212 } 1213 1214 final AttributionSource attributionSource = new AttributionSource( 1215 callingUid, androidPackage.getPackageName(), null); 1216 return holder.provider.checkUriPermission(attributionSource, uri, callingUid, 1217 modeFlags); 1218 } 1219 } catch (RemoteException e) { 1220 Log.w(TAG, "Content provider dead retrieving " + uri, e); 1221 return PackageManager.PERMISSION_DENIED; 1222 } catch (Exception e) { 1223 Log.w(TAG, "Exception while determining type of " + uri, e); 1224 return PackageManager.PERMISSION_DENIED; 1225 } finally { 1226 try { 1227 if (holder != null) { 1228 removeContentProviderExternalUnchecked(name, null, userId); 1229 } 1230 } finally { 1231 Binder.restoreCallingIdentity(ident); 1232 } 1233 } 1234 return PackageManager.PERMISSION_DENIED; 1235 } 1236 1237 @GuardedBy("mService") processContentProviderPublishTimedOutLocked(ProcessRecord app)1238 void processContentProviderPublishTimedOutLocked(ProcessRecord app) { 1239 cleanupAppInLaunchingProvidersLocked(app, true); 1240 mService.mProcessList.removeProcessLocked(app, false, true, 1241 ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, 1242 ApplicationExitInfo.SUBREASON_UNKNOWN, 1243 "timeout publishing content providers"); 1244 } 1245 generateApplicationProvidersLocked(ProcessRecord app)1246 List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) { 1247 final List<ProviderInfo> providers; 1248 try { 1249 providers = AppGlobals.getPackageManager().queryContentProviders( 1250 app.processName, app.uid, ActivityManagerService.STOCK_PM_FLAGS 1251 | PackageManager.GET_URI_PERMISSION_PATTERNS 1252 | PackageManager.MATCH_DIRECT_BOOT_AUTO, /*metaDataKey=*/ null) 1253 .getList(); 1254 } catch (RemoteException ex) { 1255 return null; 1256 } 1257 if (providers == null) { 1258 return null; 1259 } 1260 1261 if (DEBUG_MU) { 1262 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid); 1263 } 1264 1265 int numProviders = providers.size(); 1266 final ProcessProviderRecord pr = app.mProviders; 1267 pr.ensureProviderCapacity(numProviders + pr.numberOfProviders()); 1268 for (int i = 0; i < numProviders; i++) { 1269 // NOTE: keep logic in sync with installEncryptionUnawareProviders 1270 ProviderInfo cpi = providers.get(i); 1271 boolean singleton = mService.isSingleton(cpi.processName, cpi.applicationInfo, 1272 cpi.name, cpi.flags); 1273 if (isSingletonOrSystemUserOnly(cpi) && app.userId != UserHandle.USER_SYSTEM) { 1274 // This is a singleton or a SYSTEM user only provider, but a user besides the 1275 // SYSTEM user is asking to initialize a process it runs 1276 // in... well, no, it doesn't actually run in this process, 1277 // it runs in the process of the default user. Get rid of it. 1278 providers.remove(i); 1279 numProviders--; 1280 i--; 1281 continue; 1282 } 1283 final boolean isInstantApp = cpi.applicationInfo.isInstantApp(); 1284 final boolean splitInstalled = cpi.splitName == null || ArrayUtils.contains( 1285 cpi.applicationInfo.splitNames, cpi.splitName); 1286 if (isInstantApp && !splitInstalled) { 1287 // For instant app, allow provider that is defined in the provided split apk. 1288 // Skipping it if the split apk is not installed. 1289 providers.remove(i); 1290 numProviders--; 1291 i--; 1292 continue; 1293 } 1294 1295 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 1296 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, app.userId); 1297 if (cpr == null) { 1298 cpr = new ContentProviderRecord(mService, cpi, app.info, comp, singleton); 1299 mProviderMap.putProviderByClass(comp, cpr); 1300 } 1301 if (DEBUG_MU) { 1302 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid); 1303 } 1304 pr.installProvider(cpi.name, cpr); 1305 if (!cpi.multiprocess || !"android".equals(cpi.packageName)) { 1306 // Don't add this if it is a platform component that is marked 1307 // to run in multiple processes, because this is actually 1308 // part of the framework so doesn't make sense to track as a 1309 // separate apk in the process. 1310 app.addPackage(cpi.applicationInfo.packageName, cpi.applicationInfo.longVersionCode, 1311 mService.mProcessStats); 1312 } 1313 mService.notifyPackageUse(cpi.applicationInfo.packageName, 1314 PackageManager.NOTIFY_PACKAGE_USE_CONTENT_PROVIDER); 1315 } 1316 return providers.isEmpty() ? null : providers; 1317 } 1318 1319 private final class DevelopmentSettingsObserver extends ContentObserver { 1320 private final Uri mUri = Settings.Global.getUriFor( 1321 Settings.Global.DEVELOPMENT_SETTINGS_ENABLED); 1322 1323 private final ComponentName mBugreportStorageProvider = new ComponentName( 1324 "com.android.shell", "com.android.shell.BugreportStorageProvider"); 1325 DevelopmentSettingsObserver()1326 DevelopmentSettingsObserver() { 1327 super(mService.mHandler); 1328 mService.mContext.getContentResolver().registerContentObserver(mUri, false, this, 1329 UserHandle.USER_ALL); 1330 // Always kick once to ensure that we match current state 1331 onChange(); 1332 } 1333 1334 @Override onChange(boolean selfChange, Uri uri, @UserIdInt int userId)1335 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) { 1336 if (mUri.equals(uri)) { 1337 onChange(); 1338 } 1339 } 1340 onChange()1341 private void onChange() { 1342 final boolean enabled = Settings.Global.getInt(mService.mContext.getContentResolver(), 1343 Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, Build.IS_ENG ? 1 : 0) != 0; 1344 mService.mContext.getPackageManager().setComponentEnabledSetting( 1345 mBugreportStorageProvider, 1346 enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED 1347 : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 1348 0); 1349 } 1350 } 1351 installSystemProviders()1352 public final void installSystemProviders() { 1353 List<ProviderInfo> providers; 1354 synchronized (mService) { 1355 ProcessRecord app = mService.mProcessList 1356 .getProcessNamesLOSP().get("system", SYSTEM_UID); 1357 providers = generateApplicationProvidersLocked(app); 1358 if (providers != null) { 1359 for (int i = providers.size() - 1; i >= 0; i--) { 1360 ProviderInfo pi = providers.get(i); 1361 if ((pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1362 Slog.w(TAG, "Not installing system proc provider " + pi.name 1363 + ": not system .apk"); 1364 providers.remove(i); 1365 } 1366 } 1367 } 1368 } 1369 1370 if (providers != null) { 1371 mService.mSystemThread.installSystemProviders(providers); 1372 } 1373 synchronized (this) { 1374 mSystemProvidersInstalled = true; 1375 } 1376 1377 mService.mConstants.start(mService.mContext.getContentResolver()); 1378 mService.mCoreSettingsObserver = new CoreSettingsObserver(mService); 1379 mService.mActivityTaskManager.installSystemProviders(); 1380 new DevelopmentSettingsObserver(); // init to observe developer settings enable/disable 1381 SettingsToPropertiesMapper.start(mService.mContext.getContentResolver()); 1382 mService.mOomAdjuster.initSettings(); 1383 1384 // Now that the settings provider is published we can consider sending in a rescue party. 1385 CrashRecoveryAdaptor.rescuePartyOnSettingsProviderPublished(mService.mContext); 1386 } 1387 1388 /** 1389 * When a user is unlocked, we need to install encryption-unaware providers 1390 * belonging to any running apps. 1391 */ installEncryptionUnawareProviders(int userId)1392 void installEncryptionUnawareProviders(int userId) { 1393 // We're only interested in providers that are encryption unaware, and 1394 // we don't care about uninstalled apps, since there's no way they're 1395 // running at this point. 1396 final int matchFlags = 1397 PackageManager.GET_PROVIDERS | PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 1398 1399 synchronized (mService.mProcLock) { 1400 final ArrayMap<String, SparseArray<ProcessRecord>> pmap = 1401 mService.mProcessList.getProcessNamesLOSP().getMap(); 1402 final int numProc = pmap.size(); 1403 for (int iProc = 0; iProc < numProc; iProc++) { 1404 final SparseArray<ProcessRecord> apps = pmap.valueAt(iProc); 1405 for (int iApp = 0, numApps = apps.size(); iApp < numApps; iApp++) { 1406 final ProcessRecord app = apps.valueAt(iApp); 1407 if (app.userId != userId || app.getThread() == null || app.isUnlocked()) { 1408 continue; 1409 } 1410 1411 app.getPkgList().forEachPackage(pkgName -> { 1412 try { 1413 final PackageInfo pkgInfo = AppGlobals.getPackageManager() 1414 .getPackageInfo(pkgName, matchFlags, app.userId); 1415 final IApplicationThread thread = app.getThread(); 1416 if (pkgInfo != null && !ArrayUtils.isEmpty(pkgInfo.providers)) { 1417 for (ProviderInfo pi : pkgInfo.providers) { 1418 // NOTE: keep in sync with generateApplicationProvidersLocked 1419 final boolean processMatch = 1420 Objects.equals(pi.processName, app.processName) 1421 || pi.multiprocess; 1422 final boolean userMatch = !isSingletonOrSystemUserOnly(pi) 1423 || app.userId == UserHandle.USER_SYSTEM; 1424 final boolean isInstantApp = pi.applicationInfo.isInstantApp(); 1425 final boolean splitInstalled = pi.splitName == null 1426 || ArrayUtils.contains(pi.applicationInfo.splitNames, 1427 pi.splitName); 1428 if (processMatch && userMatch 1429 && (!isInstantApp || splitInstalled)) { 1430 Log.v(TAG, "Installing " + pi); 1431 thread.scheduleInstallProvider(pi); 1432 } else { 1433 Log.v(TAG, "Skipping " + pi); 1434 } 1435 } 1436 } 1437 } catch (RemoteException|SecurityException ignored) { 1438 } 1439 }); 1440 } 1441 } 1442 } 1443 } 1444 1445 @GuardedBy("mService") incProviderCountLocked(ProcessRecord r, final ContentProviderRecord cpr, IBinder externalProcessToken, int callingUid, String callingPackage, String callingTag, boolean stable, boolean updateLru, long startTime, ProcessList processList, @UserIdInt int expectedUserId)1446 private ContentProviderConnection incProviderCountLocked(ProcessRecord r, 1447 final ContentProviderRecord cpr, IBinder externalProcessToken, int callingUid, 1448 String callingPackage, String callingTag, boolean stable, boolean updateLru, 1449 long startTime, ProcessList processList, @UserIdInt int expectedUserId) { 1450 if (r == null) { 1451 mService.mProcessStateController.addExternalProviderClient(cpr, externalProcessToken, 1452 callingUid, callingTag); 1453 return null; 1454 } 1455 1456 1457 final ProcessProviderRecord pr = r.mProviders; 1458 for (int i = 0, size = pr.numberOfProviderConnections(); i < size; i++) { 1459 ContentProviderConnection conn = pr.getProviderConnectionAt(i); 1460 if (conn.provider == cpr) { 1461 conn.incrementCount(stable); 1462 return conn; 1463 } 1464 } 1465 1466 // Create a new ContentProviderConnection. The reference count is known to be 1. 1467 ContentProviderConnection conn = new ContentProviderConnection(cpr, r, callingPackage, 1468 expectedUserId); 1469 conn.startAssociationIfNeeded(); 1470 conn.initializeCount(stable); 1471 cpr.connections.add(conn); 1472 if (cpr.proc != null) { 1473 cpr.proc.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_PROVIDER); 1474 } 1475 mService.mProcessStateController.addProviderConnection(r, conn); 1476 mService.startAssociationLocked(r.uid, r.processName, r.mState.getCurProcState(), 1477 cpr.uid, cpr.appInfo.longVersionCode, cpr.name, cpr.info.processName); 1478 if (updateLru && cpr.proc != null 1479 && r.mState.getSetAdj() <= ProcessList.PERCEPTIBLE_LOW_APP_ADJ) { 1480 // If this is a perceptible app accessing the provider, make 1481 // sure to count it as being accessed and thus back up on 1482 // the LRU list. This is good because content providers are 1483 // often expensive to start. The calls to checkTime() use 1484 // the "getContentProviderImpl" tag here, because it's part 1485 // of the checktime log in getContentProviderImpl(). 1486 checkTime(startTime, "getContentProviderImpl: before updateLruProcess"); 1487 processList.updateLruProcessLocked(cpr.proc, false, null); 1488 checkTime(startTime, "getContentProviderImpl: after updateLruProcess"); 1489 } 1490 return conn; 1491 } 1492 1493 @GuardedBy("mService") decProviderCountLocked(ContentProviderConnection conn, ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable, boolean enforceDelay, boolean updateOomAdj)1494 private boolean decProviderCountLocked(ContentProviderConnection conn, 1495 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable, 1496 boolean enforceDelay, boolean updateOomAdj) { 1497 if (conn == null) { 1498 mService.mProcessStateController.removeExternalProviderClient(cpr, 1499 externalProcessToken); 1500 return false; 1501 } 1502 1503 if (conn.totalRefCount() > 1) { 1504 conn.decrementCount(stable); 1505 return false; 1506 } 1507 if (enforceDelay) { 1508 // delay the removal of the provider for 5 seconds - this optimizes for those cases 1509 // where providers are released and then quickly re-acquired, causing lots of churn. 1510 BackgroundThread.getHandler().postDelayed(() -> { 1511 handleProviderRemoval(conn, stable, updateOomAdj); 1512 }, 5 * 1000); 1513 } else { 1514 handleProviderRemoval(conn, stable, updateOomAdj); 1515 } 1516 return true; 1517 } 1518 1519 @GuardedBy("mService") hasProviderConnectionLocked(ProcessRecord proc)1520 private boolean hasProviderConnectionLocked(ProcessRecord proc) { 1521 for (int i = proc.mProviders.numberOfProviders() - 1; i >= 0; i--) { 1522 if (!proc.mProviders.getProviderAt(i).connections.isEmpty()) { 1523 return true; 1524 } 1525 } 1526 return false; 1527 } 1528 handleProviderRemoval(ContentProviderConnection conn, boolean stable, boolean updateOomAdj)1529 private void handleProviderRemoval(ContentProviderConnection conn, boolean stable, 1530 boolean updateOomAdj) { 1531 synchronized (mService) { 1532 // if the proc was already killed or this is not the last reference, simply exit. 1533 if (conn == null || conn.provider == null || conn.decrementCount(stable) != 0) { 1534 return; 1535 } 1536 1537 final ContentProviderRecord cpr = conn.provider; 1538 conn.stopAssociation(); 1539 cpr.connections.remove(conn); 1540 if (cpr.proc != null && !hasProviderConnectionLocked(cpr.proc)) { 1541 cpr.proc.mProfile.clearHostingComponentType(HOSTING_COMPONENT_TYPE_PROVIDER); 1542 } 1543 mService.mProcessStateController.removeProviderConnection(conn.client, conn); 1544 if (conn.client.mState.getSetProcState() 1545 < ActivityManager.PROCESS_STATE_LAST_ACTIVITY) { 1546 // The client is more important than last activity -- note the time this 1547 // is happening, so we keep the old provider process around a bit as last 1548 // activity to avoid thrashing it. 1549 if (cpr.proc != null) { 1550 mService.mProcessStateController.setLastProviderTime(cpr.proc, 1551 SystemClock.uptimeMillis()); 1552 } 1553 } 1554 mService.stopAssociationLocked(conn.client.uid, conn.client.processName, cpr.uid, 1555 cpr.appInfo.longVersionCode, cpr.name, cpr.info.processName); 1556 if (updateOomAdj && (!serviceBindingOomAdjPolicy() 1557 || mService.mOomAdjuster.evaluateProviderConnectionRemoval(conn.client, 1558 cpr.proc))) { 1559 mService.updateOomAdjLocked(conn.provider.proc, OOM_ADJ_REASON_REMOVE_PROVIDER); 1560 } 1561 } 1562 } 1563 1564 /** 1565 * Check if {@link ProcessRecord} has a possible chance at accessing the 1566 * given {@link ProviderInfo}. First permission checking is for enforcing 1567 * ContentProvider Restrictions from SdkSandboxManager. 1568 * Final permission checking is always done 1569 * in {@link ContentProvider}. 1570 */ checkContentProviderPermission(ProviderInfo cpi, int callingPid, int callingUid, int userId, boolean checkUser, String appName)1571 private String checkContentProviderPermission(ProviderInfo cpi, int callingPid, int callingUid, 1572 int userId, boolean checkUser, String appName) { 1573 if (!canAccessContentProviderFromSdkSandbox(cpi, callingUid)) { 1574 return "ContentProvider access not allowed from sdk sandbox UID. " 1575 + "ProviderInfo: " + cpi.toString(); 1576 } 1577 boolean checkedGrants = false; 1578 if (checkUser) { 1579 // Looking for cross-user grants before enforcing the typical cross-users permissions 1580 int tmpTargetUserId = mService.mUserController.unsafeConvertIncomingUser(userId); 1581 if (tmpTargetUserId != UserHandle.getUserId(callingUid)) { 1582 if (mService.mUgmInternal.checkAuthorityGrants( 1583 callingUid, cpi, tmpTargetUserId, checkUser)) { 1584 return null; 1585 } 1586 checkedGrants = true; 1587 } 1588 userId = mService.mUserController.handleIncomingUser(callingPid, callingUid, userId, 1589 false, ActivityManagerInternal.ALLOW_NON_FULL, 1590 "checkContentProviderPermissionLocked " + cpi.authority, null); 1591 if (userId != tmpTargetUserId) { 1592 // When we actually went to determine the final target user ID, this ended 1593 // up different than our initial check for the authority. This is because 1594 // they had asked for USER_CURRENT_OR_SELF and we ended up switching to 1595 // SELF. So we need to re-check the grants again. 1596 checkedGrants = false; 1597 } 1598 } 1599 if (ActivityManagerService.checkComponentPermission(cpi.readPermission, 1600 callingPid, callingUid, cpi.applicationInfo.uid, cpi.exported) 1601 == PackageManager.PERMISSION_GRANTED) { 1602 return null; 1603 } 1604 if (ActivityManagerService.checkComponentPermission(cpi.writePermission, 1605 callingPid, callingUid, cpi.applicationInfo.uid, cpi.exported) 1606 == PackageManager.PERMISSION_GRANTED) { 1607 return null; 1608 } 1609 1610 PathPermission[] pps = cpi.pathPermissions; 1611 if (pps != null) { 1612 int i = pps.length; 1613 while (i > 0) { 1614 i--; 1615 PathPermission pp = pps[i]; 1616 String pprperm = pp.getReadPermission(); 1617 if (pprperm != null && ActivityManagerService.checkComponentPermission(pprperm, 1618 callingPid, callingUid, cpi.applicationInfo.uid, cpi.exported) 1619 == PackageManager.PERMISSION_GRANTED) { 1620 return null; 1621 } 1622 String ppwperm = pp.getWritePermission(); 1623 if (ppwperm != null && ActivityManagerService.checkComponentPermission(ppwperm, 1624 callingPid, callingUid, cpi.applicationInfo.uid, cpi.exported) 1625 == PackageManager.PERMISSION_GRANTED) { 1626 return null; 1627 } 1628 } 1629 } 1630 if (!checkedGrants 1631 && mService.mUgmInternal.checkAuthorityGrants(callingUid, cpi, userId, checkUser)) { 1632 return null; 1633 } 1634 1635 final String suffix; 1636 if (!cpi.exported) { 1637 suffix = " that is not exported from UID " + cpi.applicationInfo.uid; 1638 } else if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(cpi.readPermission)) { 1639 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs"; 1640 } else { 1641 suffix = " requires " + cpi.readPermission + " or " + cpi.writePermission; 1642 } 1643 final String msg = "Permission Denial: opening provider " + cpi.name 1644 + " from " + (appName != null ? appName : "(null)") 1645 + " (pid=" + callingPid + ", uid=" + callingUid + ")" + suffix; 1646 Slog.w(TAG, msg); 1647 return msg; 1648 } 1649 checkContentProviderAssociation(ProcessRecord callingApp, int callingUid, ProviderInfo cpi)1650 private String checkContentProviderAssociation(ProcessRecord callingApp, int callingUid, 1651 ProviderInfo cpi) { 1652 if (callingApp == null) { 1653 return mService.validateAssociationAllowedLocked(cpi.packageName, 1654 cpi.applicationInfo.uid, null, callingUid) ? null : "<null>"; 1655 } 1656 final String r = callingApp.getPkgList().searchEachPackage(pkgName -> { 1657 if (!mService.validateAssociationAllowedLocked(pkgName, 1658 callingApp.uid, cpi.packageName, cpi.applicationInfo.uid)) { 1659 return cpi.packageName; 1660 } 1661 return null; 1662 }); 1663 return r; 1664 } 1665 getProviderInfoLocked(String authority, @UserIdInt int userId, int pmFlags)1666 ProviderInfo getProviderInfoLocked(String authority, @UserIdInt int userId, int pmFlags) { 1667 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId); 1668 if (cpr != null) { 1669 return cpr.info; 1670 } else { 1671 try { 1672 return AppGlobals.getPackageManager().resolveContentProvider( 1673 authority, PackageManager.GET_URI_PERMISSION_PATTERNS | pmFlags, userId); 1674 } catch (RemoteException ex) { 1675 return null; 1676 } 1677 } 1678 } 1679 maybeUpdateProviderUsageStatsLocked(ProcessRecord app, String providerPkgName, String authority)1680 private void maybeUpdateProviderUsageStatsLocked(ProcessRecord app, String providerPkgName, 1681 String authority) { 1682 if (app == null || app.mState.getCurProcState() 1683 > ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) { 1684 return; 1685 } 1686 1687 UserState userState = mService.mUserController.getStartedUserState(app.userId); 1688 if (userState == null) return; 1689 final long now = SystemClock.elapsedRealtime(); 1690 Long lastReported = userState.mProviderLastReportedFg.get(authority); 1691 if (lastReported == null || lastReported < now - 60 * 1000L) { 1692 if (mService.mSystemReady) { 1693 // Cannot touch the user stats if not system ready 1694 mService.mUsageStatsService.reportContentProviderUsage( 1695 authority, providerPkgName, app.userId); 1696 } 1697 userState.mProviderLastReportedFg.put(authority, now); 1698 } 1699 } 1700 1701 private static final int[] PROCESS_STATE_STATS_FORMAT = new int[] { 1702 PROC_SPACE_TERM, 1703 PROC_SPACE_TERM | PROC_PARENS, 1704 PROC_SPACE_TERM | PROC_CHAR | PROC_OUT_LONG, // 3: process state 1705 }; 1706 1707 private final long[] mProcessStateStatsLongs = new long[1]; 1708 isProcessAliveLocked(ProcessRecord proc)1709 private boolean isProcessAliveLocked(ProcessRecord proc) { 1710 final int pid = proc.getPid(); 1711 if (pid <= 0) { 1712 if (ActivityManagerDebugConfig.DEBUG_OOM_ADJ) { 1713 Slog.d(ActivityManagerService.TAG, "Process hasn't started yet: " + proc); 1714 } 1715 return false; 1716 } 1717 final String procStatFile = "/proc/" + pid + "/stat"; 1718 mProcessStateStatsLongs[0] = 0; 1719 if (!Process.readProcFile(procStatFile, PROCESS_STATE_STATS_FORMAT, null, 1720 mProcessStateStatsLongs, null)) { 1721 if (ActivityManagerDebugConfig.DEBUG_OOM_ADJ) { 1722 Slog.d(ActivityManagerService.TAG, 1723 "UNABLE TO RETRIEVE STATE FOR " + procStatFile); 1724 } 1725 return false; 1726 } 1727 final long state = mProcessStateStatsLongs[0]; 1728 if (ActivityManagerDebugConfig.DEBUG_OOM_ADJ) { 1729 Slog.d(ActivityManagerService.TAG, 1730 "RETRIEVED STATE FOR " + procStatFile + ": " + (char) state); 1731 } 1732 if (state != 'Z' && state != 'X' && state != 'x' && state != 'K') { 1733 return Process.getUidForPid(pid) == proc.uid; 1734 } 1735 return false; 1736 } 1737 1738 private static final class StartActivityRunnable implements Runnable { 1739 private final Context mContext; 1740 private final Intent mIntent; 1741 private final UserHandle mUserHandle; 1742 StartActivityRunnable(Context context, Intent intent, UserHandle userHandle)1743 StartActivityRunnable(Context context, Intent intent, UserHandle userHandle) { 1744 this.mContext = context; 1745 this.mIntent = intent; 1746 this.mUserHandle = userHandle; 1747 } 1748 1749 @Override run()1750 public void run() { 1751 mContext.startActivityAsUser(mIntent, mUserHandle); 1752 } 1753 } 1754 requestTargetProviderPermissionsReviewIfNeededLocked(ProviderInfo cpi, ProcessRecord r, final int userId, Context context)1755 private boolean requestTargetProviderPermissionsReviewIfNeededLocked(ProviderInfo cpi, 1756 ProcessRecord r, final int userId, Context context) { 1757 if (!mService.getPackageManagerInternal().isPermissionsReviewRequired( 1758 cpi.packageName, userId)) { 1759 return true; 1760 } 1761 1762 final boolean callerForeground = r == null 1763 || r.mState.getSetSchedGroup() != ProcessList.SCHED_GROUP_BACKGROUND; 1764 1765 // Show a permission review UI only for starting from a foreground app 1766 if (!callerForeground) { 1767 Slog.w(TAG, "u" + userId + " Instantiating a provider in package " 1768 + cpi.packageName + " requires a permissions review"); 1769 return false; 1770 } 1771 1772 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS); 1773 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 1774 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, cpi.packageName); 1775 1776 if (ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW) { 1777 Slog.i(TAG, "u" + userId + " Launching permission review " 1778 + "for package " + cpi.packageName); 1779 } 1780 1781 final UserHandle userHandle = new UserHandle(userId); 1782 mService.mHandler.post(new StartActivityRunnable(context, intent, userHandle)); 1783 1784 return false; 1785 } 1786 1787 /** 1788 * Remove the dying provider from known provider map and launching provider map. 1789 * @param proc The dying process recoder 1790 * @param cpr The provider to be removed. 1791 * @param always If true, remove the provider from launching map always, no more restart attempt 1792 * @return true if the given provider is in launching 1793 */ removeDyingProviderLocked(ProcessRecord proc, ContentProviderRecord cpr, boolean always)1794 boolean removeDyingProviderLocked(ProcessRecord proc, ContentProviderRecord cpr, 1795 boolean always) { 1796 boolean inLaunching = mLaunchingProviders.contains(cpr); 1797 if (inLaunching && !always && ++cpr.mRestartCount > ContentProviderRecord.MAX_RETRY_COUNT) { 1798 // It's being launched but we've reached maximum attempts, force the removal 1799 always = true; 1800 } 1801 1802 if (!inLaunching || always) { 1803 synchronized (cpr) { 1804 cpr.launchingApp = null; 1805 cpr.notifyAll(); 1806 cpr.onProviderPublishStatusLocked(false); 1807 mService.mHandler.removeMessages( 1808 ActivityManagerService.WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG, cpr); 1809 } 1810 final int userId = UserHandle.getUserId(cpr.uid); 1811 boolean removed = false; 1812 // Don't remove from provider map if it doesn't match 1813 // could be a new content provider is starting 1814 if (mProviderMap.getProviderByClass(cpr.name, userId) == cpr) { 1815 mProviderMap.removeProviderByClass(cpr.name, userId); 1816 removed = true; 1817 } 1818 String[] names = cpr.info.authority.split(";"); 1819 for (int j = 0; j < names.length; j++) { 1820 // Don't remove from provider map if it doesn't match 1821 // could be a new content provider is starting 1822 if (mProviderMap.getProviderByName(names[j], userId) == cpr) { 1823 mProviderMap.removeProviderByName(names[j], userId); 1824 removed = true; 1825 } 1826 } 1827 if (removed && cpr.proc != null) { 1828 mService.mProcessStateController.removePublishedProvider(cpr.proc, cpr.info.name); 1829 } 1830 } 1831 1832 for (int i = cpr.connections.size() - 1; i >= 0; i--) { 1833 ContentProviderConnection conn = cpr.connections.get(i); 1834 if (conn.waiting) { 1835 // If this connection is waiting for the provider, then we don't 1836 // need to mess with its process unless we are always removing 1837 // or for some reason the provider is not currently launching. 1838 if (inLaunching && !always) { 1839 continue; 1840 } 1841 } 1842 ProcessRecord capp = conn.client; 1843 final IApplicationThread thread = capp.getThread(); 1844 conn.dead = true; 1845 if (conn.stableCount() > 0) { 1846 final int pid = capp.getPid(); 1847 if (!capp.isPersistent() && thread != null 1848 && pid != 0 && pid != ActivityManagerService.MY_PID) { 1849 capp.killLocked( 1850 "depends on provider " + cpr.name.flattenToShortString() 1851 + " in dying proc " + (proc != null ? proc.processName : "??") 1852 + " (adj " + (proc != null ? proc.mState.getSetAdj() : "??") + ")", 1853 ApplicationExitInfo.REASON_DEPENDENCY_DIED, 1854 ApplicationExitInfo.SUBREASON_UNKNOWN, 1855 true); 1856 } 1857 } else if (thread != null && conn.provider.provider != null) { 1858 try { 1859 thread.unstableProviderDied(conn.provider.provider.asBinder()); 1860 } catch (RemoteException e) { 1861 } 1862 // In the protocol here, we don't expect the client to correctly 1863 // clean up this connection, we'll just remove it. 1864 cpr.connections.remove(i); 1865 if (cpr.proc != null && !hasProviderConnectionLocked(cpr.proc)) { 1866 cpr.proc.mProfile.clearHostingComponentType(HOSTING_COMPONENT_TYPE_PROVIDER); 1867 } 1868 if (conn.client.mProviders.removeProviderConnection(conn)) { 1869 mService.stopAssociationLocked(capp.uid, capp.processName, 1870 cpr.uid, cpr.appInfo.longVersionCode, cpr.name, cpr.info.processName); 1871 } 1872 } 1873 } 1874 1875 if (inLaunching && always) { 1876 mLaunchingProviders.remove(cpr); 1877 cpr.mRestartCount = 0; 1878 inLaunching = false; 1879 } 1880 return inLaunching; 1881 } 1882 checkAppInLaunchingProvidersLocked(ProcessRecord app)1883 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app) { 1884 for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) { 1885 ContentProviderRecord cpr = mLaunchingProviders.get(i); 1886 if (cpr.launchingApp == app) { 1887 return true; 1888 } 1889 } 1890 return false; 1891 } 1892 cleanupAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad)1893 boolean cleanupAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) { 1894 // Look through the content providers we are waiting to have launched, 1895 // and if any run in this process then either schedule a restart of 1896 // the process or kill the client waiting for it if this process has 1897 // gone bad. 1898 boolean restart = false; 1899 for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) { 1900 ContentProviderRecord cpr = mLaunchingProviders.get(i); 1901 if (cpr.launchingApp != app) { 1902 continue; 1903 } 1904 1905 if (++cpr.mRestartCount > ContentProviderRecord.MAX_RETRY_COUNT) { 1906 // It's being launched but we've reached maximum attempts, mark it as bad 1907 alwaysBad = true; 1908 } 1909 if (!alwaysBad && !app.mErrorState.isBad() && cpr.hasConnectionOrHandle()) { 1910 restart = true; 1911 } else { 1912 removeDyingProviderLocked(app, cpr, true); 1913 } 1914 } 1915 return restart; 1916 } 1917 cleanupLaunchingProvidersLocked()1918 void cleanupLaunchingProvidersLocked() { 1919 for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) { 1920 ContentProviderRecord cpr = mLaunchingProviders.get(i); 1921 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) { 1922 synchronized (cpr) { 1923 cpr.launchingApp = null; 1924 cpr.notifyAll(); 1925 } 1926 } 1927 } 1928 } 1929 checkTime(long startTime, String where)1930 private void checkTime(long startTime, String where) { 1931 long now = SystemClock.uptimeMillis(); 1932 if ((now - startTime) > 50) { 1933 // If we are taking more than 50ms, log about it. 1934 Slog.w(TAG, "Slow operation: " + (now - startTime) + "ms so far, now at " + where); 1935 } 1936 } 1937 dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)1938 void dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args, 1939 int opti, boolean dumpAll, String dumpPackage) { 1940 ActivityManagerService.ItemMatcher matcher = new ActivityManagerService.ItemMatcher(); 1941 matcher.build(args, opti); 1942 1943 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)"); 1944 1945 boolean needSep = mProviderMap.dumpProvidersLocked(pw, dumpAll, dumpPackage); 1946 boolean printedAnything = needSep; 1947 1948 if (mLaunchingProviders.size() > 0) { 1949 boolean printed = false; 1950 for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) { 1951 ContentProviderRecord r = mLaunchingProviders.get(i); 1952 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) { 1953 continue; 1954 } 1955 if (!printed) { 1956 if (needSep) pw.println(); 1957 needSep = true; 1958 pw.println(" Launching content providers:"); 1959 printed = true; 1960 printedAnything = true; 1961 } 1962 pw.print(" Launching #"); pw.print(i); pw.print(": "); 1963 pw.println(r); 1964 } 1965 } 1966 1967 if (!printedAnything) { 1968 pw.println(" (nothing)"); 1969 } 1970 } 1971 canAccessContentProviderFromSdkSandbox(ProviderInfo cpi, int callingUid)1972 private boolean canAccessContentProviderFromSdkSandbox(ProviderInfo cpi, 1973 int callingUid) { 1974 if (!Process.isSdkSandboxUid(callingUid)) { 1975 return true; 1976 } 1977 final SdkSandboxManagerLocal sdkSandboxManagerLocal = 1978 LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class); 1979 if (sdkSandboxManagerLocal == null) { 1980 throw new IllegalStateException("SdkSandboxManagerLocal not found " 1981 + "when checking whether SDK sandbox uid may " 1982 + "access the contentprovider."); 1983 } 1984 return sdkSandboxManagerLocal.canAccessContentProviderFromSdkSandbox(cpi); 1985 } 1986 1987 /** 1988 * There are three ways to call this: 1989 * - no provider specified: dump all the providers 1990 * - a flattened component name that matched an existing provider was specified as the 1991 * first arg: dump that one provider 1992 * - the first arg isn't the flattened component name of an existing provider: 1993 * dump all providers whose component contains the first arg as a substring 1994 */ dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args, int opti, boolean dumpAll)1995 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args, 1996 int opti, boolean dumpAll) { 1997 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll); 1998 } 1999 2000 /** 2001 * Similar to the dumpProvider, but only dumps the first matching provider. 2002 * The provider is responsible for dumping as proto. 2003 */ dumpProviderProto(FileDescriptor fd, PrintWriter pw, String name, String[] args)2004 protected boolean dumpProviderProto(FileDescriptor fd, PrintWriter pw, String name, 2005 String[] args) { 2006 return mProviderMap.dumpProviderProto(fd, pw, name, args); 2007 } 2008 isAuthorityRedirectedForCloneProfileCached(String auth)2009 private boolean isAuthorityRedirectedForCloneProfileCached(String auth) { 2010 if (mCloneProfileAuthorityRedirectionCache.containsKey(auth)) { 2011 final Boolean retVal = mCloneProfileAuthorityRedirectionCache.get(auth); 2012 return retVal == null ? false : retVal.booleanValue(); 2013 } else { 2014 boolean isAuthRedirected = isAuthorityRedirectedForCloneProfile(auth); 2015 mCloneProfileAuthorityRedirectionCache.put(auth, isAuthRedirected); 2016 return isAuthRedirected; 2017 } 2018 } 2019 2020 /** 2021 * Returns true if Provider is either singleUser or systemUserOnly provider. 2022 */ isSingletonOrSystemUserOnly(ProviderInfo pi)2023 private boolean isSingletonOrSystemUserOnly(ProviderInfo pi) { 2024 return (android.multiuser.Flags.enableSystemUserOnlyForServicesAndProviders() 2025 && mService.isSystemUserOnly(pi.flags)) 2026 || mService.isSingleton(pi.processName, pi.applicationInfo, pi.name, pi.flags); 2027 } 2028 } 2029