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