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 com.android.server.am.ActivityManagerDebugConfig.*;
     20 
     21 import java.io.FileDescriptor;
     22 import java.io.IOException;
     23 import java.io.PrintWriter;
     24 import java.io.StringWriter;
     25 import java.util.ArrayList;
     26 import java.util.HashSet;
     27 import java.util.Iterator;
     28 import java.util.List;
     29 import java.util.Set;
     30 
     31 import android.app.ActivityThread;
     32 import android.app.AppOpsManager;
     33 import android.content.IIntentSender;
     34 import android.content.IntentSender;
     35 import android.os.Build;
     36 import android.os.Bundle;
     37 import android.os.DeadObjectException;
     38 import android.os.Handler;
     39 import android.os.Looper;
     40 import android.os.RemoteCallback;
     41 import android.os.SystemProperties;
     42 import android.os.TransactionTooLargeException;
     43 import android.util.ArrayMap;
     44 import android.util.ArraySet;
     45 
     46 import com.android.internal.app.procstats.ServiceState;
     47 import com.android.internal.os.BatteryStatsImpl;
     48 import com.android.internal.os.TransferPipe;
     49 import com.android.internal.util.FastPrintWriter;
     50 import com.android.server.am.ActivityManagerService.ItemMatcher;
     51 import com.android.server.am.ActivityManagerService.NeededUriGrants;
     52 
     53 import android.app.ActivityManager;
     54 import android.app.AppGlobals;
     55 import android.app.IApplicationThread;
     56 import android.app.IServiceConnection;
     57 import android.app.Notification;
     58 import android.app.PendingIntent;
     59 import android.app.Service;
     60 import android.content.ComponentName;
     61 import android.content.Context;
     62 import android.content.Intent;
     63 import android.content.pm.ApplicationInfo;
     64 import android.content.pm.PackageManager;
     65 import android.content.pm.ResolveInfo;
     66 import android.content.pm.ServiceInfo;
     67 import android.os.Binder;
     68 import android.os.IBinder;
     69 import android.os.Message;
     70 import android.os.Process;
     71 import android.os.RemoteException;
     72 import android.os.SystemClock;
     73 import android.os.UserHandle;
     74 import android.util.EventLog;
     75 import android.util.Slog;
     76 import android.util.SparseArray;
     77 import android.util.TimeUtils;
     78 
     79 public final class ActiveServices {
     80     private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM;
     81     private static final String TAG_MU = TAG + POSTFIX_MU;
     82     private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
     83     private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING;
     84 
     85     private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE;
     86     private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE;
     87 
     88     private static final boolean LOG_SERVICE_START_STOP = false;
     89 
     90     // How long we wait for a service to finish executing.
     91     static final int SERVICE_TIMEOUT = 20*1000;
     92 
     93     // How long we wait for a service to finish executing.
     94     static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
     95 
     96     // How long a service needs to be running until restarting its process
     97     // is no longer considered to be a relaunch of the service.
     98     static final int SERVICE_RESTART_DURATION = 1*1000;
     99 
    100     // How long a service needs to be running until it will start back at
    101     // SERVICE_RESTART_DURATION after being killed.
    102     static final int SERVICE_RESET_RUN_DURATION = 60*1000;
    103 
    104     // Multiplying factor to increase restart duration time by, for each time
    105     // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
    106     static final int SERVICE_RESTART_DURATION_FACTOR = 4;
    107 
    108     // The minimum amount of time between restarting services that we allow.
    109     // That is, when multiple services are restarting, we won't allow each
    110     // to restart less than this amount of time from the last one.
    111     static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
    112 
    113     // Maximum amount of time for there to be no activity on a service before
    114     // we consider it non-essential and allow its process to go on the
    115     // LRU background list.
    116     static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
    117 
    118     // How long we wait for a background started service to stop itself before
    119     // allowing the next pending start to run.
    120     static final int BG_START_TIMEOUT = 15*1000;
    121 
    122     final ActivityManagerService mAm;
    123 
    124     // Maximum number of services that we allow to start in the background
    125     // at the same time.
    126     final int mMaxStartingBackground;
    127 
    128     final SparseArray<ServiceMap> mServiceMap = new SparseArray<>();
    129 
    130     /**
    131      * All currently bound service connections.  Keys are the IBinder of
    132      * the client's IServiceConnection.
    133      */
    134     final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>();
    135 
    136     /**
    137      * List of services that we have been asked to start,
    138      * but haven't yet been able to.  It is used to hold start requests
    139      * while waiting for their corresponding application thread to get
    140      * going.
    141      */
    142     final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>();
    143 
    144     /**
    145      * List of services that are scheduled to restart following a crash.
    146      */
    147     final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
    148 
    149     /**
    150      * List of services that are in the process of being destroyed.
    151      */
    152     final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>();
    153 
    154     /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */
    155     private ArrayList<ServiceRecord> mTmpCollectionResults = null;
    156 
    157     /** Amount of time to allow a last ANR message to exist before freeing the memory. */
    158     static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
    159 
    160     String mLastAnrDump;
    161 
    162     final Runnable mLastAnrDumpClearer = new Runnable() {
    163         @Override public void run() {
    164             synchronized (mAm) {
    165                 mLastAnrDump = null;
    166             }
    167         }
    168     };
    169 
    170     /**
    171      * Information about services for a single user.
    172      */
    173     class ServiceMap extends Handler {
    174         final int mUserId;
    175         final ArrayMap<ComponentName, ServiceRecord> mServicesByName = new ArrayMap<>();
    176         final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>();
    177 
    178         final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>();
    179         /* XXX eventually I'd like to have this based on processes instead of services.
    180          * That is, if we try to start two services in a row both running in the same
    181          * process, this should be one entry in mStartingBackground for that one process
    182          * that remains until all services in it are done.
    183         final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
    184                 = new ArrayMap<ProcessRecord, DelayingProcess>();
    185         final ArrayList<DelayingProcess> mStartingProcessList
    186                 = new ArrayList<DelayingProcess>();
    187         */
    188 
    189         final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>();
    190 
    191         static final int MSG_BG_START_TIMEOUT = 1;
    192 
    193         ServiceMap(Looper looper, int userId) {
    194             super(looper);
    195             mUserId = userId;
    196         }
    197 
    198         @Override
    199         public void handleMessage(Message msg) {
    200             switch (msg.what) {
    201                 case MSG_BG_START_TIMEOUT: {
    202                     synchronized (mAm) {
    203                         rescheduleDelayedStarts();
    204                     }
    205                 } break;
    206             }
    207         }
    208 
    209         void ensureNotStartingBackground(ServiceRecord r) {
    210             if (mStartingBackground.remove(r)) {
    211                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
    212                         "No longer background starting: " + r);
    213                 rescheduleDelayedStarts();
    214             }
    215             if (mDelayedStartList.remove(r)) {
    216                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
    217             }
    218         }
    219 
    220         void rescheduleDelayedStarts() {
    221             removeMessages(MSG_BG_START_TIMEOUT);
    222             final long now = SystemClock.uptimeMillis();
    223             for (int i=0, N=mStartingBackground.size(); i<N; i++) {
    224                 ServiceRecord r = mStartingBackground.get(i);
    225                 if (r.startingBgTimeout <= now) {
    226                     Slog.i(TAG, "Waited long enough for: " + r);
    227                     mStartingBackground.remove(i);
    228                     N--;
    229                     i--;
    230                 }
    231             }
    232             while (mDelayedStartList.size() > 0
    233                     && mStartingBackground.size() < mMaxStartingBackground) {
    234                 ServiceRecord r = mDelayedStartList.remove(0);
    235                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
    236                         "REM FR DELAY LIST (exec next): " + r);
    237                 if (r.pendingStarts.size() <= 0) {
    238                     Slog.w(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
    239                             + " delayedStop=" + r.delayedStop);
    240                 }
    241                 if (DEBUG_DELAYED_SERVICE) {
    242                     if (mDelayedStartList.size() > 0) {
    243                         Slog.v(TAG_SERVICE, "Remaining delayed list:");
    244                         for (int i=0; i<mDelayedStartList.size(); i++) {
    245                             Slog.v(TAG_SERVICE, "  #" + i + ": " + mDelayedStartList.get(i));
    246                         }
    247                     }
    248                 }
    249                 r.delayed = false;
    250                 try {
    251                     startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false, true);
    252                 } catch (TransactionTooLargeException e) {
    253                     // Ignore, nobody upstack cares.
    254                 }
    255             }
    256             if (mStartingBackground.size() > 0) {
    257                 ServiceRecord next = mStartingBackground.get(0);
    258                 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
    259                 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
    260                         + ", can delay others up to " + when);
    261                 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
    262                 sendMessageAtTime(msg, when);
    263             }
    264             if (mStartingBackground.size() < mMaxStartingBackground) {
    265                 mAm.backgroundServicesFinishedLocked(mUserId);
    266             }
    267         }
    268     }
    269 
    270     public ActiveServices(ActivityManagerService service) {
    271         mAm = service;
    272         int maxBg = 0;
    273         try {
    274             maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
    275         } catch(RuntimeException e) {
    276         }
    277         mMaxStartingBackground = maxBg > 0
    278                 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
    279     }
    280 
    281     ServiceRecord getServiceByName(ComponentName name, int callingUser) {
    282         // TODO: Deal with global services
    283         if (DEBUG_MU)
    284             Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
    285         return getServiceMap(callingUser).mServicesByName.get(name);
    286     }
    287 
    288     boolean hasBackgroundServices(int callingUser) {
    289         ServiceMap smap = mServiceMap.get(callingUser);
    290         return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
    291     }
    292 
    293     private ServiceMap getServiceMap(int callingUser) {
    294         ServiceMap smap = mServiceMap.get(callingUser);
    295         if (smap == null) {
    296             smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
    297             mServiceMap.put(callingUser, smap);
    298         }
    299         return smap;
    300     }
    301 
    302     ArrayMap<ComponentName, ServiceRecord> getServices(int callingUser) {
    303         return getServiceMap(callingUser).mServicesByName;
    304     }
    305 
    306     ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
    307             int callingPid, int callingUid, String callingPackage, final int userId)
    308             throws TransactionTooLargeException {
    309         if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
    310                 + " type=" + resolvedType + " args=" + service.getExtras());
    311 
    312         final boolean callerFg;
    313         if (caller != null) {
    314             final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
    315             if (callerApp == null) {
    316                 throw new SecurityException(
    317                         "Unable to find app for caller " + caller
    318                         + " (pid=" + Binder.getCallingPid()
    319                         + ") when starting service " + service);
    320             }
    321             callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
    322         } else {
    323             callerFg = true;
    324         }
    325 
    326 
    327         ServiceLookupResult res =
    328             retrieveServiceLocked(service, resolvedType, callingPackage,
    329                     callingPid, callingUid, userId, true, callerFg, false);
    330         if (res == null) {
    331             return null;
    332         }
    333         if (res.record == null) {
    334             return new ComponentName("!", res.permission != null
    335                     ? res.permission : "private to package");
    336         }
    337 
    338         ServiceRecord r = res.record;
    339 
    340         if (!mAm.mUserController.exists(r.userId)) {
    341             Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
    342             return null;
    343         }
    344 
    345         if (!r.startRequested) {
    346             final long token = Binder.clearCallingIdentity();
    347             try {
    348                 // Before going further -- if this app is not allowed to run in the
    349                 // background, then at this point we aren't going to let it period.
    350                 final int allowed = mAm.checkAllowBackgroundLocked(
    351                         r.appInfo.uid, r.packageName, callingPid, true);
    352                 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
    353                     Slog.w(TAG, "Background start not allowed: service "
    354                             + service + " to " + r.name.flattenToShortString()
    355                             + " from pid=" + callingPid + " uid=" + callingUid
    356                             + " pkg=" + callingPackage);
    357                     return null;
    358                 }
    359             } finally {
    360                 Binder.restoreCallingIdentity(token);
    361             }
    362         }
    363 
    364         NeededUriGrants neededGrants = mAm.checkGrantUriPermissionFromIntentLocked(
    365                 callingUid, r.packageName, service, service.getFlags(), null, r.userId);
    366 
    367         // If permissions need a review before any of the app components can run,
    368         // we do not start the service and launch a review activity if the calling app
    369         // is in the foreground passing it a pending intent to start the service when
    370         // review is completed.
    371         if (Build.PERMISSIONS_REVIEW_REQUIRED) {
    372             if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage,
    373                     callingUid, service, callerFg, userId)) {
    374                 return null;
    375             }
    376         }
    377 
    378         if (unscheduleServiceRestartLocked(r, callingUid, false)) {
    379             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
    380         }
    381         r.lastActivity = SystemClock.uptimeMillis();
    382         r.startRequested = true;
    383         r.delayedStop = false;
    384         r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
    385                 service, neededGrants));
    386 
    387         final ServiceMap smap = getServiceMap(r.userId);
    388         boolean addToStarting = false;
    389         if (!callerFg && r.app == null
    390                 && mAm.mUserController.hasStartedUserState(r.userId)) {
    391             ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
    392             if (proc == null || proc.curProcState > ActivityManager.PROCESS_STATE_RECEIVER) {
    393                 // If this is not coming from a foreground caller, then we may want
    394                 // to delay the start if there are already other background services
    395                 // that are starting.  This is to avoid process start spam when lots
    396                 // of applications are all handling things like connectivity broadcasts.
    397                 // We only do this for cached processes, because otherwise an application
    398                 // can have assumptions about calling startService() for a service to run
    399                 // in its own process, and for that process to not be killed before the
    400                 // service is started.  This is especially the case for receivers, which
    401                 // may start a service in onReceive() to do some additional work and have
    402                 // initialized some global state as part of that.
    403                 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
    404                         + r + " in " + proc);
    405                 if (r.delayed) {
    406                     // This service is already scheduled for a delayed start; just leave
    407                     // it still waiting.
    408                     if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
    409                     return r.name;
    410                 }
    411                 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
    412                     // Something else is starting, delay!
    413                     Slog.i(TAG_SERVICE, "Delaying start of: " + r);
    414                     smap.mDelayedStartList.add(r);
    415                     r.delayed = true;
    416                     return r.name;
    417                 }
    418                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
    419                 addToStarting = true;
    420             } else if (proc.curProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
    421                 // We slightly loosen when we will enqueue this new service as a background
    422                 // starting service we are waiting for, to also include processes that are
    423                 // currently running other services or receivers.
    424                 addToStarting = true;
    425                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
    426                         "Not delaying, but counting as bg: " + r);
    427             } else if (DEBUG_DELAYED_STARTS) {
    428                 StringBuilder sb = new StringBuilder(128);
    429                 sb.append("Not potential delay (state=").append(proc.curProcState)
    430                         .append(' ').append(proc.adjType);
    431                 String reason = proc.makeAdjReason();
    432                 if (reason != null) {
    433                     sb.append(' ');
    434                     sb.append(reason);
    435                 }
    436                 sb.append("): ");
    437                 sb.append(r.toString());
    438                 Slog.v(TAG_SERVICE, sb.toString());
    439             }
    440         } else if (DEBUG_DELAYED_STARTS) {
    441             if (callerFg) {
    442                 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
    443                         + callingUid + " pid=" + callingPid + "): " + r);
    444             } else if (r.app != null) {
    445                 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
    446             } else {
    447                 Slog.v(TAG_SERVICE,
    448                         "Not potential delay (user " + r.userId + " not started): " + r);
    449             }
    450         }
    451 
    452         return startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
    453     }
    454 
    455     private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
    456             String callingPackage, int callingUid, Intent service, boolean callerFg,
    457             final int userId) {
    458         if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
    459                 r.packageName, r.userId)) {
    460 
    461             // Show a permission review UI only for starting from a foreground app
    462             if (!callerFg) {
    463                 Slog.w(TAG, "u" + r.userId + " Starting a service in package"
    464                         + r.packageName + " requires a permissions review");
    465                 return false;
    466             }
    467 
    468             IIntentSender target = mAm.getIntentSenderLocked(
    469                     ActivityManager.INTENT_SENDER_SERVICE, callingPackage,
    470                     callingUid, userId, null, null, 0, new Intent[]{service},
    471                     new String[]{service.resolveType(mAm.mContext.getContentResolver())},
    472                     PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
    473                             | PendingIntent.FLAG_IMMUTABLE, null);
    474 
    475             final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
    476             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
    477                     | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
    478             intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
    479             intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
    480 
    481             if (DEBUG_PERMISSIONS_REVIEW) {
    482                 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
    483                         + r.packageName);
    484             }
    485 
    486             mAm.mHandler.post(new Runnable() {
    487                 @Override
    488                 public void run() {
    489                     mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
    490                 }
    491             });
    492 
    493             return false;
    494         }
    495 
    496         return  true;
    497     }
    498 
    499     ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
    500             boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
    501         ServiceState stracker = r.getTracker();
    502         if (stracker != null) {
    503             stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
    504         }
    505         r.callStart = false;
    506         synchronized (r.stats.getBatteryStats()) {
    507             r.stats.startRunningLocked();
    508         }
    509         String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
    510         if (error != null) {
    511             return new ComponentName("!!", error);
    512         }
    513 
    514         if (r.startRequested && addToStarting) {
    515             boolean first = smap.mStartingBackground.size() == 0;
    516             smap.mStartingBackground.add(r);
    517             r.startingBgTimeout = SystemClock.uptimeMillis() + BG_START_TIMEOUT;
    518             if (DEBUG_DELAYED_SERVICE) {
    519                 RuntimeException here = new RuntimeException("here");
    520                 here.fillInStackTrace();
    521                 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
    522             } else if (DEBUG_DELAYED_STARTS) {
    523                 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
    524             }
    525             if (first) {
    526                 smap.rescheduleDelayedStarts();
    527             }
    528         } else if (callerFg) {
    529             smap.ensureNotStartingBackground(r);
    530         }
    531 
    532         return r.name;
    533     }
    534 
    535     private void stopServiceLocked(ServiceRecord service) {
    536         if (service.delayed) {
    537             // If service isn't actually running, but is is being held in the
    538             // delayed list, then we need to keep it started but note that it
    539             // should be stopped once no longer delayed.
    540             if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
    541             service.delayedStop = true;
    542             return;
    543         }
    544         synchronized (service.stats.getBatteryStats()) {
    545             service.stats.stopRunningLocked();
    546         }
    547         service.startRequested = false;
    548         if (service.tracker != null) {
    549             service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
    550                     SystemClock.uptimeMillis());
    551         }
    552         service.callStart = false;
    553         bringDownServiceIfNeededLocked(service, false, false);
    554     }
    555 
    556     int stopServiceLocked(IApplicationThread caller, Intent service,
    557             String resolvedType, int userId) {
    558         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
    559                 + " type=" + resolvedType);
    560 
    561         final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
    562         if (caller != null && callerApp == null) {
    563             throw new SecurityException(
    564                     "Unable to find app for caller " + caller
    565                     + " (pid=" + Binder.getCallingPid()
    566                     + ") when stopping service " + service);
    567         }
    568 
    569         // If this service is active, make sure it is stopped.
    570         ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, null,
    571                 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false);
    572         if (r != null) {
    573             if (r.record != null) {
    574                 final long origId = Binder.clearCallingIdentity();
    575                 try {
    576                     stopServiceLocked(r.record);
    577                 } finally {
    578                     Binder.restoreCallingIdentity(origId);
    579                 }
    580                 return 1;
    581             }
    582             return -1;
    583         }
    584 
    585         return 0;
    586     }
    587 
    588     void stopInBackgroundLocked(int uid) {
    589         // Stop all services associated with this uid due to it going to the background
    590         // stopped state.
    591         ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
    592         ArrayList<ServiceRecord> stopping = null;
    593         if (services != null) {
    594             for (int i=services.mServicesByName.size()-1; i>=0; i--) {
    595                 ServiceRecord service = services.mServicesByName.valueAt(i);
    596                 if (service.appInfo.uid == uid && service.startRequested) {
    597                     if (mAm.mAppOpsService.noteOperation(AppOpsManager.OP_RUN_IN_BACKGROUND,
    598                             uid, service.packageName) != AppOpsManager.MODE_ALLOWED) {
    599                         if (stopping == null) {
    600                             stopping = new ArrayList<>();
    601                             stopping.add(service);
    602                         }
    603                     }
    604                 }
    605             }
    606             if (stopping != null) {
    607                 for (int i=stopping.size()-1; i>=0; i--) {
    608                     ServiceRecord service = stopping.get(i);
    609                     service.delayed = false;
    610                     services.ensureNotStartingBackground(service);
    611                     stopServiceLocked(service);
    612                 }
    613             }
    614         }
    615     }
    616 
    617     IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
    618         ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, callingPackage,
    619                 Binder.getCallingPid(), Binder.getCallingUid(),
    620                 UserHandle.getCallingUserId(), false, false, false);
    621 
    622         IBinder ret = null;
    623         if (r != null) {
    624             // r.record is null if findServiceLocked() failed the caller permission check
    625             if (r.record == null) {
    626                 throw new SecurityException(
    627                         "Permission Denial: Accessing service"
    628                         + " from pid=" + Binder.getCallingPid()
    629                         + ", uid=" + Binder.getCallingUid()
    630                         + " requires " + r.permission);
    631             }
    632             IntentBindRecord ib = r.record.bindings.get(r.record.intent);
    633             if (ib != null) {
    634                 ret = ib.binder;
    635             }
    636         }
    637 
    638         return ret;
    639     }
    640 
    641     boolean stopServiceTokenLocked(ComponentName className, IBinder token,
    642             int startId) {
    643         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
    644                 + " " + token + " startId=" + startId);
    645         ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
    646         if (r != null) {
    647             if (startId >= 0) {
    648                 // Asked to only stop if done with all work.  Note that
    649                 // to avoid leaks, we will take this as dropping all
    650                 // start items up to and including this one.
    651                 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
    652                 if (si != null) {
    653                     while (r.deliveredStarts.size() > 0) {
    654                         ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
    655                         cur.removeUriPermissionsLocked();
    656                         if (cur == si) {
    657                             break;
    658                         }
    659                     }
    660                 }
    661 
    662                 if (r.getLastStartId() != startId) {
    663                     return false;
    664                 }
    665 
    666                 if (r.deliveredStarts.size() > 0) {
    667                     Slog.w(TAG, "stopServiceToken startId " + startId
    668                             + " is last, but have " + r.deliveredStarts.size()
    669                             + " remaining args");
    670                 }
    671             }
    672 
    673             synchronized (r.stats.getBatteryStats()) {
    674                 r.stats.stopRunningLocked();
    675             }
    676             r.startRequested = false;
    677             if (r.tracker != null) {
    678                 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
    679                         SystemClock.uptimeMillis());
    680             }
    681             r.callStart = false;
    682             final long origId = Binder.clearCallingIdentity();
    683             bringDownServiceIfNeededLocked(r, false, false);
    684             Binder.restoreCallingIdentity(origId);
    685             return true;
    686         }
    687         return false;
    688     }
    689 
    690     public void setServiceForegroundLocked(ComponentName className, IBinder token,
    691             int id, Notification notification, int flags) {
    692         final int userId = UserHandle.getCallingUserId();
    693         final long origId = Binder.clearCallingIdentity();
    694         try {
    695             ServiceRecord r = findServiceLocked(className, token, userId);
    696             if (r != null) {
    697                 if (id != 0) {
    698                     if (notification == null) {
    699                         throw new IllegalArgumentException("null notification");
    700                     }
    701                     if (r.foregroundId != id) {
    702                         r.cancelNotification();
    703                         r.foregroundId = id;
    704                     }
    705                     notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
    706                     r.foregroundNoti = notification;
    707                     r.isForeground = true;
    708                     r.postNotification();
    709                     if (r.app != null) {
    710                         updateServiceForegroundLocked(r.app, true);
    711                     }
    712                     getServiceMap(r.userId).ensureNotStartingBackground(r);
    713                     mAm.notifyPackageUse(r.serviceInfo.packageName,
    714                                          PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
    715                 } else {
    716                     if (r.isForeground) {
    717                         r.isForeground = false;
    718                         if (r.app != null) {
    719                             mAm.updateLruProcessLocked(r.app, false, null);
    720                             updateServiceForegroundLocked(r.app, true);
    721                         }
    722                     }
    723                     if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
    724                         r.cancelNotification();
    725                         r.foregroundId = 0;
    726                         r.foregroundNoti = null;
    727                     } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
    728                         r.stripForegroundServiceFlagFromNotification();
    729                         if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
    730                             r.foregroundId = 0;
    731                             r.foregroundNoti = null;
    732                         }
    733                     }
    734                 }
    735             }
    736         } finally {
    737             Binder.restoreCallingIdentity(origId);
    738         }
    739     }
    740 
    741     private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
    742         boolean anyForeground = false;
    743         for (int i=proc.services.size()-1; i>=0; i--) {
    744             ServiceRecord sr = proc.services.valueAt(i);
    745             if (sr.isForeground) {
    746                 anyForeground = true;
    747                 break;
    748             }
    749         }
    750         mAm.updateProcessForegroundLocked(proc, anyForeground, oomAdj);
    751     }
    752 
    753     private void updateWhitelistManagerLocked(ProcessRecord proc) {
    754         proc.whitelistManager = false;
    755         for (int i=proc.services.size()-1; i>=0; i--) {
    756             ServiceRecord sr = proc.services.valueAt(i);
    757             if (sr.whitelistManager) {
    758                 proc.whitelistManager = true;
    759                 break;
    760             }
    761         }
    762     }
    763 
    764     public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
    765         ArraySet<ProcessRecord> updatedProcesses = null;
    766         for (int i = 0; i < clientProc.connections.size(); i++) {
    767             final ConnectionRecord conn = clientProc.connections.valueAt(i);
    768             final ProcessRecord proc = conn.binding.service.app;
    769             if (proc == null || proc == clientProc) {
    770                 continue;
    771             } else if (updatedProcesses == null) {
    772                 updatedProcesses = new ArraySet<>();
    773             } else if (updatedProcesses.contains(proc)) {
    774                 continue;
    775             }
    776             updatedProcesses.add(proc);
    777             updateServiceClientActivitiesLocked(proc, null, false);
    778         }
    779     }
    780 
    781     private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
    782             ConnectionRecord modCr, boolean updateLru) {
    783         if (modCr != null && modCr.binding.client != null) {
    784             if (modCr.binding.client.activities.size() <= 0) {
    785                 // This connection is from a client without activities, so adding
    786                 // and removing is not interesting.
    787                 return false;
    788             }
    789         }
    790 
    791         boolean anyClientActivities = false;
    792         for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
    793             ServiceRecord sr = proc.services.valueAt(i);
    794             for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) {
    795                 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni);
    796                 for (int cri=clist.size()-1; cri>=0; cri--) {
    797                     ConnectionRecord cr = clist.get(cri);
    798                     if (cr.binding.client == null || cr.binding.client == proc) {
    799                         // Binding to ourself is not interesting.
    800                         continue;
    801                     }
    802                     if (cr.binding.client.activities.size() > 0) {
    803                         anyClientActivities = true;
    804                         break;
    805                     }
    806                 }
    807             }
    808         }
    809         if (anyClientActivities != proc.hasClientActivities) {
    810             proc.hasClientActivities = anyClientActivities;
    811             if (updateLru) {
    812                 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
    813             }
    814             return true;
    815         }
    816         return false;
    817     }
    818 
    819     int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
    820             String resolvedType, final IServiceConnection connection, int flags,
    821             String callingPackage, final int userId) throws TransactionTooLargeException {
    822         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
    823                 + " type=" + resolvedType + " conn=" + connection.asBinder()
    824                 + " flags=0x" + Integer.toHexString(flags));
    825         final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
    826         if (callerApp == null) {
    827             throw new SecurityException(
    828                     "Unable to find app for caller " + caller
    829                     + " (pid=" + Binder.getCallingPid()
    830                     + ") when binding service " + service);
    831         }
    832 
    833         ActivityRecord activity = null;
    834         if (token != null) {
    835             activity = ActivityRecord.isInStackLocked(token);
    836             if (activity == null) {
    837                 Slog.w(TAG, "Binding with unknown activity: " + token);
    838                 return 0;
    839             }
    840         }
    841 
    842         int clientLabel = 0;
    843         PendingIntent clientIntent = null;
    844         final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
    845 
    846         if (isCallerSystem) {
    847             // Hacky kind of thing -- allow system stuff to tell us
    848             // what they are, so we can report this elsewhere for
    849             // others to know why certain services are running.
    850             service.setDefusable(true);
    851             clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
    852             if (clientIntent != null) {
    853                 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
    854                 if (clientLabel != 0) {
    855                     // There are no useful extras in the intent, trash them.
    856                     // System code calling with this stuff just needs to know
    857                     // this will happen.
    858                     service = service.cloneFilter();
    859                 }
    860             }
    861         }
    862 
    863         if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
    864             mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
    865                     "BIND_TREAT_LIKE_ACTIVITY");
    866         }
    867 
    868         if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
    869             throw new SecurityException(
    870                     "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
    871                     + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
    872         }
    873 
    874         final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
    875         final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
    876 
    877         ServiceLookupResult res =
    878             retrieveServiceLocked(service, resolvedType, callingPackage, Binder.getCallingPid(),
    879                     Binder.getCallingUid(), userId, true, callerFg, isBindExternal);
    880         if (res == null) {
    881             return 0;
    882         }
    883         if (res.record == null) {
    884             return -1;
    885         }
    886         ServiceRecord s = res.record;
    887 
    888         boolean permissionsReviewRequired = false;
    889 
    890         // If permissions need a review before any of the app components can run,
    891         // we schedule binding to the service but do not start its process, then
    892         // we launch a review activity to which is passed a callback to invoke
    893         // when done to start the bound service's process to completing the binding.
    894         if (Build.PERMISSIONS_REVIEW_REQUIRED) {
    895             if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
    896                     s.packageName, s.userId)) {
    897 
    898                 permissionsReviewRequired = true;
    899 
    900                 // Show a permission review UI only for binding from a foreground app
    901                 if (!callerFg) {
    902                     Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
    903                             + s.packageName + " requires a permissions review");
    904                     return 0;
    905                 }
    906 
    907                 final ServiceRecord serviceRecord = s;
    908                 final Intent serviceIntent = service;
    909 
    910                 RemoteCallback callback = new RemoteCallback(
    911                         new RemoteCallback.OnResultListener() {
    912                     @Override
    913                     public void onResult(Bundle result) {
    914                         synchronized(mAm) {
    915                             final long identity = Binder.clearCallingIdentity();
    916                             try {
    917                                 if (!mPendingServices.contains(serviceRecord)) {
    918                                     return;
    919                                 }
    920                                 // If there is still a pending record, then the service
    921                                 // binding request is still valid, so hook them up. We
    922                                 // proceed only if the caller cleared the review requirement
    923                                 // otherwise we unbind because the user didn't approve.
    924                                 if (!mAm.getPackageManagerInternalLocked()
    925                                         .isPermissionsReviewRequired(
    926                                                 serviceRecord.packageName,
    927                                                 serviceRecord.userId)) {
    928                                     try {
    929                                         bringUpServiceLocked(serviceRecord,
    930                                                 serviceIntent.getFlags(),
    931                                                 callerFg, false, false);
    932                                     } catch (RemoteException e) {
    933                                         /* ignore - local call */
    934                                     }
    935                                 } else {
    936                                     unbindServiceLocked(connection);
    937                                 }
    938                             } finally {
    939                                 Binder.restoreCallingIdentity(identity);
    940                             }
    941                         }
    942                     }
    943                 });
    944 
    945                 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
    946                 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
    947                         | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
    948                 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
    949                 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
    950 
    951                 if (DEBUG_PERMISSIONS_REVIEW) {
    952                     Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
    953                             + s.packageName);
    954                 }
    955 
    956                 mAm.mHandler.post(new Runnable() {
    957                     @Override
    958                     public void run() {
    959                         mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
    960                     }
    961                 });
    962             }
    963         }
    964 
    965         final long origId = Binder.clearCallingIdentity();
    966 
    967         try {
    968             if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
    969                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
    970                         + s);
    971             }
    972 
    973             if ((flags&Context.BIND_AUTO_CREATE) != 0) {
    974                 s.lastActivity = SystemClock.uptimeMillis();
    975                 if (!s.hasAutoCreateConnections()) {
    976                     // This is the first binding, let the tracker know.
    977                     ServiceState stracker = s.getTracker();
    978                     if (stracker != null) {
    979                         stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
    980                                 s.lastActivity);
    981                     }
    982                 }
    983             }
    984 
    985             mAm.startAssociationLocked(callerApp.uid, callerApp.processName, callerApp.curProcState,
    986                     s.appInfo.uid, s.name, s.processName);
    987 
    988             AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
    989             ConnectionRecord c = new ConnectionRecord(b, activity,
    990                     connection, flags, clientLabel, clientIntent);
    991 
    992             IBinder binder = connection.asBinder();
    993             ArrayList<ConnectionRecord> clist = s.connections.get(binder);
    994             if (clist == null) {
    995                 clist = new ArrayList<ConnectionRecord>();
    996                 s.connections.put(binder, clist);
    997             }
    998             clist.add(c);
    999             b.connections.add(c);
   1000             if (activity != null) {
   1001                 if (activity.connections == null) {
   1002                     activity.connections = new HashSet<ConnectionRecord>();
   1003                 }
   1004                 activity.connections.add(c);
   1005             }
   1006             b.client.connections.add(c);
   1007             if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
   1008                 b.client.hasAboveClient = true;
   1009             }
   1010             if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
   1011                 s.whitelistManager = true;
   1012             }
   1013             if (s.app != null) {
   1014                 updateServiceClientActivitiesLocked(s.app, c, true);
   1015             }
   1016             clist = mServiceConnections.get(binder);
   1017             if (clist == null) {
   1018                 clist = new ArrayList<ConnectionRecord>();
   1019                 mServiceConnections.put(binder, clist);
   1020             }
   1021             clist.add(c);
   1022 
   1023             if ((flags&Context.BIND_AUTO_CREATE) != 0) {
   1024                 s.lastActivity = SystemClock.uptimeMillis();
   1025                 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
   1026                         permissionsReviewRequired) != null) {
   1027                     return 0;
   1028                 }
   1029             }
   1030 
   1031             if (s.app != null) {
   1032                 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
   1033                     s.app.treatLikeActivity = true;
   1034                 }
   1035                 if (s.whitelistManager) {
   1036                     s.app.whitelistManager = true;
   1037                 }
   1038                 // This could have made the service more important.
   1039                 mAm.updateLruProcessLocked(s.app, s.app.hasClientActivities
   1040                         || s.app.treatLikeActivity, b.client);
   1041                 mAm.updateOomAdjLocked(s.app);
   1042             }
   1043 
   1044             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
   1045                     + ": received=" + b.intent.received
   1046                     + " apps=" + b.intent.apps.size()
   1047                     + " doRebind=" + b.intent.doRebind);
   1048 
   1049             if (s.app != null && b.intent.received) {
   1050                 // Service is already running, so we can immediately
   1051                 // publish the connection.
   1052                 try {
   1053                     c.conn.connected(s.name, b.intent.binder);
   1054                 } catch (Exception e) {
   1055                     Slog.w(TAG, "Failure sending service " + s.shortName
   1056                             + " to connection " + c.conn.asBinder()
   1057                             + " (in " + c.binding.client.processName + ")", e);
   1058                 }
   1059 
   1060                 // If this is the first app connected back to this binding,
   1061                 // and the service had previously asked to be told when
   1062                 // rebound, then do so.
   1063                 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
   1064                     requestServiceBindingLocked(s, b.intent, callerFg, true);
   1065                 }
   1066             } else if (!b.intent.requested) {
   1067                 requestServiceBindingLocked(s, b.intent, callerFg, false);
   1068             }
   1069 
   1070             getServiceMap(s.userId).ensureNotStartingBackground(s);
   1071 
   1072         } finally {
   1073             Binder.restoreCallingIdentity(origId);
   1074         }
   1075 
   1076         return 1;
   1077     }
   1078 
   1079     private void foo() {
   1080 
   1081     }
   1082 
   1083     void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
   1084         final long origId = Binder.clearCallingIdentity();
   1085         try {
   1086             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
   1087                     + " " + intent + ": " + service);
   1088             if (r != null) {
   1089                 Intent.FilterComparison filter
   1090                         = new Intent.FilterComparison(intent);
   1091                 IntentBindRecord b = r.bindings.get(filter);
   1092                 if (b != null && !b.received) {
   1093                     b.binder = service;
   1094                     b.requested = true;
   1095                     b.received = true;
   1096                     for (int conni=r.connections.size()-1; conni>=0; conni--) {
   1097                         ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
   1098                         for (int i=0; i<clist.size(); i++) {
   1099                             ConnectionRecord c = clist.get(i);
   1100                             if (!filter.equals(c.binding.intent.intent)) {
   1101                                 if (DEBUG_SERVICE) Slog.v(
   1102                                         TAG_SERVICE, "Not publishing to: " + c);
   1103                                 if (DEBUG_SERVICE) Slog.v(
   1104                                         TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
   1105                                 if (DEBUG_SERVICE) Slog.v(
   1106                                         TAG_SERVICE, "Published intent: " + intent);
   1107                                 continue;
   1108                             }
   1109                             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
   1110                             try {
   1111                                 c.conn.connected(r.name, service);
   1112                             } catch (Exception e) {
   1113                                 Slog.w(TAG, "Failure sending service " + r.name +
   1114                                       " to connection " + c.conn.asBinder() +
   1115                                       " (in " + c.binding.client.processName + ")", e);
   1116                             }
   1117                         }
   1118                     }
   1119                 }
   1120 
   1121                 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
   1122             }
   1123         } finally {
   1124             Binder.restoreCallingIdentity(origId);
   1125         }
   1126     }
   1127 
   1128     boolean unbindServiceLocked(IServiceConnection connection) {
   1129         IBinder binder = connection.asBinder();
   1130         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
   1131         ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
   1132         if (clist == null) {
   1133             Slog.w(TAG, "Unbind failed: could not find connection for "
   1134                   + connection.asBinder());
   1135             return false;
   1136         }
   1137 
   1138         final long origId = Binder.clearCallingIdentity();
   1139         try {
   1140             while (clist.size() > 0) {
   1141                 ConnectionRecord r = clist.get(0);
   1142                 removeConnectionLocked(r, null, null);
   1143                 if (clist.size() > 0 && clist.get(0) == r) {
   1144                     // In case it didn't get removed above, do it now.
   1145                     Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
   1146                     clist.remove(0);
   1147                 }
   1148 
   1149                 if (r.binding.service.app != null) {
   1150                     if (r.binding.service.app.whitelistManager) {
   1151                         updateWhitelistManagerLocked(r.binding.service.app);
   1152                     }
   1153                     // This could have made the service less important.
   1154                     if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
   1155                         r.binding.service.app.treatLikeActivity = true;
   1156                         mAm.updateLruProcessLocked(r.binding.service.app,
   1157                                 r.binding.service.app.hasClientActivities
   1158                                 || r.binding.service.app.treatLikeActivity, null);
   1159                     }
   1160                     mAm.updateOomAdjLocked(r.binding.service.app);
   1161                 }
   1162             }
   1163         } finally {
   1164             Binder.restoreCallingIdentity(origId);
   1165         }
   1166 
   1167         return true;
   1168     }
   1169 
   1170     void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
   1171         final long origId = Binder.clearCallingIdentity();
   1172         try {
   1173             if (r != null) {
   1174                 Intent.FilterComparison filter
   1175                         = new Intent.FilterComparison(intent);
   1176                 IntentBindRecord b = r.bindings.get(filter);
   1177                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
   1178                         + " at " + b + ": apps="
   1179                         + (b != null ? b.apps.size() : 0));
   1180 
   1181                 boolean inDestroying = mDestroyingServices.contains(r);
   1182                 if (b != null) {
   1183                     if (b.apps.size() > 0 && !inDestroying) {
   1184                         // Applications have already bound since the last
   1185                         // unbind, so just rebind right here.
   1186                         boolean inFg = false;
   1187                         for (int i=b.apps.size()-1; i>=0; i--) {
   1188                             ProcessRecord client = b.apps.valueAt(i).client;
   1189                             if (client != null && client.setSchedGroup
   1190                                     != ProcessList.SCHED_GROUP_BACKGROUND) {
   1191                                 inFg = true;
   1192                                 break;
   1193                             }
   1194                         }
   1195                         try {
   1196                             requestServiceBindingLocked(r, b, inFg, true);
   1197                         } catch (TransactionTooLargeException e) {
   1198                             // Don't pass this back to ActivityThread, it's unrelated.
   1199                         }
   1200                     } else {
   1201                         // Note to tell the service the next time there is
   1202                         // a new client.
   1203                         b.doRebind = true;
   1204                     }
   1205                 }
   1206 
   1207                 serviceDoneExecutingLocked(r, inDestroying, false);
   1208             }
   1209         } finally {
   1210             Binder.restoreCallingIdentity(origId);
   1211         }
   1212     }
   1213 
   1214     private final ServiceRecord findServiceLocked(ComponentName name,
   1215             IBinder token, int userId) {
   1216         ServiceRecord r = getServiceByName(name, userId);
   1217         return r == token ? r : null;
   1218     }
   1219 
   1220     private final class ServiceLookupResult {
   1221         final ServiceRecord record;
   1222         final String permission;
   1223 
   1224         ServiceLookupResult(ServiceRecord _record, String _permission) {
   1225             record = _record;
   1226             permission = _permission;
   1227         }
   1228     }
   1229 
   1230     private class ServiceRestarter implements Runnable {
   1231         private ServiceRecord mService;
   1232 
   1233         void setService(ServiceRecord service) {
   1234             mService = service;
   1235         }
   1236 
   1237         public void run() {
   1238             synchronized(mAm) {
   1239                 performServiceRestartLocked(mService);
   1240             }
   1241         }
   1242     }
   1243 
   1244     private ServiceLookupResult retrieveServiceLocked(Intent service,
   1245             String resolvedType, String callingPackage, int callingPid, int callingUid, int userId,
   1246             boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal) {
   1247         ServiceRecord r = null;
   1248         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
   1249                 + " type=" + resolvedType + " callingUid=" + callingUid);
   1250 
   1251         userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
   1252                 ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE, "service", null);
   1253 
   1254         ServiceMap smap = getServiceMap(userId);
   1255         final ComponentName comp = service.getComponent();
   1256         if (comp != null) {
   1257             r = smap.mServicesByName.get(comp);
   1258         }
   1259         if (r == null && !isBindExternal) {
   1260             Intent.FilterComparison filter = new Intent.FilterComparison(service);
   1261             r = smap.mServicesByIntent.get(filter);
   1262         }
   1263         if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
   1264                 && !callingPackage.equals(r.packageName)) {
   1265             // If an external service is running within its own package, other packages
   1266             // should not bind to that instance.
   1267             r = null;
   1268         }
   1269         if (r == null) {
   1270             try {
   1271                 // TODO: come back and remove this assumption to triage all services
   1272                 ResolveInfo rInfo = AppGlobals.getPackageManager().resolveService(service,
   1273                         resolvedType, ActivityManagerService.STOCK_PM_FLAGS
   1274                                 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
   1275                         userId);
   1276                 ServiceInfo sInfo =
   1277                     rInfo != null ? rInfo.serviceInfo : null;
   1278                 if (sInfo == null) {
   1279                     Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
   1280                           ": not found");
   1281                     return null;
   1282                 }
   1283                 ComponentName name = new ComponentName(
   1284                         sInfo.applicationInfo.packageName, sInfo.name);
   1285                 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
   1286                     if (isBindExternal) {
   1287                         if (!sInfo.exported) {
   1288                             throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
   1289                                     " is not exported");
   1290                         }
   1291                         if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
   1292                             throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
   1293                                     " is not an isolatedProcess");
   1294                         }
   1295                         // Run the service under the calling package's application.
   1296                         ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
   1297                                 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
   1298                         if (aInfo == null) {
   1299                             throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
   1300                                     "could not resolve client package " + callingPackage);
   1301                         }
   1302                         sInfo = new ServiceInfo(sInfo);
   1303                         sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
   1304                         sInfo.applicationInfo.packageName = aInfo.packageName;
   1305                         sInfo.applicationInfo.uid = aInfo.uid;
   1306                         name = new ComponentName(aInfo.packageName, name.getClassName());
   1307                         service.setComponent(name);
   1308                     } else {
   1309                         throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
   1310                                 name);
   1311                     }
   1312                 } else if (isBindExternal) {
   1313                     throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
   1314                             " is not an externalService");
   1315                 }
   1316                 if (userId > 0) {
   1317                     if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
   1318                             sInfo.name, sInfo.flags)
   1319                             && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
   1320                         userId = 0;
   1321                         smap = getServiceMap(0);
   1322                     }
   1323                     sInfo = new ServiceInfo(sInfo);
   1324                     sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
   1325                 }
   1326                 r = smap.mServicesByName.get(name);
   1327                 if (r == null && createIfNeeded) {
   1328                     Intent.FilterComparison filter
   1329                             = new Intent.FilterComparison(service.cloneFilter());
   1330                     ServiceRestarter res = new ServiceRestarter();
   1331                     BatteryStatsImpl.Uid.Pkg.Serv ss = null;
   1332                     BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
   1333                     synchronized (stats) {
   1334                         ss = stats.getServiceStatsLocked(
   1335                                 sInfo.applicationInfo.uid, sInfo.packageName,
   1336                                 sInfo.name);
   1337                     }
   1338                     r = new ServiceRecord(mAm, ss, name, filter, sInfo, callingFromFg, res);
   1339                     res.setService(r);
   1340                     smap.mServicesByName.put(name, r);
   1341                     smap.mServicesByIntent.put(filter, r);
   1342 
   1343                     // Make sure this component isn't in the pending list.
   1344                     for (int i=mPendingServices.size()-1; i>=0; i--) {
   1345                         ServiceRecord pr = mPendingServices.get(i);
   1346                         if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
   1347                                 && pr.name.equals(name)) {
   1348                             mPendingServices.remove(i);
   1349                         }
   1350                     }
   1351                 }
   1352             } catch (RemoteException ex) {
   1353                 // pm is in same process, this will never happen.
   1354             }
   1355         }
   1356         if (r != null) {
   1357             if (mAm.checkComponentPermission(r.permission,
   1358                     callingPid, callingUid, r.appInfo.uid, r.exported)
   1359                     != PackageManager.PERMISSION_GRANTED) {
   1360                 if (!r.exported) {
   1361                     Slog.w(TAG, "Permission Denial: Accessing service " + r.name
   1362                             + " from pid=" + callingPid
   1363                             + ", uid=" + callingUid
   1364                             + " that is not exported from uid " + r.appInfo.uid);
   1365                     return new ServiceLookupResult(null, "not exported from uid "
   1366                             + r.appInfo.uid);
   1367                 }
   1368                 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
   1369                         + " from pid=" + callingPid
   1370                         + ", uid=" + callingUid
   1371                         + " requires " + r.permission);
   1372                 return new ServiceLookupResult(null, r.permission);
   1373             } else if (r.permission != null && callingPackage != null) {
   1374                 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
   1375                 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation(
   1376                         opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
   1377                     Slog.w(TAG, "Appop Denial: Accessing service " + r.name
   1378                             + " from pid=" + callingPid
   1379                             + ", uid=" + callingUid
   1380                             + " requires appop " + AppOpsManager.opToName(opCode));
   1381                     return null;
   1382                 }
   1383             }
   1384 
   1385             if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
   1386                     resolvedType, r.appInfo)) {
   1387                 return null;
   1388             }
   1389             return new ServiceLookupResult(r, null);
   1390         }
   1391         return null;
   1392     }
   1393 
   1394     private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
   1395         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
   1396                 + why + " of " + r + " in app " + r.app);
   1397         else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
   1398                 + why + " of " + r.shortName);
   1399         long now = SystemClock.uptimeMillis();
   1400         if (r.executeNesting == 0) {
   1401             r.executeFg = fg;
   1402             ServiceState stracker = r.getTracker();
   1403             if (stracker != null) {
   1404                 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
   1405             }
   1406             if (r.app != null) {
   1407                 r.app.executingServices.add(r);
   1408                 r.app.execServicesFg |= fg;
   1409                 if (r.app.executingServices.size() == 1) {
   1410                     scheduleServiceTimeoutLocked(r.app);
   1411                 }
   1412             }
   1413         } else if (r.app != null && fg && !r.app.execServicesFg) {
   1414             r.app.execServicesFg = true;
   1415             scheduleServiceTimeoutLocked(r.app);
   1416         }
   1417         r.executeFg |= fg;
   1418         r.executeNesting++;
   1419         r.executingStart = now;
   1420     }
   1421 
   1422     private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
   1423             boolean execInFg, boolean rebind) throws TransactionTooLargeException {
   1424         if (r.app == null || r.app.thread == null) {
   1425             // If service is not currently running, can't yet bind.
   1426             return false;
   1427         }
   1428         if ((!i.requested || rebind) && i.apps.size() > 0) {
   1429             try {
   1430                 bumpServiceExecutingLocked(r, execInFg, "bind");
   1431                 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
   1432                 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
   1433                         r.app.repProcState);
   1434                 if (!rebind) {
   1435                     i.requested = true;
   1436                 }
   1437                 i.hasBound = true;
   1438                 i.doRebind = false;
   1439             } catch (TransactionTooLargeException e) {
   1440                 // Keep the executeNesting count accurate.
   1441                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
   1442                 final boolean inDestroying = mDestroyingServices.contains(r);
   1443                 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
   1444                 throw e;
   1445             } catch (RemoteException e) {
   1446                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
   1447                 // Keep the executeNesting count accurate.
   1448                 final boolean inDestroying = mDestroyingServices.contains(r);
   1449                 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
   1450                 return false;
   1451             }
   1452         }
   1453         return true;
   1454     }
   1455 
   1456     private final boolean scheduleServiceRestartLocked(ServiceRecord r,
   1457             boolean allowCancel) {
   1458         boolean canceled = false;
   1459 
   1460         if (mAm.isShuttingDownLocked()) {
   1461             Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortName
   1462                     + " - system is shutting down");
   1463             return false;
   1464         }
   1465 
   1466         ServiceMap smap = getServiceMap(r.userId);
   1467         if (smap.mServicesByName.get(r.name) != r) {
   1468             ServiceRecord cur = smap.mServicesByName.get(r.name);
   1469             Slog.wtf(TAG, "Attempting to schedule restart of " + r
   1470                     + " when found in map: " + cur);
   1471             return false;
   1472         }
   1473 
   1474         final long now = SystemClock.uptimeMillis();
   1475 
   1476         if ((r.serviceInfo.applicationInfo.flags
   1477                 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
   1478             long minDuration = SERVICE_RESTART_DURATION;
   1479             long resetTime = SERVICE_RESET_RUN_DURATION;
   1480 
   1481             // Any delivered but not yet finished starts should be put back
   1482             // on the pending list.
   1483             final int N = r.deliveredStarts.size();
   1484             if (N > 0) {
   1485                 for (int i=N-1; i>=0; i--) {
   1486                     ServiceRecord.StartItem si = r.deliveredStarts.get(i);
   1487                     si.removeUriPermissionsLocked();
   1488                     if (si.intent == null) {
   1489                         // We'll generate this again if needed.
   1490                     } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
   1491                             && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
   1492                         r.pendingStarts.add(0, si);
   1493                         long dur = SystemClock.uptimeMillis() - si.deliveredTime;
   1494                         dur *= 2;
   1495                         if (minDuration < dur) minDuration = dur;
   1496                         if (resetTime < dur) resetTime = dur;
   1497                     } else {
   1498                         Slog.w(TAG, "Canceling start item " + si.intent + " in service "
   1499                                 + r.name);
   1500                         canceled = true;
   1501                     }
   1502                 }
   1503                 r.deliveredStarts.clear();
   1504             }
   1505 
   1506             r.totalRestartCount++;
   1507             if (r.restartDelay == 0) {
   1508                 r.restartCount++;
   1509                 r.restartDelay = minDuration;
   1510             } else {
   1511                 // If it has been a "reasonably long time" since the service
   1512                 // was started, then reset our restart duration back to
   1513                 // the beginning, so we don't infinitely increase the duration
   1514                 // on a service that just occasionally gets killed (which is
   1515                 // a normal case, due to process being killed to reclaim memory).
   1516                 if (now > (r.restartTime+resetTime)) {
   1517                     r.restartCount = 1;
   1518                     r.restartDelay = minDuration;
   1519                 } else {
   1520                     r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
   1521                     if (r.restartDelay < minDuration) {
   1522                         r.restartDelay = minDuration;
   1523                     }
   1524                 }
   1525             }
   1526 
   1527             r.nextRestartTime = now + r.restartDelay;
   1528 
   1529             // Make sure that we don't end up restarting a bunch of services
   1530             // all at the same time.
   1531             boolean repeat;
   1532             do {
   1533                 repeat = false;
   1534                 for (int i=mRestartingServices.size()-1; i>=0; i--) {
   1535                     ServiceRecord r2 = mRestartingServices.get(i);
   1536                     if (r2 != r && r.nextRestartTime
   1537                             >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
   1538                             && r.nextRestartTime
   1539                             < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
   1540                         r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
   1541                         r.restartDelay = r.nextRestartTime - now;
   1542                         repeat = true;
   1543                         break;
   1544                     }
   1545                 }
   1546             } while (repeat);
   1547 
   1548         } else {
   1549             // Persistent processes are immediately restarted, so there is no
   1550             // reason to hold of on restarting their services.
   1551             r.totalRestartCount++;
   1552             r.restartCount = 0;
   1553             r.restartDelay = 0;
   1554             r.nextRestartTime = now;
   1555         }
   1556 
   1557         if (!mRestartingServices.contains(r)) {
   1558             r.createdFromFg = false;
   1559             mRestartingServices.add(r);
   1560             r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
   1561         }
   1562 
   1563         r.cancelNotification();
   1564 
   1565         mAm.mHandler.removeCallbacks(r.restarter);
   1566         mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
   1567         r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
   1568         Slog.w(TAG, "Scheduling restart of crashed service "
   1569                 + r.shortName + " in " + r.restartDelay + "ms");
   1570         EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
   1571                 r.userId, r.shortName, r.restartDelay);
   1572 
   1573         return canceled;
   1574     }
   1575 
   1576     final void performServiceRestartLocked(ServiceRecord r) {
   1577         if (!mRestartingServices.contains(r)) {
   1578             return;
   1579         }
   1580         if (!isServiceNeeded(r, false, false)) {
   1581             // Paranoia: is this service actually needed?  In theory a service that is not
   1582             // needed should never remain on the restart list.  In practice...  well, there
   1583             // have been bugs where this happens, and bad things happen because the process
   1584             // ends up just being cached, so quickly killed, then restarted again and again.
   1585             // Let's not let that happen.
   1586             Slog.wtf(TAG, "Restarting service that is not needed: " + r);
   1587             return;
   1588         }
   1589         try {
   1590             bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
   1591         } catch (TransactionTooLargeException e) {
   1592             // Ignore, it's been logged and nothing upstack cares.
   1593         }
   1594     }
   1595 
   1596     private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
   1597             boolean force) {
   1598         if (!force && r.restartDelay == 0) {
   1599             return false;
   1600         }
   1601         // Remove from the restarting list; if the service is currently on the
   1602         // restarting list, or the call is coming from another app, then this
   1603         // service has become of much more interest so we reset the restart interval.
   1604         boolean removed = mRestartingServices.remove(r);
   1605         if (removed || callingUid != r.appInfo.uid) {
   1606             r.resetRestartCounter();
   1607         }
   1608         if (removed) {
   1609             clearRestartingIfNeededLocked(r);
   1610         }
   1611         mAm.mHandler.removeCallbacks(r.restarter);
   1612         return true;
   1613     }
   1614 
   1615     private void clearRestartingIfNeededLocked(ServiceRecord r) {
   1616         if (r.restartTracker != null) {
   1617             // If this is the last restarting record with this tracker, then clear
   1618             // the tracker's restarting state.
   1619             boolean stillTracking = false;
   1620             for (int i=mRestartingServices.size()-1; i>=0; i--) {
   1621                 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
   1622                     stillTracking = true;
   1623                     break;
   1624                 }
   1625             }
   1626             if (!stillTracking) {
   1627                 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
   1628                         SystemClock.uptimeMillis());
   1629                 r.restartTracker = null;
   1630             }
   1631         }
   1632     }
   1633 
   1634     private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
   1635             boolean whileRestarting, boolean permissionsReviewRequired)
   1636             throws TransactionTooLargeException {
   1637         //Slog.i(TAG, "Bring up service:");
   1638         //r.dump("  ");
   1639 
   1640         if (r.app != null && r.app.thread != null) {
   1641             sendServiceArgsLocked(r, execInFg, false);
   1642             return null;
   1643         }
   1644 
   1645         if (!whileRestarting && r.restartDelay > 0) {
   1646             // If waiting for a restart, then do nothing.
   1647             return null;
   1648         }
   1649 
   1650         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent);
   1651 
   1652         // We are now bringing the service up, so no longer in the
   1653         // restarting state.
   1654         if (mRestartingServices.remove(r)) {
   1655             r.resetRestartCounter();
   1656             clearRestartingIfNeededLocked(r);
   1657         }
   1658 
   1659         // Make sure this service is no longer considered delayed, we are starting it now.
   1660         if (r.delayed) {
   1661             if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
   1662             getServiceMap(r.userId).mDelayedStartList.remove(r);
   1663             r.delayed = false;
   1664         }
   1665 
   1666         // Make sure that the user who owns this service is started.  If not,
   1667         // we don't want to allow it to run.
   1668         if (!mAm.mUserController.hasStartedUserState(r.userId)) {
   1669             String msg = "Unable to launch app "
   1670                     + r.appInfo.packageName + "/"
   1671                     + r.appInfo.uid + " for service "
   1672                     + r.intent.getIntent() + ": user " + r.userId + " is stopped";
   1673             Slog.w(TAG, msg);
   1674             bringDownServiceLocked(r);
   1675             return msg;
   1676         }
   1677 
   1678         // Service is now being launched, its package can't be stopped.
   1679         try {
   1680             AppGlobals.getPackageManager().setPackageStoppedState(
   1681                     r.packageName, false, r.userId);
   1682         } catch (RemoteException e) {
   1683         } catch (IllegalArgumentException e) {
   1684             Slog.w(TAG, "Failed trying to unstop package "
   1685                     + r.packageName + ": " + e);
   1686         }
   1687 
   1688         final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
   1689         final String procName = r.processName;
   1690         ProcessRecord app;
   1691 
   1692         if (!isolated) {
   1693             app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
   1694             if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
   1695                         + " app=" + app);
   1696             if (app != null && app.thread != null) {
   1697                 try {
   1698                     app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
   1699                     realStartServiceLocked(r, app, execInFg);
   1700                     return null;
   1701                 } catch (TransactionTooLargeException e) {
   1702                     throw e;
   1703                 } catch (RemoteException e) {
   1704                     Slog.w(TAG, "Exception when starting service " + r.shortName, e);
   1705                 }
   1706 
   1707                 // If a dead object exception was thrown -- fall through to
   1708                 // restart the application.
   1709             }
   1710         } else {
   1711             // If this service runs in an isolated process, then each time
   1712             // we call startProcessLocked() we will get a new isolated
   1713             // process, starting another process if we are currently waiting
   1714             // for a previous process to come up.  To deal with this, we store
   1715             // in the service any current isolated process it is running in or
   1716             // waiting to have come up.
   1717             app = r.isolatedProc;
   1718         }
   1719 
   1720         // Not running -- get it started, and enqueue this service record
   1721         // to be executed when the app comes up.
   1722         if (app == null && !permissionsReviewRequired) {
   1723             if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
   1724                     "service", r.name, false, isolated, false)) == null) {
   1725                 String msg = "Unable to launch app "
   1726                         + r.appInfo.packageName + "/"
   1727                         + r.appInfo.uid + " for service "
   1728                         + r.intent.getIntent() + ": process is bad";
   1729                 Slog.w(TAG, msg);
   1730                 bringDownServiceLocked(r);
   1731                 return msg;
   1732             }
   1733             if (isolated) {
   1734                 r.isolatedProc = app;
   1735             }
   1736         }
   1737 
   1738         if (!mPendingServices.contains(r)) {
   1739             mPendingServices.add(r);
   1740         }
   1741 
   1742         if (r.delayedStop) {
   1743             // Oh and hey we've already been asked to stop!
   1744             r.delayedStop = false;
   1745             if (r.startRequested) {
   1746                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
   1747                         "Applying delayed stop (in bring up): " + r);
   1748                 stopServiceLocked(r);
   1749             }
   1750         }
   1751 
   1752         return null;
   1753     }
   1754 
   1755     private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
   1756             throws TransactionTooLargeException {
   1757         for (int i=r.bindings.size()-1; i>=0; i--) {
   1758             IntentBindRecord ibr = r.bindings.valueAt(i);
   1759             if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
   1760                 break;
   1761             }
   1762         }
   1763     }
   1764 
   1765     private final void realStartServiceLocked(ServiceRecord r,
   1766             ProcessRecord app, boolean execInFg) throws RemoteException {
   1767         if (app.thread == null) {
   1768             throw new RemoteException();
   1769         }
   1770         if (DEBUG_MU)
   1771             Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
   1772                     + ", ProcessRecord.uid = " + app.uid);
   1773         r.app = app;
   1774         r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
   1775 
   1776         final boolean newService = app.services.add(r);
   1777         bumpServiceExecutingLocked(r, execInFg, "create");
   1778         mAm.updateLruProcessLocked(app, false, null);
   1779         mAm.updateOomAdjLocked();
   1780 
   1781         boolean created = false;
   1782         try {
   1783             if (LOG_SERVICE_START_STOP) {
   1784                 String nameTerm;
   1785                 int lastPeriod = r.shortName.lastIndexOf('.');
   1786                 nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
   1787                 EventLogTags.writeAmCreateService(
   1788                         r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
   1789             }
   1790             synchronized (r.stats.getBatteryStats()) {
   1791                 r.stats.startLaunchedLocked();
   1792             }
   1793             mAm.notifyPackageUse(r.serviceInfo.packageName,
   1794                                  PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
   1795             app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
   1796             app.thread.scheduleCreateService(r, r.serviceInfo,
   1797                     mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
   1798                     app.repProcState);
   1799             r.postNotification();
   1800             created = true;
   1801         } catch (DeadObjectException e) {
   1802             Slog.w(TAG, "Application dead when creating service " + r);
   1803             mAm.appDiedLocked(app);
   1804             throw e;
   1805         } finally {
   1806             if (!created) {
   1807                 // Keep the executeNesting count accurate.
   1808                 final boolean inDestroying = mDestroyingServices.contains(r);
   1809                 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
   1810 
   1811                 // Cleanup.
   1812                 if (newService) {
   1813                     app.services.remove(r);
   1814                     r.app = null;
   1815                 }
   1816 
   1817                 // Retry.
   1818                 if (!inDestroying) {
   1819                     scheduleServiceRestartLocked(r, false);
   1820                 }
   1821             }
   1822         }
   1823 
   1824         if (r.whitelistManager) {
   1825             app.whitelistManager = true;
   1826         }
   1827 
   1828         requestServiceBindingsLocked(r, execInFg);
   1829 
   1830         updateServiceClientActivitiesLocked(app, null, true);
   1831 
   1832         // If the service is in the started state, and there are no
   1833         // pending arguments, then fake up one so its onStartCommand() will
   1834         // be called.
   1835         if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
   1836             r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
   1837                     null, null));
   1838         }
   1839 
   1840         sendServiceArgsLocked(r, execInFg, true);
   1841 
   1842         if (r.delayed) {
   1843             if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
   1844             getServiceMap(r.userId).mDelayedStartList.remove(r);
   1845             r.delayed = false;
   1846         }
   1847 
   1848         if (r.delayedStop) {
   1849             // Oh and hey we've already been asked to stop!
   1850             r.delayedStop = false;
   1851             if (r.startRequested) {
   1852                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
   1853                         "Applying delayed stop (from start): " + r);
   1854                 stopServiceLocked(r);
   1855             }
   1856         }
   1857     }
   1858 
   1859     private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
   1860             boolean oomAdjusted) throws TransactionTooLargeException {
   1861         final int N = r.pendingStarts.size();
   1862         if (N == 0) {
   1863             return;
   1864         }
   1865 
   1866         while (r.pendingStarts.size() > 0) {
   1867             Exception caughtException = null;
   1868             ServiceRecord.StartItem si = null;
   1869             try {
   1870                 si = r.pendingStarts.remove(0);
   1871                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Sending arguments to: "
   1872                         + r + " " + r.intent + " args=" + si.intent);
   1873                 if (si.intent == null && N > 1) {
   1874                     // If somehow we got a dummy null intent in the middle,
   1875                     // then skip it.  DO NOT skip a null intent when it is
   1876                     // the only one in the list -- this is to support the
   1877                     // onStartCommand(null) case.
   1878                     continue;
   1879                 }
   1880                 si.deliveredTime = SystemClock.uptimeMillis();
   1881                 r.deliveredStarts.add(si);
   1882                 si.deliveryCount++;
   1883                 if (si.neededGrants != null) {
   1884                     mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
   1885                             si.getUriPermissionsLocked());
   1886                 }
   1887                 bumpServiceExecutingLocked(r, execInFg, "start");
   1888                 if (!oomAdjusted) {
   1889                     oomAdjusted = true;
   1890                     mAm.updateOomAdjLocked(r.app);
   1891                 }
   1892                 int flags = 0;
   1893                 if (si.deliveryCount > 1) {
   1894                     flags |= Service.START_FLAG_RETRY;
   1895                 }
   1896                 if (si.doneExecutingCount > 0) {
   1897                     flags |= Service.START_FLAG_REDELIVERY;
   1898                 }
   1899                 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
   1900             } catch (TransactionTooLargeException e) {
   1901                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large: intent="
   1902                         + si.intent);
   1903                 caughtException = e;
   1904             } catch (RemoteException e) {
   1905                 // Remote process gone...  we'll let the normal cleanup take care of this.
   1906                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
   1907                 caughtException = e;
   1908             } catch (Exception e) {
   1909                 Slog.w(TAG, "Unexpected exception", e);
   1910                 caughtException = e;
   1911             }
   1912 
   1913             if (caughtException != null) {
   1914                 // Keep nesting count correct
   1915                 final boolean inDestroying = mDestroyingServices.contains(r);
   1916                 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
   1917                 if (caughtException instanceof TransactionTooLargeException) {
   1918                     throw (TransactionTooLargeException)caughtException;
   1919                 }
   1920                 break;
   1921             }
   1922         }
   1923     }
   1924 
   1925     private final boolean isServiceNeeded(ServiceRecord r, boolean knowConn, boolean hasConn) {
   1926         // Are we still explicitly being asked to run?
   1927         if (r.startRequested) {
   1928             return true;
   1929         }
   1930 
   1931         // Is someone still bound to us keepign us running?
   1932         if (!knowConn) {
   1933             hasConn = r.hasAutoCreateConnections();
   1934         }
   1935         if (hasConn) {
   1936             return true;
   1937         }
   1938 
   1939         return false;
   1940     }
   1941 
   1942     private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
   1943             boolean hasConn) {
   1944         //Slog.i(TAG, "Bring down service:");
   1945         //r.dump("  ");
   1946 
   1947         if (isServiceNeeded(r, knowConn, hasConn)) {
   1948             return;
   1949         }
   1950 
   1951         // Are we in the process of launching?
   1952         if (mPendingServices.contains(r)) {
   1953             return;
   1954         }
   1955 
   1956         bringDownServiceLocked(r);
   1957     }
   1958 
   1959     private final void bringDownServiceLocked(ServiceRecord r) {
   1960         //Slog.i(TAG, "Bring down service:");
   1961         //r.dump("  ");
   1962 
   1963         // Report to all of the connections that the service is no longer
   1964         // available.
   1965         for (int conni=r.connections.size()-1; conni>=0; conni--) {
   1966             ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
   1967             for (int i=0; i<c.size(); i++) {
   1968                 ConnectionRecord cr = c.get(i);
   1969                 // There is still a connection to the service that is
   1970                 // being brought down.  Mark it as dead.
   1971                 cr.serviceDead = true;
   1972                 try {
   1973                     cr.conn.connected(r.name, null);
   1974                 } catch (Exception e) {
   1975                     Slog.w(TAG, "Failure disconnecting service " + r.name +
   1976                           " to connection " + c.get(i).conn.asBinder() +
   1977                           " (in " + c.get(i).binding.client.processName + ")", e);
   1978                 }
   1979             }
   1980         }
   1981 
   1982         // Tell the service that it has been unbound.
   1983         if (r.app != null && r.app.thread != null) {
   1984             for (int i=r.bindings.size()-1; i>=0; i--) {
   1985                 IntentBindRecord ibr = r.bindings.valueAt(i);
   1986                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
   1987                         + ": hasBound=" + ibr.hasBound);
   1988                 if (ibr.hasBound) {
   1989                     try {
   1990                         bumpServiceExecutingLocked(r, false, "bring down unbind");
   1991                         mAm.updateOomAdjLocked(r.app);
   1992                         ibr.hasBound = false;
   1993                         r.app.thread.scheduleUnbindService(r,
   1994                                 ibr.intent.getIntent());
   1995                     } catch (Exception e) {
   1996                         Slog.w(TAG, "Exception when unbinding service "
   1997                                 + r.shortName, e);
   1998                         serviceProcessGoneLocked(r);
   1999                     }
   2000                 }
   2001             }
   2002         }
   2003 
   2004         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent);
   2005         r.destroyTime = SystemClock.uptimeMillis();
   2006         if (LOG_SERVICE_START_STOP) {
   2007             EventLogTags.writeAmDestroyService(
   2008                     r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
   2009         }
   2010 
   2011         final ServiceMap smap = getServiceMap(r.userId);
   2012         smap.mServicesByName.remove(r.name);
   2013         smap.mServicesByIntent.remove(r.intent);
   2014         r.totalRestartCount = 0;
   2015         unscheduleServiceRestartLocked(r, 0, true);
   2016 
   2017         // Also make sure it is not on the pending list.
   2018         for (int i=mPendingServices.size()-1; i>=0; i--) {
   2019             if (mPendingServices.get(i) == r) {
   2020                 mPendingServices.remove(i);
   2021                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
   2022             }
   2023         }
   2024 
   2025         r.cancelNotification();
   2026         r.isForeground = false;
   2027         r.foregroundId = 0;
   2028         r.foregroundNoti = null;
   2029 
   2030         // Clear start entries.
   2031         r.clearDeliveredStartsLocked();
   2032         r.pendingStarts.clear();
   2033 
   2034         if (r.app != null) {
   2035             synchronized (r.stats.getBatteryStats()) {
   2036                 r.stats.stopLaunchedLocked();
   2037             }
   2038             r.app.services.remove(r);
   2039             if (r.whitelistManager) {
   2040                 updateWhitelistManagerLocked(r.app);
   2041             }
   2042             if (r.app.thread != null) {
   2043                 updateServiceForegroundLocked(r.app, false);
   2044                 try {
   2045                     bumpServiceExecutingLocked(r, false, "destroy");
   2046                     mDestroyingServices.add(r);
   2047                     r.destroying = true;
   2048                     mAm.updateOomAdjLocked(r.app);
   2049                     r.app.thread.scheduleStopService(r);
   2050                 } catch (Exception e) {
   2051                     Slog.w(TAG, "Exception when destroying service "
   2052                             + r.shortName, e);
   2053                     serviceProcessGoneLocked(r);
   2054                 }
   2055             } else {
   2056                 if (DEBUG_SERVICE) Slog.v(
   2057                     TAG_SERVICE, "Removed service that has no process: " + r);
   2058             }
   2059         } else {
   2060             if (DEBUG_SERVICE) Slog.v(
   2061                 TAG_SERVICE, "Removed service that is not running: " + r);
   2062         }
   2063 
   2064         if (r.bindings.size() > 0) {
   2065             r.bindings.clear();
   2066         }
   2067 
   2068         if (r.restarter instanceof ServiceRestarter) {
   2069            ((ServiceRestarter)r.restarter).setService(null);
   2070         }
   2071 
   2072         int memFactor = mAm.mProcessStats.getMemFactorLocked();
   2073         long now = SystemClock.uptimeMillis();
   2074         if (r.tracker != null) {
   2075             r.tracker.setStarted(false, memFactor, now);
   2076             r.tracker.setBound(false, memFactor, now);
   2077             if (r.executeNesting == 0) {
   2078                 r.tracker.clearCurrentOwner(r, false);
   2079                 r.tracker = null;
   2080             }
   2081         }
   2082 
   2083         smap.ensureNotStartingBackground(r);
   2084     }
   2085 
   2086     void removeConnectionLocked(
   2087         ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
   2088         IBinder binder = c.conn.asBinder();
   2089         AppBindRecord b = c.binding;
   2090         ServiceRecord s = b.service;
   2091         ArrayList<ConnectionRecord> clist = s.connections.get(binder);
   2092         if (clist != null) {
   2093             clist.remove(c);
   2094             if (clist.size() == 0) {
   2095                 s.connections.remove(binder);
   2096             }
   2097         }
   2098         b.connections.remove(c);
   2099         if (c.activity != null && c.activity != skipAct) {
   2100             if (c.activity.connections != null) {
   2101                 c.activity.connections.remove(c);
   2102             }
   2103         }
   2104         if (b.client != skipApp) {
   2105             b.client.connections.remove(c);
   2106             if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
   2107                 b.client.updateHasAboveClientLocked();
   2108             }
   2109             // If this connection requested whitelist management, see if we should
   2110             // now clear that state.
   2111             if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
   2112                 s.updateWhitelistManager();
   2113                 if (!s.whitelistManager && s.app != null) {
   2114                     updateWhitelistManagerLocked(s.app);
   2115                 }
   2116             }
   2117             if (s.app != null) {
   2118                 updateServiceClientActivitiesLocked(s.app, c, true);
   2119             }
   2120         }
   2121         clist = mServiceConnections.get(binder);
   2122         if (clist != null) {
   2123             clist.remove(c);
   2124             if (clist.size() == 0) {
   2125                 mServiceConnections.remove(binder);
   2126             }
   2127         }
   2128 
   2129         mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid, s.name);
   2130 
   2131         if (b.connections.size() == 0) {
   2132             b.intent.apps.remove(b.client);
   2133         }
   2134 
   2135         if (!c.serviceDead) {
   2136             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
   2137                     + ": shouldUnbind=" + b.intent.hasBound);
   2138             if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
   2139                     && b.intent.hasBound) {
   2140                 try {
   2141                     bumpServiceExecutingLocked(s, false, "unbind");
   2142                     if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
   2143                             && s.app.setProcState <= ActivityManager.PROCESS_STATE_RECEIVER) {
   2144                         // If this service's process is not already in the cached list,
   2145                         // then update it in the LRU list here because this may be causing
   2146                         // it to go down there and we want it to start out near the top.
   2147                         mAm.updateLruProcessLocked(s.app, false, null);
   2148                     }
   2149                     mAm.updateOomAdjLocked(s.app);
   2150                     b.intent.hasBound = false;
   2151                     // Assume the client doesn't want to know about a rebind;
   2152                     // we will deal with that later if it asks for one.
   2153                     b.intent.doRebind = false;
   2154                     s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
   2155                 } catch (Exception e) {
   2156                     Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
   2157                     serviceProcessGoneLocked(s);
   2158                 }
   2159             }
   2160 
   2161             // If unbound while waiting to start, remove the pending service
   2162             mPendingServices.remove(s);
   2163 
   2164             if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
   2165                 boolean hasAutoCreate = s.hasAutoCreateConnections();
   2166                 if (!hasAutoCreate) {
   2167                     if (s.tracker != null) {
   2168                         s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
   2169                                 SystemClock.uptimeMillis());
   2170                     }
   2171                 }
   2172                 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
   2173             }
   2174         }
   2175     }
   2176 
   2177     void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
   2178         boolean inDestroying = mDestroyingServices.contains(r);
   2179         if (r != null) {
   2180             if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
   2181                 // This is a call from a service start...  take care of
   2182                 // book-keeping.
   2183                 r.callStart = true;
   2184                 switch (res) {
   2185                     case Service.START_STICKY_COMPATIBILITY:
   2186                     case Service.START_STICKY: {
   2187                         // We are done with the associated start arguments.
   2188                         r.findDeliveredStart(startId, true);
   2189                         // Don't stop if killed.
   2190                         r.stopIfKilled = false;
   2191                         break;
   2192                     }
   2193                     case Service.START_NOT_STICKY: {
   2194                         // We are done with the associated start arguments.
   2195                         r.findDeliveredStart(startId, true);
   2196                         if (r.getLastStartId() == startId) {
   2197                             // There is no more work, and this service
   2198                             // doesn't want to hang around if killed.
   2199                             r.stopIfKilled = true;
   2200                         }
   2201                         break;
   2202                     }
   2203                     case Service.START_REDELIVER_INTENT: {
   2204                         // We'll keep this item until they explicitly
   2205                         // call stop for it, but keep track of the fact
   2206                         // that it was delivered.
   2207                         ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
   2208                         if (si != null) {
   2209                             si.deliveryCount = 0;
   2210                             si.doneExecutingCount++;
   2211                             // Don't stop if killed.
   2212                             r.stopIfKilled = true;
   2213                         }
   2214                         break;
   2215                     }
   2216                     case Service.START_TASK_REMOVED_COMPLETE: {
   2217                         // Special processing for onTaskRemoved().  Don't
   2218                         // impact normal onStartCommand() processing.
   2219                         r.findDeliveredStart(startId, true);
   2220                         break;
   2221                     }
   2222                     default:
   2223                         throw new IllegalArgumentException(
   2224                                 "Unknown service start result: " + res);
   2225                 }
   2226                 if (res == Service.START_STICKY_COMPATIBILITY) {
   2227                     r.callStart = false;
   2228                 }
   2229             } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
   2230                 // This is the final call from destroying the service...  we should
   2231                 // actually be getting rid of the service at this point.  Do some
   2232                 // validation of its state, and ensure it will be fully removed.
   2233                 if (!inDestroying) {
   2234                     // Not sure what else to do with this...  if it is not actually in the
   2235                     // destroying list, we don't need to make sure to remove it from it.
   2236                     // If the app is null, then it was probably removed because the process died,
   2237                     // otherwise wtf
   2238                     if (r.app != null) {
   2239                         Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
   2240                                 + r + ", app=" + r.app);
   2241                     }
   2242                 } else if (r.executeNesting != 1) {
   2243                     Slog.w(TAG, "Service done with onDestroy, but executeNesting="
   2244                             + r.executeNesting + ": " + r);
   2245                     // Fake it to keep from ANR due to orphaned entry.
   2246                     r.executeNesting = 1;
   2247                 }
   2248             }
   2249             final long origId = Binder.clearCallingIdentity();
   2250             serviceDoneExecutingLocked(r, inDestroying, inDestroying);
   2251             Binder.restoreCallingIdentity(origId);
   2252         } else {
   2253             Slog.w(TAG, "Done executing unknown service from pid "
   2254                     + Binder.getCallingPid());
   2255         }
   2256     }
   2257 
   2258     private void serviceProcessGoneLocked(ServiceRecord r) {
   2259         if (r.tracker != null) {
   2260             int memFactor = mAm.mProcessStats.getMemFactorLocked();
   2261             long now = SystemClock.uptimeMillis();
   2262             r.tracker.setExecuting(false, memFactor, now);
   2263             r.tracker.setBound(false, memFactor, now);
   2264             r.tracker.setStarted(false, memFactor, now);
   2265         }
   2266         serviceDoneExecutingLocked(r, true, true);
   2267     }
   2268 
   2269     private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
   2270             boolean finishing) {
   2271         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
   2272                 + ": nesting=" + r.executeNesting
   2273                 + ", inDestroying=" + inDestroying + ", app=" + r.app);
   2274         else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
   2275                 "<<< DONE EXECUTING " + r.shortName);
   2276         r.executeNesting--;
   2277         if (r.executeNesting <= 0) {
   2278             if (r.app != null) {
   2279                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
   2280                         "Nesting at 0 of " + r.shortName);
   2281                 r.app.execServicesFg = false;
   2282                 r.app.executingServices.remove(r);
   2283                 if (r.app.executingServices.size() == 0) {
   2284                     if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
   2285                             "No more executingServices of " + r.shortName);
   2286                     mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
   2287                 } else if (r.executeFg) {
   2288                     // Need to re-evaluate whether the app still needs to be in the foreground.
   2289                     for (int i=r.app.executingServices.size()-1; i>=0; i--) {
   2290                         if (r.app.executingServices.valueAt(i).executeFg) {
   2291                             r.app.execServicesFg = true;
   2292                             break;
   2293                         }
   2294                     }
   2295                 }
   2296                 if (inDestroying) {
   2297                     if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
   2298                             "doneExecuting remove destroying " + r);
   2299                     mDestroyingServices.remove(r);
   2300                     r.bindings.clear();
   2301                 }
   2302                 mAm.updateOomAdjLocked(r.app);
   2303             }
   2304             r.executeFg = false;
   2305             if (r.tracker != null) {
   2306                 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
   2307                         SystemClock.uptimeMillis());
   2308                 if (finishing) {
   2309                     r.tracker.clearCurrentOwner(r, false);
   2310                     r.tracker = null;
   2311                 }
   2312             }
   2313             if (finishing) {
   2314                 if (r.app != null && !r.app.persistent) {
   2315                     r.app.services.remove(r);
   2316                     if (r.whitelistManager) {
   2317                         updateWhitelistManagerLocked(r.app);
   2318                     }
   2319                 }
   2320                 r.app = null;
   2321             }
   2322         }
   2323     }
   2324 
   2325     boolean attachApplicationLocked(ProcessRecord proc, String processName)
   2326             throws RemoteException {
   2327         boolean didSomething = false;
   2328         // Collect any services that are waiting for this process to come up.
   2329         if (mPendingServices.size() > 0) {
   2330             ServiceRecord sr = null;
   2331             try {
   2332                 for (int i=0; i<mPendingServices.size(); i++) {
   2333                     sr = mPendingServices.get(i);
   2334                     if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
   2335                             || !processName.equals(sr.processName))) {
   2336                         continue;
   2337                     }
   2338 
   2339                     mPendingServices.remove(i);
   2340                     i--;
   2341                     proc.addPackage(sr.appInfo.packageName, sr.appInfo.versionCode,
   2342                             mAm.mProcessStats);
   2343                     realStartServiceLocked(sr, proc, sr.createdFromFg);
   2344                     didSomething = true;
   2345                     if (!isServiceNeeded(sr, false, false)) {
   2346                         // We were waiting for this service to start, but it is actually no
   2347                         // longer needed.  This could happen because bringDownServiceIfNeeded
   2348                         // won't bring down a service that is pending...  so now the pending
   2349                         // is done, so let's drop it.
   2350                         bringDownServiceLocked(sr);
   2351                     }
   2352                 }
   2353             } catch (RemoteException e) {
   2354                 Slog.w(TAG, "Exception in new application when starting service "
   2355                         + sr.shortName, e);
   2356                 throw e;
   2357             }
   2358         }
   2359         // Also, if there are any services that are waiting to restart and
   2360         // would run in this process, now is a good time to start them.  It would
   2361         // be weird to bring up the process but arbitrarily not let the services
   2362         // run at this point just because their restart time hasn't come up.
   2363         if (mRestartingServices.size() > 0) {
   2364             ServiceRecord sr;
   2365             for (int i=0; i<mRestartingServices.size(); i++) {
   2366                 sr = mRestartingServices.get(i);
   2367                 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
   2368                         || !processName.equals(sr.processName))) {
   2369                     continue;
   2370                 }
   2371                 mAm.mHandler.removeCallbacks(sr.restarter);
   2372                 mAm.mHandler.post(sr.restarter);
   2373             }
   2374         }
   2375         return didSomething;
   2376     }
   2377 
   2378     void processStartTimedOutLocked(ProcessRecord proc) {
   2379         for (int i=0; i<mPendingServices.size(); i++) {
   2380             ServiceRecord sr = mPendingServices.get(i);
   2381             if ((proc.uid == sr.appInfo.uid
   2382                     && proc.processName.equals(sr.processName))
   2383                     || sr.isolatedProc == proc) {
   2384                 Slog.w(TAG, "Forcing bringing down service: " + sr);
   2385                 sr.isolatedProc = null;
   2386                 mPendingServices.remove(i);
   2387                 i--;
   2388                 bringDownServiceLocked(sr);
   2389             }
   2390         }
   2391     }
   2392 
   2393     private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
   2394             boolean evenPersistent, boolean doit, boolean killProcess,
   2395             ArrayMap<ComponentName, ServiceRecord> services) {
   2396         boolean didSomething = false;
   2397         for (int i = services.size() - 1; i >= 0; i--) {
   2398             ServiceRecord service = services.valueAt(i);
   2399             final boolean sameComponent = packageName == null
   2400                     || (service.packageName.equals(packageName)
   2401                         && (filterByClasses == null
   2402                             || filterByClasses.contains(service.name.getClassName())));
   2403             if (sameComponent
   2404                     && (service.app == null || evenPersistent || !service.app.persistent)) {
   2405                 if (!doit) {
   2406                     return true;
   2407                 }
   2408                 didSomething = true;
   2409                 Slog.i(TAG, "  Force stopping service " + service);
   2410                 if (service.app != null) {
   2411                     service.app.removed = killProcess;
   2412                     if (!service.app.persistent) {
   2413                         service.app.services.remove(service);
   2414                         if (service.whitelistManager) {
   2415                             updateWhitelistManagerLocked(service.app);
   2416                         }
   2417                     }
   2418                 }
   2419                 service.app = null;
   2420                 service.isolatedProc = null;
   2421                 if (mTmpCollectionResults == null) {
   2422                     mTmpCollectionResults = new ArrayList<>();
   2423                 }
   2424                 mTmpCollectionResults.add(service);
   2425             }
   2426         }
   2427         return didSomething;
   2428     }
   2429 
   2430     boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
   2431             int userId, boolean evenPersistent, boolean killProcess, boolean doit) {
   2432         boolean didSomething = false;
   2433 
   2434         if (mTmpCollectionResults != null) {
   2435             mTmpCollectionResults.clear();
   2436         }
   2437 
   2438         if (userId == UserHandle.USER_ALL) {
   2439             for (int i = mServiceMap.size() - 1; i >= 0; i--) {
   2440                 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
   2441                         evenPersistent, doit, killProcess, mServiceMap.valueAt(i).mServicesByName);
   2442                 if (!doit && didSomething) {
   2443                     return true;
   2444                 }
   2445             }
   2446         } else {
   2447             ServiceMap smap = mServiceMap.get(userId);
   2448             if (smap != null) {
   2449                 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByName;
   2450                 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
   2451                         evenPersistent, doit, killProcess, items);
   2452             }
   2453         }
   2454 
   2455         if (mTmpCollectionResults != null) {
   2456             for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
   2457                 bringDownServiceLocked(mTmpCollectionResults.get(i));
   2458             }
   2459             mTmpCollectionResults.clear();
   2460         }
   2461         return didSomething;
   2462     }
   2463 
   2464     void cleanUpRemovedTaskLocked(TaskRecord tr, ComponentName component, Intent baseIntent) {
   2465         ArrayList<ServiceRecord> services = new ArrayList<>();
   2466         ArrayMap<ComponentName, ServiceRecord> alls = getServices(tr.userId);
   2467         for (int i = alls.size() - 1; i >= 0; i--) {
   2468             ServiceRecord sr = alls.valueAt(i);
   2469             if (sr.packageName.equals(component.getPackageName())) {
   2470                 services.add(sr);
   2471             }
   2472         }
   2473 
   2474         // Take care of any running services associated with the app.
   2475         for (int i = services.size() - 1; i >= 0; i--) {
   2476             ServiceRecord sr = services.get(i);
   2477             if (sr.startRequested) {
   2478                 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
   2479                     Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
   2480                     stopServiceLocked(sr);
   2481                 } else {
   2482                     sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
   2483                             sr.makeNextStartId(), baseIntent, null));
   2484                     if (sr.app != null && sr.app.thread != null) {
   2485                         // We always run in the foreground, since this is called as
   2486                         // part of the "remove task" UI operation.
   2487                         try {
   2488                             sendServiceArgsLocked(sr, true, false);
   2489                         } catch (TransactionTooLargeException e) {
   2490                             // Ignore, keep going.
   2491                         }
   2492                     }
   2493                 }
   2494             }
   2495         }
   2496     }
   2497 
   2498     final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
   2499         // Report disconnected services.
   2500         if (false) {
   2501             // XXX we are letting the client link to the service for
   2502             // death notifications.
   2503             if (app.services.size() > 0) {
   2504                 Iterator<ServiceRecord> it = app.services.iterator();
   2505                 while (it.hasNext()) {
   2506                     ServiceRecord r = it.next();
   2507                     for (int conni=r.connections.size()-1; conni>=0; conni--) {
   2508                         ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
   2509                         for (int i=0; i<cl.size(); i++) {
   2510                             ConnectionRecord c = cl.get(i);
   2511                             if (c.binding.client != app) {
   2512                                 try {
   2513                                     //c.conn.connected(r.className, null);
   2514                                 } catch (Exception e) {
   2515                                     // todo: this should be asynchronous!
   2516                                     Slog.w(TAG, "Exception thrown disconnected servce "
   2517                                           + r.shortName
   2518                                           + " from app " + app.processName, e);
   2519                                 }
   2520                             }
   2521                         }
   2522                     }
   2523                 }
   2524             }
   2525         }
   2526 
   2527         // Clean up any connections this application has to other services.
   2528         for (int i = app.connections.size() - 1; i >= 0; i--) {
   2529             ConnectionRecord r = app.connections.valueAt(i);
   2530             removeConnectionLocked(r, app, null);
   2531         }
   2532         updateServiceConnectionActivitiesLocked(app);
   2533         app.connections.clear();
   2534 
   2535         app.whitelistManager = false;
   2536 
   2537         // Clear app state from services.
   2538         for (int i = app.services.size() - 1; i >= 0; i--) {
   2539             ServiceRecord sr = app.services.valueAt(i);
   2540             synchronized (sr.stats.getBatteryStats()) {
   2541                 sr.stats.stopLaunchedLocked();
   2542             }
   2543             if (sr.app != app && sr.app != null && !sr.app.persistent) {
   2544                 sr.app.services.remove(sr);
   2545             }
   2546             sr.app = null;
   2547             sr.isolatedProc = null;
   2548             sr.executeNesting = 0;
   2549             sr.forceClearTracker();
   2550             if (mDestroyingServices.remove(sr)) {
   2551                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
   2552             }
   2553 
   2554             final int numClients = sr.bindings.size();
   2555             for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
   2556                 IntentBindRecord b = sr.bindings.valueAt(bindingi);
   2557                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
   2558                         + ": shouldUnbind=" + b.hasBound);
   2559                 b.binder = null;
   2560                 b.requested = b.received = b.hasBound = false;
   2561                 // If this binding is coming from a cached process and is asking to keep
   2562                 // the service created, then we'll kill the cached process as well -- we
   2563                 // don't want to be thrashing around restarting processes that are only
   2564                 // there to be cached.
   2565                 for (int appi=b.apps.size()-1; appi>=0; appi--) {
   2566                     final ProcessRecord proc = b.apps.keyAt(appi);
   2567                     // If the process is already gone, skip it.
   2568                     if (proc.killedByAm || proc.thread == null) {
   2569                         continue;
   2570                     }
   2571                     // Only do this for processes that have an auto-create binding;
   2572                     // otherwise the binding can be left, because it won't cause the
   2573                     // service to restart.
   2574                     final AppBindRecord abind = b.apps.valueAt(appi);
   2575                     boolean hasCreate = false;
   2576                     for (int conni=abind.connections.size()-1; conni>=0; conni--) {
   2577                         ConnectionRecord conn = abind.connections.valueAt(conni);
   2578                         if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
   2579                                 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
   2580                             hasCreate = true;
   2581                             break;
   2582                         }
   2583                     }
   2584                     if (!hasCreate) {
   2585                         continue;
   2586                     }
   2587                     // XXX turned off for now until we have more time to get a better policy.
   2588                     if (false && proc != null && !proc.persistent && proc.thread != null
   2589                             && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
   2590                             && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
   2591                         proc.kill("bound to service " + sr.name.flattenToShortString()
   2592                                 + " in dying proc " + (app != null ? app.processName : "??"), true);
   2593                     }
   2594                 }
   2595             }
   2596         }
   2597 
   2598         ServiceMap smap = getServiceMap(app.userId);
   2599 
   2600         // Now do remaining service cleanup.
   2601         for (int i=app.services.size()-1; i>=0; i--) {
   2602             ServiceRecord sr = app.services.valueAt(i);
   2603 
   2604             // Unless the process is persistent, this process record is going away,
   2605             // so make sure the service is cleaned out of it.
   2606             if (!app.persistent) {
   2607                 app.services.removeAt(i);
   2608             }
   2609 
   2610             // Sanity check: if the service listed for the app is not one
   2611             // we actually are maintaining, just let it drop.
   2612             final ServiceRecord curRec = smap.mServicesByName.get(sr.name);
   2613             if (curRec != sr) {
   2614                 if (curRec != null) {
   2615                     Slog.wtf(TAG, "Service " + sr + " in process " + app
   2616                             + " not same as in map: " + curRec);
   2617                 }
   2618                 continue;
   2619             }
   2620 
   2621             // Any services running in the application may need to be placed
   2622             // back in the pending list.
   2623             if (allowRestart && sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
   2624                     &ApplicationInfo.FLAG_PERSISTENT) == 0) {
   2625                 Slog.w(TAG, "Service crashed " + sr.crashCount
   2626                         + " times, stopping: " + sr);
   2627                 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
   2628                         sr.userId, sr.crashCount, sr.shortName, app.pid);
   2629                 bringDownServiceLocked(sr);
   2630             } else if (!allowRestart
   2631                     || !mAm.mUserController.isUserRunningLocked(sr.userId, 0)) {
   2632                 bringDownServiceLocked(sr);
   2633             } else {
   2634                 boolean canceled = scheduleServiceRestartLocked(sr, true);
   2635 
   2636                 // Should the service remain running?  Note that in the
   2637                 // extreme case of so many attempts to deliver a command
   2638                 // that it failed we also will stop it here.
   2639                 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
   2640                     if (sr.pendingStarts.size() == 0) {
   2641                         sr.startRequested = false;
   2642                         if (sr.tracker != null) {
   2643                             sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
   2644                                     SystemClock.uptimeMillis());
   2645                         }
   2646                         if (!sr.hasAutoCreateConnections()) {
   2647                             // Whoops, no reason to restart!
   2648                             bringDownServiceLocked(sr);
   2649                         }
   2650                     }
   2651                 }
   2652             }
   2653         }
   2654 
   2655         if (!allowRestart) {
   2656             app.services.clear();
   2657 
   2658             // Make sure there are no more restarting services for this process.
   2659             for (int i=mRestartingServices.size()-1; i>=0; i--) {
   2660                 ServiceRecord r = mRestartingServices.get(i);
   2661                 if (r.processName.equals(app.processName) &&
   2662                         r.serviceInfo.applicationInfo.uid == app.info.uid) {
   2663                     mRestartingServices.remove(i);
   2664                     clearRestartingIfNeededLocked(r);
   2665                 }
   2666             }
   2667             for (int i=mPendingServices.size()-1; i>=0; i--) {
   2668                 ServiceRecord r = mPendingServices.get(i);
   2669                 if (r.processName.equals(app.processName) &&
   2670                         r.serviceInfo.applicationInfo.uid == app.info.uid) {
   2671                     mPendingServices.remove(i);
   2672                 }
   2673             }
   2674         }
   2675 
   2676         // Make sure we have no more records on the stopping list.
   2677         int i = mDestroyingServices.size();
   2678         while (i > 0) {
   2679             i--;
   2680             ServiceRecord sr = mDestroyingServices.get(i);
   2681             if (sr.app == app) {
   2682                 sr.forceClearTracker();
   2683                 mDestroyingServices.remove(i);
   2684                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
   2685             }
   2686         }
   2687 
   2688         app.executingServices.clear();
   2689     }
   2690 
   2691     ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
   2692         ActivityManager.RunningServiceInfo info =
   2693             new ActivityManager.RunningServiceInfo();
   2694         info.service = r.name;
   2695         if (r.app != null) {
   2696             info.pid = r.app.pid;
   2697         }
   2698         info.uid = r.appInfo.uid;
   2699         info.process = r.processName;
   2700         info.foreground = r.isForeground;
   2701         info.activeSince = r.createTime;
   2702         info.started = r.startRequested;
   2703         info.clientCount = r.connections.size();
   2704         info.crashCount = r.crashCount;
   2705         info.lastActivityTime = r.lastActivity;
   2706         if (r.isForeground) {
   2707             info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
   2708         }
   2709         if (r.startRequested) {
   2710             info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
   2711         }
   2712         if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
   2713             info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
   2714         }
   2715         if (r.app != null && r.app.persistent) {
   2716             info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
   2717         }
   2718 
   2719         for (int conni=r.connections.size()-1; conni>=0; conni--) {
   2720             ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
   2721             for (int i=0; i<connl.size(); i++) {
   2722                 ConnectionRecord conn = connl.get(i);
   2723                 if (conn.clientLabel != 0) {
   2724                     info.clientPackage = conn.binding.client.info.packageName;
   2725                     info.clientLabel = conn.clientLabel;
   2726                     return info;
   2727                 }
   2728             }
   2729         }
   2730         return info;
   2731     }
   2732 
   2733     List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum,
   2734             int flags) {
   2735         ArrayList<ActivityManager.RunningServiceInfo> res
   2736                 = new ArrayList<ActivityManager.RunningServiceInfo>();
   2737 
   2738         final int uid = Binder.getCallingUid();
   2739         final long ident = Binder.clearCallingIdentity();
   2740         try {
   2741             if (ActivityManager.checkUidPermission(
   2742                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
   2743                     uid) == PackageManager.PERMISSION_GRANTED) {
   2744                 int[] users = mAm.mUserController.getUsers();
   2745                 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
   2746                     ArrayMap<ComponentName, ServiceRecord> alls = getServices(users[ui]);
   2747                     for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
   2748                         ServiceRecord sr = alls.valueAt(i);
   2749                         res.add(makeRunningServiceInfoLocked(sr));
   2750                     }
   2751                 }
   2752 
   2753                 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
   2754                     ServiceRecord r = mRestartingServices.get(i);
   2755                     ActivityManager.RunningServiceInfo info =
   2756                             makeRunningServiceInfoLocked(r);
   2757                     info.restarting = r.nextRestartTime;
   2758                     res.add(info);
   2759                 }
   2760             } else {
   2761                 int userId = UserHandle.getUserId(uid);
   2762                 ArrayMap<ComponentName, ServiceRecord> alls = getServices(userId);
   2763                 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
   2764                     ServiceRecord sr = alls.valueAt(i);
   2765                     res.add(makeRunningServiceInfoLocked(sr));
   2766                 }
   2767 
   2768                 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
   2769                     ServiceRecord r = mRestartingServices.get(i);
   2770                     if (r.userId == userId) {
   2771                         ActivityManager.RunningServiceInfo info =
   2772                                 makeRunningServiceInfoLocked(r);
   2773                         info.restarting = r.nextRestartTime;
   2774                         res.add(info);
   2775                     }
   2776                 }
   2777             }
   2778         } finally {
   2779             Binder.restoreCallingIdentity(ident);
   2780         }
   2781 
   2782         return res;
   2783     }
   2784 
   2785     public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
   2786         int userId = UserHandle.getUserId(Binder.getCallingUid());
   2787         ServiceRecord r = getServiceByName(name, userId);
   2788         if (r != null) {
   2789             for (int conni=r.connections.size()-1; conni>=0; conni--) {
   2790                 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
   2791                 for (int i=0; i<conn.size(); i++) {
   2792                     if (conn.get(i).clientIntent != null) {
   2793                         return conn.get(i).clientIntent;
   2794                     }
   2795                 }
   2796             }
   2797         }
   2798         return null;
   2799     }
   2800 
   2801     void serviceTimeout(ProcessRecord proc) {
   2802         String anrMessage = null;
   2803 
   2804         synchronized(mAm) {
   2805             if (proc.executingServices.size() == 0 || proc.thread == null) {
   2806                 return;
   2807             }
   2808             final long now = SystemClock.uptimeMillis();
   2809             final long maxTime =  now -
   2810                     (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
   2811             ServiceRecord timeout = null;
   2812             long nextTime = 0;
   2813             for (int i=proc.executingServices.size()-1; i>=0; i--) {
   2814                 ServiceRecord sr = proc.executingServices.valueAt(i);
   2815                 if (sr.executingStart < maxTime) {
   2816                     timeout = sr;
   2817                     break;
   2818                 }
   2819                 if (sr.executingStart > nextTime) {
   2820                     nextTime = sr.executingStart;
   2821                 }
   2822             }
   2823             if (timeout != null && mAm.mLruProcesses.contains(proc)) {
   2824                 Slog.w(TAG, "Timeout executing service: " + timeout);
   2825                 StringWriter sw = new StringWriter();
   2826                 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
   2827                 pw.println(timeout);
   2828                 timeout.dump(pw, "    ");
   2829                 pw.close();
   2830                 mLastAnrDump = sw.toString();
   2831                 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
   2832                 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
   2833                 anrMessage = "executing service " + timeout.shortName;
   2834             } else {
   2835                 Message msg = mAm.mHandler.obtainMessage(
   2836                         ActivityManagerService.SERVICE_TIMEOUT_MSG);
   2837                 msg.obj = proc;
   2838                 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
   2839                         ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
   2840             }
   2841         }
   2842 
   2843         if (anrMessage != null) {
   2844             mAm.mAppErrors.appNotResponding(proc, null, null, false, anrMessage);
   2845         }
   2846     }
   2847 
   2848     void scheduleServiceTimeoutLocked(ProcessRecord proc) {
   2849         if (proc.executingServices.size() == 0 || proc.thread == null) {
   2850             return;
   2851         }
   2852         long now = SystemClock.uptimeMillis();
   2853         Message msg = mAm.mHandler.obtainMessage(
   2854                 ActivityManagerService.SERVICE_TIMEOUT_MSG);
   2855         msg.obj = proc;
   2856         mAm.mHandler.sendMessageAtTime(msg,
   2857                 proc.execServicesFg ? (now+SERVICE_TIMEOUT) : (now+ SERVICE_BACKGROUND_TIMEOUT));
   2858     }
   2859 
   2860     /**
   2861      * Prints a list of ServiceRecords (dumpsys activity services)
   2862      */
   2863     List<ServiceRecord> collectServicesToDumpLocked(ItemMatcher matcher, String dumpPackage) {
   2864         final ArrayList<ServiceRecord> services = new ArrayList<>();
   2865         final int[] users = mAm.mUserController.getUsers();
   2866         for (int user : users) {
   2867             ServiceMap smap = getServiceMap(user);
   2868             if (smap.mServicesByName.size() > 0) {
   2869                 for (int si=0; si<smap.mServicesByName.size(); si++) {
   2870                     ServiceRecord r = smap.mServicesByName.valueAt(si);
   2871                     if (!matcher.match(r, r.name)) {
   2872                         continue;
   2873                     }
   2874                     if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
   2875                         continue;
   2876                     }
   2877                     services.add(r);
   2878                 }
   2879             }
   2880         }
   2881 
   2882         return services;
   2883     }
   2884 
   2885     final class ServiceDumper {
   2886         private final FileDescriptor fd;
   2887         private final PrintWriter pw;
   2888         private final String[] args;
   2889         private final int opti;
   2890         private final boolean dumpAll;
   2891         private final String dumpPackage;
   2892         private final ItemMatcher matcher;
   2893         private final ArrayList<ServiceRecord> services = new ArrayList<>();
   2894 
   2895         private final long nowReal = SystemClock.elapsedRealtime();
   2896 
   2897         private boolean needSep = false;
   2898         private boolean printedAnything = false;
   2899         private boolean printed = false;
   2900 
   2901         /**
   2902          * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
   2903          * must be called with the lock held).
   2904          */
   2905         ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
   2906                 int opti, boolean dumpAll, String dumpPackage) {
   2907             this.fd = fd;
   2908             this.pw = pw;
   2909             this.args = args;
   2910             this.opti = opti;
   2911             this.dumpAll = dumpAll;
   2912             this.dumpPackage = dumpPackage;
   2913             matcher = new ItemMatcher();
   2914             matcher.build(args, opti);
   2915 
   2916             final int[] users = mAm.mUserController.getUsers();
   2917             for (int user : users) {
   2918                 ServiceMap smap = getServiceMap(user);
   2919                 if (smap.mServicesByName.size() > 0) {
   2920                     for (int si=0; si<smap.mServicesByName.size(); si++) {
   2921                         ServiceRecord r = smap.mServicesByName.valueAt(si);
   2922                         if (!matcher.match(r, r.name)) {
   2923                             continue;
   2924                         }
   2925                         if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
   2926                             continue;
   2927                         }
   2928                         services.add(r);
   2929                     }
   2930                 }
   2931             }
   2932         }
   2933 
   2934         private void dumpHeaderLocked() {
   2935             pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
   2936             if (mLastAnrDump != null) {
   2937                 pw.println("  Last ANR service:");
   2938                 pw.print(mLastAnrDump);
   2939                 pw.println();
   2940             }
   2941         }
   2942 
   2943         void dumpLocked() {
   2944             dumpHeaderLocked();
   2945 
   2946             try {
   2947                 int[] users = mAm.mUserController.getUsers();
   2948                 for (int user : users) {
   2949                     // Find the first service for this user.
   2950                     int serviceIdx = 0;
   2951                     while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
   2952                         serviceIdx++;
   2953                     }
   2954                     printed = false;
   2955                     if (serviceIdx < services.size()) {
   2956                         needSep = false;
   2957                         while (serviceIdx < services.size()) {
   2958                             ServiceRecord r = services.get(serviceIdx);
   2959                             serviceIdx++;
   2960                             if (r.userId != user) {
   2961                                 break;
   2962                             }
   2963                             dumpServiceLocalLocked(r);
   2964                         }
   2965                         needSep |= printed;
   2966                     }
   2967 
   2968                     dumpUserRemainsLocked(user);
   2969                 }
   2970             } catch (Exception e) {
   2971                 Slog.w(TAG, "Exception in dumpServicesLocked", e);
   2972             }
   2973 
   2974             dumpRemainsLocked();
   2975         }
   2976 
   2977         void dumpWithClient() {
   2978             synchronized(mAm) {
   2979                 dumpHeaderLocked();
   2980             }
   2981 
   2982             try {
   2983                 int[] users = mAm.mUserController.getUsers();
   2984                 for (int user : users) {
   2985                     // Find the first service for this user.
   2986                     int serviceIdx = 0;
   2987                     while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
   2988                         serviceIdx++;
   2989                     }
   2990                     printed = false;
   2991                     if (serviceIdx < services.size()) {
   2992                         needSep = false;
   2993                         while (serviceIdx < services.size()) {
   2994                             ServiceRecord r = services.get(serviceIdx);
   2995                             serviceIdx++;
   2996                             if (r.userId != user) {
   2997                                 break;
   2998                             }
   2999                             synchronized(mAm) {
   3000                                 dumpServiceLocalLocked(r);
   3001                             }
   3002                             dumpServiceClient(r);
   3003                         }
   3004                         needSep |= printed;
   3005                     }
   3006 
   3007                     synchronized(mAm) {
   3008                         dumpUserRemainsLocked(user);
   3009                     }
   3010                 }
   3011             } catch (Exception e) {
   3012                 Slog.w(TAG, "Exception in dumpServicesLocked", e);
   3013             }
   3014 
   3015             synchronized(mAm) {
   3016                 dumpRemainsLocked();
   3017             }
   3018         }
   3019 
   3020         private void dumpUserHeaderLocked(int user) {
   3021             if (!printed) {
   3022                 if (printedAnything) {
   3023                     pw.println();
   3024                 }
   3025                 pw.println("  User " + user + " active services:");
   3026                 printed = true;
   3027             }
   3028             printedAnything = true;
   3029             if (needSep) {
   3030                 pw.println();
   3031             }
   3032         }
   3033 
   3034         private void dumpServiceLocalLocked(ServiceRecord r) {
   3035             dumpUserHeaderLocked(r.userId);
   3036             pw.print("  * ");
   3037             pw.println(r);
   3038             if (dumpAll) {
   3039                 r.dump(pw, "    ");
   3040                 needSep = true;
   3041             } else {
   3042                 pw.print("    app=");
   3043                 pw.println(r.app);
   3044                 pw.print("    created=");
   3045                 TimeUtils.formatDuration(r.createTime, nowReal, pw);
   3046                 pw.print(" started=");
   3047                 pw.print(r.startRequested);
   3048                 pw.print(" connections=");
   3049                 pw.println(r.connections.size());
   3050                 if (r.connections.size() > 0) {
   3051                     pw.println("    Connections:");
   3052                     for (int conni=0; conni<r.connections.size(); conni++) {
   3053                         ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
   3054                         for (int i = 0; i < clist.size(); i++) {
   3055                             ConnectionRecord conn = clist.get(i);
   3056                             pw.print("      ");
   3057                             pw.print(conn.binding.intent.intent.getIntent()
   3058                                     .toShortString(false, false, false, false));
   3059                             pw.print(" -> ");
   3060                             ProcessRecord proc = conn.binding.client;
   3061                             pw.println(proc != null ? proc.toShortString() : "null");
   3062                         }
   3063                     }
   3064                 }
   3065             }
   3066         }
   3067 
   3068         private void dumpServiceClient(ServiceRecord r) {
   3069             final ProcessRecord proc = r.app;
   3070             if (proc == null) {
   3071                 return;
   3072             }
   3073             final IApplicationThread thread = proc.thread;
   3074             if (thread == null) {
   3075                 return;
   3076             }
   3077             pw.println("    Client:");
   3078             pw.flush();
   3079             try {
   3080                 TransferPipe tp = new TransferPipe();
   3081                 try {
   3082                     thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
   3083                     tp.setBufferPrefix("      ");
   3084                     // Short timeout, since blocking here can
   3085                     // deadlock with the application.
   3086                     tp.go(fd, 2000);
   3087                 } finally {
   3088                     tp.kill();
   3089                 }
   3090             } catch (IOException e) {
   3091                 pw.println("      Failure while dumping the service: " + e);
   3092             } catch (RemoteException e) {
   3093                 pw.println("      Got a RemoteException while dumping the service");
   3094             }
   3095             needSep = true;
   3096         }
   3097 
   3098         private void dumpUserRemainsLocked(int user) {
   3099             ServiceMap smap = getServiceMap(user);
   3100             printed = false;
   3101             for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
   3102                 ServiceRecord r = smap.mDelayedStartList.get(si);
   3103                 if (!matcher.match(r, r.name)) {
   3104                     continue;
   3105                 }
   3106                 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
   3107                     continue;
   3108                 }
   3109                 if (!printed) {
   3110                     if (printedAnything) {
   3111                         pw.println();
   3112                     }
   3113                     pw.println("  User " + user + " delayed start services:");
   3114                     printed = true;
   3115                 }
   3116                 printedAnything = true;
   3117                 pw.print("  * Delayed start "); pw.println(r);
   3118             }
   3119             printed = false;
   3120             for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
   3121                 ServiceRecord r = smap.mStartingBackground.get(si);
   3122                 if (!matcher.match(r, r.name)) {
   3123                     continue;
   3124                 }
   3125                 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
   3126                     continue;
   3127                 }
   3128                 if (!printed) {
   3129                     if (printedAnything) {
   3130                         pw.println();
   3131                     }
   3132                     pw.println("  User " + user + " starting in background:");
   3133                     printed = true;
   3134                 }
   3135                 printedAnything = true;
   3136                 pw.print("  * Starting bg "); pw.println(r);
   3137             }
   3138         }
   3139 
   3140         private void dumpRemainsLocked() {
   3141             if (mPendingServices.size() > 0) {
   3142                 printed = false;
   3143                 for (int i=0; i<mPendingServices.size(); i++) {
   3144                     ServiceRecord r = mPendingServices.get(i);
   3145                     if (!matcher.match(r, r.name)) {
   3146                         continue;
   3147                     }
   3148                     if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
   3149                         continue;
   3150                     }
   3151                     printedAnything = true;
   3152                     if (!printed) {
   3153                         if (needSep) pw.println();
   3154                         needSep = true;
   3155                         pw.println("  Pending services:");
   3156                         printed = true;
   3157                     }
   3158                     pw.print("  * Pending "); pw.println(r);
   3159                     r.dump(pw, "    ");
   3160                 }
   3161                 needSep = true;
   3162             }
   3163 
   3164             if (mRestartingServices.size() > 0) {
   3165                 printed = false;
   3166                 for (int i=0; i<mRestartingServices.size(); i++) {
   3167                     ServiceRecord r = mRestartingServices.get(i);
   3168                     if (!matcher.match(r, r.name)) {
   3169                         continue;
   3170                     }
   3171                     if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
   3172                         continue;
   3173                     }
   3174                     printedAnything = true;
   3175                     if (!printed) {
   3176                         if (needSep) pw.println();
   3177                         needSep = true;
   3178                         pw.println("  Restarting services:");
   3179                         printed = true;
   3180                     }
   3181                     pw.print("  * Restarting "); pw.println(r);
   3182                     r.dump(pw, "    ");
   3183                 }
   3184                 needSep = true;
   3185             }
   3186 
   3187             if (mDestroyingServices.size() > 0) {
   3188                 printed = false;
   3189                 for (int i=0; i< mDestroyingServices.size(); i++) {
   3190                     ServiceRecord r = mDestroyingServices.get(i);
   3191                     if (!matcher.match(r, r.name)) {
   3192                         continue;
   3193                     }
   3194                     if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
   3195                         continue;
   3196                     }
   3197                     printedAnything = true;
   3198                     if (!printed) {
   3199                         if (needSep) pw.println();
   3200                         needSep = true;
   3201                         pw.println("  Destroying services:");
   3202                         printed = true;
   3203                     }
   3204                     pw.print("  * Destroy "); pw.println(r);
   3205                     r.dump(pw, "    ");
   3206                 }
   3207                 needSep = true;
   3208             }
   3209 
   3210             if (dumpAll) {
   3211                 printed = false;
   3212                 for (int ic=0; ic<mServiceConnections.size(); ic++) {
   3213                     ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
   3214                     for (int i=0; i<r.size(); i++) {
   3215                         ConnectionRecord cr = r.get(i);
   3216                         if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
   3217                             continue;
   3218                         }
   3219                         if (dumpPackage != null && (cr.binding.client == null
   3220                                 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
   3221                             continue;
   3222                         }
   3223                         printedAnything = true;
   3224                         if (!printed) {
   3225                             if (needSep) pw.println();
   3226                             needSep = true;
   3227                             pw.println("  Connection bindings to services:");
   3228                             printed = true;
   3229                         }
   3230                         pw.print("  * "); pw.println(cr);
   3231                         cr.dump(pw, "    ");
   3232                     }
   3233                 }
   3234             }
   3235 
   3236             if (!printedAnything) {
   3237                 pw.println("  (nothing)");
   3238             }
   3239         }
   3240     }
   3241 
   3242     ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
   3243             int opti, boolean dumpAll, String dumpPackage) {
   3244         return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
   3245     }
   3246 
   3247     /**
   3248      * There are three ways to call this:
   3249      *  - no service specified: dump all the services
   3250      *  - a flattened component name that matched an existing service was specified as the
   3251      *    first arg: dump that one service
   3252      *  - the first arg isn't the flattened component name of an existing service:
   3253      *    dump all services whose component contains the first arg as a substring
   3254      */
   3255     protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
   3256             int opti, boolean dumpAll) {
   3257         ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
   3258 
   3259         synchronized (mAm) {
   3260             int[] users = mAm.mUserController.getUsers();
   3261             if ("all".equals(name)) {
   3262                 for (int user : users) {
   3263                     ServiceMap smap = mServiceMap.get(user);
   3264                     if (smap == null) {
   3265                         continue;
   3266                     }
   3267                     ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
   3268                     for (int i=0; i<alls.size(); i++) {
   3269                         ServiceRecord r1 = alls.valueAt(i);
   3270                         services.add(r1);
   3271                     }
   3272                 }
   3273             } else {
   3274                 ComponentName componentName = name != null
   3275                         ? ComponentName.unflattenFromString(name) : null;
   3276                 int objectId = 0;
   3277                 if (componentName == null) {
   3278                     // Not a '/' separated full component name; maybe an object ID?
   3279                     try {
   3280                         objectId = Integer.parseInt(name, 16);
   3281                         name = null;
   3282                         componentName = null;
   3283                     } catch (RuntimeException e) {
   3284                     }
   3285                 }
   3286 
   3287                 for (int user : users) {
   3288                     ServiceMap smap = mServiceMap.get(user);
   3289                     if (smap == null) {
   3290                         continue;
   3291                     }
   3292                     ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
   3293                     for (int i=0; i<alls.size(); i++) {
   3294                         ServiceRecord r1 = alls.valueAt(i);
   3295                         if (componentName != null) {
   3296                             if (r1.name.equals(componentName)) {
   3297                                 services.add(r1);
   3298                             }
   3299                         } else if (name != null) {
   3300                             if (r1.name.flattenToString().contains(name)) {
   3301                                 services.add(r1);
   3302                             }
   3303                         } else if (System.identityHashCode(r1) == objectId) {
   3304                             services.add(r1);
   3305                         }
   3306                     }
   3307                 }
   3308             }
   3309         }
   3310 
   3311         if (services.size() <= 0) {
   3312             return false;
   3313         }
   3314 
   3315         boolean needSep = false;
   3316         for (int i=0; i<services.size(); i++) {
   3317             if (needSep) {
   3318                 pw.println();
   3319             }
   3320             needSep = true;
   3321             dumpService("", fd, pw, services.get(i), args, dumpAll);
   3322         }
   3323         return true;
   3324     }
   3325 
   3326     /**
   3327      * Invokes IApplicationThread.dumpService() on the thread of the specified service if
   3328      * there is a thread associated with the service.
   3329      */
   3330     private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
   3331             final ServiceRecord r, String[] args, boolean dumpAll) {
   3332         String innerPrefix = prefix + "  ";
   3333         synchronized (mAm) {
   3334             pw.print(prefix); pw.print("SERVICE ");
   3335                     pw.print(r.shortName); pw.print(" ");
   3336                     pw.print(Integer.toHexString(System.identityHashCode(r)));
   3337                     pw.print(" pid=");
   3338                     if (r.app != null) pw.println(r.app.pid);
   3339                     else pw.println("(not running)");
   3340             if (dumpAll) {
   3341                 r.dump(pw, innerPrefix);
   3342             }
   3343         }
   3344         if (r.app != null && r.app.thread != null) {
   3345             pw.print(prefix); pw.println("  Client:");
   3346             pw.flush();
   3347             try {
   3348                 TransferPipe tp = new TransferPipe();
   3349                 try {
   3350                     r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
   3351                     tp.setBufferPrefix(prefix + "    ");
   3352                     tp.go(fd);
   3353                 } finally {
   3354                     tp.kill();
   3355                 }
   3356             } catch (IOException e) {
   3357                 pw.println(prefix + "    Failure while dumping the service: " + e);
   3358             } catch (RemoteException e) {
   3359                 pw.println(prefix + "    Got a RemoteException while dumping the service");
   3360             }
   3361         }
   3362     }
   3363 }
   3364