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