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