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