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