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