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