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