1 /*
2  * Copyright (C) 2012 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 
17 package com.android.server.am;
18 
19 import static android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND;
20 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
21 import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST;
22 import static android.os.Process.NFC_UID;
23 import static android.os.Process.ROOT_UID;
24 import static android.os.Process.SHELL_UID;
25 import static android.os.Process.SYSTEM_UID;
26 import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY;
27 
28 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK;
29 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOREGROUND_SERVICE;
30 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
31 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
32 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE;
33 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE_EXECUTING;
34 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
35 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE;
36 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE_EXECUTING;
37 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
38 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
39 
40 import android.annotation.NonNull;
41 import android.annotation.Nullable;
42 import android.app.ActivityManager;
43 import android.app.ActivityManagerInternal;
44 import android.app.ActivityThread;
45 import android.app.AppGlobals;
46 import android.app.AppOpsManager;
47 import android.app.ApplicationExitInfo;
48 import android.app.IApplicationThread;
49 import android.app.IServiceConnection;
50 import android.app.Notification;
51 import android.app.NotificationManager;
52 import android.app.PendingIntent;
53 import android.app.Service;
54 import android.app.ServiceStartArgs;
55 import android.app.admin.DevicePolicyEventLogger;
56 import android.appwidget.AppWidgetManagerInternal;
57 import android.content.ComponentName;
58 import android.content.ComponentName.WithComponentName;
59 import android.content.Context;
60 import android.content.IIntentSender;
61 import android.content.Intent;
62 import android.content.IntentSender;
63 import android.content.pm.ApplicationInfo;
64 import android.content.pm.PackageManager;
65 import android.content.pm.ParceledListSlice;
66 import android.content.pm.ResolveInfo;
67 import android.content.pm.ServiceInfo;
68 import android.net.Uri;
69 import android.os.Binder;
70 import android.os.Build;
71 import android.os.Bundle;
72 import android.os.DeadObjectException;
73 import android.os.Handler;
74 import android.os.IBinder;
75 import android.os.Looper;
76 import android.os.Message;
77 import android.os.Process;
78 import android.os.RemoteCallback;
79 import android.os.RemoteException;
80 import android.os.SystemClock;
81 import android.os.SystemProperties;
82 import android.os.TransactionTooLargeException;
83 import android.os.UserHandle;
84 import android.provider.Settings;
85 import android.stats.devicepolicy.DevicePolicyEnums;
86 import android.text.TextUtils;
87 import android.util.ArrayMap;
88 import android.util.ArraySet;
89 import android.util.EventLog;
90 import android.util.PrintWriterPrinter;
91 import android.util.Slog;
92 import android.util.SparseArray;
93 import android.util.SparseIntArray;
94 import android.util.TimeUtils;
95 import android.util.proto.ProtoOutputStream;
96 import android.webkit.WebViewZygote;
97 
98 import com.android.internal.R;
99 import com.android.internal.annotations.GuardedBy;
100 import com.android.internal.app.procstats.ServiceState;
101 import com.android.internal.messages.nano.SystemMessageProto;
102 import com.android.internal.notification.SystemNotificationChannels;
103 import com.android.internal.os.BatteryStatsImpl;
104 import com.android.internal.os.TransferPipe;
105 import com.android.internal.util.DumpUtils;
106 import com.android.internal.util.FastPrintWriter;
107 import com.android.internal.util.FrameworkStatsLog;
108 import com.android.server.AppStateTracker;
109 import com.android.server.LocalServices;
110 import com.android.server.SystemService;
111 import com.android.server.am.ActivityManagerService.ItemMatcher;
112 import com.android.server.uri.NeededUriGrants;
113 import com.android.server.wm.ActivityServiceConnectionsHolder;
114 
115 import java.io.FileDescriptor;
116 import java.io.IOException;
117 import java.io.PrintWriter;
118 import java.io.StringWriter;
119 import java.util.ArrayList;
120 import java.util.Comparator;
121 import java.util.List;
122 import java.util.Set;
123 import java.util.function.Predicate;
124 
125 public final class ActiveServices {
126     private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM;
127     private static final String TAG_MU = TAG + POSTFIX_MU;
128     private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
129     private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING;
130 
131     private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE;
132     private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE;
133 
134     private static final boolean LOG_SERVICE_START_STOP = false;
135 
136     private static final boolean SHOW_DUNGEON_NOTIFICATION = false;
137 
138     //TODO: remove this when development is done.
139     private static final int DEBUG_FGS_ALLOW_WHILE_IN_USE = 0;
140     private static final int DEBUG_FGS_ENFORCE_TYPE = 1;
141 
142     // How long we wait for a service to finish executing.
143     static final int SERVICE_TIMEOUT = 20*1000;
144 
145     // How long we wait for a service to finish executing.
146     static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
147 
148     // How long the startForegroundService() grace period is to get around to
149     // calling startForeground() before we ANR + stop it.
150     static final int SERVICE_START_FOREGROUND_TIMEOUT = 10*1000;
151 
152     final ActivityManagerService mAm;
153 
154     // Maximum number of services that we allow to start in the background
155     // at the same time.
156     final int mMaxStartingBackground;
157 
158     final SparseArray<ServiceMap> mServiceMap = new SparseArray<>();
159 
160     /**
161      * All currently bound service connections.  Keys are the IBinder of
162      * the client's IServiceConnection.
163      */
164     final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>();
165 
166     /**
167      * List of services that we have been asked to start,
168      * but haven't yet been able to.  It is used to hold start requests
169      * while waiting for their corresponding application thread to get
170      * going.
171      */
172     final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>();
173 
174     /**
175      * List of services that are scheduled to restart following a crash.
176      */
177     final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
178 
179     /**
180      * List of services that are in the process of being destroyed.
181      */
182     final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>();
183 
184     /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */
185     private ArrayList<ServiceRecord> mTmpCollectionResults = null;
186 
187     /** Mapping from uid to their foreground service AppOpCallbacks (if they have one). */
188     @GuardedBy("mAm")
189     private final SparseArray<AppOpCallback> mFgsAppOpCallbacks = new SparseArray<>();
190 
191     /**
192      * For keeping ActiveForegroundApps retaining state while the screen is off.
193      */
194     boolean mScreenOn = true;
195 
196     /** Amount of time to allow a last ANR message to exist before freeing the memory. */
197     static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
198 
199     String mLastAnrDump;
200 
201     AppWidgetManagerInternal mAppWidgetManagerInternal;
202 
203     // white listed packageName.
204     ArraySet<String> mWhiteListAllowWhileInUsePermissionInFgs = new ArraySet<>();
205 
206     final Runnable mLastAnrDumpClearer = new Runnable() {
207         @Override public void run() {
208             synchronized (mAm) {
209                 mLastAnrDump = null;
210             }
211         }
212     };
213 
214     /**
215      * Watch for apps being put into forced app standby, so we can step their fg
216      * services down.
217      */
218     class ForcedStandbyListener extends AppStateTracker.Listener {
219         @Override
stopForegroundServicesForUidPackage(final int uid, final String packageName)220         public void stopForegroundServicesForUidPackage(final int uid, final String packageName) {
221             synchronized (mAm) {
222                 stopAllForegroundServicesLocked(uid, packageName);
223             }
224         }
225     }
226 
stopAllForegroundServicesLocked(final int uid, final String packageName)227     void stopAllForegroundServicesLocked(final int uid, final String packageName) {
228         final ServiceMap smap = getServiceMapLocked(UserHandle.getUserId(uid));
229         final int N = smap.mServicesByInstanceName.size();
230         final ArrayList<ServiceRecord> toStop = new ArrayList<>(N);
231         for (int i = 0; i < N; i++) {
232             final ServiceRecord r = smap.mServicesByInstanceName.valueAt(i);
233             if (uid == r.serviceInfo.applicationInfo.uid
234                     || packageName.equals(r.serviceInfo.packageName)) {
235                 if (r.isForeground) {
236                     toStop.add(r);
237                 }
238             }
239         }
240 
241         // Now stop them all
242         final int numToStop = toStop.size();
243         if (numToStop > 0 && DEBUG_FOREGROUND_SERVICE) {
244             Slog.i(TAG, "Package " + packageName + "/" + uid
245                     + " in FAS with foreground services");
246         }
247         for (int i = 0; i < numToStop; i++) {
248             final ServiceRecord r = toStop.get(i);
249             if (DEBUG_FOREGROUND_SERVICE) {
250                 Slog.i(TAG, "  Stopping fg for service " + r);
251             }
252             setServiceForegroundInnerLocked(r, 0, null, 0, 0);
253         }
254     }
255 
256     /**
257      * Information about an app that is currently running one or more foreground services.
258      * (This maps directly to the running apps we show in the notification.)
259      */
260     static final class ActiveForegroundApp {
261         String mPackageName;
262         int mUid;
263         CharSequence mLabel;
264         boolean mShownWhileScreenOn;
265         boolean mAppOnTop;
266         boolean mShownWhileTop;
267         long mStartTime;
268         long mStartVisibleTime;
269         long mEndTime;
270         int mNumActive;
271 
272         // Temp output of foregroundAppShownEnoughLocked
273         long mHideTime;
274     }
275 
276     /**
277      * Information about services for a single user.
278      */
279     final class ServiceMap extends Handler {
280         final int mUserId;
281         final ArrayMap<ComponentName, ServiceRecord> mServicesByInstanceName = new ArrayMap<>();
282         final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>();
283 
284         final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>();
285         /* XXX eventually I'd like to have this based on processes instead of services.
286          * That is, if we try to start two services in a row both running in the same
287          * process, this should be one entry in mStartingBackground for that one process
288          * that remains until all services in it are done.
289         final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
290                 = new ArrayMap<ProcessRecord, DelayingProcess>();
291         final ArrayList<DelayingProcess> mStartingProcessList
292                 = new ArrayList<DelayingProcess>();
293         */
294 
295         final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>();
296 
297         final ArrayMap<String, ActiveForegroundApp> mActiveForegroundApps = new ArrayMap<>();
298         boolean mActiveForegroundAppsChanged;
299 
300         static final int MSG_BG_START_TIMEOUT = 1;
301         static final int MSG_UPDATE_FOREGROUND_APPS = 2;
302         static final int MSG_ENSURE_NOT_START_BG = 3;
303 
ServiceMap(Looper looper, int userId)304         ServiceMap(Looper looper, int userId) {
305             super(looper);
306             mUserId = userId;
307         }
308 
309         @Override
handleMessage(Message msg)310         public void handleMessage(Message msg) {
311             switch (msg.what) {
312                 case MSG_BG_START_TIMEOUT: {
313                     synchronized (mAm) {
314                         rescheduleDelayedStartsLocked();
315                     }
316                 } break;
317                 case MSG_UPDATE_FOREGROUND_APPS: {
318                     updateForegroundApps(this);
319                 } break;
320                 case MSG_ENSURE_NOT_START_BG: {
321                     synchronized (mAm) {
322                         rescheduleDelayedStartsLocked();
323                     }
324                 } break;
325             }
326         }
327 
ensureNotStartingBackgroundLocked(ServiceRecord r)328         void ensureNotStartingBackgroundLocked(ServiceRecord r) {
329             if (mStartingBackground.remove(r)) {
330                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
331                         "No longer background starting: " + r);
332                 removeMessages(MSG_ENSURE_NOT_START_BG);
333                 Message msg = obtainMessage(MSG_ENSURE_NOT_START_BG);
334                 sendMessage(msg);
335             }
336             if (mDelayedStartList.remove(r)) {
337                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
338             }
339         }
340 
rescheduleDelayedStartsLocked()341         void rescheduleDelayedStartsLocked() {
342             removeMessages(MSG_BG_START_TIMEOUT);
343             final long now = SystemClock.uptimeMillis();
344             for (int i=0, N=mStartingBackground.size(); i<N; i++) {
345                 ServiceRecord r = mStartingBackground.get(i);
346                 if (r.startingBgTimeout <= now) {
347                     Slog.i(TAG, "Waited long enough for: " + r);
348                     mStartingBackground.remove(i);
349                     N--;
350                     i--;
351                 }
352             }
353             while (mDelayedStartList.size() > 0
354                     && mStartingBackground.size() < mMaxStartingBackground) {
355                 ServiceRecord r = mDelayedStartList.remove(0);
356                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
357                         "REM FR DELAY LIST (exec next): " + r);
358                 if (DEBUG_DELAYED_SERVICE) {
359                     if (mDelayedStartList.size() > 0) {
360                         Slog.v(TAG_SERVICE, "Remaining delayed list:");
361                         for (int i=0; i<mDelayedStartList.size(); i++) {
362                             Slog.v(TAG_SERVICE, "  #" + i + ": " + mDelayedStartList.get(i));
363                         }
364                     }
365                 }
366                 r.delayed = false;
367                 if (r.pendingStarts.size() <= 0) {
368                     Slog.wtf(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
369                             + " delayedStop=" + r.delayedStop);
370                 } else {
371                     try {
372                         startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false,
373                                 true);
374                     } catch (TransactionTooLargeException e) {
375                         // Ignore, nobody upstack cares.
376                     }
377                 }
378             }
379             if (mStartingBackground.size() > 0) {
380                 ServiceRecord next = mStartingBackground.get(0);
381                 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
382                 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
383                         + ", can delay others up to " + when);
384                 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
385                 sendMessageAtTime(msg, when);
386             }
387             if (mStartingBackground.size() < mMaxStartingBackground) {
388                 mAm.backgroundServicesFinishedLocked(mUserId);
389             }
390         }
391     }
392 
ActiveServices(ActivityManagerService service)393     public ActiveServices(ActivityManagerService service) {
394         mAm = service;
395         int maxBg = 0;
396         try {
397             maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
398         } catch(RuntimeException e) {
399         }
400         mMaxStartingBackground = maxBg > 0
401                 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
402     }
403 
systemServicesReady()404     void systemServicesReady() {
405         AppStateTracker ast = LocalServices.getService(AppStateTracker.class);
406         ast.addListener(new ForcedStandbyListener());
407         mAppWidgetManagerInternal = LocalServices.getService(AppWidgetManagerInternal.class);
408         setWhiteListAllowWhileInUsePermissionInFgs();
409     }
410 
setWhiteListAllowWhileInUsePermissionInFgs()411     private void setWhiteListAllowWhileInUsePermissionInFgs() {
412         final String attentionServicePackageName =
413                 mAm.mContext.getPackageManager().getAttentionServicePackageName();
414         if (!TextUtils.isEmpty(attentionServicePackageName)) {
415             mWhiteListAllowWhileInUsePermissionInFgs.add(attentionServicePackageName);
416         }
417         final String systemCaptionsServicePackageName =
418                 mAm.mContext.getPackageManager().getSystemCaptionsServicePackageName();
419         if (!TextUtils.isEmpty(systemCaptionsServicePackageName)) {
420             mWhiteListAllowWhileInUsePermissionInFgs.add(systemCaptionsServicePackageName);
421         }
422     }
423 
getServiceByNameLocked(ComponentName name, int callingUser)424     ServiceRecord getServiceByNameLocked(ComponentName name, int callingUser) {
425         // TODO: Deal with global services
426         if (DEBUG_MU)
427             Slog.v(TAG_MU, "getServiceByNameLocked(" + name + "), callingUser = " + callingUser);
428         return getServiceMapLocked(callingUser).mServicesByInstanceName.get(name);
429     }
430 
hasBackgroundServicesLocked(int callingUser)431     boolean hasBackgroundServicesLocked(int callingUser) {
432         ServiceMap smap = mServiceMap.get(callingUser);
433         return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
434     }
435 
getServiceMapLocked(int callingUser)436     private ServiceMap getServiceMapLocked(int callingUser) {
437         ServiceMap smap = mServiceMap.get(callingUser);
438         if (smap == null) {
439             smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
440             mServiceMap.put(callingUser, smap);
441         }
442         return smap;
443     }
444 
getServicesLocked(int callingUser)445     ArrayMap<ComponentName, ServiceRecord> getServicesLocked(int callingUser) {
446         return getServiceMapLocked(callingUser).mServicesByInstanceName;
447     }
448 
appRestrictedAnyInBackground(final int uid, final String packageName)449     private boolean appRestrictedAnyInBackground(final int uid, final String packageName) {
450         final int mode = mAm.getAppOpsManager().checkOpNoThrow(
451                 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, uid, packageName);
452         return (mode != AppOpsManager.MODE_ALLOWED);
453     }
454 
startServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int callingPid, int callingUid, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, final int userId)455     ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
456             int callingPid, int callingUid, boolean fgRequired, String callingPackage,
457             @Nullable String callingFeatureId, final int userId)
458             throws TransactionTooLargeException {
459         return startServiceLocked(caller, service, resolvedType, callingPid, callingUid, fgRequired,
460                 callingPackage, callingFeatureId, userId, false);
461     }
462 
startServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int callingPid, int callingUid, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, final int userId, boolean allowBackgroundActivityStarts)463     ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
464             int callingPid, int callingUid, boolean fgRequired, String callingPackage,
465             @Nullable String callingFeatureId, final int userId,
466             boolean allowBackgroundActivityStarts) throws TransactionTooLargeException {
467         if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
468                 + " type=" + resolvedType + " args=" + service.getExtras());
469 
470         final boolean callerFg;
471         if (caller != null) {
472             final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
473             if (callerApp == null) {
474                 throw new SecurityException(
475                         "Unable to find app for caller " + caller
476                         + " (pid=" + callingPid
477                         + ") when starting service " + service);
478             }
479             callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
480         } else {
481             callerFg = true;
482         }
483 
484         ServiceLookupResult res =
485             retrieveServiceLocked(service, null, resolvedType, callingPackage,
486                     callingPid, callingUid, userId, true, callerFg, false, false);
487         if (res == null) {
488             return null;
489         }
490         if (res.record == null) {
491             return new ComponentName("!", res.permission != null
492                     ? res.permission : "private to package");
493         }
494 
495         ServiceRecord r = res.record;
496 
497         if (!mAm.mUserController.exists(r.userId)) {
498             Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
499             return null;
500         }
501 
502         // If we're starting indirectly (e.g. from PendingIntent), figure out whether
503         // we're launching into an app in a background state.  This keys off of the same
504         // idleness state tracking as e.g. O+ background service start policy.
505         final boolean bgLaunch = !mAm.isUidActiveLocked(r.appInfo.uid);
506 
507         // If the app has strict background restrictions, we treat any bg service
508         // start analogously to the legacy-app forced-restrictions case, regardless
509         // of its target SDK version.
510         boolean forcedStandby = false;
511         if (bgLaunch && appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
512             if (DEBUG_FOREGROUND_SERVICE) {
513                 Slog.d(TAG, "Forcing bg-only service start only for " + r.shortInstanceName
514                         + " : bgLaunch=" + bgLaunch + " callerFg=" + callerFg);
515             }
516             forcedStandby = true;
517         }
518 
519         // If this is a direct-to-foreground start, make sure it is allowed as per the app op.
520         boolean forceSilentAbort = false;
521         if (fgRequired) {
522             final int mode = mAm.getAppOpsManager().checkOpNoThrow(
523                     AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
524             switch (mode) {
525                 case AppOpsManager.MODE_ALLOWED:
526                 case AppOpsManager.MODE_DEFAULT:
527                     // All okay.
528                     break;
529                 case AppOpsManager.MODE_IGNORED:
530                     // Not allowed, fall back to normal start service, failing siliently
531                     // if background check restricts that.
532                     Slog.w(TAG, "startForegroundService not allowed due to app op: service "
533                             + service + " to " + r.shortInstanceName
534                             + " from pid=" + callingPid + " uid=" + callingUid
535                             + " pkg=" + callingPackage);
536                     fgRequired = false;
537                     forceSilentAbort = true;
538                     break;
539                 default:
540                     return new ComponentName("!!", "foreground not allowed as per app op");
541             }
542         }
543 
544         // If this isn't a direct-to-foreground start, check our ability to kick off an
545         // arbitrary service
546         if (forcedStandby || (!r.startRequested && !fgRequired)) {
547             // Before going further -- if this app is not allowed to start services in the
548             // background, then at this point we aren't going to let it period.
549             final int allowed = mAm.getAppStartModeLocked(r.appInfo.uid, r.packageName,
550                     r.appInfo.targetSdkVersion, callingPid, false, false, forcedStandby);
551             if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
552                 Slog.w(TAG, "Background start not allowed: service "
553                         + service + " to " + r.shortInstanceName
554                         + " from pid=" + callingPid + " uid=" + callingUid
555                         + " pkg=" + callingPackage + " startFg?=" + fgRequired);
556                 if (allowed == ActivityManager.APP_START_MODE_DELAYED || forceSilentAbort) {
557                     // In this case we are silently disabling the app, to disrupt as
558                     // little as possible existing apps.
559                     return null;
560                 }
561                 if (forcedStandby) {
562                     // This is an O+ app, but we might be here because the user has placed
563                     // it under strict background restrictions.  Don't punish the app if it's
564                     // trying to do the right thing but we're denying it for that reason.
565                     if (fgRequired) {
566                         if (DEBUG_BACKGROUND_CHECK) {
567                             Slog.v(TAG, "Silently dropping foreground service launch due to FAS");
568                         }
569                         return null;
570                     }
571                 }
572                 // This app knows it is in the new model where this operation is not
573                 // allowed, so tell it what has happened.
574                 UidRecord uidRec = mAm.mProcessList.getUidRecordLocked(r.appInfo.uid);
575                 return new ComponentName("?", "app is in background uid " + uidRec);
576             }
577         }
578 
579         // At this point we've applied allowed-to-start policy based on whether this was
580         // an ordinary startService() or a startForegroundService().  Now, only require that
581         // the app follow through on the startForegroundService() -> startForeground()
582         // contract if it actually targets O+.
583         if (r.appInfo.targetSdkVersion < Build.VERSION_CODES.O && fgRequired) {
584             if (DEBUG_BACKGROUND_CHECK || DEBUG_FOREGROUND_SERVICE) {
585                 Slog.i(TAG, "startForegroundService() but host targets "
586                         + r.appInfo.targetSdkVersion + " - not requiring startForeground()");
587             }
588             fgRequired = false;
589         }
590 
591         NeededUriGrants neededGrants = mAm.mUgmInternal.checkGrantUriPermissionFromIntent(
592                 service, callingUid, r.packageName, r.userId);
593 
594         // If permissions need a review before any of the app components can run,
595         // we do not start the service and launch a review activity if the calling app
596         // is in the foreground passing it a pending intent to start the service when
597         // review is completed.
598 
599         // XXX This is not dealing with fgRequired!
600         if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage, callingFeatureId,
601                 callingUid, service, callerFg, userId)) {
602             return null;
603         }
604 
605         if (unscheduleServiceRestartLocked(r, callingUid, false)) {
606             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
607         }
608         r.lastActivity = SystemClock.uptimeMillis();
609         r.startRequested = true;
610         r.delayedStop = false;
611         r.fgRequired = fgRequired;
612         r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
613                 service, neededGrants, callingUid));
614 
615         if (fgRequired) {
616             // We are now effectively running a foreground service.
617             ServiceState stracker = r.getTracker();
618             if (stracker != null) {
619                 stracker.setForeground(true, mAm.mProcessStats.getMemFactorLocked(),
620                         r.lastActivity);
621             }
622             mAm.mAppOpsService.startOperation(AppOpsManager.getToken(mAm.mAppOpsService),
623                     AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, null,
624                     true, false, null, false);
625         }
626 
627         final ServiceMap smap = getServiceMapLocked(r.userId);
628         boolean addToStarting = false;
629         if (!callerFg && !fgRequired && r.app == null
630                 && mAm.mUserController.hasStartedUserState(r.userId)) {
631             ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
632             if (proc == null || proc.getCurProcState() > ActivityManager.PROCESS_STATE_RECEIVER) {
633                 // If this is not coming from a foreground caller, then we may want
634                 // to delay the start if there are already other background services
635                 // that are starting.  This is to avoid process start spam when lots
636                 // of applications are all handling things like connectivity broadcasts.
637                 // We only do this for cached processes, because otherwise an application
638                 // can have assumptions about calling startService() for a service to run
639                 // in its own process, and for that process to not be killed before the
640                 // service is started.  This is especially the case for receivers, which
641                 // may start a service in onReceive() to do some additional work and have
642                 // initialized some global state as part of that.
643                 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
644                         + r + " in " + proc);
645                 if (r.delayed) {
646                     // This service is already scheduled for a delayed start; just leave
647                     // it still waiting.
648                     if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
649                     return r.name;
650                 }
651                 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
652                     // Something else is starting, delay!
653                     Slog.i(TAG_SERVICE, "Delaying start of: " + r);
654                     smap.mDelayedStartList.add(r);
655                     r.delayed = true;
656                     return r.name;
657                 }
658                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
659                 addToStarting = true;
660             } else if (proc.getCurProcState() >= ActivityManager.PROCESS_STATE_SERVICE) {
661                 // We slightly loosen when we will enqueue this new service as a background
662                 // starting service we are waiting for, to also include processes that are
663                 // currently running other services or receivers.
664                 addToStarting = true;
665                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
666                         "Not delaying, but counting as bg: " + r);
667             } else if (DEBUG_DELAYED_STARTS) {
668                 StringBuilder sb = new StringBuilder(128);
669                 sb.append("Not potential delay (state=").append(proc.getCurProcState())
670                         .append(' ').append(proc.adjType);
671                 String reason = proc.makeAdjReason();
672                 if (reason != null) {
673                     sb.append(' ');
674                     sb.append(reason);
675                 }
676                 sb.append("): ");
677                 sb.append(r.toString());
678                 Slog.v(TAG_SERVICE, sb.toString());
679             }
680         } else if (DEBUG_DELAYED_STARTS) {
681             if (callerFg || fgRequired) {
682                 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
683                         + callingUid + " pid=" + callingPid + " fgRequired=" + fgRequired + "): " + r);
684             } else if (r.app != null) {
685                 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
686             } else {
687                 Slog.v(TAG_SERVICE,
688                         "Not potential delay (user " + r.userId + " not started): " + r);
689             }
690         }
691 
692         if (allowBackgroundActivityStarts) {
693             r.whitelistBgActivityStartsOnServiceStart();
694         }
695         ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
696 
697         if (!r.mAllowWhileInUsePermissionInFgs) {
698             r.mAllowWhileInUsePermissionInFgs =
699                     shouldAllowWhileInUsePermissionInFgsLocked(callingPackage, callingPid,
700                             callingUid, service, r, allowBackgroundActivityStarts);
701         }
702 
703         return cmp;
704     }
705 
requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r, String callingPackage, @Nullable String callingFeatureId, int callingUid, Intent service, boolean callerFg, final int userId)706     private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
707             String callingPackage, @Nullable String callingFeatureId, int callingUid,
708             Intent service, boolean callerFg, final int userId) {
709         if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
710                 r.packageName, r.userId)) {
711 
712             // Show a permission review UI only for starting from a foreground app
713             if (!callerFg) {
714                 Slog.w(TAG, "u" + r.userId + " Starting a service in package"
715                         + r.packageName + " requires a permissions review");
716                 return false;
717             }
718 
719             IIntentSender target = mAm.mPendingIntentController.getIntentSender(
720                     ActivityManager.INTENT_SENDER_SERVICE, callingPackage, callingFeatureId,
721                     callingUid, userId, null, null, 0, new Intent[]{service},
722                     new String[]{service.resolveType(mAm.mContext.getContentResolver())},
723                     PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
724                             | PendingIntent.FLAG_IMMUTABLE, null);
725 
726             final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
727             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
728                     | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
729                     | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
730             intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
731             intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
732 
733             if (DEBUG_PERMISSIONS_REVIEW) {
734                 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
735                         + r.packageName);
736             }
737 
738             mAm.mHandler.post(new Runnable() {
739                 @Override
740                 public void run() {
741                     mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
742                 }
743             });
744 
745             return false;
746         }
747 
748         return  true;
749     }
750 
startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r, boolean callerFg, boolean addToStarting)751     ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
752             boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
753         ServiceState stracker = r.getTracker();
754         if (stracker != null) {
755             stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
756         }
757         r.callStart = false;
758         FrameworkStatsLog.write(FrameworkStatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid,
759                 r.name.getPackageName(), r.name.getClassName(),
760                 FrameworkStatsLog.SERVICE_STATE_CHANGED__STATE__START);
761         synchronized (r.stats.getBatteryStats()) {
762             r.stats.startRunningLocked();
763         }
764         String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
765         if (error != null) {
766             return new ComponentName("!!", error);
767         }
768 
769         if (r.startRequested && addToStarting) {
770             boolean first = smap.mStartingBackground.size() == 0;
771             smap.mStartingBackground.add(r);
772             r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
773             if (DEBUG_DELAYED_SERVICE) {
774                 RuntimeException here = new RuntimeException("here");
775                 here.fillInStackTrace();
776                 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
777             } else if (DEBUG_DELAYED_STARTS) {
778                 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
779             }
780             if (first) {
781                 smap.rescheduleDelayedStartsLocked();
782             }
783         } else if (callerFg || r.fgRequired) {
784             smap.ensureNotStartingBackgroundLocked(r);
785         }
786 
787         return r.name;
788     }
789 
stopServiceLocked(ServiceRecord service)790     private void stopServiceLocked(ServiceRecord service) {
791         if (service.delayed) {
792             // If service isn't actually running, but is being held in the
793             // delayed list, then we need to keep it started but note that it
794             // should be stopped once no longer delayed.
795             if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
796             service.delayedStop = true;
797             return;
798         }
799         FrameworkStatsLog.write(FrameworkStatsLog.SERVICE_STATE_CHANGED, service.appInfo.uid,
800                 service.name.getPackageName(), service.name.getClassName(),
801                 FrameworkStatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
802         synchronized (service.stats.getBatteryStats()) {
803             service.stats.stopRunningLocked();
804         }
805         service.startRequested = false;
806         if (service.tracker != null) {
807             service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
808                     SystemClock.uptimeMillis());
809         }
810         service.callStart = false;
811 
812         bringDownServiceIfNeededLocked(service, false, false);
813     }
814 
stopServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int userId)815     int stopServiceLocked(IApplicationThread caller, Intent service,
816             String resolvedType, int userId) {
817         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
818                 + " type=" + resolvedType);
819 
820         final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
821         if (caller != null && callerApp == null) {
822             throw new SecurityException(
823                     "Unable to find app for caller " + caller
824                     + " (pid=" + Binder.getCallingPid()
825                     + ") when stopping service " + service);
826         }
827 
828         // If this service is active, make sure it is stopped.
829         ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, null,
830                 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false, false);
831         if (r != null) {
832             if (r.record != null) {
833                 final long origId = Binder.clearCallingIdentity();
834                 try {
835                     stopServiceLocked(r.record);
836                 } finally {
837                     Binder.restoreCallingIdentity(origId);
838                 }
839                 return 1;
840             }
841             return -1;
842         }
843 
844         return 0;
845     }
846 
stopInBackgroundLocked(int uid)847     void stopInBackgroundLocked(int uid) {
848         // Stop all services associated with this uid due to it going to the background
849         // stopped state.
850         ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
851         ArrayList<ServiceRecord> stopping = null;
852         if (services != null) {
853             for (int i = services.mServicesByInstanceName.size() - 1; i >= 0; i--) {
854                 ServiceRecord service = services.mServicesByInstanceName.valueAt(i);
855                 if (service.appInfo.uid == uid && service.startRequested) {
856                     if (mAm.getAppStartModeLocked(service.appInfo.uid, service.packageName,
857                             service.appInfo.targetSdkVersion, -1, false, false, false)
858                             != ActivityManager.APP_START_MODE_NORMAL) {
859                         if (stopping == null) {
860                             stopping = new ArrayList<>();
861                         }
862                         String compName = service.shortInstanceName;
863                         EventLogTags.writeAmStopIdleService(service.appInfo.uid, compName);
864                         StringBuilder sb = new StringBuilder(64);
865                         sb.append("Stopping service due to app idle: ");
866                         UserHandle.formatUid(sb, service.appInfo.uid);
867                         sb.append(" ");
868                         TimeUtils.formatDuration(service.createRealTime
869                                 - SystemClock.elapsedRealtime(), sb);
870                         sb.append(" ");
871                         sb.append(compName);
872                         Slog.w(TAG, sb.toString());
873                         stopping.add(service);
874 
875                         // If the app is under bg restrictions, also make sure that
876                         // any notification is dismissed
877                         if (appRestrictedAnyInBackground(
878                                 service.appInfo.uid, service.packageName)) {
879                             cancelForegroundNotificationLocked(service);
880                         }
881                     }
882                 }
883             }
884             if (stopping != null) {
885                 for (int i=stopping.size()-1; i>=0; i--) {
886                     ServiceRecord service = stopping.get(i);
887                     service.delayed = false;
888                     services.ensureNotStartingBackgroundLocked(service);
889                     stopServiceLocked(service);
890                 }
891             }
892         }
893     }
894 
killMisbehavingService(ServiceRecord r, int appUid, int appPid, String localPackageName)895     void killMisbehavingService(ServiceRecord r,
896             int appUid, int appPid, String localPackageName) {
897         synchronized (mAm) {
898             stopServiceLocked(r);
899             mAm.crashApplication(appUid, appPid, localPackageName, -1,
900                     "Bad notification for startForeground", true /*force*/);
901         }
902     }
903 
peekServiceLocked(Intent service, String resolvedType, String callingPackage)904     IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
905         ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, callingPackage,
906                 Binder.getCallingPid(), Binder.getCallingUid(),
907                 UserHandle.getCallingUserId(), false, false, false, false);
908 
909         IBinder ret = null;
910         if (r != null) {
911             // r.record is null if findServiceLocked() failed the caller permission check
912             if (r.record == null) {
913                 throw new SecurityException(
914                         "Permission Denial: Accessing service"
915                         + " from pid=" + Binder.getCallingPid()
916                         + ", uid=" + Binder.getCallingUid()
917                         + " requires " + r.permission);
918             }
919             IntentBindRecord ib = r.record.bindings.get(r.record.intent);
920             if (ib != null) {
921                 ret = ib.binder;
922             }
923         }
924 
925         return ret;
926     }
927 
stopServiceTokenLocked(ComponentName className, IBinder token, int startId)928     boolean stopServiceTokenLocked(ComponentName className, IBinder token,
929             int startId) {
930         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
931                 + " " + token + " startId=" + startId);
932         ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
933         if (r != null) {
934             if (startId >= 0) {
935                 // Asked to only stop if done with all work.  Note that
936                 // to avoid leaks, we will take this as dropping all
937                 // start items up to and including this one.
938                 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
939                 if (si != null) {
940                     while (r.deliveredStarts.size() > 0) {
941                         ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
942                         cur.removeUriPermissionsLocked();
943                         if (cur == si) {
944                             break;
945                         }
946                     }
947                 }
948 
949                 if (r.getLastStartId() != startId) {
950                     return false;
951                 }
952 
953                 if (r.deliveredStarts.size() > 0) {
954                     Slog.w(TAG, "stopServiceToken startId " + startId
955                             + " is last, but have " + r.deliveredStarts.size()
956                             + " remaining args");
957                 }
958             }
959 
960             FrameworkStatsLog.write(FrameworkStatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid,
961                     r.name.getPackageName(), r.name.getClassName(),
962                     FrameworkStatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
963             synchronized (r.stats.getBatteryStats()) {
964                 r.stats.stopRunningLocked();
965             }
966             r.startRequested = false;
967             if (r.tracker != null) {
968                 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
969                         SystemClock.uptimeMillis());
970             }
971             r.callStart = false;
972             final long origId = Binder.clearCallingIdentity();
973             bringDownServiceIfNeededLocked(r, false, false);
974             Binder.restoreCallingIdentity(origId);
975             return true;
976         }
977         return false;
978     }
979 
setServiceForegroundLocked(ComponentName className, IBinder token, int id, Notification notification, int flags, int foregroundServiceType)980     public void setServiceForegroundLocked(ComponentName className, IBinder token,
981             int id, Notification notification, int flags, int foregroundServiceType) {
982         final int userId = UserHandle.getCallingUserId();
983         final long origId = Binder.clearCallingIdentity();
984         try {
985             ServiceRecord r = findServiceLocked(className, token, userId);
986             if (r != null) {
987                 setServiceForegroundInnerLocked(r, id, notification, flags, foregroundServiceType);
988             }
989         } finally {
990             Binder.restoreCallingIdentity(origId);
991         }
992     }
993 
994     /**
995      * Return the current foregroundServiceType of the ServiceRecord.
996      * @param className ComponentName of the Service class.
997      * @param token IBinder token.
998      * @return current foreground service type.
999      */
getForegroundServiceTypeLocked(ComponentName className, IBinder token)1000     public int getForegroundServiceTypeLocked(ComponentName className, IBinder token) {
1001         final int userId = UserHandle.getCallingUserId();
1002         final long origId = Binder.clearCallingIdentity();
1003         int ret = ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE;
1004         try {
1005             ServiceRecord r = findServiceLocked(className, token, userId);
1006             if (r != null) {
1007                 ret = r.foregroundServiceType;
1008             }
1009         } finally {
1010             Binder.restoreCallingIdentity(origId);
1011         }
1012         return ret;
1013     }
1014 
foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed)1015     boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) {
1016         if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid="
1017                 + aa.mUid);
1018         boolean canRemove = false;
1019         aa.mHideTime = Long.MAX_VALUE;
1020         if (aa.mShownWhileTop) {
1021             // If the app was ever at the top of the screen while the foreground
1022             // service was running, then we can always just immediately remove it.
1023             canRemove = true;
1024             if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown while on top");
1025         } else if (mScreenOn || aa.mShownWhileScreenOn) {
1026             final long minTime = aa.mStartVisibleTime
1027                     + (aa.mStartTime != aa.mStartVisibleTime
1028                             ? mAm.mConstants.FGSERVICE_SCREEN_ON_AFTER_TIME
1029                             : mAm.mConstants.FGSERVICE_MIN_SHOWN_TIME);
1030             if (nowElapsed >= minTime) {
1031                 // If shown while the screen is on, and it has been shown for
1032                 // at least the minimum show time, then we can now remove it.
1033                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown long enough with screen on");
1034                 canRemove = true;
1035             } else {
1036                 // This is when we will be okay to stop telling the user.
1037                 long reportTime = nowElapsed + mAm.mConstants.FGSERVICE_MIN_REPORT_TIME;
1038                 aa.mHideTime = reportTime > minTime ? reportTime : minTime;
1039                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
1040                         + " with screen on");
1041             }
1042         } else {
1043             final long minTime = aa.mEndTime
1044                     + mAm.mConstants.FGSERVICE_SCREEN_ON_BEFORE_TIME;
1045             if (nowElapsed >= minTime) {
1046                 // If the foreground service has only run while the screen is
1047                 // off, but it has been gone now for long enough that we won't
1048                 // care to tell the user about it when the screen comes back on,
1049                 // then we can remove it now.
1050                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - gone long enough with screen off");
1051                 canRemove = true;
1052             } else {
1053                 // This is when we won't care about this old fg service.
1054                 aa.mHideTime = minTime;
1055                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
1056                         + " with screen off");
1057             }
1058         }
1059         return canRemove;
1060     }
1061 
updateForegroundApps(ServiceMap smap)1062     void updateForegroundApps(ServiceMap smap) {
1063         // This is called from the handler without the lock held.
1064         ArrayList<ActiveForegroundApp> active = null;
1065         synchronized (mAm) {
1066             final long now = SystemClock.elapsedRealtime();
1067             long nextUpdateTime = Long.MAX_VALUE;
1068             if (smap != null) {
1069                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Updating foreground apps for user "
1070                         + smap.mUserId);
1071                 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
1072                     ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
1073                     if (aa.mEndTime != 0) {
1074                         boolean canRemove = foregroundAppShownEnoughLocked(aa, now);
1075                         if (canRemove) {
1076                             // This was up for longer than the timeout, so just remove immediately.
1077                             smap.mActiveForegroundApps.removeAt(i);
1078                             smap.mActiveForegroundAppsChanged = true;
1079                             continue;
1080                         }
1081                         if (aa.mHideTime < nextUpdateTime) {
1082                             nextUpdateTime = aa.mHideTime;
1083                         }
1084                     }
1085                     if (!aa.mAppOnTop) {
1086                         // Transitioning a fg-service host app out of top: if it's bg restricted,
1087                         // it loses the fg service state now.
1088                         if (!appRestrictedAnyInBackground(aa.mUid, aa.mPackageName)) {
1089                             if (active == null) {
1090                                 active = new ArrayList<>();
1091                             }
1092                             if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
1093                                     + aa.mPackageName + ", uid=" + aa.mUid);
1094                             active.add(aa);
1095                         } else {
1096                             if (DEBUG_FOREGROUND_SERVICE) {
1097                                 Slog.d(TAG, "bg-restricted app "
1098                                         + aa.mPackageName + "/" + aa.mUid
1099                                         + " exiting top; demoting fg services ");
1100                             }
1101                             stopAllForegroundServicesLocked(aa.mUid, aa.mPackageName);
1102                         }
1103                     }
1104                 }
1105                 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
1106                 if (nextUpdateTime < Long.MAX_VALUE) {
1107                     if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Next update time in: "
1108                             + (nextUpdateTime-now));
1109                     Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
1110                     smap.sendMessageAtTime(msg, nextUpdateTime
1111                             + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
1112                 }
1113             }
1114             if (!smap.mActiveForegroundAppsChanged) {
1115                 return;
1116             }
1117             smap.mActiveForegroundAppsChanged = false;
1118         }
1119 
1120         if (!SHOW_DUNGEON_NOTIFICATION) {
1121             return;
1122         }
1123 
1124         final NotificationManager nm = (NotificationManager) mAm.mContext.getSystemService(
1125                 Context.NOTIFICATION_SERVICE);
1126         final Context context = mAm.mContext;
1127 
1128         if (active != null) {
1129             for (int i = 0; i < active.size(); i++) {
1130                 ActiveForegroundApp aa = active.get(i);
1131                 if (aa.mLabel == null) {
1132                     PackageManager pm = context.getPackageManager();
1133                     try {
1134                         ApplicationInfo ai = pm.getApplicationInfoAsUser(aa.mPackageName,
1135                                 PackageManager.MATCH_KNOWN_PACKAGES, smap.mUserId);
1136                         aa.mLabel = ai.loadLabel(pm);
1137                     } catch (PackageManager.NameNotFoundException e) {
1138                         aa.mLabel = aa.mPackageName;
1139                     }
1140                 }
1141             }
1142 
1143             Intent intent;
1144             String title;
1145             String msg;
1146             String[] pkgs;
1147             final long nowElapsed = SystemClock.elapsedRealtime();
1148             long oldestStartTime = nowElapsed;
1149             if (active.size() == 1) {
1150                 intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
1151                 intent.setData(Uri.fromParts("package", active.get(0).mPackageName, null));
1152                 title = context.getString(
1153                         R.string.foreground_service_app_in_background, active.get(0).mLabel);
1154                 msg = context.getString(R.string.foreground_service_tap_for_details);
1155                 pkgs = new String[] { active.get(0).mPackageName };
1156                 oldestStartTime = active.get(0).mStartTime;
1157             } else {
1158                 intent = new Intent(Settings.ACTION_FOREGROUND_SERVICES_SETTINGS);
1159                 pkgs = new String[active.size()];
1160                 for (int i = 0; i < active.size(); i++) {
1161                     pkgs[i] = active.get(i).mPackageName;
1162                     oldestStartTime = Math.min(oldestStartTime, active.get(i).mStartTime);
1163                 }
1164                 intent.putExtra("packages", pkgs);
1165                 title = context.getString(
1166                         R.string.foreground_service_apps_in_background, active.size());
1167                 msg = active.get(0).mLabel.toString();
1168                 for (int i = 1; i < active.size(); i++) {
1169                     msg = context.getString(R.string.foreground_service_multiple_separator,
1170                             msg, active.get(i).mLabel);
1171                 }
1172             }
1173             Bundle notificationBundle = new Bundle();
1174             notificationBundle.putStringArray(Notification.EXTRA_FOREGROUND_APPS, pkgs);
1175             Notification.Builder n =
1176                     new Notification.Builder(context,
1177                             SystemNotificationChannels.FOREGROUND_SERVICE)
1178                             .addExtras(notificationBundle)
1179                             .setSmallIcon(R.drawable.stat_sys_vitals)
1180                             .setOngoing(true)
1181                             .setShowWhen(oldestStartTime < nowElapsed)
1182                             .setWhen(System.currentTimeMillis() - (nowElapsed - oldestStartTime))
1183                             .setColor(context.getColor(
1184                                     com.android.internal.R.color.system_notification_accent_color))
1185                             .setContentTitle(title)
1186                             .setContentText(msg)
1187                             .setContentIntent(
1188                                     PendingIntent.getActivityAsUser(context, 0, intent,
1189                                             PendingIntent.FLAG_UPDATE_CURRENT,
1190                                             null, new UserHandle(smap.mUserId)));
1191             nm.notifyAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1192                     n.build(), new UserHandle(smap.mUserId));
1193         } else {
1194             nm.cancelAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1195                     new UserHandle(smap.mUserId));
1196         }
1197     }
1198 
requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed)1199     private void requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed) {
1200         Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
1201         if (timeElapsed != 0) {
1202             smap.sendMessageAtTime(msg,
1203                     timeElapsed + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
1204         } else {
1205             smap.mActiveForegroundAppsChanged = true;
1206             smap.sendMessage(msg);
1207         }
1208     }
1209 
decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r)1210     private void decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r) {
1211         ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1212         if (active != null) {
1213             active.mNumActive--;
1214             if (active.mNumActive <= 0) {
1215                 active.mEndTime = SystemClock.elapsedRealtime();
1216                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Ended running of service");
1217                 if (foregroundAppShownEnoughLocked(active, active.mEndTime)) {
1218                     // Have been active for long enough that we will remove it immediately.
1219                     smap.mActiveForegroundApps.remove(r.packageName);
1220                     smap.mActiveForegroundAppsChanged = true;
1221                     requestUpdateActiveForegroundAppsLocked(smap, 0);
1222                 } else if (active.mHideTime < Long.MAX_VALUE){
1223                     requestUpdateActiveForegroundAppsLocked(smap, active.mHideTime);
1224                 }
1225             }
1226         }
1227     }
1228 
updateScreenStateLocked(boolean screenOn)1229     void updateScreenStateLocked(boolean screenOn) {
1230         if (mScreenOn != screenOn) {
1231             mScreenOn = screenOn;
1232 
1233             // If screen is turning on, then we now reset the start time of any foreground
1234             // services that were started while the screen was off.
1235             if (screenOn) {
1236                 final long nowElapsed = SystemClock.elapsedRealtime();
1237                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Screen turned on");
1238                 for (int i = mServiceMap.size()-1; i >= 0; i--) {
1239                     ServiceMap smap = mServiceMap.valueAt(i);
1240                     long nextUpdateTime = Long.MAX_VALUE;
1241                     boolean changed = false;
1242                     for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1243                         ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
1244                         if (active.mEndTime == 0) {
1245                             if (!active.mShownWhileScreenOn) {
1246                                 active.mShownWhileScreenOn = true;
1247                                 active.mStartVisibleTime = nowElapsed;
1248                             }
1249                         } else {
1250                             if (!active.mShownWhileScreenOn
1251                                     && active.mStartVisibleTime == active.mStartTime) {
1252                                 // If this was never shown while the screen was on, then we will
1253                                 // count the time it started being visible as now, to tell the user
1254                                 // about it now that they have a screen to look at.
1255                                 active.mEndTime = active.mStartVisibleTime = nowElapsed;
1256                             }
1257                             if (foregroundAppShownEnoughLocked(active, nowElapsed)) {
1258                                 // Have been active for long enough that we will remove it
1259                                 // immediately.
1260                                 smap.mActiveForegroundApps.remove(active.mPackageName);
1261                                 smap.mActiveForegroundAppsChanged = true;
1262                                 changed = true;
1263                             } else {
1264                                 if (active.mHideTime < nextUpdateTime) {
1265                                     nextUpdateTime = active.mHideTime;
1266                                 }
1267                             }
1268                         }
1269                     }
1270                     if (changed) {
1271                         // Need to immediately update.
1272                         requestUpdateActiveForegroundAppsLocked(smap, 0);
1273                     } else if (nextUpdateTime < Long.MAX_VALUE) {
1274                         requestUpdateActiveForegroundAppsLocked(smap, nextUpdateTime);
1275                     }
1276                 }
1277             }
1278         }
1279     }
1280 
foregroundServiceProcStateChangedLocked(UidRecord uidRec)1281     void foregroundServiceProcStateChangedLocked(UidRecord uidRec) {
1282         ServiceMap smap = mServiceMap.get(UserHandle.getUserId(uidRec.uid));
1283         if (smap != null) {
1284             boolean changed = false;
1285             for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1286                 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
1287                 if (active.mUid == uidRec.uid) {
1288                     if (uidRec.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP) {
1289                         if (!active.mAppOnTop) {
1290                             active.mAppOnTop = true;
1291                             changed = true;
1292                         }
1293                         active.mShownWhileTop = true;
1294                     } else if (active.mAppOnTop) {
1295                         active.mAppOnTop = false;
1296                         changed = true;
1297                     }
1298                 }
1299             }
1300             if (changed) {
1301                 requestUpdateActiveForegroundAppsLocked(smap, 0);
1302             }
1303         }
1304     }
1305 
appIsTopLocked(int uid)1306     private boolean appIsTopLocked(int uid) {
1307         return mAm.getUidState(uid) <= ActivityManager.PROCESS_STATE_TOP;
1308     }
1309 
1310     /**
1311      * @param id Notification ID.  Zero === exit foreground state for the given service.
1312      */
setServiceForegroundInnerLocked(final ServiceRecord r, int id, Notification notification, int flags, int foregroundServiceType)1313     private void setServiceForegroundInnerLocked(final ServiceRecord r, int id,
1314             Notification notification, int flags, int foregroundServiceType) {
1315         if (id != 0) {
1316             if (notification == null) {
1317                 throw new IllegalArgumentException("null notification");
1318             }
1319             // Instant apps need permission to create foreground services.
1320             if (r.appInfo.isInstantApp()) {
1321                 final int mode = mAm.getAppOpsManager().checkOpNoThrow(
1322                         AppOpsManager.OP_INSTANT_APP_START_FOREGROUND,
1323                         r.appInfo.uid,
1324                         r.appInfo.packageName);
1325                 switch (mode) {
1326                     case AppOpsManager.MODE_ALLOWED:
1327                         break;
1328                     case AppOpsManager.MODE_IGNORED:
1329                         Slog.w(TAG, "Instant app " + r.appInfo.packageName
1330                                 + " does not have permission to create foreground services"
1331                                 + ", ignoring.");
1332                         return;
1333                     case AppOpsManager.MODE_ERRORED:
1334                         throw new SecurityException("Instant app " + r.appInfo.packageName
1335                                 + " does not have permission to create foreground services");
1336                     default:
1337                         mAm.enforcePermission(
1338                                 android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
1339                                 r.app.pid, r.appInfo.uid, "startForeground");
1340                 }
1341             } else {
1342                 if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
1343                     mAm.enforcePermission(
1344                             android.Manifest.permission.FOREGROUND_SERVICE,
1345                             r.app.pid, r.appInfo.uid, "startForeground");
1346                 }
1347 
1348                 int manifestType = r.serviceInfo.getForegroundServiceType();
1349                 // If passed in foreground service type is FOREGROUND_SERVICE_TYPE_MANIFEST,
1350                 // consider it is the same as manifest foreground service type.
1351                 if (foregroundServiceType == FOREGROUND_SERVICE_TYPE_MANIFEST) {
1352                     foregroundServiceType = manifestType;
1353                 }
1354                 // Check the passed in foreground service type flags is a subset of manifest
1355                 // foreground service type flags.
1356                 if ((foregroundServiceType & manifestType) != foregroundServiceType) {
1357                     throw new IllegalArgumentException("foregroundServiceType "
1358                         + String.format("0x%08X", foregroundServiceType)
1359                         + " is not a subset of foregroundServiceType attribute "
1360                         +  String.format("0x%08X", manifestType)
1361                         + " in service element of manifest file");
1362                 }
1363                 // If the foreground service is not started from TOP process, do not allow it to
1364                 // have while-in-use location/camera/microphone access.
1365                 if (!r.mAllowWhileInUsePermissionInFgs) {
1366                     Slog.w(TAG,
1367                             "Foreground service started from background can not have "
1368                                     + "location/camera/microphone access: service "
1369                                     + r.shortInstanceName);
1370                 }
1371             }
1372             boolean alreadyStartedOp = false;
1373             boolean stopProcStatsOp = false;
1374             if (r.fgRequired) {
1375                 if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) {
1376                     Slog.i(TAG, "Service called startForeground() as required: " + r);
1377                 }
1378                 r.fgRequired = false;
1379                 r.fgWaiting = false;
1380                 alreadyStartedOp = stopProcStatsOp = true;
1381                 mAm.mHandler.removeMessages(
1382                         ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
1383             }
1384 
1385             try {
1386                 boolean ignoreForeground = false;
1387                 final int mode = mAm.getAppOpsManager().checkOpNoThrow(
1388                         AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
1389                 switch (mode) {
1390                     case AppOpsManager.MODE_ALLOWED:
1391                     case AppOpsManager.MODE_DEFAULT:
1392                         // All okay.
1393                         break;
1394                     case AppOpsManager.MODE_IGNORED:
1395                         // Whoops, silently ignore this.
1396                         Slog.w(TAG, "Service.startForeground() not allowed due to app op: service "
1397                                 + r.shortInstanceName);
1398                         ignoreForeground = true;
1399                         break;
1400                     default:
1401                         throw new SecurityException("Foreground not allowed as per app op");
1402                 }
1403 
1404                 // Apps that are TOP or effectively similar may call startForeground() on
1405                 // their services even if they are restricted from doing that while in bg.
1406                 if (!ignoreForeground
1407                         && !appIsTopLocked(r.appInfo.uid)
1408                         && appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
1409                     Slog.w(TAG,
1410                             "Service.startForeground() not allowed due to bg restriction: service "
1411                             + r.shortInstanceName);
1412                     // Back off of any foreground expectations around this service, since we've
1413                     // just turned down its fg request.
1414                     updateServiceForegroundLocked(r.app, false);
1415                     ignoreForeground = true;
1416                 }
1417 
1418                 // Apps under strict background restrictions simply don't get to have foreground
1419                 // services, so now that we've enforced the startForegroundService() contract
1420                 // we only do the machinery of making the service foreground when the app
1421                 // is not restricted.
1422                 if (!ignoreForeground) {
1423                     if (r.foregroundId != id) {
1424                         cancelForegroundNotificationLocked(r);
1425                         r.foregroundId = id;
1426                     }
1427                     notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
1428                     r.foregroundNoti = notification;
1429                     r.foregroundServiceType = foregroundServiceType;
1430                     if (!r.isForeground) {
1431                         final ServiceMap smap = getServiceMapLocked(r.userId);
1432                         if (smap != null) {
1433                             ActiveForegroundApp active = smap.mActiveForegroundApps
1434                                     .get(r.packageName);
1435                             if (active == null) {
1436                                 active = new ActiveForegroundApp();
1437                                 active.mPackageName = r.packageName;
1438                                 active.mUid = r.appInfo.uid;
1439                                 active.mShownWhileScreenOn = mScreenOn;
1440                                 if (r.app != null && r.app.uidRecord != null) {
1441                                     active.mAppOnTop = active.mShownWhileTop =
1442                                             r.app.uidRecord.getCurProcState()
1443                                                     <= ActivityManager.PROCESS_STATE_TOP;
1444                                 }
1445                                 active.mStartTime = active.mStartVisibleTime
1446                                         = SystemClock.elapsedRealtime();
1447                                 smap.mActiveForegroundApps.put(r.packageName, active);
1448                                 requestUpdateActiveForegroundAppsLocked(smap, 0);
1449                             }
1450                             active.mNumActive++;
1451                         }
1452                         r.isForeground = true;
1453                         if (!stopProcStatsOp) {
1454                             ServiceState stracker = r.getTracker();
1455                             if (stracker != null) {
1456                                 stracker.setForeground(true,
1457                                         mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
1458                             }
1459                         } else {
1460                             stopProcStatsOp = false;
1461                         }
1462                         mAm.mAppOpsService.startOperation(
1463                                 AppOpsManager.getToken(mAm.mAppOpsService),
1464                                 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName,
1465                                 null, true, false, "", false);
1466                         FrameworkStatsLog.write(FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
1467                                 r.appInfo.uid, r.shortInstanceName,
1468                                 FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER,
1469                                 r.mAllowWhileInUsePermissionInFgs);
1470                         registerAppOpCallbackLocked(r);
1471                         mAm.updateForegroundServiceUsageStats(r.name, r.userId, true);
1472                     }
1473                     r.postNotification();
1474                     if (r.app != null) {
1475                         updateServiceForegroundLocked(r.app, true);
1476                     }
1477                     getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
1478                     mAm.notifyPackageUse(r.serviceInfo.packageName,
1479                             PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
1480                 } else {
1481                     if (DEBUG_FOREGROUND_SERVICE) {
1482                         Slog.d(TAG, "Suppressing startForeground() for FAS " + r);
1483                     }
1484                 }
1485             } finally {
1486                 if (stopProcStatsOp) {
1487                     // We got through to this point with it actively being started foreground,
1488                     // and never decided we wanted to keep it like that, so drop it.
1489                     ServiceState stracker = r.getTracker();
1490                     if (stracker != null) {
1491                         stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1492                                 r.lastActivity);
1493                     }
1494                 }
1495                 if (alreadyStartedOp) {
1496                     // If we had previously done a start op for direct foreground start,
1497                     // we have cleared the flag so can now drop it.
1498                     mAm.mAppOpsService.finishOperation(
1499                             AppOpsManager.getToken(mAm.mAppOpsService),
1500                             AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName,
1501                             null);
1502                 }
1503             }
1504         } else {
1505             if (r.isForeground) {
1506                 final ServiceMap smap = getServiceMapLocked(r.userId);
1507                 if (smap != null) {
1508                     decActiveForegroundAppLocked(smap, r);
1509                 }
1510                 r.isForeground = false;
1511                 ServiceState stracker = r.getTracker();
1512                 if (stracker != null) {
1513                     stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1514                             r.lastActivity);
1515                 }
1516                 mAm.mAppOpsService.finishOperation(
1517                         AppOpsManager.getToken(mAm.mAppOpsService),
1518                         AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, null);
1519                 unregisterAppOpCallbackLocked(r);
1520                 FrameworkStatsLog.write(FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
1521                         r.appInfo.uid, r.shortInstanceName,
1522                         FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT,
1523                         r.mAllowWhileInUsePermissionInFgs);
1524                 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
1525                 if (r.app != null) {
1526                     mAm.updateLruProcessLocked(r.app, false, null);
1527                     updateServiceForegroundLocked(r.app, true);
1528                 }
1529             }
1530             if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
1531                 cancelForegroundNotificationLocked(r);
1532                 r.foregroundId = 0;
1533                 r.foregroundNoti = null;
1534             } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1535                 r.stripForegroundServiceFlagFromNotification();
1536                 if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
1537                     r.foregroundId = 0;
1538                     r.foregroundNoti = null;
1539                 }
1540             }
1541         }
1542     }
1543 
1544     /** Registers an AppOpCallback for monitoring special AppOps for this foreground service. */
registerAppOpCallbackLocked(@onNull ServiceRecord r)1545     private void registerAppOpCallbackLocked(@NonNull ServiceRecord r) {
1546         if (r.app == null) {
1547             return;
1548         }
1549         final int uid = r.appInfo.uid;
1550         AppOpCallback callback = mFgsAppOpCallbacks.get(uid);
1551         if (callback == null) {
1552             callback = new AppOpCallback(r.app, mAm.getAppOpsManager());
1553             mFgsAppOpCallbacks.put(uid, callback);
1554         }
1555         callback.registerLocked();
1556     }
1557 
1558     /** Unregisters a foreground service's AppOpCallback. */
unregisterAppOpCallbackLocked(@onNull ServiceRecord r)1559     private void unregisterAppOpCallbackLocked(@NonNull ServiceRecord r) {
1560         final int uid = r.appInfo.uid;
1561         final AppOpCallback callback = mFgsAppOpCallbacks.get(uid);
1562         if (callback != null) {
1563             callback.unregisterLocked();
1564             if (callback.isObsoleteLocked()) {
1565                 mFgsAppOpCallbacks.remove(uid);
1566             }
1567         }
1568     }
1569 
1570     /**
1571      * For monitoring when {@link #LOGGED_AP_OPS} AppOps occur by an app while it is holding
1572      * at least one foreground service and is not also in the TOP state.
1573      * Once the uid no longer holds any foreground services, this callback becomes stale
1574      * (marked by {@link #isObsoleteLocked()}) and must no longer be used.
1575      *
1576      * Methods that end in Locked should only be called while the mAm lock is held.
1577      */
1578     private static final class AppOpCallback {
1579         /** AppOps that should be logged if they occur during a foreground service. */
1580         private static final int[] LOGGED_AP_OPS = new int[] {
1581                 AppOpsManager.OP_COARSE_LOCATION,
1582                 AppOpsManager.OP_FINE_LOCATION,
1583                 AppOpsManager.OP_RECORD_AUDIO,
1584                 AppOpsManager.OP_CAMERA
1585         };
1586 
1587         private final ProcessRecord mProcessRecord;
1588 
1589         /** Count of acceptances per appop (for LOGGED_AP_OPS) during this fgs session. */
1590         @GuardedBy("mCounterLock")
1591         private final SparseIntArray mAcceptedOps = new SparseIntArray();
1592         /** Count of rejections per appop (for LOGGED_AP_OPS) during this fgs session. */
1593         @GuardedBy("mCounterLock")
1594         private final SparseIntArray mRejectedOps = new SparseIntArray();
1595 
1596         /** Lock for the purposes of mAcceptedOps and mRejectedOps. */
1597         private final Object mCounterLock = new Object();
1598 
1599         /**
1600          * AppOp Mode (e.g. {@link AppOpsManager#MODE_ALLOWED} per op.
1601          * This currently cannot change without the process being killed, so they are constants.
1602          */
1603         private final SparseIntArray mAppOpModes = new SparseIntArray();
1604 
1605         /**
1606          * Number of foreground services currently associated with this AppOpCallback (i.e.
1607          * currently held for this uid).
1608          */
1609         @GuardedBy("mAm")
1610         private int mNumFgs = 0;
1611 
1612         /**
1613          * Indicates that this Object is stale and must not be used.
1614          * Specifically, when mNumFgs decreases down to 0, the callbacks will be unregistered and
1615          * this AppOpCallback is unusable.
1616          */
1617         @GuardedBy("mAm")
1618         private boolean mDestroyed = false;
1619 
1620         private final AppOpsManager mAppOpsManager;
1621 
AppOpCallback(@onNull ProcessRecord r, @NonNull AppOpsManager appOpsManager)1622         AppOpCallback(@NonNull ProcessRecord r, @NonNull AppOpsManager appOpsManager) {
1623             mProcessRecord = r;
1624             mAppOpsManager = appOpsManager;
1625             for (int op : LOGGED_AP_OPS) {
1626                 int mode = appOpsManager.unsafeCheckOpRawNoThrow(op, r.uid, r.info.packageName);
1627                 mAppOpModes.put(op, mode);
1628             }
1629         }
1630 
1631         private final AppOpsManager.OnOpNotedListener mOpNotedCallback =
1632                 new AppOpsManager.OnOpNotedListener() {
1633                     @Override
1634                     public void onOpNoted(int op, int uid, String pkgName, int result) {
1635                         incrementOpCountIfNeeded(op, uid, result);
1636                     }
1637         };
1638 
1639         private final AppOpsManager.OnOpStartedListener mOpStartedCallback =
1640                 new AppOpsManager.OnOpStartedListener() {
1641                     @Override
1642                     public void onOpStarted(int op, int uid, String pkgName, int result) {
1643                         incrementOpCountIfNeeded(op, uid, result);
1644                     }
1645         };
1646 
incrementOpCountIfNeeded(int op, int uid, @AppOpsManager.Mode int result)1647         private void incrementOpCountIfNeeded(int op, int uid, @AppOpsManager.Mode int result) {
1648             if (uid == mProcessRecord.uid && isNotTop()) {
1649                 incrementOpCount(op, result == AppOpsManager.MODE_ALLOWED);
1650             }
1651         }
1652 
isNotTop()1653         private boolean isNotTop() {
1654             return mProcessRecord.getCurProcState() != ActivityManager.PROCESS_STATE_TOP;
1655         }
1656 
incrementOpCount(int op, boolean allowed)1657         private void incrementOpCount(int op, boolean allowed) {
1658             synchronized (mCounterLock) {
1659                 final SparseIntArray counter = allowed ? mAcceptedOps : mRejectedOps;
1660                 final int index = counter.indexOfKey(op);
1661                 if (index < 0) {
1662                     counter.put(op, 1);
1663                 } else {
1664                     counter.setValueAt(index, counter.valueAt(index) + 1);
1665                 }
1666             }
1667         }
1668 
registerLocked()1669         void registerLocked() {
1670             if (isObsoleteLocked()) {
1671                 Slog.wtf(TAG, "Trying to register on a stale AppOpCallback.");
1672                 return;
1673             }
1674             mNumFgs++;
1675             if (mNumFgs == 1) {
1676                 mAppOpsManager.startWatchingNoted(LOGGED_AP_OPS, mOpNotedCallback);
1677                 mAppOpsManager.startWatchingStarted(LOGGED_AP_OPS, mOpStartedCallback);
1678             }
1679         }
1680 
unregisterLocked()1681         void unregisterLocked() {
1682             mNumFgs--;
1683             if (mNumFgs <= 0) {
1684                 mDestroyed = true;
1685                 logFinalValues();
1686                 mAppOpsManager.stopWatchingNoted(mOpNotedCallback);
1687                 mAppOpsManager.stopWatchingStarted(mOpStartedCallback);
1688             }
1689         }
1690 
1691         /**
1692          * Indicates that all foreground services for this uid are now over and the callback is
1693          * stale and must never be used again.
1694          */
isObsoleteLocked()1695         boolean isObsoleteLocked() {
1696             return mDestroyed;
1697         }
1698 
logFinalValues()1699         private void logFinalValues() {
1700             synchronized (mCounterLock) {
1701                 for (int op : LOGGED_AP_OPS) {
1702                     final int acceptances = mAcceptedOps.get(op);
1703                     final int rejections = mRejectedOps.get(op);
1704                     if (acceptances > 0 ||  rejections > 0) {
1705                         FrameworkStatsLog.write(
1706                                 FrameworkStatsLog.FOREGROUND_SERVICE_APP_OP_SESSION_ENDED,
1707                                 mProcessRecord.uid, op,
1708                                 modeToEnum(mAppOpModes.get(op)),
1709                                 acceptances, rejections
1710                         );
1711                     }
1712                 }
1713             }
1714         }
1715 
1716         /** Maps AppOp mode to atoms.proto enum. */
modeToEnum(int mode)1717         private static int modeToEnum(int mode) {
1718             switch (mode) {
1719                 case AppOpsManager.MODE_ALLOWED: return FrameworkStatsLog
1720                         .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_MODE__MODE_ALLOWED;
1721                 case AppOpsManager.MODE_IGNORED: return FrameworkStatsLog
1722                         .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_MODE__MODE_IGNORED;
1723                 case AppOpsManager.MODE_FOREGROUND: return FrameworkStatsLog
1724                         .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_MODE__MODE_FOREGROUND;
1725                 default: return FrameworkStatsLog
1726                         .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_MODE__MODE_UNKNOWN;
1727             }
1728         }
1729     }
1730 
cancelForegroundNotificationLocked(ServiceRecord r)1731     private void cancelForegroundNotificationLocked(ServiceRecord r) {
1732         if (r.foregroundId != 0) {
1733             // First check to see if this app has any other active foreground services
1734             // with the same notification ID.  If so, we shouldn't actually cancel it,
1735             // because that would wipe away the notification that still needs to be shown
1736             // due the other service.
1737             ServiceMap sm = getServiceMapLocked(r.userId);
1738             if (sm != null) {
1739                 for (int i = sm.mServicesByInstanceName.size() - 1; i >= 0; i--) {
1740                     ServiceRecord other = sm.mServicesByInstanceName.valueAt(i);
1741                     if (other != r && other.foregroundId == r.foregroundId
1742                             && other.packageName.equals(r.packageName)) {
1743                         // Found one!  Abort the cancel.
1744                         return;
1745                     }
1746                 }
1747             }
1748             r.cancelNotification();
1749         }
1750     }
1751 
updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj)1752     private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
1753         boolean anyForeground = false;
1754         int fgServiceTypes = 0;
1755         for (int i = proc.numberOfRunningServices() - 1; i >= 0; i--) {
1756             ServiceRecord sr = proc.getRunningServiceAt(i);
1757             if (sr.isForeground || sr.fgRequired) {
1758                 anyForeground = true;
1759                 fgServiceTypes |= sr.foregroundServiceType;
1760             }
1761         }
1762         mAm.updateProcessForegroundLocked(proc, anyForeground, fgServiceTypes, oomAdj);
1763     }
1764 
updateWhitelistManagerLocked(ProcessRecord proc)1765     private void updateWhitelistManagerLocked(ProcessRecord proc) {
1766         proc.whitelistManager = false;
1767         for (int i = proc.numberOfRunningServices() - 1; i >= 0; i--) {
1768             ServiceRecord sr = proc.getRunningServiceAt(i);
1769             if (sr.whitelistManager) {
1770                 proc.whitelistManager = true;
1771                 break;
1772             }
1773         }
1774     }
1775 
updateServiceConnectionActivitiesLocked(ProcessRecord clientProc)1776     public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
1777         ArraySet<ProcessRecord> updatedProcesses = null;
1778         for (int i = 0; i < clientProc.connections.size(); i++) {
1779             final ConnectionRecord conn = clientProc.connections.valueAt(i);
1780             final ProcessRecord proc = conn.binding.service.app;
1781             if (proc == null || proc == clientProc) {
1782                 continue;
1783             } else if (updatedProcesses == null) {
1784                 updatedProcesses = new ArraySet<>();
1785             } else if (updatedProcesses.contains(proc)) {
1786                 continue;
1787             }
1788             updatedProcesses.add(proc);
1789             updateServiceClientActivitiesLocked(proc, null, false);
1790         }
1791     }
1792 
updateServiceClientActivitiesLocked(ProcessRecord proc, ConnectionRecord modCr, boolean updateLru)1793     private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
1794             ConnectionRecord modCr, boolean updateLru) {
1795         if (modCr != null && modCr.binding.client != null) {
1796             if (!modCr.binding.client.hasActivities()) {
1797                 // This connection is from a client without activities, so adding
1798                 // and removing is not interesting.
1799                 return false;
1800             }
1801         }
1802 
1803         boolean anyClientActivities = false;
1804         for (int i = proc.numberOfRunningServices() - 1; i >= 0 && !anyClientActivities; i--) {
1805             ServiceRecord sr = proc.getRunningServiceAt(i);
1806             ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = sr.getConnections();
1807             for (int conni = connections.size() - 1; conni >= 0 && !anyClientActivities; conni--) {
1808                 ArrayList<ConnectionRecord> clist = connections.valueAt(conni);
1809                 for (int cri=clist.size()-1; cri>=0; cri--) {
1810                     ConnectionRecord cr = clist.get(cri);
1811                     if (cr.binding.client == null || cr.binding.client == proc) {
1812                         // Binding to ourself is not interesting.
1813                         continue;
1814                     }
1815                     if (cr.binding.client.hasActivities()) {
1816                         anyClientActivities = true;
1817                         break;
1818                     }
1819                 }
1820             }
1821         }
1822         if (anyClientActivities != proc.hasClientActivities()) {
1823             proc.setHasClientActivities(anyClientActivities);
1824             if (updateLru) {
1825                 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
1826             }
1827             return true;
1828         }
1829         return false;
1830     }
1831 
bindServiceLocked(IApplicationThread caller, IBinder token, Intent service, String resolvedType, final IServiceConnection connection, int flags, String instanceName, String callingPackage, final int userId)1832     int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
1833             String resolvedType, final IServiceConnection connection, int flags,
1834             String instanceName, String callingPackage, final int userId)
1835             throws TransactionTooLargeException {
1836         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
1837                 + " type=" + resolvedType + " conn=" + connection.asBinder()
1838                 + " flags=0x" + Integer.toHexString(flags));
1839         final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
1840         if (callerApp == null) {
1841             throw new SecurityException(
1842                     "Unable to find app for caller " + caller
1843                     + " (pid=" + Binder.getCallingPid()
1844                     + ") when binding service " + service);
1845         }
1846 
1847         ActivityServiceConnectionsHolder<ConnectionRecord> activity = null;
1848         if (token != null) {
1849             activity = mAm.mAtmInternal.getServiceConnectionsHolder(token);
1850             if (activity == null) {
1851                 Slog.w(TAG, "Binding with unknown activity: " + token);
1852                 return 0;
1853             }
1854         }
1855 
1856         int clientLabel = 0;
1857         PendingIntent clientIntent = null;
1858         final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
1859 
1860         if (isCallerSystem) {
1861             // Hacky kind of thing -- allow system stuff to tell us
1862             // what they are, so we can report this elsewhere for
1863             // others to know why certain services are running.
1864             service.setDefusable(true);
1865             clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
1866             if (clientIntent != null) {
1867                 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
1868                 if (clientLabel != 0) {
1869                     // There are no useful extras in the intent, trash them.
1870                     // System code calling with this stuff just needs to know
1871                     // this will happen.
1872                     service = service.cloneFilter();
1873                 }
1874             }
1875         }
1876 
1877         if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1878             mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
1879                     "BIND_TREAT_LIKE_ACTIVITY");
1880         }
1881 
1882         if ((flags & Context.BIND_SCHEDULE_LIKE_TOP_APP) != 0 && !isCallerSystem) {
1883             throw new SecurityException("Non-system caller (pid=" + Binder.getCallingPid()
1884                     + ") set BIND_SCHEDULE_LIKE_TOP_APP when binding service " + service);
1885         }
1886 
1887         if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
1888             throw new SecurityException(
1889                     "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1890                     + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
1891         }
1892 
1893         if ((flags & Context.BIND_ALLOW_INSTANT) != 0 && !isCallerSystem) {
1894             throw new SecurityException(
1895                     "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1896                             + ") set BIND_ALLOW_INSTANT when binding service " + service);
1897         }
1898 
1899         if ((flags & Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS) != 0) {
1900             mAm.enforceCallingPermission(
1901                     android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND,
1902                     "BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS");
1903         }
1904 
1905         final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
1906         final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
1907         final boolean allowInstant = (flags & Context.BIND_ALLOW_INSTANT) != 0;
1908 
1909         ServiceLookupResult res =
1910             retrieveServiceLocked(service, instanceName, resolvedType, callingPackage,
1911                     Binder.getCallingPid(), Binder.getCallingUid(), userId, true,
1912                     callerFg, isBindExternal, allowInstant);
1913         if (res == null) {
1914             return 0;
1915         }
1916         if (res.record == null) {
1917             return -1;
1918         }
1919         ServiceRecord s = res.record;
1920         boolean permissionsReviewRequired = false;
1921 
1922         // If permissions need a review before any of the app components can run,
1923         // we schedule binding to the service but do not start its process, then
1924         // we launch a review activity to which is passed a callback to invoke
1925         // when done to start the bound service's process to completing the binding.
1926         if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
1927                 s.packageName, s.userId)) {
1928 
1929             permissionsReviewRequired = true;
1930 
1931             // Show a permission review UI only for binding from a foreground app
1932             if (!callerFg) {
1933                 Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
1934                         + s.packageName + " requires a permissions review");
1935                 return 0;
1936             }
1937 
1938             final ServiceRecord serviceRecord = s;
1939             final Intent serviceIntent = service;
1940 
1941             RemoteCallback callback = new RemoteCallback(
1942                     new RemoteCallback.OnResultListener() {
1943                 @Override
1944                 public void onResult(Bundle result) {
1945                     synchronized(mAm) {
1946                         final long identity = Binder.clearCallingIdentity();
1947                         try {
1948                             if (!mPendingServices.contains(serviceRecord)) {
1949                                 return;
1950                             }
1951                             // If there is still a pending record, then the service
1952                             // binding request is still valid, so hook them up. We
1953                             // proceed only if the caller cleared the review requirement
1954                             // otherwise we unbind because the user didn't approve.
1955                             if (!mAm.getPackageManagerInternalLocked()
1956                                     .isPermissionsReviewRequired(
1957                                             serviceRecord.packageName,
1958                                             serviceRecord.userId)) {
1959                                 try {
1960                                     bringUpServiceLocked(serviceRecord,
1961                                             serviceIntent.getFlags(),
1962                                             callerFg, false, false);
1963                                 } catch (RemoteException e) {
1964                                     /* ignore - local call */
1965                                 }
1966                             } else {
1967                                 unbindServiceLocked(connection);
1968                             }
1969                         } finally {
1970                             Binder.restoreCallingIdentity(identity);
1971                         }
1972                     }
1973                 }
1974             });
1975 
1976             final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
1977             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1978                     | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
1979                     | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1980             intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
1981             intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
1982 
1983             if (DEBUG_PERMISSIONS_REVIEW) {
1984                 Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
1985                         + s.packageName);
1986             }
1987 
1988             mAm.mHandler.post(new Runnable() {
1989                 @Override
1990                 public void run() {
1991                     mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
1992                 }
1993             });
1994         }
1995 
1996         final long origId = Binder.clearCallingIdentity();
1997 
1998         try {
1999             if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
2000                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
2001                         + s);
2002             }
2003 
2004             if ((flags&Context.BIND_AUTO_CREATE) != 0) {
2005                 s.lastActivity = SystemClock.uptimeMillis();
2006                 if (!s.hasAutoCreateConnections()) {
2007                     // This is the first binding, let the tracker know.
2008                     ServiceState stracker = s.getTracker();
2009                     if (stracker != null) {
2010                         stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
2011                                 s.lastActivity);
2012                     }
2013                 }
2014             }
2015 
2016             if ((flags & Context.BIND_RESTRICT_ASSOCIATIONS) != 0) {
2017                 mAm.requireAllowedAssociationsLocked(s.appInfo.packageName);
2018             }
2019 
2020             mAm.startAssociationLocked(callerApp.uid, callerApp.processName,
2021                     callerApp.getCurProcState(), s.appInfo.uid, s.appInfo.longVersionCode,
2022                     s.instanceName, s.processName);
2023             // Once the apps have become associated, if one of them is caller is ephemeral
2024             // the target app should now be able to see the calling app
2025             mAm.grantImplicitAccess(callerApp.userId, service,
2026                     callerApp.uid, UserHandle.getAppId(s.appInfo.uid));
2027 
2028             AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
2029             ConnectionRecord c = new ConnectionRecord(b, activity,
2030                     connection, flags, clientLabel, clientIntent,
2031                     callerApp.uid, callerApp.processName, callingPackage);
2032 
2033             IBinder binder = connection.asBinder();
2034             s.addConnection(binder, c);
2035             b.connections.add(c);
2036             if (activity != null) {
2037                 activity.addConnection(c);
2038             }
2039             b.client.connections.add(c);
2040             c.startAssociationIfNeeded();
2041             if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
2042                 b.client.hasAboveClient = true;
2043             }
2044             if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
2045                 s.whitelistManager = true;
2046             }
2047             if ((flags & Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS) != 0) {
2048                 s.setHasBindingWhitelistingBgActivityStarts(true);
2049             }
2050             if (s.app != null) {
2051                 updateServiceClientActivitiesLocked(s.app, c, true);
2052             }
2053             ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
2054             if (clist == null) {
2055                 clist = new ArrayList<>();
2056                 mServiceConnections.put(binder, clist);
2057             }
2058             clist.add(c);
2059 
2060             if ((flags&Context.BIND_AUTO_CREATE) != 0) {
2061                 s.lastActivity = SystemClock.uptimeMillis();
2062                 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
2063                         permissionsReviewRequired) != null) {
2064                     return 0;
2065                 }
2066             }
2067 
2068             if (!s.mAllowWhileInUsePermissionInFgs) {
2069                 s.mAllowWhileInUsePermissionInFgs =
2070                         shouldAllowWhileInUsePermissionInFgsLocked(callingPackage,
2071                                 Binder.getCallingPid(), Binder.getCallingUid(),
2072                                 service, s, false);
2073             }
2074 
2075             if (s.app != null) {
2076                 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
2077                     s.app.treatLikeActivity = true;
2078                 }
2079                 if (s.whitelistManager) {
2080                     s.app.whitelistManager = true;
2081                 }
2082                 // This could have made the service more important.
2083                 mAm.updateLruProcessLocked(s.app,
2084                         (callerApp.hasActivitiesOrRecentTasks() && s.app.hasClientActivities())
2085                                 || (callerApp.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP
2086                                         && (flags & Context.BIND_TREAT_LIKE_ACTIVITY) != 0),
2087                         b.client);
2088                 mAm.updateOomAdjLocked(s.app, OomAdjuster.OOM_ADJ_REASON_BIND_SERVICE);
2089             }
2090 
2091             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
2092                     + ": received=" + b.intent.received
2093                     + " apps=" + b.intent.apps.size()
2094                     + " doRebind=" + b.intent.doRebind);
2095 
2096             if (s.app != null && b.intent.received) {
2097                 // Service is already running, so we can immediately
2098                 // publish the connection.
2099                 try {
2100                     c.conn.connected(s.name, b.intent.binder, false);
2101                 } catch (Exception e) {
2102                     Slog.w(TAG, "Failure sending service " + s.shortInstanceName
2103                             + " to connection " + c.conn.asBinder()
2104                             + " (in " + c.binding.client.processName + ")", e);
2105                 }
2106 
2107                 // If this is the first app connected back to this binding,
2108                 // and the service had previously asked to be told when
2109                 // rebound, then do so.
2110                 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
2111                     requestServiceBindingLocked(s, b.intent, callerFg, true);
2112                 }
2113             } else if (!b.intent.requested) {
2114                 requestServiceBindingLocked(s, b.intent, callerFg, false);
2115             }
2116 
2117             maybeLogBindCrossProfileService(userId, callingPackage, callerApp.info.uid);
2118 
2119             getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
2120 
2121         } finally {
2122             Binder.restoreCallingIdentity(origId);
2123         }
2124 
2125         return 1;
2126     }
2127 
maybeLogBindCrossProfileService( int userId, String callingPackage, int callingUid)2128     private void maybeLogBindCrossProfileService(
2129             int userId, String callingPackage, int callingUid) {
2130         if (UserHandle.isCore(callingUid)) {
2131             return;
2132         }
2133         final int callingUserId = UserHandle.getCallingUserId();
2134         if (callingUserId == userId
2135                 || !mAm.mUserController.isSameProfileGroup(callingUserId, userId)) {
2136             return;
2137         }
2138         DevicePolicyEventLogger.createEvent(DevicePolicyEnums.BIND_CROSS_PROFILE_SERVICE)
2139                 .setStrings(callingPackage)
2140                 .write();
2141     }
2142 
publishServiceLocked(ServiceRecord r, Intent intent, IBinder service)2143     void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
2144         final long origId = Binder.clearCallingIdentity();
2145         try {
2146             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
2147                     + " " + intent + ": " + service);
2148             if (r != null) {
2149                 Intent.FilterComparison filter
2150                         = new Intent.FilterComparison(intent);
2151                 IntentBindRecord b = r.bindings.get(filter);
2152                 if (b != null && !b.received) {
2153                     b.binder = service;
2154                     b.requested = true;
2155                     b.received = true;
2156                     ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
2157                     for (int conni = connections.size() - 1; conni >= 0; conni--) {
2158                         ArrayList<ConnectionRecord> clist = connections.valueAt(conni);
2159                         for (int i=0; i<clist.size(); i++) {
2160                             ConnectionRecord c = clist.get(i);
2161                             if (!filter.equals(c.binding.intent.intent)) {
2162                                 if (DEBUG_SERVICE) Slog.v(
2163                                         TAG_SERVICE, "Not publishing to: " + c);
2164                                 if (DEBUG_SERVICE) Slog.v(
2165                                         TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
2166                                 if (DEBUG_SERVICE) Slog.v(
2167                                         TAG_SERVICE, "Published intent: " + intent);
2168                                 continue;
2169                             }
2170                             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
2171                             try {
2172                                 c.conn.connected(r.name, service, false);
2173                             } catch (Exception e) {
2174                                 Slog.w(TAG, "Failure sending service " + r.shortInstanceName
2175                                       + " to connection " + c.conn.asBinder()
2176                                       + " (in " + c.binding.client.processName + ")", e);
2177                             }
2178                         }
2179                     }
2180                 }
2181 
2182                 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
2183             }
2184         } finally {
2185             Binder.restoreCallingIdentity(origId);
2186         }
2187     }
2188 
updateServiceGroupLocked(IServiceConnection connection, int group, int importance)2189     void updateServiceGroupLocked(IServiceConnection connection, int group, int importance) {
2190         final IBinder binder = connection.asBinder();
2191         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "updateServiceGroup: conn=" + binder);
2192         final ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
2193         if (clist == null) {
2194             throw new IllegalArgumentException("Could not find connection for "
2195                     + connection.asBinder());
2196         }
2197         for (int i = clist.size() - 1; i >= 0; i--) {
2198             final ConnectionRecord crec = clist.get(i);
2199             final ServiceRecord srec = crec.binding.service;
2200             if (srec != null && (srec.serviceInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) != 0) {
2201                 if (srec.app != null) {
2202                     if (group > 0) {
2203                         srec.app.connectionService = srec;
2204                         srec.app.connectionGroup = group;
2205                         srec.app.connectionImportance = importance;
2206                     } else {
2207                         srec.app.connectionService = null;
2208                         srec.app.connectionGroup = 0;
2209                         srec.app.connectionImportance = 0;
2210                     }
2211                 } else {
2212                     if (group > 0) {
2213                         srec.pendingConnectionGroup = group;
2214                         srec.pendingConnectionImportance = importance;
2215                     } else {
2216                         srec.pendingConnectionGroup = 0;
2217                         srec.pendingConnectionImportance = 0;
2218                     }
2219                 }
2220             }
2221         }
2222     }
2223 
unbindServiceLocked(IServiceConnection connection)2224     boolean unbindServiceLocked(IServiceConnection connection) {
2225         IBinder binder = connection.asBinder();
2226         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
2227         ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
2228         if (clist == null) {
2229             Slog.w(TAG, "Unbind failed: could not find connection for "
2230                   + connection.asBinder());
2231             return false;
2232         }
2233 
2234         final long origId = Binder.clearCallingIdentity();
2235         try {
2236             while (clist.size() > 0) {
2237                 ConnectionRecord r = clist.get(0);
2238                 removeConnectionLocked(r, null, null);
2239                 if (clist.size() > 0 && clist.get(0) == r) {
2240                     // In case it didn't get removed above, do it now.
2241                     Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
2242                     clist.remove(0);
2243                 }
2244 
2245                 if (r.binding.service.app != null) {
2246                     if (r.binding.service.app.whitelistManager) {
2247                         updateWhitelistManagerLocked(r.binding.service.app);
2248                     }
2249                     // This could have made the service less important.
2250                     if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
2251                         r.binding.service.app.treatLikeActivity = true;
2252                         mAm.updateLruProcessLocked(r.binding.service.app,
2253                                 r.binding.service.app.hasClientActivities()
2254                                 || r.binding.service.app.treatLikeActivity, null);
2255                     }
2256                 }
2257             }
2258 
2259             mAm.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
2260 
2261         } finally {
2262             Binder.restoreCallingIdentity(origId);
2263         }
2264 
2265         return true;
2266     }
2267 
unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind)2268     void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
2269         final long origId = Binder.clearCallingIdentity();
2270         try {
2271             if (r != null) {
2272                 Intent.FilterComparison filter
2273                         = new Intent.FilterComparison(intent);
2274                 IntentBindRecord b = r.bindings.get(filter);
2275                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
2276                         + " at " + b + ": apps="
2277                         + (b != null ? b.apps.size() : 0));
2278 
2279                 boolean inDestroying = mDestroyingServices.contains(r);
2280                 if (b != null) {
2281                     if (b.apps.size() > 0 && !inDestroying) {
2282                         // Applications have already bound since the last
2283                         // unbind, so just rebind right here.
2284                         boolean inFg = false;
2285                         for (int i=b.apps.size()-1; i>=0; i--) {
2286                             ProcessRecord client = b.apps.valueAt(i).client;
2287                             if (client != null && client.setSchedGroup
2288                                     != ProcessList.SCHED_GROUP_BACKGROUND) {
2289                                 inFg = true;
2290                                 break;
2291                             }
2292                         }
2293                         try {
2294                             requestServiceBindingLocked(r, b, inFg, true);
2295                         } catch (TransactionTooLargeException e) {
2296                             // Don't pass this back to ActivityThread, it's unrelated.
2297                         }
2298                     } else {
2299                         // Note to tell the service the next time there is
2300                         // a new client.
2301                         b.doRebind = true;
2302                     }
2303                 }
2304 
2305                 serviceDoneExecutingLocked(r, inDestroying, false);
2306             }
2307         } finally {
2308             Binder.restoreCallingIdentity(origId);
2309         }
2310     }
2311 
findServiceLocked(ComponentName name, IBinder token, int userId)2312     private final ServiceRecord findServiceLocked(ComponentName name,
2313             IBinder token, int userId) {
2314         ServiceRecord r = getServiceByNameLocked(name, userId);
2315         return r == token ? r : null;
2316     }
2317 
2318     private final class ServiceLookupResult {
2319         final ServiceRecord record;
2320         final String permission;
2321 
ServiceLookupResult(ServiceRecord _record, String _permission)2322         ServiceLookupResult(ServiceRecord _record, String _permission) {
2323             record = _record;
2324             permission = _permission;
2325         }
2326     }
2327 
2328     private class ServiceRestarter implements Runnable {
2329         private ServiceRecord mService;
2330 
setService(ServiceRecord service)2331         void setService(ServiceRecord service) {
2332             mService = service;
2333         }
2334 
run()2335         public void run() {
2336             synchronized(mAm) {
2337                 performServiceRestartLocked(mService);
2338             }
2339         }
2340     }
2341 
retrieveServiceLocked(Intent service, String instanceName, String resolvedType, String callingPackage, int callingPid, int callingUid, int userId, boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal, boolean allowInstant)2342     private ServiceLookupResult retrieveServiceLocked(Intent service,
2343             String instanceName, String resolvedType, String callingPackage,
2344             int callingPid, int callingUid, int userId,
2345             boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
2346             boolean allowInstant) {
2347         ServiceRecord r = null;
2348         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
2349                 + " type=" + resolvedType + " callingUid=" + callingUid);
2350 
2351         userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId,
2352                 /* allowAll= */false, getAllowMode(service, callingPackage),
2353                 /* name= */ "service", callingPackage);
2354 
2355         ServiceMap smap = getServiceMapLocked(userId);
2356         final ComponentName comp;
2357         if (instanceName == null) {
2358             comp = service.getComponent();
2359         } else {
2360             final ComponentName realComp = service.getComponent();
2361             if (realComp == null) {
2362                 throw new IllegalArgumentException("Can't use custom instance name '" + instanceName
2363                         + "' without expicit component in Intent");
2364             }
2365             comp = new ComponentName(realComp.getPackageName(),
2366                     realComp.getClassName() + ":" + instanceName);
2367         }
2368         if (comp != null) {
2369             r = smap.mServicesByInstanceName.get(comp);
2370             if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r);
2371         }
2372         if (r == null && !isBindExternal && instanceName == null) {
2373             Intent.FilterComparison filter = new Intent.FilterComparison(service);
2374             r = smap.mServicesByIntent.get(filter);
2375             if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r);
2376         }
2377         if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
2378                 && !callingPackage.equals(r.packageName)) {
2379             // If an external service is running within its own package, other packages
2380             // should not bind to that instance.
2381             r = null;
2382             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Whoops, can't use existing external service");
2383         }
2384         if (r == null) {
2385             try {
2386                 int flags = ActivityManagerService.STOCK_PM_FLAGS
2387                         | PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
2388                 if (allowInstant) {
2389                     flags |= PackageManager.MATCH_INSTANT;
2390                 }
2391                 // TODO: come back and remove this assumption to triage all services
2392                 ResolveInfo rInfo = mAm.getPackageManagerInternalLocked().resolveService(service,
2393                         resolvedType, flags, userId, callingUid);
2394                 ServiceInfo sInfo = rInfo != null ? rInfo.serviceInfo : null;
2395                 if (sInfo == null) {
2396                     Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
2397                           ": not found");
2398                     return null;
2399                 }
2400                 if (instanceName != null
2401                         && (sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
2402                     throw new IllegalArgumentException("Can't use instance name '" + instanceName
2403                             + "' with non-isolated service '" + sInfo.name + "'");
2404                 }
2405                 ComponentName className = new ComponentName(
2406                         sInfo.applicationInfo.packageName, sInfo.name);
2407                 ComponentName name = comp != null ? comp : className;
2408                 if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid,
2409                         name.getPackageName(), sInfo.applicationInfo.uid)) {
2410                     String msg = "association not allowed between packages "
2411                             + callingPackage + " and " + name.getPackageName();
2412                     Slog.w(TAG, "Service lookup failed: " + msg);
2413                     return new ServiceLookupResult(null, msg);
2414                 }
2415 
2416                 // Store the defining packageName and uid, as they might be changed in
2417                 // the ApplicationInfo for external services (which run with the package name
2418                 // and uid of the caller).
2419                 String definingPackageName = sInfo.applicationInfo.packageName;
2420                 int definingUid = sInfo.applicationInfo.uid;
2421                 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
2422                     if (isBindExternal) {
2423                         if (!sInfo.exported) {
2424                             throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
2425                                     + className + " is not exported");
2426                         }
2427                         if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
2428                             throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
2429                                     + className + " is not an isolatedProcess");
2430                         }
2431                         // Run the service under the calling package's application.
2432                         ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
2433                                 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
2434                         if (aInfo == null) {
2435                             throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
2436                                     "could not resolve client package " + callingPackage);
2437                         }
2438                         sInfo = new ServiceInfo(sInfo);
2439                         sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
2440                         sInfo.applicationInfo.packageName = aInfo.packageName;
2441                         sInfo.applicationInfo.uid = aInfo.uid;
2442                         name = new ComponentName(aInfo.packageName, name.getClassName());
2443                         className = new ComponentName(aInfo.packageName,
2444                                 instanceName == null ? className.getClassName()
2445                                         : (className.getClassName() + ":" + instanceName));
2446                         service.setComponent(name);
2447                     } else {
2448                         throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
2449                                 name);
2450                     }
2451                 } else if (isBindExternal) {
2452                     throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
2453                             " is not an externalService");
2454                 }
2455                 if (userId > 0) {
2456                     if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
2457                             sInfo.name, sInfo.flags)
2458                             && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
2459                         userId = 0;
2460                         smap = getServiceMapLocked(0);
2461                         // Bypass INTERACT_ACROSS_USERS permission check
2462                         final long token = Binder.clearCallingIdentity();
2463                         try {
2464                             ResolveInfo rInfoForUserId0 =
2465                                     mAm.getPackageManagerInternalLocked().resolveService(service,
2466                                             resolvedType, flags, userId, callingUid);
2467                             if (rInfoForUserId0 == null) {
2468                                 Slog.w(TAG_SERVICE,
2469                                         "Unable to resolve service " + service + " U=" + userId
2470                                                 + ": not found");
2471                                 return null;
2472                             }
2473                             sInfo = rInfoForUserId0.serviceInfo;
2474                         } finally {
2475                             Binder.restoreCallingIdentity(token);
2476                         }
2477                     }
2478                     sInfo = new ServiceInfo(sInfo);
2479                     sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
2480                 }
2481                 r = smap.mServicesByInstanceName.get(name);
2482                 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE,
2483                         "Retrieved via pm by intent: " + r);
2484                 if (r == null && createIfNeeded) {
2485                     final Intent.FilterComparison filter
2486                             = new Intent.FilterComparison(service.cloneFilter());
2487                     final ServiceRestarter res = new ServiceRestarter();
2488                     final BatteryStatsImpl.Uid.Pkg.Serv ss;
2489                     final BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
2490                     synchronized (stats) {
2491                         ss = stats.getServiceStatsLocked(
2492                                 sInfo.applicationInfo.uid, name.getPackageName(),
2493                                 name.getClassName());
2494                     }
2495                     r = new ServiceRecord(mAm, ss, className, name, definingPackageName,
2496                             definingUid, filter, sInfo, callingFromFg, res);
2497                     r.mRecentCallingPackage = callingPackage;
2498                     res.setService(r);
2499                     smap.mServicesByInstanceName.put(name, r);
2500                     smap.mServicesByIntent.put(filter, r);
2501 
2502                     // Make sure this component isn't in the pending list.
2503                     for (int i=mPendingServices.size()-1; i>=0; i--) {
2504                         final ServiceRecord pr = mPendingServices.get(i);
2505                         if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
2506                                 && pr.instanceName.equals(name)) {
2507                             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr);
2508                             mPendingServices.remove(i);
2509                         }
2510                     }
2511                     if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
2512                 }
2513             } catch (RemoteException ex) {
2514                 // pm is in same process, this will never happen.
2515             }
2516         }
2517         if (r != null) {
2518             if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid, r.packageName,
2519                     r.appInfo.uid)) {
2520                 String msg = "association not allowed between packages "
2521                         + callingPackage + " and " + r.packageName;
2522                 Slog.w(TAG, "Service lookup failed: " + msg);
2523                 return new ServiceLookupResult(null, msg);
2524             }
2525             if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
2526                     resolvedType, r.appInfo)) {
2527                 return new ServiceLookupResult(null, "blocked by firewall");
2528             }
2529             if (mAm.checkComponentPermission(r.permission,
2530                     callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) {
2531                 if (!r.exported) {
2532                     Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
2533                             + " from pid=" + callingPid
2534                             + ", uid=" + callingUid
2535                             + " that is not exported from uid " + r.appInfo.uid);
2536                     return new ServiceLookupResult(null, "not exported from uid "
2537                             + r.appInfo.uid);
2538                 }
2539                 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
2540                         + " from pid=" + callingPid
2541                         + ", uid=" + callingUid
2542                         + " requires " + r.permission);
2543                 return new ServiceLookupResult(null, r.permission);
2544             } else if (r.permission != null && callingPackage != null) {
2545                 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
2546                 if (opCode != AppOpsManager.OP_NONE && mAm.getAppOpsManager().checkOpNoThrow(
2547                         opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
2548                     Slog.w(TAG, "Appop Denial: Accessing service " + r.shortInstanceName
2549                             + " from pid=" + callingPid
2550                             + ", uid=" + callingUid
2551                             + " requires appop " + AppOpsManager.opToName(opCode));
2552                     return null;
2553                 }
2554             }
2555             return new ServiceLookupResult(r, null);
2556         }
2557         return null;
2558     }
2559 
getAllowMode(Intent service, @Nullable String callingPackage)2560     private int getAllowMode(Intent service, @Nullable String callingPackage) {
2561         if (callingPackage == null || service.getComponent() == null) {
2562             return ActivityManagerInternal.ALLOW_NON_FULL_IN_PROFILE;
2563         }
2564         if (callingPackage.equals(service.getComponent().getPackageName())) {
2565             return ActivityManagerInternal.ALLOW_ALL_PROFILE_PERMISSIONS_IN_PROFILE;
2566         } else {
2567             return ActivityManagerInternal.ALLOW_NON_FULL_IN_PROFILE;
2568         }
2569     }
2570 
bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why)2571     private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
2572         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
2573                 + why + " of " + r + " in app " + r.app);
2574         else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
2575                 + why + " of " + r.shortInstanceName);
2576 
2577         // For b/34123235: Services within the system server won't start until SystemServer
2578         // does Looper.loop(), so we shouldn't try to start/bind to them too early in the boot
2579         // process. However, since there's a little point of showing the ANR dialog in that case,
2580         // let's suppress the timeout until PHASE_THIRD_PARTY_APPS_CAN_START.
2581         //
2582         // (Note there are multiple services start at PHASE_THIRD_PARTY_APPS_CAN_START too,
2583         // which technically could also trigger this timeout if there's a system server
2584         // that takes a long time to handle PHASE_THIRD_PARTY_APPS_CAN_START, but that shouldn't
2585         // happen.)
2586         boolean timeoutNeeded = true;
2587         if ((mAm.mBootPhase < SystemService.PHASE_THIRD_PARTY_APPS_CAN_START)
2588                 && (r.app != null) && (r.app.pid == android.os.Process.myPid())) {
2589 
2590             Slog.w(TAG, "Too early to start/bind service in system_server: Phase=" + mAm.mBootPhase
2591                     + " " + r.getComponentName());
2592             timeoutNeeded = false;
2593         }
2594 
2595         long now = SystemClock.uptimeMillis();
2596         if (r.executeNesting == 0) {
2597             r.executeFg = fg;
2598             ServiceState stracker = r.getTracker();
2599             if (stracker != null) {
2600                 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
2601             }
2602             if (r.app != null) {
2603                 r.app.executingServices.add(r);
2604                 r.app.execServicesFg |= fg;
2605                 if (timeoutNeeded && r.app.executingServices.size() == 1) {
2606                     scheduleServiceTimeoutLocked(r.app);
2607                 }
2608             }
2609         } else if (r.app != null && fg && !r.app.execServicesFg) {
2610             r.app.execServicesFg = true;
2611             if (timeoutNeeded) {
2612                 scheduleServiceTimeoutLocked(r.app);
2613             }
2614         }
2615         r.executeFg |= fg;
2616         r.executeNesting++;
2617         r.executingStart = now;
2618     }
2619 
requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i, boolean execInFg, boolean rebind)2620     private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
2621             boolean execInFg, boolean rebind) throws TransactionTooLargeException {
2622         if (r.app == null || r.app.thread == null) {
2623             // If service is not currently running, can't yet bind.
2624             return false;
2625         }
2626         if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
2627                 + " rebind=" + rebind);
2628         if ((!i.requested || rebind) && i.apps.size() > 0) {
2629             try {
2630                 bumpServiceExecutingLocked(r, execInFg, "bind");
2631                 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
2632                 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
2633                         r.app.getReportedProcState());
2634                 if (!rebind) {
2635                     i.requested = true;
2636                 }
2637                 i.hasBound = true;
2638                 i.doRebind = false;
2639             } catch (TransactionTooLargeException e) {
2640                 // Keep the executeNesting count accurate.
2641                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
2642                 final boolean inDestroying = mDestroyingServices.contains(r);
2643                 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2644                 throw e;
2645             } catch (RemoteException e) {
2646                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
2647                 // Keep the executeNesting count accurate.
2648                 final boolean inDestroying = mDestroyingServices.contains(r);
2649                 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2650                 return false;
2651             }
2652         }
2653         return true;
2654     }
2655 
2656     /** @return {@code true} if the restart is scheduled. */
scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel)2657     private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) {
2658         if (mAm.mAtmInternal.isShuttingDown()) {
2659             Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortInstanceName
2660                     + " - system is shutting down");
2661             return false;
2662         }
2663 
2664         ServiceMap smap = getServiceMapLocked(r.userId);
2665         if (smap.mServicesByInstanceName.get(r.instanceName) != r) {
2666             ServiceRecord cur = smap.mServicesByInstanceName.get(r.instanceName);
2667             Slog.wtf(TAG, "Attempting to schedule restart of " + r
2668                     + " when found in map: " + cur);
2669             return false;
2670         }
2671 
2672         final long now = SystemClock.uptimeMillis();
2673 
2674         final String reason;
2675         if ((r.serviceInfo.applicationInfo.flags
2676                 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
2677             long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION;
2678             long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION;
2679             boolean canceled = false;
2680 
2681             // Any delivered but not yet finished starts should be put back
2682             // on the pending list.
2683             final int N = r.deliveredStarts.size();
2684             if (N > 0) {
2685                 for (int i=N-1; i>=0; i--) {
2686                     ServiceRecord.StartItem si = r.deliveredStarts.get(i);
2687                     si.removeUriPermissionsLocked();
2688                     if (si.intent == null) {
2689                         // We'll generate this again if needed.
2690                     } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
2691                             && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
2692                         r.pendingStarts.add(0, si);
2693                         long dur = SystemClock.uptimeMillis() - si.deliveredTime;
2694                         dur *= 2;
2695                         if (minDuration < dur) minDuration = dur;
2696                         if (resetTime < dur) resetTime = dur;
2697                     } else {
2698                         Slog.w(TAG, "Canceling start item " + si.intent + " in service "
2699                                 + r.shortInstanceName);
2700                         canceled = true;
2701                     }
2702                 }
2703                 r.deliveredStarts.clear();
2704             }
2705 
2706             if (allowCancel) {
2707                 final boolean shouldStop = r.canStopIfKilled(canceled);
2708                 if (shouldStop && !r.hasAutoCreateConnections()) {
2709                     // Nothing to restart.
2710                     return false;
2711                 }
2712                 reason = (r.startRequested && !shouldStop) ? "start-requested" : "connection";
2713             } else {
2714                 reason = "always";
2715             }
2716 
2717             r.totalRestartCount++;
2718             if (r.restartDelay == 0) {
2719                 r.restartCount++;
2720                 r.restartDelay = minDuration;
2721             } else if (r.crashCount > 1) {
2722                 r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
2723                         * (r.crashCount - 1);
2724             } else {
2725                 // If it has been a "reasonably long time" since the service
2726                 // was started, then reset our restart duration back to
2727                 // the beginning, so we don't infinitely increase the duration
2728                 // on a service that just occasionally gets killed (which is
2729                 // a normal case, due to process being killed to reclaim memory).
2730                 if (now > (r.restartTime+resetTime)) {
2731                     r.restartCount = 1;
2732                     r.restartDelay = minDuration;
2733                 } else {
2734                     r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
2735                     if (r.restartDelay < minDuration) {
2736                         r.restartDelay = minDuration;
2737                     }
2738                 }
2739             }
2740 
2741             r.nextRestartTime = now + r.restartDelay;
2742 
2743             // Make sure that we don't end up restarting a bunch of services
2744             // all at the same time.
2745             boolean repeat;
2746             do {
2747                 repeat = false;
2748                 final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
2749                 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2750                     ServiceRecord r2 = mRestartingServices.get(i);
2751                     if (r2 != r && r.nextRestartTime >= (r2.nextRestartTime-restartTimeBetween)
2752                             && r.nextRestartTime < (r2.nextRestartTime+restartTimeBetween)) {
2753                         r.nextRestartTime = r2.nextRestartTime + restartTimeBetween;
2754                         r.restartDelay = r.nextRestartTime - now;
2755                         repeat = true;
2756                         break;
2757                     }
2758                 }
2759             } while (repeat);
2760 
2761         } else {
2762             // Persistent processes are immediately restarted, so there is no
2763             // reason to hold of on restarting their services.
2764             r.totalRestartCount++;
2765             r.restartCount = 0;
2766             r.restartDelay = 0;
2767             r.nextRestartTime = now;
2768             reason = "persistent";
2769         }
2770 
2771         if (!mRestartingServices.contains(r)) {
2772             r.createdFromFg = false;
2773             mRestartingServices.add(r);
2774             r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
2775         }
2776 
2777         cancelForegroundNotificationLocked(r);
2778 
2779         mAm.mHandler.removeCallbacks(r.restarter);
2780         mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
2781         r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
2782         Slog.w(TAG, "Scheduling restart of crashed service "
2783                 + r.shortInstanceName + " in " + r.restartDelay + "ms for " + reason);
2784         EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
2785                 r.userId, r.shortInstanceName, r.restartDelay);
2786 
2787         return true;
2788     }
2789 
performServiceRestartLocked(ServiceRecord r)2790     final void performServiceRestartLocked(ServiceRecord r) {
2791         if (!mRestartingServices.contains(r)) {
2792             return;
2793         }
2794         if (!isServiceNeededLocked(r, false, false)) {
2795             // Paranoia: is this service actually needed?  In theory a service that is not
2796             // needed should never remain on the restart list.  In practice...  well, there
2797             // have been bugs where this happens, and bad things happen because the process
2798             // ends up just being cached, so quickly killed, then restarted again and again.
2799             // Let's not let that happen.
2800             Slog.wtf(TAG, "Restarting service that is not needed: " + r);
2801             return;
2802         }
2803         try {
2804             bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
2805         } catch (TransactionTooLargeException e) {
2806             // Ignore, it's been logged and nothing upstack cares.
2807         }
2808     }
2809 
unscheduleServiceRestartLocked(ServiceRecord r, int callingUid, boolean force)2810     private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
2811             boolean force) {
2812         if (!force && r.restartDelay == 0) {
2813             return false;
2814         }
2815         // Remove from the restarting list; if the service is currently on the
2816         // restarting list, or the call is coming from another app, then this
2817         // service has become of much more interest so we reset the restart interval.
2818         boolean removed = mRestartingServices.remove(r);
2819         if (removed || callingUid != r.appInfo.uid) {
2820             r.resetRestartCounter();
2821         }
2822         if (removed) {
2823             clearRestartingIfNeededLocked(r);
2824         }
2825         mAm.mHandler.removeCallbacks(r.restarter);
2826         return true;
2827     }
2828 
clearRestartingIfNeededLocked(ServiceRecord r)2829     private void clearRestartingIfNeededLocked(ServiceRecord r) {
2830         if (r.restartTracker != null) {
2831             // If this is the last restarting record with this tracker, then clear
2832             // the tracker's restarting state.
2833             boolean stillTracking = false;
2834             for (int i=mRestartingServices.size()-1; i>=0; i--) {
2835                 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
2836                     stillTracking = true;
2837                     break;
2838                 }
2839             }
2840             if (!stillTracking) {
2841                 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
2842                         SystemClock.uptimeMillis());
2843                 r.restartTracker = null;
2844             }
2845         }
2846     }
2847 
bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg, boolean whileRestarting, boolean permissionsReviewRequired)2848     private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
2849             boolean whileRestarting, boolean permissionsReviewRequired)
2850             throws TransactionTooLargeException {
2851         if (r.app != null && r.app.thread != null) {
2852             sendServiceArgsLocked(r, execInFg, false);
2853             return null;
2854         }
2855 
2856         if (!whileRestarting && mRestartingServices.contains(r)) {
2857             // If waiting for a restart, then do nothing.
2858             return null;
2859         }
2860 
2861         if (DEBUG_SERVICE) {
2862             Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
2863         }
2864 
2865         // We are now bringing the service up, so no longer in the
2866         // restarting state.
2867         if (mRestartingServices.remove(r)) {
2868             clearRestartingIfNeededLocked(r);
2869         }
2870 
2871         // Make sure this service is no longer considered delayed, we are starting it now.
2872         if (r.delayed) {
2873             if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
2874             getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
2875             r.delayed = false;
2876         }
2877 
2878         // Make sure that the user who owns this service is started.  If not,
2879         // we don't want to allow it to run.
2880         if (!mAm.mUserController.hasStartedUserState(r.userId)) {
2881             String msg = "Unable to launch app "
2882                     + r.appInfo.packageName + "/"
2883                     + r.appInfo.uid + " for service "
2884                     + r.intent.getIntent() + ": user " + r.userId + " is stopped";
2885             Slog.w(TAG, msg);
2886             bringDownServiceLocked(r);
2887             return msg;
2888         }
2889 
2890         // Service is now being launched, its package can't be stopped.
2891         try {
2892             AppGlobals.getPackageManager().setPackageStoppedState(
2893                     r.packageName, false, r.userId);
2894         } catch (RemoteException e) {
2895         } catch (IllegalArgumentException e) {
2896             Slog.w(TAG, "Failed trying to unstop package "
2897                     + r.packageName + ": " + e);
2898         }
2899 
2900         final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
2901         final String procName = r.processName;
2902         HostingRecord hostingRecord = new HostingRecord("service", r.instanceName);
2903         ProcessRecord app;
2904 
2905         if (!isolated) {
2906             app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
2907             if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
2908                         + " app=" + app);
2909             if (app != null && app.thread != null) {
2910                 try {
2911                     app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode, mAm.mProcessStats);
2912                     realStartServiceLocked(r, app, execInFg);
2913                     return null;
2914                 } catch (TransactionTooLargeException e) {
2915                     throw e;
2916                 } catch (RemoteException e) {
2917                     Slog.w(TAG, "Exception when starting service " + r.shortInstanceName, e);
2918                 }
2919 
2920                 // If a dead object exception was thrown -- fall through to
2921                 // restart the application.
2922             }
2923         } else {
2924             // If this service runs in an isolated process, then each time
2925             // we call startProcessLocked() we will get a new isolated
2926             // process, starting another process if we are currently waiting
2927             // for a previous process to come up.  To deal with this, we store
2928             // in the service any current isolated process it is running in or
2929             // waiting to have come up.
2930             app = r.isolatedProc;
2931             if (WebViewZygote.isMultiprocessEnabled()
2932                     && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
2933                 hostingRecord = HostingRecord.byWebviewZygote(r.instanceName);
2934             }
2935             if ((r.serviceInfo.flags & ServiceInfo.FLAG_USE_APP_ZYGOTE) != 0) {
2936                 hostingRecord = HostingRecord.byAppZygote(r.instanceName, r.definingPackageName,
2937                         r.definingUid);
2938             }
2939         }
2940 
2941         // Not running -- get it started, and enqueue this service record
2942         // to be executed when the app comes up.
2943         if (app == null && !permissionsReviewRequired) {
2944             // TODO (chriswailes): Change the Zygote policy flags based on if the launch-for-service
2945             //  was initiated from a notification tap or not.
2946             if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
2947                     hostingRecord, ZYGOTE_POLICY_FLAG_EMPTY, false, isolated, false)) == null) {
2948                 String msg = "Unable to launch app "
2949                         + r.appInfo.packageName + "/"
2950                         + r.appInfo.uid + " for service "
2951                         + r.intent.getIntent() + ": process is bad";
2952                 Slog.w(TAG, msg);
2953                 bringDownServiceLocked(r);
2954                 return msg;
2955             }
2956             if (isolated) {
2957                 r.isolatedProc = app;
2958             }
2959         }
2960 
2961         if (r.fgRequired) {
2962             if (DEBUG_FOREGROUND_SERVICE) {
2963                 Slog.v(TAG, "Whitelisting " + UserHandle.formatUid(r.appInfo.uid)
2964                         + " for fg-service launch");
2965             }
2966             mAm.tempWhitelistUidLocked(r.appInfo.uid,
2967                     SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch");
2968         }
2969 
2970         if (!mPendingServices.contains(r)) {
2971             mPendingServices.add(r);
2972         }
2973 
2974         if (r.delayedStop) {
2975             // Oh and hey we've already been asked to stop!
2976             r.delayedStop = false;
2977             if (r.startRequested) {
2978                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2979                         "Applying delayed stop (in bring up): " + r);
2980                 stopServiceLocked(r);
2981             }
2982         }
2983 
2984         return null;
2985     }
2986 
requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)2987     private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
2988             throws TransactionTooLargeException {
2989         for (int i=r.bindings.size()-1; i>=0; i--) {
2990             IntentBindRecord ibr = r.bindings.valueAt(i);
2991             if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
2992                 break;
2993             }
2994         }
2995     }
2996 
2997     /**
2998      * Note the name of this method should not be confused with the started services concept.
2999      * The "start" here means bring up the instance in the client, and this method is called
3000      * from bindService() as well.
3001      */
realStartServiceLocked(ServiceRecord r, ProcessRecord app, boolean execInFg)3002     private final void realStartServiceLocked(ServiceRecord r,
3003             ProcessRecord app, boolean execInFg) throws RemoteException {
3004         if (app.thread == null) {
3005             throw new RemoteException();
3006         }
3007         if (DEBUG_MU)
3008             Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
3009                     + ", ProcessRecord.uid = " + app.uid);
3010         r.setProcess(app);
3011         r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
3012 
3013         final boolean newService = app.startService(r);
3014         bumpServiceExecutingLocked(r, execInFg, "create");
3015         mAm.updateLruProcessLocked(app, false, null);
3016         updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
3017         mAm.updateOomAdjLocked(app, OomAdjuster.OOM_ADJ_REASON_START_SERVICE);
3018 
3019         boolean created = false;
3020         try {
3021             if (LOG_SERVICE_START_STOP) {
3022                 String nameTerm;
3023                 int lastPeriod = r.shortInstanceName.lastIndexOf('.');
3024                 nameTerm = lastPeriod >= 0 ? r.shortInstanceName.substring(lastPeriod)
3025                         : r.shortInstanceName;
3026                 EventLogTags.writeAmCreateService(
3027                         r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
3028             }
3029             FrameworkStatsLog.write(FrameworkStatsLog.SERVICE_LAUNCH_REPORTED, r.appInfo.uid,
3030                     r.name.getPackageName(), r.name.getClassName());
3031             synchronized (r.stats.getBatteryStats()) {
3032                 r.stats.startLaunchedLocked();
3033             }
3034             mAm.notifyPackageUse(r.serviceInfo.packageName,
3035                                  PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
3036             app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
3037             app.thread.scheduleCreateService(r, r.serviceInfo,
3038                     mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),
3039                     app.getReportedProcState());
3040             r.postNotification();
3041             created = true;
3042         } catch (DeadObjectException e) {
3043             Slog.w(TAG, "Application dead when creating service " + r);
3044             mAm.appDiedLocked(app, "Died when creating service");
3045             throw e;
3046         } finally {
3047             if (!created) {
3048                 // Keep the executeNesting count accurate.
3049                 final boolean inDestroying = mDestroyingServices.contains(r);
3050                 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
3051 
3052                 // Cleanup.
3053                 if (newService) {
3054                     app.stopService(r);
3055                     r.setProcess(null);
3056                 }
3057 
3058                 // Retry.
3059                 if (!inDestroying) {
3060                     scheduleServiceRestartLocked(r, false);
3061                 }
3062             }
3063         }
3064 
3065         if (r.whitelistManager) {
3066             app.whitelistManager = true;
3067         }
3068 
3069         requestServiceBindingsLocked(r, execInFg);
3070 
3071         updateServiceClientActivitiesLocked(app, null, true);
3072 
3073         if (newService && created) {
3074             app.addBoundClientUidsOfNewService(r);
3075         }
3076 
3077         // If the service is in the started state, and there are no
3078         // pending arguments, then fake up one so its onStartCommand() will
3079         // be called.
3080         if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
3081             r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
3082                     null, null, 0));
3083         }
3084 
3085         sendServiceArgsLocked(r, execInFg, true);
3086 
3087         if (r.delayed) {
3088             if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
3089             getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
3090             r.delayed = false;
3091         }
3092 
3093         if (r.delayedStop) {
3094             // Oh and hey we've already been asked to stop!
3095             r.delayedStop = false;
3096             if (r.startRequested) {
3097                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
3098                         "Applying delayed stop (from start): " + r);
3099                 stopServiceLocked(r);
3100             }
3101         }
3102     }
3103 
sendServiceArgsLocked(ServiceRecord r, boolean execInFg, boolean oomAdjusted)3104     private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
3105             boolean oomAdjusted) throws TransactionTooLargeException {
3106         final int N = r.pendingStarts.size();
3107         if (N == 0) {
3108             return;
3109         }
3110 
3111         ArrayList<ServiceStartArgs> args = new ArrayList<>();
3112 
3113         while (r.pendingStarts.size() > 0) {
3114             ServiceRecord.StartItem si = r.pendingStarts.remove(0);
3115             if (DEBUG_SERVICE) {
3116                 Slog.v(TAG_SERVICE, "Sending arguments to: "
3117                         + r + " " + r.intent + " args=" + si.intent);
3118             }
3119             if (si.intent == null && N > 1) {
3120                 // If somehow we got a dummy null intent in the middle,
3121                 // then skip it.  DO NOT skip a null intent when it is
3122                 // the only one in the list -- this is to support the
3123                 // onStartCommand(null) case.
3124                 continue;
3125             }
3126             si.deliveredTime = SystemClock.uptimeMillis();
3127             r.deliveredStarts.add(si);
3128             si.deliveryCount++;
3129             if (si.neededGrants != null) {
3130                 mAm.mUgmInternal.grantUriPermissionUncheckedFromIntent(si.neededGrants,
3131                         si.getUriPermissionsLocked());
3132             }
3133             mAm.grantImplicitAccess(r.userId, si.intent, si.callingId,
3134                     UserHandle.getAppId(r.appInfo.uid)
3135             );
3136             bumpServiceExecutingLocked(r, execInFg, "start");
3137             if (!oomAdjusted) {
3138                 oomAdjusted = true;
3139                 mAm.updateOomAdjLocked(r.app, true, OomAdjuster.OOM_ADJ_REASON_START_SERVICE);
3140             }
3141             if (r.fgRequired && !r.fgWaiting) {
3142                 if (!r.isForeground) {
3143                     if (DEBUG_BACKGROUND_CHECK) {
3144                         Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r);
3145                     }
3146                     scheduleServiceForegroundTransitionTimeoutLocked(r);
3147                 } else {
3148                     if (DEBUG_BACKGROUND_CHECK) {
3149                         Slog.i(TAG, "Service already foreground; no new timeout: " + r);
3150                     }
3151                     r.fgRequired = false;
3152                 }
3153             }
3154             int flags = 0;
3155             if (si.deliveryCount > 1) {
3156                 flags |= Service.START_FLAG_RETRY;
3157             }
3158             if (si.doneExecutingCount > 0) {
3159                 flags |= Service.START_FLAG_REDELIVERY;
3160             }
3161             args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
3162         }
3163 
3164         ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
3165         slice.setInlineCountLimit(4);
3166         Exception caughtException = null;
3167         try {
3168             r.app.thread.scheduleServiceArgs(r, slice);
3169         } catch (TransactionTooLargeException e) {
3170             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
3171                     + " args, first: " + args.get(0).args);
3172             Slog.w(TAG, "Failed delivering service starts", e);
3173             caughtException = e;
3174         } catch (RemoteException e) {
3175             // Remote process gone...  we'll let the normal cleanup take care of this.
3176             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
3177             Slog.w(TAG, "Failed delivering service starts", e);
3178             caughtException = e;
3179         } catch (Exception e) {
3180             Slog.w(TAG, "Unexpected exception", e);
3181             caughtException = e;
3182         }
3183 
3184         if (caughtException != null) {
3185             // Keep nesting count correct
3186             final boolean inDestroying = mDestroyingServices.contains(r);
3187             for (int i = 0; i < args.size(); i++) {
3188                 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
3189             }
3190             if (caughtException instanceof TransactionTooLargeException) {
3191                 throw (TransactionTooLargeException)caughtException;
3192             }
3193         }
3194     }
3195 
isServiceNeededLocked(ServiceRecord r, boolean knowConn, boolean hasConn)3196     private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn,
3197             boolean hasConn) {
3198         // Are we still explicitly being asked to run?
3199         if (r.startRequested) {
3200             return true;
3201         }
3202 
3203         // Is someone still bound to us keeping us running?
3204         if (!knowConn) {
3205             hasConn = r.hasAutoCreateConnections();
3206         }
3207         if (hasConn) {
3208             return true;
3209         }
3210 
3211         return false;
3212     }
3213 
bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn, boolean hasConn)3214     private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
3215             boolean hasConn) {
3216         //Slog.i(TAG, "Bring down service:");
3217         //r.dump("  ");
3218 
3219         if (isServiceNeededLocked(r, knowConn, hasConn)) {
3220             return;
3221         }
3222 
3223         // Are we in the process of launching?
3224         if (mPendingServices.contains(r)) {
3225             return;
3226         }
3227 
3228         bringDownServiceLocked(r);
3229     }
3230 
bringDownServiceLocked(ServiceRecord r)3231     private final void bringDownServiceLocked(ServiceRecord r) {
3232         //Slog.i(TAG, "Bring down service:");
3233         //r.dump("  ");
3234 
3235         // Report to all of the connections that the service is no longer
3236         // available.
3237         ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
3238         for (int conni = connections.size() - 1; conni >= 0; conni--) {
3239             ArrayList<ConnectionRecord> c = connections.valueAt(conni);
3240             for (int i=0; i<c.size(); i++) {
3241                 ConnectionRecord cr = c.get(i);
3242                 // There is still a connection to the service that is
3243                 // being brought down.  Mark it as dead.
3244                 cr.serviceDead = true;
3245                 cr.stopAssociation();
3246                 try {
3247                     cr.conn.connected(r.name, null, true);
3248                 } catch (Exception e) {
3249                     Slog.w(TAG, "Failure disconnecting service " + r.shortInstanceName
3250                           + " to connection " + c.get(i).conn.asBinder()
3251                           + " (in " + c.get(i).binding.client.processName + ")", e);
3252                 }
3253             }
3254         }
3255 
3256         // Tell the service that it has been unbound.
3257         if (r.app != null && r.app.thread != null) {
3258             boolean needOomAdj = false;
3259             for (int i = r.bindings.size() - 1; i >= 0; i--) {
3260                 IntentBindRecord ibr = r.bindings.valueAt(i);
3261                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
3262                         + ": hasBound=" + ibr.hasBound);
3263                 if (ibr.hasBound) {
3264                     try {
3265                         bumpServiceExecutingLocked(r, false, "bring down unbind");
3266                         needOomAdj = true;
3267                         ibr.hasBound = false;
3268                         ibr.requested = false;
3269                         r.app.thread.scheduleUnbindService(r,
3270                                 ibr.intent.getIntent());
3271                     } catch (Exception e) {
3272                         Slog.w(TAG, "Exception when unbinding service "
3273                                 + r.shortInstanceName, e);
3274                         needOomAdj = false;
3275                         serviceProcessGoneLocked(r);
3276                         break;
3277                     }
3278                 }
3279             }
3280             if (needOomAdj) {
3281                 mAm.updateOomAdjLocked(r.app, true,
3282                         OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
3283             }
3284         }
3285 
3286         // Check to see if the service had been started as foreground, but being
3287         // brought down before actually showing a notification.  That is not allowed.
3288         if (r.fgRequired) {
3289             Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
3290                     + r);
3291             r.fgRequired = false;
3292             r.fgWaiting = false;
3293             ServiceState stracker = r.getTracker();
3294             if (stracker != null) {
3295                 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
3296                         r.lastActivity);
3297             }
3298             mAm.mAppOpsService.finishOperation(AppOpsManager.getToken(mAm.mAppOpsService),
3299                     AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, null);
3300             mAm.mHandler.removeMessages(
3301                     ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
3302             if (r.app != null) {
3303                 Message msg = mAm.mHandler.obtainMessage(
3304                         ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
3305                 msg.obj = r.app;
3306                 msg.getData().putCharSequence(
3307                     ActivityManagerService.SERVICE_RECORD_KEY, r.toString());
3308                 mAm.mHandler.sendMessage(msg);
3309             }
3310         }
3311 
3312         if (DEBUG_SERVICE) {
3313             RuntimeException here = new RuntimeException();
3314             here.fillInStackTrace();
3315             Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here);
3316         }
3317         r.destroyTime = SystemClock.uptimeMillis();
3318         if (LOG_SERVICE_START_STOP) {
3319             EventLogTags.writeAmDestroyService(
3320                     r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
3321         }
3322 
3323         final ServiceMap smap = getServiceMapLocked(r.userId);
3324         ServiceRecord found = smap.mServicesByInstanceName.remove(r.instanceName);
3325 
3326         // Note when this method is called by bringUpServiceLocked(), the service is not found
3327         // in mServicesByInstanceName and found will be null.
3328         if (found != null && found != r) {
3329             // This is not actually the service we think is running...  this should not happen,
3330             // but if it does, fail hard.
3331             smap.mServicesByInstanceName.put(r.instanceName, found);
3332             throw new IllegalStateException("Bringing down " + r + " but actually running "
3333                     + found);
3334         }
3335         smap.mServicesByIntent.remove(r.intent);
3336         r.totalRestartCount = 0;
3337         unscheduleServiceRestartLocked(r, 0, true);
3338 
3339         // Also make sure it is not on the pending list.
3340         for (int i=mPendingServices.size()-1; i>=0; i--) {
3341             if (mPendingServices.get(i) == r) {
3342                 mPendingServices.remove(i);
3343                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
3344             }
3345         }
3346 
3347         cancelForegroundNotificationLocked(r);
3348         if (r.isForeground) {
3349             decActiveForegroundAppLocked(smap, r);
3350             ServiceState stracker = r.getTracker();
3351             if (stracker != null) {
3352                 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
3353                         r.lastActivity);
3354             }
3355             mAm.mAppOpsService.finishOperation(
3356                     AppOpsManager.getToken(mAm.mAppOpsService),
3357                     AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, null);
3358             unregisterAppOpCallbackLocked(r);
3359             FrameworkStatsLog.write(FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
3360                     r.appInfo.uid, r.shortInstanceName,
3361                     FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT,
3362                     r.mAllowWhileInUsePermissionInFgs);
3363             mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
3364         }
3365 
3366         r.isForeground = false;
3367         r.foregroundId = 0;
3368         r.foregroundNoti = null;
3369         r.mAllowWhileInUsePermissionInFgs = false;
3370 
3371         // Clear start entries.
3372         r.clearDeliveredStartsLocked();
3373         r.pendingStarts.clear();
3374         smap.mDelayedStartList.remove(r);
3375 
3376         if (r.app != null) {
3377             synchronized (r.stats.getBatteryStats()) {
3378                 r.stats.stopLaunchedLocked();
3379             }
3380             r.app.stopService(r);
3381             r.app.updateBoundClientUids();
3382             if (r.whitelistManager) {
3383                 updateWhitelistManagerLocked(r.app);
3384             }
3385             if (r.app.thread != null) {
3386                 updateServiceForegroundLocked(r.app, false);
3387                 try {
3388                     bumpServiceExecutingLocked(r, false, "destroy");
3389                     mDestroyingServices.add(r);
3390                     r.destroying = true;
3391                     mAm.updateOomAdjLocked(r.app, true,
3392                             OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
3393                     r.app.thread.scheduleStopService(r);
3394                 } catch (Exception e) {
3395                     Slog.w(TAG, "Exception when destroying service "
3396                             + r.shortInstanceName, e);
3397                     serviceProcessGoneLocked(r);
3398                 }
3399             } else {
3400                 if (DEBUG_SERVICE) Slog.v(
3401                     TAG_SERVICE, "Removed service that has no process: " + r);
3402             }
3403         } else {
3404             if (DEBUG_SERVICE) Slog.v(
3405                 TAG_SERVICE, "Removed service that is not running: " + r);
3406         }
3407 
3408         if (r.bindings.size() > 0) {
3409             r.bindings.clear();
3410         }
3411 
3412         if (r.restarter instanceof ServiceRestarter) {
3413            ((ServiceRestarter)r.restarter).setService(null);
3414         }
3415 
3416         int memFactor = mAm.mProcessStats.getMemFactorLocked();
3417         long now = SystemClock.uptimeMillis();
3418         if (r.tracker != null) {
3419             r.tracker.setStarted(false, memFactor, now);
3420             r.tracker.setBound(false, memFactor, now);
3421             if (r.executeNesting == 0) {
3422                 r.tracker.clearCurrentOwner(r, false);
3423                 r.tracker = null;
3424             }
3425         }
3426 
3427         smap.ensureNotStartingBackgroundLocked(r);
3428     }
3429 
removeConnectionLocked(ConnectionRecord c, ProcessRecord skipApp, ActivityServiceConnectionsHolder skipAct)3430     void removeConnectionLocked(ConnectionRecord c, ProcessRecord skipApp,
3431             ActivityServiceConnectionsHolder skipAct) {
3432         IBinder binder = c.conn.asBinder();
3433         AppBindRecord b = c.binding;
3434         ServiceRecord s = b.service;
3435         ArrayList<ConnectionRecord> clist = s.getConnections().get(binder);
3436         if (clist != null) {
3437             clist.remove(c);
3438             if (clist.size() == 0) {
3439                 s.removeConnection(binder);
3440             }
3441         }
3442         b.connections.remove(c);
3443         c.stopAssociation();
3444         if (c.activity != null && c.activity != skipAct) {
3445             c.activity.removeConnection(c);
3446         }
3447         if (b.client != skipApp) {
3448             b.client.connections.remove(c);
3449             if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
3450                 b.client.updateHasAboveClientLocked();
3451             }
3452             // If this connection requested whitelist management, see if we should
3453             // now clear that state.
3454             if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
3455                 s.updateWhitelistManager();
3456                 if (!s.whitelistManager && s.app != null) {
3457                     updateWhitelistManagerLocked(s.app);
3458                 }
3459             }
3460             // And do the same for bg activity starts whitelisting.
3461             if ((c.flags & Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS) != 0) {
3462                 s.updateHasBindingWhitelistingBgActivityStarts();
3463             }
3464             if (s.app != null) {
3465                 updateServiceClientActivitiesLocked(s.app, c, true);
3466             }
3467         }
3468         clist = mServiceConnections.get(binder);
3469         if (clist != null) {
3470             clist.remove(c);
3471             if (clist.size() == 0) {
3472                 mServiceConnections.remove(binder);
3473             }
3474         }
3475 
3476         mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid,
3477                 s.appInfo.longVersionCode, s.instanceName, s.processName);
3478 
3479         if (b.connections.size() == 0) {
3480             b.intent.apps.remove(b.client);
3481         }
3482 
3483         if (!c.serviceDead) {
3484             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
3485                     + ": shouldUnbind=" + b.intent.hasBound);
3486             if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
3487                     && b.intent.hasBound) {
3488                 try {
3489                     bumpServiceExecutingLocked(s, false, "unbind");
3490                     if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
3491                             && s.app.setProcState <= ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
3492                         // If this service's process is not already in the cached list,
3493                         // then update it in the LRU list here because this may be causing
3494                         // it to go down there and we want it to start out near the top.
3495                         mAm.updateLruProcessLocked(s.app, false, null);
3496                     }
3497                     mAm.updateOomAdjLocked(s.app, true,
3498                             OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
3499                     b.intent.hasBound = false;
3500                     // Assume the client doesn't want to know about a rebind;
3501                     // we will deal with that later if it asks for one.
3502                     b.intent.doRebind = false;
3503                     s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
3504                 } catch (Exception e) {
3505                     Slog.w(TAG, "Exception when unbinding service " + s.shortInstanceName, e);
3506                     serviceProcessGoneLocked(s);
3507                 }
3508             }
3509 
3510             // If unbound while waiting to start and there is no connection left in this service,
3511             // remove the pending service
3512             if (s.getConnections().isEmpty()) {
3513                 mPendingServices.remove(s);
3514             }
3515 
3516             if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
3517                 boolean hasAutoCreate = s.hasAutoCreateConnections();
3518                 if (!hasAutoCreate) {
3519                     if (s.tracker != null) {
3520                         s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
3521                                 SystemClock.uptimeMillis());
3522                     }
3523                 }
3524                 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
3525             }
3526         }
3527     }
3528 
serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res)3529     void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
3530         boolean inDestroying = mDestroyingServices.contains(r);
3531         if (r != null) {
3532             if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
3533                 // This is a call from a service start...  take care of
3534                 // book-keeping.
3535                 r.callStart = true;
3536                 switch (res) {
3537                     case Service.START_STICKY_COMPATIBILITY:
3538                     case Service.START_STICKY: {
3539                         // We are done with the associated start arguments.
3540                         r.findDeliveredStart(startId, false, true);
3541                         // Don't stop if killed.
3542                         r.stopIfKilled = false;
3543                         break;
3544                     }
3545                     case Service.START_NOT_STICKY: {
3546                         // We are done with the associated start arguments.
3547                         r.findDeliveredStart(startId, false, true);
3548                         if (r.getLastStartId() == startId) {
3549                             // There is no more work, and this service
3550                             // doesn't want to hang around if killed.
3551                             r.stopIfKilled = true;
3552                         }
3553                         break;
3554                     }
3555                     case Service.START_REDELIVER_INTENT: {
3556                         // We'll keep this item until they explicitly
3557                         // call stop for it, but keep track of the fact
3558                         // that it was delivered.
3559                         ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
3560                         if (si != null) {
3561                             si.deliveryCount = 0;
3562                             si.doneExecutingCount++;
3563                             // Don't stop if killed.
3564                             r.stopIfKilled = true;
3565                         }
3566                         break;
3567                     }
3568                     case Service.START_TASK_REMOVED_COMPLETE: {
3569                         // Special processing for onTaskRemoved().  Don't
3570                         // impact normal onStartCommand() processing.
3571                         r.findDeliveredStart(startId, true, true);
3572                         break;
3573                     }
3574                     default:
3575                         throw new IllegalArgumentException(
3576                                 "Unknown service start result: " + res);
3577                 }
3578                 if (res == Service.START_STICKY_COMPATIBILITY) {
3579                     r.callStart = false;
3580                 }
3581             } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
3582                 // This is the final call from destroying the service...  we should
3583                 // actually be getting rid of the service at this point.  Do some
3584                 // validation of its state, and ensure it will be fully removed.
3585                 if (!inDestroying) {
3586                     // Not sure what else to do with this...  if it is not actually in the
3587                     // destroying list, we don't need to make sure to remove it from it.
3588                     // If the app is null, then it was probably removed because the process died,
3589                     // otherwise wtf
3590                     if (r.app != null) {
3591                         Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
3592                                 + r + ", app=" + r.app);
3593                     }
3594                 } else if (r.executeNesting != 1) {
3595                     Slog.w(TAG, "Service done with onDestroy, but executeNesting="
3596                             + r.executeNesting + ": " + r);
3597                     // Fake it to keep from ANR due to orphaned entry.
3598                     r.executeNesting = 1;
3599                 }
3600             }
3601             final long origId = Binder.clearCallingIdentity();
3602             serviceDoneExecutingLocked(r, inDestroying, inDestroying);
3603             Binder.restoreCallingIdentity(origId);
3604         } else {
3605             Slog.w(TAG, "Done executing unknown service from pid "
3606                     + Binder.getCallingPid());
3607         }
3608     }
3609 
serviceProcessGoneLocked(ServiceRecord r)3610     private void serviceProcessGoneLocked(ServiceRecord r) {
3611         if (r.tracker != null) {
3612             int memFactor = mAm.mProcessStats.getMemFactorLocked();
3613             long now = SystemClock.uptimeMillis();
3614             r.tracker.setExecuting(false, memFactor, now);
3615             r.tracker.setForeground(false, memFactor, now);
3616             r.tracker.setBound(false, memFactor, now);
3617             r.tracker.setStarted(false, memFactor, now);
3618         }
3619         serviceDoneExecutingLocked(r, true, true);
3620     }
3621 
serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying, boolean finishing)3622     private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
3623             boolean finishing) {
3624         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
3625                 + ": nesting=" + r.executeNesting
3626                 + ", inDestroying=" + inDestroying + ", app=" + r.app);
3627         else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
3628                 "<<< DONE EXECUTING " + r.shortInstanceName);
3629         r.executeNesting--;
3630         if (r.executeNesting <= 0) {
3631             if (r.app != null) {
3632                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
3633                         "Nesting at 0 of " + r.shortInstanceName);
3634                 r.app.execServicesFg = false;
3635                 r.app.executingServices.remove(r);
3636                 if (r.app.executingServices.size() == 0) {
3637                     if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
3638                             "No more executingServices of " + r.shortInstanceName);
3639                     mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
3640                 } else if (r.executeFg) {
3641                     // Need to re-evaluate whether the app still needs to be in the foreground.
3642                     for (int i=r.app.executingServices.size()-1; i>=0; i--) {
3643                         if (r.app.executingServices.valueAt(i).executeFg) {
3644                             r.app.execServicesFg = true;
3645                             break;
3646                         }
3647                     }
3648                 }
3649                 if (inDestroying) {
3650                     if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
3651                             "doneExecuting remove destroying " + r);
3652                     mDestroyingServices.remove(r);
3653                     r.bindings.clear();
3654                 }
3655                 mAm.updateOomAdjLocked(r.app, true, OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
3656             }
3657             r.executeFg = false;
3658             if (r.tracker != null) {
3659                 final int memFactor = mAm.mProcessStats.getMemFactorLocked();
3660                 final long now = SystemClock.uptimeMillis();
3661                 r.tracker.setExecuting(false, memFactor, now);
3662                 r.tracker.setForeground(false, memFactor, now);
3663                 if (finishing) {
3664                     r.tracker.clearCurrentOwner(r, false);
3665                     r.tracker = null;
3666                 }
3667             }
3668             if (finishing) {
3669                 if (r.app != null && !r.app.isPersistent()) {
3670                     r.app.stopService(r);
3671                     r.app.updateBoundClientUids();
3672                     if (r.whitelistManager) {
3673                         updateWhitelistManagerLocked(r.app);
3674                     }
3675                 }
3676                 r.setProcess(null);
3677             }
3678         }
3679     }
3680 
attachApplicationLocked(ProcessRecord proc, String processName)3681     boolean attachApplicationLocked(ProcessRecord proc, String processName)
3682             throws RemoteException {
3683         boolean didSomething = false;
3684         // Collect any services that are waiting for this process to come up.
3685         if (mPendingServices.size() > 0) {
3686             ServiceRecord sr = null;
3687             try {
3688                 for (int i=0; i<mPendingServices.size(); i++) {
3689                     sr = mPendingServices.get(i);
3690                     if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3691                             || !processName.equals(sr.processName))) {
3692                         continue;
3693                     }
3694 
3695                     mPendingServices.remove(i);
3696                     i--;
3697                     proc.addPackage(sr.appInfo.packageName, sr.appInfo.longVersionCode,
3698                             mAm.mProcessStats);
3699                     realStartServiceLocked(sr, proc, sr.createdFromFg);
3700                     didSomething = true;
3701                     if (!isServiceNeededLocked(sr, false, false)) {
3702                         // We were waiting for this service to start, but it is actually no
3703                         // longer needed.  This could happen because bringDownServiceIfNeeded
3704                         // won't bring down a service that is pending...  so now the pending
3705                         // is done, so let's drop it.
3706                         bringDownServiceLocked(sr);
3707                     }
3708                 }
3709             } catch (RemoteException e) {
3710                 Slog.w(TAG, "Exception in new application when starting service "
3711                         + sr.shortInstanceName, e);
3712                 throw e;
3713             }
3714         }
3715         // Also, if there are any services that are waiting to restart and
3716         // would run in this process, now is a good time to start them.  It would
3717         // be weird to bring up the process but arbitrarily not let the services
3718         // run at this point just because their restart time hasn't come up.
3719         if (mRestartingServices.size() > 0) {
3720             ServiceRecord sr;
3721             for (int i=0; i<mRestartingServices.size(); i++) {
3722                 sr = mRestartingServices.get(i);
3723                 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3724                         || !processName.equals(sr.processName))) {
3725                     continue;
3726                 }
3727                 mAm.mHandler.removeCallbacks(sr.restarter);
3728                 mAm.mHandler.post(sr.restarter);
3729             }
3730         }
3731         return didSomething;
3732     }
3733 
processStartTimedOutLocked(ProcessRecord proc)3734     void processStartTimedOutLocked(ProcessRecord proc) {
3735         for (int i=0; i<mPendingServices.size(); i++) {
3736             ServiceRecord sr = mPendingServices.get(i);
3737             if ((proc.uid == sr.appInfo.uid
3738                     && proc.processName.equals(sr.processName))
3739                     || sr.isolatedProc == proc) {
3740                 Slog.w(TAG, "Forcing bringing down service: " + sr);
3741                 sr.isolatedProc = null;
3742                 mPendingServices.remove(i);
3743                 i--;
3744                 bringDownServiceLocked(sr);
3745             }
3746         }
3747     }
3748 
collectPackageServicesLocked(String packageName, Set<String> filterByClasses, boolean evenPersistent, boolean doit, ArrayMap<ComponentName, ServiceRecord> services)3749     private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
3750             boolean evenPersistent, boolean doit, ArrayMap<ComponentName, ServiceRecord> services) {
3751         boolean didSomething = false;
3752         for (int i = services.size() - 1; i >= 0; i--) {
3753             ServiceRecord service = services.valueAt(i);
3754             final boolean sameComponent = packageName == null
3755                     || (service.packageName.equals(packageName)
3756                         && (filterByClasses == null
3757                             || filterByClasses.contains(service.name.getClassName())));
3758             if (sameComponent
3759                     && (service.app == null || evenPersistent || !service.app.isPersistent())) {
3760                 if (!doit) {
3761                     return true;
3762                 }
3763                 didSomething = true;
3764                 Slog.i(TAG, "  Force stopping service " + service);
3765                 if (service.app != null && !service.app.isPersistent()) {
3766                     service.app.stopService(service);
3767                     service.app.updateBoundClientUids();
3768                     if (service.whitelistManager) {
3769                         updateWhitelistManagerLocked(service.app);
3770                     }
3771                 }
3772                 service.setProcess(null);
3773                 service.isolatedProc = null;
3774                 if (mTmpCollectionResults == null) {
3775                     mTmpCollectionResults = new ArrayList<>();
3776                 }
3777                 mTmpCollectionResults.add(service);
3778             }
3779         }
3780         return didSomething;
3781     }
3782 
bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses, int userId, boolean evenPersistent, boolean doit)3783     boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
3784             int userId, boolean evenPersistent, boolean doit) {
3785         boolean didSomething = false;
3786 
3787         if (mTmpCollectionResults != null) {
3788             mTmpCollectionResults.clear();
3789         }
3790 
3791         if (userId == UserHandle.USER_ALL) {
3792             for (int i = mServiceMap.size() - 1; i >= 0; i--) {
3793                 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
3794                         evenPersistent, doit, mServiceMap.valueAt(i).mServicesByInstanceName);
3795                 if (!doit && didSomething) {
3796                     return true;
3797                 }
3798                 if (doit && filterByClasses == null) {
3799                     forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId);
3800                 }
3801             }
3802         } else {
3803             ServiceMap smap = mServiceMap.get(userId);
3804             if (smap != null) {
3805                 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByInstanceName;
3806                 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
3807                         evenPersistent, doit, items);
3808             }
3809             if (doit && filterByClasses == null) {
3810                 forceStopPackageLocked(packageName, userId);
3811             }
3812         }
3813 
3814         if (mTmpCollectionResults != null) {
3815             for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
3816                 bringDownServiceLocked(mTmpCollectionResults.get(i));
3817             }
3818             mTmpCollectionResults.clear();
3819         }
3820 
3821         return didSomething;
3822     }
3823 
forceStopPackageLocked(String packageName, int userId)3824     void forceStopPackageLocked(String packageName, int userId) {
3825         ServiceMap smap = mServiceMap.get(userId);
3826         if (smap != null && smap.mActiveForegroundApps.size() > 0) {
3827             for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
3828                 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
3829                 if (aa.mPackageName.equals(packageName)) {
3830                     smap.mActiveForegroundApps.removeAt(i);
3831                     smap.mActiveForegroundAppsChanged = true;
3832                 }
3833             }
3834             if (smap.mActiveForegroundAppsChanged) {
3835                 requestUpdateActiveForegroundAppsLocked(smap, 0);
3836             }
3837         }
3838     }
3839 
cleanUpServices(int userId, ComponentName component, Intent baseIntent)3840     void cleanUpServices(int userId, ComponentName component, Intent baseIntent) {
3841         ArrayList<ServiceRecord> services = new ArrayList<>();
3842         ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
3843         for (int i = alls.size() - 1; i >= 0; i--) {
3844             ServiceRecord sr = alls.valueAt(i);
3845             if (sr.packageName.equals(component.getPackageName())) {
3846                 services.add(sr);
3847             }
3848         }
3849 
3850         // Take care of any running services associated with the app.
3851         for (int i = services.size() - 1; i >= 0; i--) {
3852             ServiceRecord sr = services.get(i);
3853             if (sr.startRequested) {
3854                 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
3855                     Slog.i(TAG, "Stopping service " + sr.shortInstanceName + ": remove task");
3856                     stopServiceLocked(sr);
3857                 } else {
3858                     sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
3859                             sr.getLastStartId(), baseIntent, null, 0));
3860                     if (sr.app != null && sr.app.thread != null) {
3861                         // We always run in the foreground, since this is called as
3862                         // part of the "remove task" UI operation.
3863                         try {
3864                             sendServiceArgsLocked(sr, true, false);
3865                         } catch (TransactionTooLargeException e) {
3866                             // Ignore, keep going.
3867                         }
3868                     }
3869                 }
3870             }
3871         }
3872     }
3873 
killServicesLocked(ProcessRecord app, boolean allowRestart)3874     final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
3875         // Report disconnected services.
3876         if (false) {
3877             // XXX we are letting the client link to the service for
3878             // death notifications.
3879             int numberOfRunningServices = app.numberOfRunningServices();
3880             for (int sIndex = 0; sIndex < numberOfRunningServices; sIndex++) {
3881                 ServiceRecord r = app.getRunningServiceAt(sIndex);
3882                 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
3883                 for (int conni = connections.size() - 1; conni >= 0; conni--) {
3884                     ArrayList<ConnectionRecord> cl = connections.valueAt(conni);
3885                     for (int i = 0; i < cl.size(); i++) {
3886                         ConnectionRecord c = cl.get(i);
3887                         if (c.binding.client != app) {
3888                             try {
3889                                 //c.conn.connected(r.className, null);
3890                             } catch (Exception e) {
3891                                 // todo: this should be asynchronous!
3892                                 Slog.w(TAG, "Exception thrown disconnected servce "
3893                                         + r.shortInstanceName
3894                                         + " from app " + app.processName, e);
3895                             }
3896                         }
3897                     }
3898                 }
3899             }
3900         }
3901 
3902         // Clean up any connections this application has to other services.
3903         for (int i = app.connections.size() - 1; i >= 0; i--) {
3904             ConnectionRecord r = app.connections.valueAt(i);
3905             removeConnectionLocked(r, app, null);
3906         }
3907         updateServiceConnectionActivitiesLocked(app);
3908         app.connections.clear();
3909 
3910         app.whitelistManager = false;
3911 
3912         // Clear app state from services.
3913         for (int i = app.numberOfRunningServices() - 1; i >= 0; i--) {
3914             ServiceRecord sr = app.getRunningServiceAt(i);
3915             synchronized (sr.stats.getBatteryStats()) {
3916                 sr.stats.stopLaunchedLocked();
3917             }
3918             if (sr.app != app && sr.app != null && !sr.app.isPersistent()) {
3919                 sr.app.stopService(sr);
3920                 sr.app.updateBoundClientUids();
3921             }
3922             sr.setProcess(null);
3923             sr.isolatedProc = null;
3924             sr.executeNesting = 0;
3925             sr.forceClearTracker();
3926             if (mDestroyingServices.remove(sr)) {
3927                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
3928             }
3929 
3930             final int numClients = sr.bindings.size();
3931             for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
3932                 IntentBindRecord b = sr.bindings.valueAt(bindingi);
3933                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
3934                         + ": shouldUnbind=" + b.hasBound);
3935                 b.binder = null;
3936                 b.requested = b.received = b.hasBound = false;
3937                 // If this binding is coming from a cached process and is asking to keep
3938                 // the service created, then we'll kill the cached process as well -- we
3939                 // don't want to be thrashing around restarting processes that are only
3940                 // there to be cached.
3941                 for (int appi=b.apps.size()-1; appi>=0; appi--) {
3942                     final ProcessRecord proc = b.apps.keyAt(appi);
3943                     // If the process is already gone, skip it.
3944                     if (proc.killedByAm || proc.thread == null) {
3945                         continue;
3946                     }
3947                     // Only do this for processes that have an auto-create binding;
3948                     // otherwise the binding can be left, because it won't cause the
3949                     // service to restart.
3950                     final AppBindRecord abind = b.apps.valueAt(appi);
3951                     boolean hasCreate = false;
3952                     for (int conni=abind.connections.size()-1; conni>=0; conni--) {
3953                         ConnectionRecord conn = abind.connections.valueAt(conni);
3954                         if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
3955                                 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
3956                             hasCreate = true;
3957                             break;
3958                         }
3959                     }
3960                     if (!hasCreate) {
3961                         continue;
3962                     }
3963                     // XXX turned off for now until we have more time to get a better policy.
3964                     if (false && proc != null && !proc.isPersistent() && proc.thread != null
3965                             && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
3966                             && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
3967                         proc.kill("bound to service " + sr.shortInstanceName
3968                                 + " in dying proc " + (app != null ? app.processName : "??"),
3969                                 ApplicationExitInfo.REASON_OTHER, true);
3970                     }
3971                 }
3972             }
3973         }
3974 
3975         ServiceMap smap = getServiceMapLocked(app.userId);
3976 
3977         // Now do remaining service cleanup.
3978         for (int i = app.numberOfRunningServices() - 1; i >= 0; i--) {
3979             ServiceRecord sr = app.getRunningServiceAt(i);
3980 
3981             // Unless the process is persistent, this process record is going away,
3982             // so make sure the service is cleaned out of it.
3983             if (!app.isPersistent()) {
3984                 app.stopService(sr);
3985                 app.updateBoundClientUids();
3986             }
3987 
3988             // Sanity check: if the service listed for the app is not one
3989             // we actually are maintaining, just let it drop.
3990             final ServiceRecord curRec = smap.mServicesByInstanceName.get(sr.instanceName);
3991             if (curRec != sr) {
3992                 if (curRec != null) {
3993                     Slog.wtf(TAG, "Service " + sr + " in process " + app
3994                             + " not same as in map: " + curRec);
3995                 }
3996                 continue;
3997             }
3998 
3999             // Any services running in the application may need to be placed
4000             // back in the pending list.
4001             if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
4002                     && (sr.serviceInfo.applicationInfo.flags
4003                         &ApplicationInfo.FLAG_PERSISTENT) == 0) {
4004                 Slog.w(TAG, "Service crashed " + sr.crashCount
4005                         + " times, stopping: " + sr);
4006                 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
4007                         sr.userId, sr.crashCount, sr.shortInstanceName, app.pid);
4008                 bringDownServiceLocked(sr);
4009             } else if (!allowRestart
4010                     || !mAm.mUserController.isUserRunning(sr.userId, 0)) {
4011                 bringDownServiceLocked(sr);
4012             } else {
4013                 final boolean scheduled = scheduleServiceRestartLocked(sr, true /* allowCancel */);
4014 
4015                 // Should the service remain running?  Note that in the
4016                 // extreme case of so many attempts to deliver a command
4017                 // that it failed we also will stop it here.
4018                 if (!scheduled) {
4019                     bringDownServiceLocked(sr);
4020                 } else if (sr.canStopIfKilled(false /* isStartCanceled */)) {
4021                     // Update to stopped state because the explicit start is gone. The service is
4022                     // scheduled to restart for other reason (e.g. connections) so we don't bring
4023                     // down it.
4024                     sr.startRequested = false;
4025                     if (sr.tracker != null) {
4026                         sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
4027                                 SystemClock.uptimeMillis());
4028                     }
4029                 }
4030             }
4031         }
4032 
4033         if (!allowRestart) {
4034             app.stopAllServices();
4035             app.clearBoundClientUids();
4036 
4037             // Make sure there are no more restarting services for this process.
4038             for (int i=mRestartingServices.size()-1; i>=0; i--) {
4039                 ServiceRecord r = mRestartingServices.get(i);
4040                 if (r.processName.equals(app.processName) &&
4041                         r.serviceInfo.applicationInfo.uid == app.info.uid) {
4042                     mRestartingServices.remove(i);
4043                     clearRestartingIfNeededLocked(r);
4044                 }
4045             }
4046             for (int i=mPendingServices.size()-1; i>=0; i--) {
4047                 ServiceRecord r = mPendingServices.get(i);
4048                 if (r.processName.equals(app.processName) &&
4049                         r.serviceInfo.applicationInfo.uid == app.info.uid) {
4050                     mPendingServices.remove(i);
4051                 }
4052             }
4053         }
4054 
4055         // Make sure we have no more records on the stopping list.
4056         int i = mDestroyingServices.size();
4057         while (i > 0) {
4058             i--;
4059             ServiceRecord sr = mDestroyingServices.get(i);
4060             if (sr.app == app) {
4061                 sr.forceClearTracker();
4062                 mDestroyingServices.remove(i);
4063                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
4064             }
4065         }
4066 
4067         app.executingServices.clear();
4068     }
4069 
makeRunningServiceInfoLocked(ServiceRecord r)4070     ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
4071         ActivityManager.RunningServiceInfo info =
4072             new ActivityManager.RunningServiceInfo();
4073         info.service = r.name;
4074         if (r.app != null) {
4075             info.pid = r.app.pid;
4076         }
4077         info.uid = r.appInfo.uid;
4078         info.process = r.processName;
4079         info.foreground = r.isForeground;
4080         info.activeSince = r.createRealTime;
4081         info.started = r.startRequested;
4082         info.clientCount = r.getConnections().size();
4083         info.crashCount = r.crashCount;
4084         info.lastActivityTime = r.lastActivity;
4085         if (r.isForeground) {
4086             info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
4087         }
4088         if (r.startRequested) {
4089             info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
4090         }
4091         if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
4092             info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
4093         }
4094         if (r.app != null && r.app.isPersistent()) {
4095             info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
4096         }
4097 
4098         ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
4099         for (int conni = connections.size() - 1; conni >= 0; conni--) {
4100             ArrayList<ConnectionRecord> connl = connections.valueAt(conni);
4101             for (int i=0; i<connl.size(); i++) {
4102                 ConnectionRecord conn = connl.get(i);
4103                 if (conn.clientLabel != 0) {
4104                     info.clientPackage = conn.binding.client.info.packageName;
4105                     info.clientLabel = conn.clientLabel;
4106                     return info;
4107                 }
4108             }
4109         }
4110         return info;
4111     }
4112 
getRunningServiceInfoLocked(int maxNum, int flags, int callingUid, boolean allowed, boolean canInteractAcrossUsers)4113     List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags,
4114         int callingUid, boolean allowed, boolean canInteractAcrossUsers) {
4115         ArrayList<ActivityManager.RunningServiceInfo> res
4116                 = new ArrayList<ActivityManager.RunningServiceInfo>();
4117 
4118         final long ident = Binder.clearCallingIdentity();
4119         try {
4120             if (canInteractAcrossUsers) {
4121                 int[] users = mAm.mUserController.getUsers();
4122                 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
4123                     ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
4124                     for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
4125                         ServiceRecord sr = alls.valueAt(i);
4126                         res.add(makeRunningServiceInfoLocked(sr));
4127                     }
4128                 }
4129 
4130                 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
4131                     ServiceRecord r = mRestartingServices.get(i);
4132                     ActivityManager.RunningServiceInfo info =
4133                             makeRunningServiceInfoLocked(r);
4134                     info.restarting = r.nextRestartTime;
4135                     res.add(info);
4136                 }
4137             } else {
4138                 int userId = UserHandle.getUserId(callingUid);
4139                 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
4140                 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
4141                     ServiceRecord sr = alls.valueAt(i);
4142 
4143                     if (allowed || (sr.app != null && sr.app.uid == callingUid)) {
4144                         res.add(makeRunningServiceInfoLocked(sr));
4145                     }
4146                 }
4147 
4148                 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
4149                     ServiceRecord r = mRestartingServices.get(i);
4150                     if (r.userId == userId
4151                         && (allowed || (r.app != null && r.app.uid == callingUid))) {
4152                         ActivityManager.RunningServiceInfo info =
4153                                 makeRunningServiceInfoLocked(r);
4154                         info.restarting = r.nextRestartTime;
4155                         res.add(info);
4156                     }
4157                 }
4158             }
4159         } finally {
4160             Binder.restoreCallingIdentity(ident);
4161         }
4162 
4163         return res;
4164     }
4165 
getRunningServiceControlPanelLocked(ComponentName name)4166     public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
4167         int userId = UserHandle.getUserId(Binder.getCallingUid());
4168         ServiceRecord r = getServiceByNameLocked(name, userId);
4169         if (r != null) {
4170             ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
4171             for (int conni = connections.size() - 1; conni >= 0; conni--) {
4172                 ArrayList<ConnectionRecord> conn = connections.valueAt(conni);
4173                 for (int i=0; i<conn.size(); i++) {
4174                     if (conn.get(i).clientIntent != null) {
4175                         return conn.get(i).clientIntent;
4176                     }
4177                 }
4178             }
4179         }
4180         return null;
4181     }
4182 
serviceTimeout(ProcessRecord proc)4183     void serviceTimeout(ProcessRecord proc) {
4184         String anrMessage = null;
4185         synchronized(mAm) {
4186             if (proc.isDebugging()) {
4187                 // The app's being debugged, ignore timeout.
4188                 return;
4189             }
4190             if (proc.executingServices.size() == 0 || proc.thread == null) {
4191                 return;
4192             }
4193             final long now = SystemClock.uptimeMillis();
4194             final long maxTime =  now -
4195                     (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
4196             ServiceRecord timeout = null;
4197             long nextTime = 0;
4198             for (int i=proc.executingServices.size()-1; i>=0; i--) {
4199                 ServiceRecord sr = proc.executingServices.valueAt(i);
4200                 if (sr.executingStart < maxTime) {
4201                     timeout = sr;
4202                     break;
4203                 }
4204                 if (sr.executingStart > nextTime) {
4205                     nextTime = sr.executingStart;
4206                 }
4207             }
4208             if (timeout != null && mAm.mProcessList.mLruProcesses.contains(proc)) {
4209                 Slog.w(TAG, "Timeout executing service: " + timeout);
4210                 StringWriter sw = new StringWriter();
4211                 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
4212                 pw.println(timeout);
4213                 timeout.dump(pw, "    ");
4214                 pw.close();
4215                 mLastAnrDump = sw.toString();
4216                 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
4217                 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
4218                 anrMessage = "executing service " + timeout.shortInstanceName;
4219             } else {
4220                 Message msg = mAm.mHandler.obtainMessage(
4221                         ActivityManagerService.SERVICE_TIMEOUT_MSG);
4222                 msg.obj = proc;
4223                 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
4224                         ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
4225             }
4226         }
4227 
4228         if (anrMessage != null) {
4229             mAm.mAnrHelper.appNotResponding(proc, anrMessage);
4230         }
4231     }
4232 
serviceForegroundTimeout(ServiceRecord r)4233     void serviceForegroundTimeout(ServiceRecord r) {
4234         ProcessRecord app;
4235         synchronized (mAm) {
4236             if (!r.fgRequired || r.destroying) {
4237                 return;
4238             }
4239 
4240             app = r.app;
4241             if (app != null && app.isDebugging()) {
4242                 // The app's being debugged; let it ride
4243                 return;
4244             }
4245 
4246             if (DEBUG_BACKGROUND_CHECK) {
4247                 Slog.i(TAG, "Service foreground-required timeout for " + r);
4248             }
4249             r.fgWaiting = false;
4250             stopServiceLocked(r);
4251         }
4252 
4253         if (app != null) {
4254             mAm.mAnrHelper.appNotResponding(app,
4255                     "Context.startForegroundService() did not then call Service.startForeground(): "
4256                         + r);
4257         }
4258     }
4259 
updateServiceApplicationInfoLocked(ApplicationInfo applicationInfo)4260     public void updateServiceApplicationInfoLocked(ApplicationInfo applicationInfo) {
4261         final int userId = UserHandle.getUserId(applicationInfo.uid);
4262         ServiceMap serviceMap = mServiceMap.get(userId);
4263         if (serviceMap != null) {
4264             ArrayMap<ComponentName, ServiceRecord> servicesByName
4265                     = serviceMap.mServicesByInstanceName;
4266             for (int j = servicesByName.size() - 1; j >= 0; j--) {
4267                 ServiceRecord serviceRecord = servicesByName.valueAt(j);
4268                 if (applicationInfo.packageName.equals(serviceRecord.appInfo.packageName)) {
4269                     serviceRecord.appInfo = applicationInfo;
4270                     serviceRecord.serviceInfo.applicationInfo = applicationInfo;
4271                 }
4272             }
4273         }
4274     }
4275 
serviceForegroundCrash(ProcessRecord app, CharSequence serviceRecord)4276     void serviceForegroundCrash(ProcessRecord app, CharSequence serviceRecord) {
4277         mAm.crashApplication(app.uid, app.pid, app.info.packageName, app.userId,
4278                 "Context.startForegroundService() did not then call Service.startForeground(): "
4279                     + serviceRecord, false /*force*/);
4280     }
4281 
scheduleServiceTimeoutLocked(ProcessRecord proc)4282     void scheduleServiceTimeoutLocked(ProcessRecord proc) {
4283         if (proc.executingServices.size() == 0 || proc.thread == null) {
4284             return;
4285         }
4286         Message msg = mAm.mHandler.obtainMessage(
4287                 ActivityManagerService.SERVICE_TIMEOUT_MSG);
4288         msg.obj = proc;
4289         mAm.mHandler.sendMessageDelayed(msg,
4290                 proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
4291     }
4292 
scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r)4293     void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
4294         if (r.app.executingServices.size() == 0 || r.app.thread == null) {
4295             return;
4296         }
4297         Message msg = mAm.mHandler.obtainMessage(
4298                 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG);
4299         msg.obj = r;
4300         r.fgWaiting = true;
4301         mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT);
4302     }
4303 
4304     final class ServiceDumper {
4305         private final FileDescriptor fd;
4306         private final PrintWriter pw;
4307         private final String[] args;
4308         private final boolean dumpAll;
4309         private final String dumpPackage;
4310         private final ItemMatcher matcher;
4311         private final ArrayList<ServiceRecord> services = new ArrayList<>();
4312 
4313         private final long nowReal = SystemClock.elapsedRealtime();
4314 
4315         private boolean needSep = false;
4316         private boolean printedAnything = false;
4317         private boolean printed = false;
4318 
4319         /**
4320          * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
4321          * must be called with the lock held).
4322          */
ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)4323         ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
4324                 int opti, boolean dumpAll, String dumpPackage) {
4325             this.fd = fd;
4326             this.pw = pw;
4327             this.args = args;
4328             this.dumpAll = dumpAll;
4329             this.dumpPackage = dumpPackage;
4330             matcher = new ItemMatcher();
4331             matcher.build(args, opti);
4332 
4333             final int[] users = mAm.mUserController.getUsers();
4334             for (int user : users) {
4335                 ServiceMap smap = getServiceMapLocked(user);
4336                 if (smap.mServicesByInstanceName.size() > 0) {
4337                     for (int si=0; si<smap.mServicesByInstanceName.size(); si++) {
4338                         ServiceRecord r = smap.mServicesByInstanceName.valueAt(si);
4339                         if (!matcher.match(r, r.name)) {
4340                             continue;
4341                         }
4342                         if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4343                             continue;
4344                         }
4345                         services.add(r);
4346                     }
4347                 }
4348             }
4349         }
4350 
dumpHeaderLocked()4351         private void dumpHeaderLocked() {
4352             pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
4353             if (mLastAnrDump != null) {
4354                 pw.println("  Last ANR service:");
4355                 pw.print(mLastAnrDump);
4356                 pw.println();
4357             }
4358         }
4359 
dumpLocked()4360         void dumpLocked() {
4361             dumpHeaderLocked();
4362 
4363             try {
4364                 int[] users = mAm.mUserController.getUsers();
4365                 for (int user : users) {
4366                     // Find the first service for this user.
4367                     int serviceIdx = 0;
4368                     while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
4369                         serviceIdx++;
4370                     }
4371                     printed = false;
4372                     if (serviceIdx < services.size()) {
4373                         needSep = false;
4374                         while (serviceIdx < services.size()) {
4375                             ServiceRecord r = services.get(serviceIdx);
4376                             serviceIdx++;
4377                             if (r.userId != user) {
4378                                 break;
4379                             }
4380                             dumpServiceLocalLocked(r);
4381                         }
4382                         needSep |= printed;
4383                     }
4384 
4385                     dumpUserRemainsLocked(user);
4386                 }
4387             } catch (Exception e) {
4388                 Slog.w(TAG, "Exception in dumpServicesLocked", e);
4389             }
4390 
4391             dumpRemainsLocked();
4392         }
4393 
dumpWithClient()4394         void dumpWithClient() {
4395             synchronized(mAm) {
4396                 dumpHeaderLocked();
4397             }
4398 
4399             try {
4400                 int[] users = mAm.mUserController.getUsers();
4401                 for (int user : users) {
4402                     // Find the first service for this user.
4403                     int serviceIdx = 0;
4404                     while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
4405                         serviceIdx++;
4406                     }
4407                     printed = false;
4408                     if (serviceIdx < services.size()) {
4409                         needSep = false;
4410                         while (serviceIdx < services.size()) {
4411                             ServiceRecord r = services.get(serviceIdx);
4412                             serviceIdx++;
4413                             if (r.userId != user) {
4414                                 break;
4415                             }
4416                             synchronized(mAm) {
4417                                 dumpServiceLocalLocked(r);
4418                             }
4419                             dumpServiceClient(r);
4420                         }
4421                         needSep |= printed;
4422                     }
4423 
4424                     synchronized(mAm) {
4425                         dumpUserRemainsLocked(user);
4426                     }
4427                 }
4428             } catch (Exception e) {
4429                 Slog.w(TAG, "Exception in dumpServicesLocked", e);
4430             }
4431 
4432             synchronized(mAm) {
4433                 dumpRemainsLocked();
4434             }
4435         }
4436 
dumpUserHeaderLocked(int user)4437         private void dumpUserHeaderLocked(int user) {
4438             if (!printed) {
4439                 if (printedAnything) {
4440                     pw.println();
4441                 }
4442                 pw.println("  User " + user + " active services:");
4443                 printed = true;
4444             }
4445             printedAnything = true;
4446             if (needSep) {
4447                 pw.println();
4448             }
4449         }
4450 
dumpServiceLocalLocked(ServiceRecord r)4451         private void dumpServiceLocalLocked(ServiceRecord r) {
4452             dumpUserHeaderLocked(r.userId);
4453             pw.print("  * ");
4454             pw.println(r);
4455             if (dumpAll) {
4456                 r.dump(pw, "    ");
4457                 needSep = true;
4458             } else {
4459                 pw.print("    app=");
4460                 pw.println(r.app);
4461                 pw.print("    created=");
4462                 TimeUtils.formatDuration(r.createRealTime, nowReal, pw);
4463                 pw.print(" started=");
4464                 pw.print(r.startRequested);
4465                 pw.print(" connections=");
4466                 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
4467                 pw.println(connections.size());
4468                 if (connections.size() > 0) {
4469                     pw.println("    Connections:");
4470                     for (int conni = 0; conni < connections.size(); conni++) {
4471                         ArrayList<ConnectionRecord> clist = connections.valueAt(conni);
4472                         for (int i = 0; i < clist.size(); i++) {
4473                             ConnectionRecord conn = clist.get(i);
4474                             pw.print("      ");
4475                             pw.print(conn.binding.intent.intent.getIntent()
4476                                     .toShortString(false, false, false, false));
4477                             pw.print(" -> ");
4478                             ProcessRecord proc = conn.binding.client;
4479                             pw.println(proc != null ? proc.toShortString() : "null");
4480                         }
4481                     }
4482                 }
4483             }
4484         }
4485 
dumpServiceClient(ServiceRecord r)4486         private void dumpServiceClient(ServiceRecord r) {
4487             final ProcessRecord proc = r.app;
4488             if (proc == null) {
4489                 return;
4490             }
4491             final IApplicationThread thread = proc.thread;
4492             if (thread == null) {
4493                 return;
4494             }
4495             pw.println("    Client:");
4496             pw.flush();
4497             try {
4498                 TransferPipe tp = new TransferPipe();
4499                 try {
4500                     thread.dumpService(tp.getWriteFd(), r, args);
4501                     tp.setBufferPrefix("      ");
4502                     // Short timeout, since blocking here can
4503                     // deadlock with the application.
4504                     tp.go(fd, 2000);
4505                 } finally {
4506                     tp.kill();
4507                 }
4508             } catch (IOException e) {
4509                 pw.println("      Failure while dumping the service: " + e);
4510             } catch (RemoteException e) {
4511                 pw.println("      Got a RemoteException while dumping the service");
4512             }
4513             needSep = true;
4514         }
4515 
dumpUserRemainsLocked(int user)4516         private void dumpUserRemainsLocked(int user) {
4517             ServiceMap smap = getServiceMapLocked(user);
4518             printed = false;
4519             for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
4520                 ServiceRecord r = smap.mDelayedStartList.get(si);
4521                 if (!matcher.match(r, r.name)) {
4522                     continue;
4523                 }
4524                 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4525                     continue;
4526                 }
4527                 if (!printed) {
4528                     if (printedAnything) {
4529                         pw.println();
4530                     }
4531                     pw.println("  User " + user + " delayed start services:");
4532                     printed = true;
4533                 }
4534                 printedAnything = true;
4535                 pw.print("  * Delayed start "); pw.println(r);
4536             }
4537             printed = false;
4538             for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
4539                 ServiceRecord r = smap.mStartingBackground.get(si);
4540                 if (!matcher.match(r, r.name)) {
4541                     continue;
4542                 }
4543                 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4544                     continue;
4545                 }
4546                 if (!printed) {
4547                     if (printedAnything) {
4548                         pw.println();
4549                     }
4550                     pw.println("  User " + user + " starting in background:");
4551                     printed = true;
4552                 }
4553                 printedAnything = true;
4554                 pw.print("  * Starting bg "); pw.println(r);
4555             }
4556         }
4557 
dumpRemainsLocked()4558         private void dumpRemainsLocked() {
4559             if (mPendingServices.size() > 0) {
4560                 printed = false;
4561                 for (int i=0; i<mPendingServices.size(); i++) {
4562                     ServiceRecord r = mPendingServices.get(i);
4563                     if (!matcher.match(r, r.name)) {
4564                         continue;
4565                     }
4566                     if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4567                         continue;
4568                     }
4569                     printedAnything = true;
4570                     if (!printed) {
4571                         if (needSep) pw.println();
4572                         needSep = true;
4573                         pw.println("  Pending services:");
4574                         printed = true;
4575                     }
4576                     pw.print("  * Pending "); pw.println(r);
4577                     r.dump(pw, "    ");
4578                 }
4579                 needSep = true;
4580             }
4581 
4582             if (mRestartingServices.size() > 0) {
4583                 printed = false;
4584                 for (int i=0; i<mRestartingServices.size(); i++) {
4585                     ServiceRecord r = mRestartingServices.get(i);
4586                     if (!matcher.match(r, r.name)) {
4587                         continue;
4588                     }
4589                     if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4590                         continue;
4591                     }
4592                     printedAnything = true;
4593                     if (!printed) {
4594                         if (needSep) pw.println();
4595                         needSep = true;
4596                         pw.println("  Restarting services:");
4597                         printed = true;
4598                     }
4599                     pw.print("  * Restarting "); pw.println(r);
4600                     r.dump(pw, "    ");
4601                 }
4602                 needSep = true;
4603             }
4604 
4605             if (mDestroyingServices.size() > 0) {
4606                 printed = false;
4607                 for (int i=0; i< mDestroyingServices.size(); i++) {
4608                     ServiceRecord r = mDestroyingServices.get(i);
4609                     if (!matcher.match(r, r.name)) {
4610                         continue;
4611                     }
4612                     if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4613                         continue;
4614                     }
4615                     printedAnything = true;
4616                     if (!printed) {
4617                         if (needSep) pw.println();
4618                         needSep = true;
4619                         pw.println("  Destroying services:");
4620                         printed = true;
4621                     }
4622                     pw.print("  * Destroy "); pw.println(r);
4623                     r.dump(pw, "    ");
4624                 }
4625                 needSep = true;
4626             }
4627 
4628             if (dumpAll) {
4629                 printed = false;
4630                 for (int ic=0; ic<mServiceConnections.size(); ic++) {
4631                     ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
4632                     for (int i=0; i<r.size(); i++) {
4633                         ConnectionRecord cr = r.get(i);
4634                         if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
4635                             continue;
4636                         }
4637                         if (dumpPackage != null && (cr.binding.client == null
4638                                 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
4639                             continue;
4640                         }
4641                         printedAnything = true;
4642                         if (!printed) {
4643                             if (needSep) pw.println();
4644                             needSep = true;
4645                             pw.println("  Connection bindings to services:");
4646                             printed = true;
4647                         }
4648                         pw.print("  * "); pw.println(cr);
4649                         cr.dump(pw, "    ");
4650                     }
4651                 }
4652             }
4653 
4654             if (matcher.all) {
4655                 final long nowElapsed = SystemClock.elapsedRealtime();
4656                 final int[] users = mAm.mUserController.getUsers();
4657                 for (int user : users) {
4658                     boolean printedUser = false;
4659                     ServiceMap smap = mServiceMap.get(user);
4660                     if (smap == null) {
4661                         continue;
4662                     }
4663                     for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) {
4664                         ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
4665                         if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) {
4666                             continue;
4667                         }
4668                         if (!printedUser) {
4669                             printedUser = true;
4670                             printedAnything = true;
4671                             if (needSep) pw.println();
4672                             needSep = true;
4673                             pw.print("Active foreground apps - user ");
4674                             pw.print(user);
4675                             pw.println(":");
4676                         }
4677                         pw.print("  #");
4678                         pw.print(i);
4679                         pw.print(": ");
4680                         pw.println(aa.mPackageName);
4681                         if (aa.mLabel != null) {
4682                             pw.print("    mLabel=");
4683                             pw.println(aa.mLabel);
4684                         }
4685                         pw.print("    mNumActive=");
4686                         pw.print(aa.mNumActive);
4687                         pw.print(" mAppOnTop=");
4688                         pw.print(aa.mAppOnTop);
4689                         pw.print(" mShownWhileTop=");
4690                         pw.print(aa.mShownWhileTop);
4691                         pw.print(" mShownWhileScreenOn=");
4692                         pw.println(aa.mShownWhileScreenOn);
4693                         pw.print("    mStartTime=");
4694                         TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw);
4695                         pw.print(" mStartVisibleTime=");
4696                         TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw);
4697                         pw.println();
4698                         if (aa.mEndTime != 0) {
4699                             pw.print("    mEndTime=");
4700                             TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw);
4701                             pw.println();
4702                         }
4703                     }
4704                     if (smap.hasMessagesOrCallbacks()) {
4705                         if (needSep) {
4706                             pw.println();
4707                         }
4708                         printedAnything = true;
4709                         needSep = true;
4710                         pw.print("  Handler - user ");
4711                         pw.print(user);
4712                         pw.println(":");
4713                         smap.dumpMine(new PrintWriterPrinter(pw), "    ");
4714                     }
4715                 }
4716             }
4717 
4718             if (!printedAnything) {
4719                 pw.println("  (nothing)");
4720             }
4721         }
4722     }
4723 
newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)4724     ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4725             int opti, boolean dumpAll, String dumpPackage) {
4726         return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
4727     }
4728 
dumpDebug(ProtoOutputStream proto, long fieldId)4729     protected void dumpDebug(ProtoOutputStream proto, long fieldId) {
4730         synchronized (mAm) {
4731             final long outterToken = proto.start(fieldId);
4732             int[] users = mAm.mUserController.getUsers();
4733             for (int user : users) {
4734                 ServiceMap smap = mServiceMap.get(user);
4735                 if (smap == null) {
4736                     continue;
4737                 }
4738                 long token = proto.start(ActiveServicesProto.SERVICES_BY_USERS);
4739                 proto.write(ActiveServicesProto.ServicesByUser.USER_ID, user);
4740                 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
4741                 for (int i=0; i<alls.size(); i++) {
4742                     alls.valueAt(i).dumpDebug(proto,
4743                             ActiveServicesProto.ServicesByUser.SERVICE_RECORDS);
4744                 }
4745                 proto.end(token);
4746             }
4747             proto.end(outterToken);
4748         }
4749     }
4750 
4751     /**
4752      * There are three ways to call this:
4753      *  - no service specified: dump all the services
4754      *  - a flattened component name that matched an existing service was specified as the
4755      *    first arg: dump that one service
4756      *  - the first arg isn't the flattened component name of an existing service:
4757      *    dump all services whose component contains the first arg as a substring
4758      */
dumpService(FileDescriptor fd, PrintWriter pw, final String name, String[] args, int opti, boolean dumpAll)4759     protected boolean dumpService(FileDescriptor fd, PrintWriter pw, final String name,
4760             String[] args, int opti, boolean dumpAll) {
4761         final ArrayList<ServiceRecord> services = new ArrayList<>();
4762 
4763         final Predicate<ServiceRecord> filter = DumpUtils.filterRecord(name);
4764 
4765         synchronized (mAm) {
4766             int[] users = mAm.mUserController.getUsers();
4767 
4768             for (int user : users) {
4769                 ServiceMap smap = mServiceMap.get(user);
4770                 if (smap == null) {
4771                     continue;
4772                 }
4773                 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
4774                 for (int i=0; i<alls.size(); i++) {
4775                     ServiceRecord r1 = alls.valueAt(i);
4776 
4777                     if (filter.test(r1)) {
4778                         services.add(r1);
4779                     }
4780                 }
4781             }
4782         }
4783 
4784         if (services.size() <= 0) {
4785             return false;
4786         }
4787 
4788         // Sort by component name.
4789         services.sort(Comparator.comparing(WithComponentName::getComponentName));
4790 
4791         boolean needSep = false;
4792         for (int i=0; i<services.size(); i++) {
4793             if (needSep) {
4794                 pw.println();
4795             }
4796             needSep = true;
4797             dumpService("", fd, pw, services.get(i), args, dumpAll);
4798         }
4799         return true;
4800     }
4801 
4802     /**
4803      * Invokes IApplicationThread.dumpService() on the thread of the specified service if
4804      * there is a thread associated with the service.
4805      */
dumpService(String prefix, FileDescriptor fd, PrintWriter pw, final ServiceRecord r, String[] args, boolean dumpAll)4806     private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
4807             final ServiceRecord r, String[] args, boolean dumpAll) {
4808         String innerPrefix = prefix + "  ";
4809         synchronized (mAm) {
4810             pw.print(prefix); pw.print("SERVICE ");
4811                     pw.print(r.shortInstanceName); pw.print(" ");
4812                     pw.print(Integer.toHexString(System.identityHashCode(r)));
4813                     pw.print(" pid=");
4814                     if (r.app != null) pw.println(r.app.pid);
4815                     else pw.println("(not running)");
4816             if (dumpAll) {
4817                 r.dump(pw, innerPrefix);
4818             }
4819         }
4820         if (r.app != null && r.app.thread != null) {
4821             pw.print(prefix); pw.println("  Client:");
4822             pw.flush();
4823             try {
4824                 TransferPipe tp = new TransferPipe();
4825                 try {
4826                     r.app.thread.dumpService(tp.getWriteFd(), r, args);
4827                     tp.setBufferPrefix(prefix + "    ");
4828                     tp.go(fd);
4829                 } finally {
4830                     tp.kill();
4831                 }
4832             } catch (IOException e) {
4833                 pw.println(prefix + "    Failure while dumping the service: " + e);
4834             } catch (RemoteException e) {
4835                 pw.println(prefix + "    Got a RemoteException while dumping the service");
4836             }
4837         }
4838     }
4839 
4840     /**
4841      * Should allow while-in-use permissions in foreground service or not.
4842      * while-in-use permissions in FGS started from background might be restricted.
4843      * @param callingPackage caller app's package name.
4844      * @param callingUid caller app's uid.
4845      * @param intent intent to start/bind service.
4846      * @param r the service to start.
4847      * @return true if allow, false otherwise.
4848      */
shouldAllowWhileInUsePermissionInFgsLocked(String callingPackage, int callingPid, int callingUid, Intent intent, ServiceRecord r, boolean allowBackgroundActivityStarts)4849     private boolean shouldAllowWhileInUsePermissionInFgsLocked(String callingPackage,
4850             int callingPid, int callingUid, Intent intent, ServiceRecord r,
4851             boolean allowBackgroundActivityStarts) {
4852         // Is the background FGS start restriction turned on?
4853         if (!mAm.mConstants.mFlagBackgroundFgsStartRestrictionEnabled) {
4854             return true;
4855         }
4856         // Is the allow activity background start flag on?
4857         if (allowBackgroundActivityStarts) {
4858             return true;
4859         }
4860 
4861         boolean isCallerSystem = false;
4862         final int callingAppId = UserHandle.getAppId(callingUid);
4863         switch (callingAppId) {
4864             case ROOT_UID:
4865             case SYSTEM_UID:
4866             case NFC_UID:
4867             case SHELL_UID:
4868                 isCallerSystem = true;
4869                 break;
4870             default:
4871                 isCallerSystem = false;
4872                 break;
4873         }
4874 
4875         if (isCallerSystem) {
4876             return true;
4877         }
4878 
4879         if (r.app != null) {
4880             ActiveInstrumentation instr = r.app.getActiveInstrumentation();
4881             if (instr != null && instr.mHasBackgroundActivityStartsPermission) {
4882                 return true;
4883             }
4884         }
4885 
4886         final boolean hasAllowBackgroundActivityStartsToken = r.app != null
4887                 ? !r.app.mAllowBackgroundActivityStartsTokens.isEmpty() : false;
4888         if (hasAllowBackgroundActivityStartsToken) {
4889             return true;
4890         }
4891 
4892         if (mAm.checkPermission(START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid)
4893                 == PERMISSION_GRANTED) {
4894             return true;
4895         }
4896 
4897         // Is the calling UID at PROCESS_STATE_TOP or above?
4898         final boolean isCallingUidTopApp = appIsTopLocked(callingUid);
4899         if (isCallingUidTopApp) {
4900             return true;
4901         }
4902         // Does the calling UID have any visible activity?
4903         final boolean isCallingUidVisible = mAm.mAtmInternal.isUidForeground(callingUid);
4904         if (isCallingUidVisible) {
4905             return true;
4906         }
4907 
4908         final boolean isWhiteListedPackage =
4909                 mWhiteListAllowWhileInUsePermissionInFgs.contains(callingPackage);
4910         if (isWhiteListedPackage) {
4911             return true;
4912         }
4913 
4914         // Is the calling UID a device owner app?
4915         final boolean isDeviceOwner = mAm.mInternal.isDeviceOwner(callingUid);
4916         if (isDeviceOwner) {
4917             return true;
4918         }
4919         return false;
4920     }
4921 }
4922