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