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, UserHandle.getUserId(r.appInfo.uid))
1047                                            != 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 if (r.crashCount > 1) {
1930                r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
1931                        * (r.crashCount - 1);
1932            } else {
1933                // If it has been a "reasonably long time" since the service
1934                // was started, then reset our restart duration back to
1935                // the beginning, so we don't infinitely increase the duration
1936                // on a service that just occasionally gets killed (which is
1937                // a normal case, due to process being killed to reclaim memory).
1938                if (now > (r.restartTime+resetTime)) {
1939                    r.restartCount = 1;
1940                    r.restartDelay = minDuration;
1941                } else {
1942                    r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
1943                    if (r.restartDelay < minDuration) {
1944                        r.restartDelay = minDuration;
1945                    }
1946                }
1947            }
1948
1949            r.nextRestartTime = now + r.restartDelay;
1950
1951            // Make sure that we don't end up restarting a bunch of services
1952            // all at the same time.
1953            boolean repeat;
1954            do {
1955                repeat = false;
1956                final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
1957                for (int i=mRestartingServices.size()-1; i>=0; i--) {
1958                    ServiceRecord r2 = mRestartingServices.get(i);
1959                    if (r2 != r && r.nextRestartTime >= (r2.nextRestartTime-restartTimeBetween)
1960                            && r.nextRestartTime < (r2.nextRestartTime+restartTimeBetween)) {
1961                        r.nextRestartTime = r2.nextRestartTime + restartTimeBetween;
1962                        r.restartDelay = r.nextRestartTime - now;
1963                        repeat = true;
1964                        break;
1965                    }
1966                }
1967            } while (repeat);
1968
1969        } else {
1970            // Persistent processes are immediately restarted, so there is no
1971            // reason to hold of on restarting their services.
1972            r.totalRestartCount++;
1973            r.restartCount = 0;
1974            r.restartDelay = 0;
1975            r.nextRestartTime = now;
1976        }
1977
1978        if (!mRestartingServices.contains(r)) {
1979            r.createdFromFg = false;
1980            mRestartingServices.add(r);
1981            r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
1982        }
1983
1984        cancelForegroundNotificationLocked(r);
1985
1986        mAm.mHandler.removeCallbacks(r.restarter);
1987        mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
1988        r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
1989        Slog.w(TAG, "Scheduling restart of crashed service "
1990                + r.shortName + " in " + r.restartDelay + "ms");
1991        EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
1992                r.userId, r.shortName, r.restartDelay);
1993
1994        return canceled;
1995    }
1996
1997    final void performServiceRestartLocked(ServiceRecord r) {
1998        if (!mRestartingServices.contains(r)) {
1999            return;
2000        }
2001        if (!isServiceNeededLocked(r, false, false)) {
2002            // Paranoia: is this service actually needed?  In theory a service that is not
2003            // needed should never remain on the restart list.  In practice...  well, there
2004            // have been bugs where this happens, and bad things happen because the process
2005            // ends up just being cached, so quickly killed, then restarted again and again.
2006            // Let's not let that happen.
2007            Slog.wtf(TAG, "Restarting service that is not needed: " + r);
2008            return;
2009        }
2010        try {
2011            bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
2012        } catch (TransactionTooLargeException e) {
2013            // Ignore, it's been logged and nothing upstack cares.
2014        }
2015    }
2016
2017    private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
2018            boolean force) {
2019        if (!force && r.restartDelay == 0) {
2020            return false;
2021        }
2022        // Remove from the restarting list; if the service is currently on the
2023        // restarting list, or the call is coming from another app, then this
2024        // service has become of much more interest so we reset the restart interval.
2025        boolean removed = mRestartingServices.remove(r);
2026        if (removed || callingUid != r.appInfo.uid) {
2027            r.resetRestartCounter();
2028        }
2029        if (removed) {
2030            clearRestartingIfNeededLocked(r);
2031        }
2032        mAm.mHandler.removeCallbacks(r.restarter);
2033        return true;
2034    }
2035
2036    private void clearRestartingIfNeededLocked(ServiceRecord r) {
2037        if (r.restartTracker != null) {
2038            // If this is the last restarting record with this tracker, then clear
2039            // the tracker's restarting state.
2040            boolean stillTracking = false;
2041            for (int i=mRestartingServices.size()-1; i>=0; i--) {
2042                if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
2043                    stillTracking = true;
2044                    break;
2045                }
2046            }
2047            if (!stillTracking) {
2048                r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
2049                        SystemClock.uptimeMillis());
2050                r.restartTracker = null;
2051            }
2052        }
2053    }
2054
2055    private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
2056            boolean whileRestarting, boolean permissionsReviewRequired)
2057            throws TransactionTooLargeException {
2058        //Slog.i(TAG, "Bring up service:");
2059        //r.dump("  ");
2060
2061        if (r.app != null && r.app.thread != null) {
2062            sendServiceArgsLocked(r, execInFg, false);
2063            return null;
2064        }
2065
2066        if (!whileRestarting && mRestartingServices.contains(r)) {
2067            // If waiting for a restart, then do nothing.
2068            return null;
2069        }
2070
2071        if (DEBUG_SERVICE) {
2072            Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
2073        }
2074
2075        // We are now bringing the service up, so no longer in the
2076        // restarting state.
2077        if (mRestartingServices.remove(r)) {
2078            clearRestartingIfNeededLocked(r);
2079        }
2080
2081        // Make sure this service is no longer considered delayed, we are starting it now.
2082        if (r.delayed) {
2083            if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
2084            getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
2085            r.delayed = false;
2086        }
2087
2088        // Make sure that the user who owns this service is started.  If not,
2089        // we don't want to allow it to run.
2090        if (!mAm.mUserController.hasStartedUserState(r.userId)) {
2091            String msg = "Unable to launch app "
2092                    + r.appInfo.packageName + "/"
2093                    + r.appInfo.uid + " for service "
2094                    + r.intent.getIntent() + ": user " + r.userId + " is stopped";
2095            Slog.w(TAG, msg);
2096            bringDownServiceLocked(r);
2097            return msg;
2098        }
2099
2100        // Service is now being launched, its package can't be stopped.
2101        try {
2102            AppGlobals.getPackageManager().setPackageStoppedState(
2103                    r.packageName, false, r.userId);
2104        } catch (RemoteException e) {
2105        } catch (IllegalArgumentException e) {
2106            Slog.w(TAG, "Failed trying to unstop package "
2107                    + r.packageName + ": " + e);
2108        }
2109
2110        final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
2111        final String procName = r.processName;
2112        String hostingType = "service";
2113        ProcessRecord app;
2114
2115        if (!isolated) {
2116            app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
2117            if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
2118                        + " app=" + app);
2119            if (app != null && app.thread != null) {
2120                try {
2121                    app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
2122                    realStartServiceLocked(r, app, execInFg);
2123                    return null;
2124                } catch (TransactionTooLargeException e) {
2125                    throw e;
2126                } catch (RemoteException e) {
2127                    Slog.w(TAG, "Exception when starting service " + r.shortName, e);
2128                }
2129
2130                // If a dead object exception was thrown -- fall through to
2131                // restart the application.
2132            }
2133        } else {
2134            // If this service runs in an isolated process, then each time
2135            // we call startProcessLocked() we will get a new isolated
2136            // process, starting another process if we are currently waiting
2137            // for a previous process to come up.  To deal with this, we store
2138            // in the service any current isolated process it is running in or
2139            // waiting to have come up.
2140            app = r.isolatedProc;
2141            if (WebViewZygote.isMultiprocessEnabled()
2142                    && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
2143                hostingType = "webview_service";
2144            }
2145        }
2146
2147        // Not running -- get it started, and enqueue this service record
2148        // to be executed when the app comes up.
2149        if (app == null && !permissionsReviewRequired) {
2150            if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
2151                    hostingType, r.name, false, isolated, false)) == null) {
2152                String msg = "Unable to launch app "
2153                        + r.appInfo.packageName + "/"
2154                        + r.appInfo.uid + " for service "
2155                        + r.intent.getIntent() + ": process is bad";
2156                Slog.w(TAG, msg);
2157                bringDownServiceLocked(r);
2158                return msg;
2159            }
2160            if (isolated) {
2161                r.isolatedProc = app;
2162            }
2163        }
2164
2165        if (r.fgRequired) {
2166            if (DEBUG_FOREGROUND_SERVICE) {
2167                Slog.v(TAG, "Whitelisting " + UserHandle.formatUid(r.appInfo.uid)
2168                        + " for fg-service launch");
2169            }
2170            mAm.tempWhitelistUidLocked(r.appInfo.uid,
2171                    SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch");
2172        }
2173
2174        if (!mPendingServices.contains(r)) {
2175            mPendingServices.add(r);
2176        }
2177
2178        if (r.delayedStop) {
2179            // Oh and hey we've already been asked to stop!
2180            r.delayedStop = false;
2181            if (r.startRequested) {
2182                if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2183                        "Applying delayed stop (in bring up): " + r);
2184                stopServiceLocked(r);
2185            }
2186        }
2187
2188        return null;
2189    }
2190
2191    private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
2192            throws TransactionTooLargeException {
2193        for (int i=r.bindings.size()-1; i>=0; i--) {
2194            IntentBindRecord ibr = r.bindings.valueAt(i);
2195            if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
2196                break;
2197            }
2198        }
2199    }
2200
2201    private final void realStartServiceLocked(ServiceRecord r,
2202            ProcessRecord app, boolean execInFg) throws RemoteException {
2203        if (app.thread == null) {
2204            throw new RemoteException();
2205        }
2206        if (DEBUG_MU)
2207            Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
2208                    + ", ProcessRecord.uid = " + app.uid);
2209        r.app = app;
2210        r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
2211
2212        final boolean newService = app.services.add(r);
2213        bumpServiceExecutingLocked(r, execInFg, "create");
2214        mAm.updateLruProcessLocked(app, false, null);
2215        updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
2216        mAm.updateOomAdjLocked();
2217
2218        boolean created = false;
2219        try {
2220            if (LOG_SERVICE_START_STOP) {
2221                String nameTerm;
2222                int lastPeriod = r.shortName.lastIndexOf('.');
2223                nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
2224                EventLogTags.writeAmCreateService(
2225                        r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
2226            }
2227            synchronized (r.stats.getBatteryStats()) {
2228                r.stats.startLaunchedLocked();
2229            }
2230            mAm.notifyPackageUse(r.serviceInfo.packageName,
2231                                 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
2232            app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
2233            app.thread.scheduleCreateService(r, r.serviceInfo,
2234                    mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
2235                    app.repProcState);
2236            r.postNotification();
2237            created = true;
2238        } catch (DeadObjectException e) {
2239            Slog.w(TAG, "Application dead when creating service " + r);
2240            mAm.appDiedLocked(app);
2241            throw e;
2242        } finally {
2243            if (!created) {
2244                // Keep the executeNesting count accurate.
2245                final boolean inDestroying = mDestroyingServices.contains(r);
2246                serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2247
2248                // Cleanup.
2249                if (newService) {
2250                    app.services.remove(r);
2251                    r.app = null;
2252                }
2253
2254                // Retry.
2255                if (!inDestroying) {
2256                    scheduleServiceRestartLocked(r, false);
2257                }
2258            }
2259        }
2260
2261        if (r.whitelistManager) {
2262            app.whitelistManager = true;
2263        }
2264
2265        requestServiceBindingsLocked(r, execInFg);
2266
2267        updateServiceClientActivitiesLocked(app, null, true);
2268
2269        // If the service is in the started state, and there are no
2270        // pending arguments, then fake up one so its onStartCommand() will
2271        // be called.
2272        if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
2273            r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
2274                    null, null, 0));
2275        }
2276
2277        sendServiceArgsLocked(r, execInFg, true);
2278
2279        if (r.delayed) {
2280            if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
2281            getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
2282            r.delayed = false;
2283        }
2284
2285        if (r.delayedStop) {
2286            // Oh and hey we've already been asked to stop!
2287            r.delayedStop = false;
2288            if (r.startRequested) {
2289                if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2290                        "Applying delayed stop (from start): " + r);
2291                stopServiceLocked(r);
2292            }
2293        }
2294    }
2295
2296    private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
2297            boolean oomAdjusted) throws TransactionTooLargeException {
2298        final int N = r.pendingStarts.size();
2299        if (N == 0) {
2300            return;
2301        }
2302
2303        ArrayList<ServiceStartArgs> args = new ArrayList<>();
2304
2305        while (r.pendingStarts.size() > 0) {
2306            ServiceRecord.StartItem si = r.pendingStarts.remove(0);
2307            if (DEBUG_SERVICE) {
2308                Slog.v(TAG_SERVICE, "Sending arguments to: "
2309                        + r + " " + r.intent + " args=" + si.intent);
2310            }
2311            if (si.intent == null && N > 1) {
2312                // If somehow we got a dummy null intent in the middle,
2313                // then skip it.  DO NOT skip a null intent when it is
2314                // the only one in the list -- this is to support the
2315                // onStartCommand(null) case.
2316                continue;
2317            }
2318            si.deliveredTime = SystemClock.uptimeMillis();
2319            r.deliveredStarts.add(si);
2320            si.deliveryCount++;
2321            if (si.neededGrants != null) {
2322                mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
2323                        si.getUriPermissionsLocked());
2324            }
2325            mAm.grantEphemeralAccessLocked(r.userId, si.intent,
2326                    r.appInfo.uid, UserHandle.getAppId(si.callingId));
2327            bumpServiceExecutingLocked(r, execInFg, "start");
2328            if (!oomAdjusted) {
2329                oomAdjusted = true;
2330                mAm.updateOomAdjLocked(r.app, true);
2331            }
2332            if (r.fgRequired && !r.fgWaiting) {
2333                if (!r.isForeground) {
2334                    if (DEBUG_BACKGROUND_CHECK) {
2335                        Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r);
2336                    }
2337                    scheduleServiceForegroundTransitionTimeoutLocked(r);
2338                } else {
2339                    if (DEBUG_BACKGROUND_CHECK) {
2340                        Slog.i(TAG, "Service already foreground; no new timeout: " + r);
2341                    }
2342                    r.fgRequired = false;
2343                }
2344            }
2345            int flags = 0;
2346            if (si.deliveryCount > 1) {
2347                flags |= Service.START_FLAG_RETRY;
2348            }
2349            if (si.doneExecutingCount > 0) {
2350                flags |= Service.START_FLAG_REDELIVERY;
2351            }
2352            args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
2353        }
2354
2355        ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
2356        slice.setInlineCountLimit(4);
2357        Exception caughtException = null;
2358        try {
2359            r.app.thread.scheduleServiceArgs(r, slice);
2360        } catch (TransactionTooLargeException e) {
2361            if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
2362                    + " args, first: " + args.get(0).args);
2363            Slog.w(TAG, "Failed delivering service starts", e);
2364            caughtException = e;
2365        } catch (RemoteException e) {
2366            // Remote process gone...  we'll let the normal cleanup take care of this.
2367            if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
2368            Slog.w(TAG, "Failed delivering service starts", e);
2369            caughtException = e;
2370        } catch (Exception e) {
2371            Slog.w(TAG, "Unexpected exception", e);
2372            caughtException = e;
2373        }
2374
2375        if (caughtException != null) {
2376            // Keep nesting count correct
2377            final boolean inDestroying = mDestroyingServices.contains(r);
2378            for (int i = 0; i < args.size(); i++) {
2379                serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2380            }
2381            if (caughtException instanceof TransactionTooLargeException) {
2382                throw (TransactionTooLargeException)caughtException;
2383            }
2384        }
2385    }
2386
2387    private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn,
2388            boolean hasConn) {
2389        // Are we still explicitly being asked to run?
2390        if (r.startRequested) {
2391            return true;
2392        }
2393
2394        // Is someone still bound to us keeping us running?
2395        if (!knowConn) {
2396            hasConn = r.hasAutoCreateConnections();
2397        }
2398        if (hasConn) {
2399            return true;
2400        }
2401
2402        return false;
2403    }
2404
2405    private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
2406            boolean hasConn) {
2407        //Slog.i(TAG, "Bring down service:");
2408        //r.dump("  ");
2409
2410        if (isServiceNeededLocked(r, knowConn, hasConn)) {
2411            return;
2412        }
2413
2414        // Are we in the process of launching?
2415        if (mPendingServices.contains(r)) {
2416            return;
2417        }
2418
2419        bringDownServiceLocked(r);
2420    }
2421
2422    private final void bringDownServiceLocked(ServiceRecord r) {
2423        //Slog.i(TAG, "Bring down service:");
2424        //r.dump("  ");
2425
2426        // Report to all of the connections that the service is no longer
2427        // available.
2428        for (int conni=r.connections.size()-1; conni>=0; conni--) {
2429            ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
2430            for (int i=0; i<c.size(); i++) {
2431                ConnectionRecord cr = c.get(i);
2432                // There is still a connection to the service that is
2433                // being brought down.  Mark it as dead.
2434                cr.serviceDead = true;
2435                try {
2436                    cr.conn.connected(r.name, null, true);
2437                } catch (Exception e) {
2438                    Slog.w(TAG, "Failure disconnecting service " + r.name +
2439                          " to connection " + c.get(i).conn.asBinder() +
2440                          " (in " + c.get(i).binding.client.processName + ")", e);
2441                }
2442            }
2443        }
2444
2445        // Tell the service that it has been unbound.
2446        if (r.app != null && r.app.thread != null) {
2447            for (int i=r.bindings.size()-1; i>=0; i--) {
2448                IntentBindRecord ibr = r.bindings.valueAt(i);
2449                if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
2450                        + ": hasBound=" + ibr.hasBound);
2451                if (ibr.hasBound) {
2452                    try {
2453                        bumpServiceExecutingLocked(r, false, "bring down unbind");
2454                        mAm.updateOomAdjLocked(r.app, true);
2455                        ibr.hasBound = false;
2456                        ibr.requested = false;
2457                        r.app.thread.scheduleUnbindService(r,
2458                                ibr.intent.getIntent());
2459                    } catch (Exception e) {
2460                        Slog.w(TAG, "Exception when unbinding service "
2461                                + r.shortName, e);
2462                        serviceProcessGoneLocked(r);
2463                    }
2464                }
2465            }
2466        }
2467
2468        // Check to see if the service had been started as foreground, but being
2469        // brought down before actually showing a notification.  That is not allowed.
2470        if (r.fgRequired) {
2471            Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
2472                    + r);
2473            r.fgRequired = false;
2474            r.fgWaiting = false;
2475            mAm.mHandler.removeMessages(
2476                    ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
2477            if (r.app != null) {
2478                Message msg = mAm.mHandler.obtainMessage(
2479                        ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
2480                msg.obj = r.app;
2481                mAm.mHandler.sendMessage(msg);
2482            }
2483        }
2484
2485        if (DEBUG_SERVICE) {
2486            RuntimeException here = new RuntimeException();
2487            here.fillInStackTrace();
2488            Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here);
2489        }
2490        r.destroyTime = SystemClock.uptimeMillis();
2491        if (LOG_SERVICE_START_STOP) {
2492            EventLogTags.writeAmDestroyService(
2493                    r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
2494        }
2495
2496        final ServiceMap smap = getServiceMapLocked(r.userId);
2497        ServiceRecord found = smap.mServicesByName.remove(r.name);
2498
2499        // Note when this method is called by bringUpServiceLocked(), the service is not found
2500        // in mServicesByName and found will be null.
2501        if (found != null && found != r) {
2502            // This is not actually the service we think is running...  this should not happen,
2503            // but if it does, fail hard.
2504            smap.mServicesByName.put(r.name, found);
2505            throw new IllegalStateException("Bringing down " + r + " but actually running "
2506                    + found);
2507        }
2508        smap.mServicesByIntent.remove(r.intent);
2509        r.totalRestartCount = 0;
2510        unscheduleServiceRestartLocked(r, 0, true);
2511
2512        // Also make sure it is not on the pending list.
2513        for (int i=mPendingServices.size()-1; i>=0; i--) {
2514            if (mPendingServices.get(i) == r) {
2515                mPendingServices.remove(i);
2516                if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
2517            }
2518        }
2519
2520        cancelForegroundNotificationLocked(r);
2521        if (r.isForeground) {
2522            decActiveForegroundAppLocked(smap, r);
2523        }
2524        r.isForeground = false;
2525        r.foregroundId = 0;
2526        r.foregroundNoti = null;
2527
2528        // Clear start entries.
2529        r.clearDeliveredStartsLocked();
2530        r.pendingStarts.clear();
2531
2532        if (r.app != null) {
2533            synchronized (r.stats.getBatteryStats()) {
2534                r.stats.stopLaunchedLocked();
2535            }
2536            r.app.services.remove(r);
2537            if (r.whitelistManager) {
2538                updateWhitelistManagerLocked(r.app);
2539            }
2540            if (r.app.thread != null) {
2541                updateServiceForegroundLocked(r.app, false);
2542                try {
2543                    bumpServiceExecutingLocked(r, false, "destroy");
2544                    mDestroyingServices.add(r);
2545                    r.destroying = true;
2546                    mAm.updateOomAdjLocked(r.app, true);
2547                    r.app.thread.scheduleStopService(r);
2548                } catch (Exception e) {
2549                    Slog.w(TAG, "Exception when destroying service "
2550                            + r.shortName, e);
2551                    serviceProcessGoneLocked(r);
2552                }
2553            } else {
2554                if (DEBUG_SERVICE) Slog.v(
2555                    TAG_SERVICE, "Removed service that has no process: " + r);
2556            }
2557        } else {
2558            if (DEBUG_SERVICE) Slog.v(
2559                TAG_SERVICE, "Removed service that is not running: " + r);
2560        }
2561
2562        if (r.bindings.size() > 0) {
2563            r.bindings.clear();
2564        }
2565
2566        if (r.restarter instanceof ServiceRestarter) {
2567           ((ServiceRestarter)r.restarter).setService(null);
2568        }
2569
2570        int memFactor = mAm.mProcessStats.getMemFactorLocked();
2571        long now = SystemClock.uptimeMillis();
2572        if (r.tracker != null) {
2573            r.tracker.setStarted(false, memFactor, now);
2574            r.tracker.setBound(false, memFactor, now);
2575            if (r.executeNesting == 0) {
2576                r.tracker.clearCurrentOwner(r, false);
2577                r.tracker = null;
2578            }
2579        }
2580
2581        smap.ensureNotStartingBackgroundLocked(r);
2582    }
2583
2584    void removeConnectionLocked(
2585        ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
2586        IBinder binder = c.conn.asBinder();
2587        AppBindRecord b = c.binding;
2588        ServiceRecord s = b.service;
2589        ArrayList<ConnectionRecord> clist = s.connections.get(binder);
2590        if (clist != null) {
2591            clist.remove(c);
2592            if (clist.size() == 0) {
2593                s.connections.remove(binder);
2594            }
2595        }
2596        b.connections.remove(c);
2597        if (c.activity != null && c.activity != skipAct) {
2598            if (c.activity.connections != null) {
2599                c.activity.connections.remove(c);
2600            }
2601        }
2602        if (b.client != skipApp) {
2603            b.client.connections.remove(c);
2604            if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
2605                b.client.updateHasAboveClientLocked();
2606            }
2607            // If this connection requested whitelist management, see if we should
2608            // now clear that state.
2609            if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
2610                s.updateWhitelistManager();
2611                if (!s.whitelistManager && s.app != null) {
2612                    updateWhitelistManagerLocked(s.app);
2613                }
2614            }
2615            if (s.app != null) {
2616                updateServiceClientActivitiesLocked(s.app, c, true);
2617            }
2618        }
2619        clist = mServiceConnections.get(binder);
2620        if (clist != null) {
2621            clist.remove(c);
2622            if (clist.size() == 0) {
2623                mServiceConnections.remove(binder);
2624            }
2625        }
2626
2627        mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid, s.name);
2628
2629        if (b.connections.size() == 0) {
2630            b.intent.apps.remove(b.client);
2631        }
2632
2633        if (!c.serviceDead) {
2634            if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
2635                    + ": shouldUnbind=" + b.intent.hasBound);
2636            if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
2637                    && b.intent.hasBound) {
2638                try {
2639                    bumpServiceExecutingLocked(s, false, "unbind");
2640                    if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
2641                            && s.app.setProcState <= ActivityManager.PROCESS_STATE_RECEIVER) {
2642                        // If this service's process is not already in the cached list,
2643                        // then update it in the LRU list here because this may be causing
2644                        // it to go down there and we want it to start out near the top.
2645                        mAm.updateLruProcessLocked(s.app, false, null);
2646                    }
2647                    mAm.updateOomAdjLocked(s.app, true);
2648                    b.intent.hasBound = false;
2649                    // Assume the client doesn't want to know about a rebind;
2650                    // we will deal with that later if it asks for one.
2651                    b.intent.doRebind = false;
2652                    s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
2653                } catch (Exception e) {
2654                    Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
2655                    serviceProcessGoneLocked(s);
2656                }
2657            }
2658
2659            // If unbound while waiting to start, remove the pending service
2660            mPendingServices.remove(s);
2661
2662            if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
2663                boolean hasAutoCreate = s.hasAutoCreateConnections();
2664                if (!hasAutoCreate) {
2665                    if (s.tracker != null) {
2666                        s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
2667                                SystemClock.uptimeMillis());
2668                    }
2669                }
2670                bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
2671            }
2672        }
2673    }
2674
2675    void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
2676        boolean inDestroying = mDestroyingServices.contains(r);
2677        if (r != null) {
2678            if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
2679                // This is a call from a service start...  take care of
2680                // book-keeping.
2681                r.callStart = true;
2682                switch (res) {
2683                    case Service.START_STICKY_COMPATIBILITY:
2684                    case Service.START_STICKY: {
2685                        // We are done with the associated start arguments.
2686                        r.findDeliveredStart(startId, true);
2687                        // Don't stop if killed.
2688                        r.stopIfKilled = false;
2689                        break;
2690                    }
2691                    case Service.START_NOT_STICKY: {
2692                        // We are done with the associated start arguments.
2693                        r.findDeliveredStart(startId, true);
2694                        if (r.getLastStartId() == startId) {
2695                            // There is no more work, and this service
2696                            // doesn't want to hang around if killed.
2697                            r.stopIfKilled = true;
2698                        }
2699                        break;
2700                    }
2701                    case Service.START_REDELIVER_INTENT: {
2702                        // We'll keep this item until they explicitly
2703                        // call stop for it, but keep track of the fact
2704                        // that it was delivered.
2705                        ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
2706                        if (si != null) {
2707                            si.deliveryCount = 0;
2708                            si.doneExecutingCount++;
2709                            // Don't stop if killed.
2710                            r.stopIfKilled = true;
2711                        }
2712                        break;
2713                    }
2714                    case Service.START_TASK_REMOVED_COMPLETE: {
2715                        // Special processing for onTaskRemoved().  Don't
2716                        // impact normal onStartCommand() processing.
2717                        r.findDeliveredStart(startId, true);
2718                        break;
2719                    }
2720                    default:
2721                        throw new IllegalArgumentException(
2722                                "Unknown service start result: " + res);
2723                }
2724                if (res == Service.START_STICKY_COMPATIBILITY) {
2725                    r.callStart = false;
2726                }
2727            } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
2728                // This is the final call from destroying the service...  we should
2729                // actually be getting rid of the service at this point.  Do some
2730                // validation of its state, and ensure it will be fully removed.
2731                if (!inDestroying) {
2732                    // Not sure what else to do with this...  if it is not actually in the
2733                    // destroying list, we don't need to make sure to remove it from it.
2734                    // If the app is null, then it was probably removed because the process died,
2735                    // otherwise wtf
2736                    if (r.app != null) {
2737                        Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
2738                                + r + ", app=" + r.app);
2739                    }
2740                } else if (r.executeNesting != 1) {
2741                    Slog.w(TAG, "Service done with onDestroy, but executeNesting="
2742                            + r.executeNesting + ": " + r);
2743                    // Fake it to keep from ANR due to orphaned entry.
2744                    r.executeNesting = 1;
2745                }
2746            }
2747            final long origId = Binder.clearCallingIdentity();
2748            serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2749            Binder.restoreCallingIdentity(origId);
2750        } else {
2751            Slog.w(TAG, "Done executing unknown service from pid "
2752                    + Binder.getCallingPid());
2753        }
2754    }
2755
2756    private void serviceProcessGoneLocked(ServiceRecord r) {
2757        if (r.tracker != null) {
2758            int memFactor = mAm.mProcessStats.getMemFactorLocked();
2759            long now = SystemClock.uptimeMillis();
2760            r.tracker.setExecuting(false, memFactor, now);
2761            r.tracker.setBound(false, memFactor, now);
2762            r.tracker.setStarted(false, memFactor, now);
2763        }
2764        serviceDoneExecutingLocked(r, true, true);
2765    }
2766
2767    private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
2768            boolean finishing) {
2769        if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
2770                + ": nesting=" + r.executeNesting
2771                + ", inDestroying=" + inDestroying + ", app=" + r.app);
2772        else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
2773                "<<< DONE EXECUTING " + r.shortName);
2774        r.executeNesting--;
2775        if (r.executeNesting <= 0) {
2776            if (r.app != null) {
2777                if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
2778                        "Nesting at 0 of " + r.shortName);
2779                r.app.execServicesFg = false;
2780                r.app.executingServices.remove(r);
2781                if (r.app.executingServices.size() == 0) {
2782                    if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
2783                            "No more executingServices of " + r.shortName);
2784                    mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
2785                } else if (r.executeFg) {
2786                    // Need to re-evaluate whether the app still needs to be in the foreground.
2787                    for (int i=r.app.executingServices.size()-1; i>=0; i--) {
2788                        if (r.app.executingServices.valueAt(i).executeFg) {
2789                            r.app.execServicesFg = true;
2790                            break;
2791                        }
2792                    }
2793                }
2794                if (inDestroying) {
2795                    if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
2796                            "doneExecuting remove destroying " + r);
2797                    mDestroyingServices.remove(r);
2798                    r.bindings.clear();
2799                }
2800                mAm.updateOomAdjLocked(r.app, true);
2801            }
2802            r.executeFg = false;
2803            if (r.tracker != null) {
2804                r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
2805                        SystemClock.uptimeMillis());
2806                if (finishing) {
2807                    r.tracker.clearCurrentOwner(r, false);
2808                    r.tracker = null;
2809                }
2810            }
2811            if (finishing) {
2812                if (r.app != null && !r.app.persistent) {
2813                    r.app.services.remove(r);
2814                    if (r.whitelistManager) {
2815                        updateWhitelistManagerLocked(r.app);
2816                    }
2817                }
2818                r.app = null;
2819            }
2820        }
2821    }
2822
2823    boolean attachApplicationLocked(ProcessRecord proc, String processName)
2824            throws RemoteException {
2825        boolean didSomething = false;
2826        // Collect any services that are waiting for this process to come up.
2827        if (mPendingServices.size() > 0) {
2828            ServiceRecord sr = null;
2829            try {
2830                for (int i=0; i<mPendingServices.size(); i++) {
2831                    sr = mPendingServices.get(i);
2832                    if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
2833                            || !processName.equals(sr.processName))) {
2834                        continue;
2835                    }
2836
2837                    mPendingServices.remove(i);
2838                    i--;
2839                    proc.addPackage(sr.appInfo.packageName, sr.appInfo.versionCode,
2840                            mAm.mProcessStats);
2841                    realStartServiceLocked(sr, proc, sr.createdFromFg);
2842                    didSomething = true;
2843                    if (!isServiceNeededLocked(sr, false, false)) {
2844                        // We were waiting for this service to start, but it is actually no
2845                        // longer needed.  This could happen because bringDownServiceIfNeeded
2846                        // won't bring down a service that is pending...  so now the pending
2847                        // is done, so let's drop it.
2848                        bringDownServiceLocked(sr);
2849                    }
2850                }
2851            } catch (RemoteException e) {
2852                Slog.w(TAG, "Exception in new application when starting service "
2853                        + sr.shortName, e);
2854                throw e;
2855            }
2856        }
2857        // Also, if there are any services that are waiting to restart and
2858        // would run in this process, now is a good time to start them.  It would
2859        // be weird to bring up the process but arbitrarily not let the services
2860        // run at this point just because their restart time hasn't come up.
2861        if (mRestartingServices.size() > 0) {
2862            ServiceRecord sr;
2863            for (int i=0; i<mRestartingServices.size(); i++) {
2864                sr = mRestartingServices.get(i);
2865                if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
2866                        || !processName.equals(sr.processName))) {
2867                    continue;
2868                }
2869                mAm.mHandler.removeCallbacks(sr.restarter);
2870                mAm.mHandler.post(sr.restarter);
2871            }
2872        }
2873        return didSomething;
2874    }
2875
2876    void processStartTimedOutLocked(ProcessRecord proc) {
2877        for (int i=0; i<mPendingServices.size(); i++) {
2878            ServiceRecord sr = mPendingServices.get(i);
2879            if ((proc.uid == sr.appInfo.uid
2880                    && proc.processName.equals(sr.processName))
2881                    || sr.isolatedProc == proc) {
2882                Slog.w(TAG, "Forcing bringing down service: " + sr);
2883                sr.isolatedProc = null;
2884                mPendingServices.remove(i);
2885                i--;
2886                bringDownServiceLocked(sr);
2887            }
2888        }
2889    }
2890
2891    private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
2892            boolean evenPersistent, boolean doit, boolean killProcess,
2893            ArrayMap<ComponentName, ServiceRecord> services) {
2894        boolean didSomething = false;
2895        for (int i = services.size() - 1; i >= 0; i--) {
2896            ServiceRecord service = services.valueAt(i);
2897            final boolean sameComponent = packageName == null
2898                    || (service.packageName.equals(packageName)
2899                        && (filterByClasses == null
2900                            || filterByClasses.contains(service.name.getClassName())));
2901            if (sameComponent
2902                    && (service.app == null || evenPersistent || !service.app.persistent)) {
2903                if (!doit) {
2904                    return true;
2905                }
2906                didSomething = true;
2907                Slog.i(TAG, "  Force stopping service " + service);
2908                if (service.app != null) {
2909                    service.app.removed = killProcess;
2910                    if (!service.app.persistent) {
2911                        service.app.services.remove(service);
2912                        if (service.whitelistManager) {
2913                            updateWhitelistManagerLocked(service.app);
2914                        }
2915                    }
2916                }
2917                service.app = null;
2918                service.isolatedProc = null;
2919                if (mTmpCollectionResults == null) {
2920                    mTmpCollectionResults = new ArrayList<>();
2921                }
2922                mTmpCollectionResults.add(service);
2923            }
2924        }
2925        return didSomething;
2926    }
2927
2928    boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
2929            int userId, boolean evenPersistent, boolean killProcess, boolean doit) {
2930        boolean didSomething = false;
2931
2932        if (mTmpCollectionResults != null) {
2933            mTmpCollectionResults.clear();
2934        }
2935
2936        if (userId == UserHandle.USER_ALL) {
2937            for (int i = mServiceMap.size() - 1; i >= 0; i--) {
2938                didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
2939                        evenPersistent, doit, killProcess, mServiceMap.valueAt(i).mServicesByName);
2940                if (!doit && didSomething) {
2941                    return true;
2942                }
2943                if (doit && filterByClasses == null) {
2944                    forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId);
2945                }
2946            }
2947        } else {
2948            ServiceMap smap = mServiceMap.get(userId);
2949            if (smap != null) {
2950                ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByName;
2951                didSomething = collectPackageServicesLocked(packageName, filterByClasses,
2952                        evenPersistent, doit, killProcess, items);
2953            }
2954            if (doit && filterByClasses == null) {
2955                forceStopPackageLocked(packageName, userId);
2956            }
2957        }
2958
2959        if (mTmpCollectionResults != null) {
2960            for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
2961                bringDownServiceLocked(mTmpCollectionResults.get(i));
2962            }
2963            mTmpCollectionResults.clear();
2964        }
2965
2966        return didSomething;
2967    }
2968
2969    void forceStopPackageLocked(String packageName, int userId) {
2970        ServiceMap smap = mServiceMap.get(userId);
2971        if (smap != null && smap.mActiveForegroundApps.size() > 0) {
2972            for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
2973                ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
2974                if (aa.mPackageName.equals(packageName)) {
2975                    smap.mActiveForegroundApps.removeAt(i);
2976                    smap.mActiveForegroundAppsChanged = true;
2977                }
2978            }
2979            if (smap.mActiveForegroundAppsChanged) {
2980                requestUpdateActiveForegroundAppsLocked(smap, 0);
2981            }
2982        }
2983    }
2984
2985    void cleanUpRemovedTaskLocked(TaskRecord tr, ComponentName component, Intent baseIntent) {
2986        ArrayList<ServiceRecord> services = new ArrayList<>();
2987        ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(tr.userId);
2988        for (int i = alls.size() - 1; i >= 0; i--) {
2989            ServiceRecord sr = alls.valueAt(i);
2990            if (sr.packageName.equals(component.getPackageName())) {
2991                services.add(sr);
2992            }
2993        }
2994
2995        // Take care of any running services associated with the app.
2996        for (int i = services.size() - 1; i >= 0; i--) {
2997            ServiceRecord sr = services.get(i);
2998            if (sr.startRequested) {
2999                if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
3000                    Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
3001                    stopServiceLocked(sr);
3002                } else {
3003                    sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
3004                            sr.makeNextStartId(), baseIntent, null, 0));
3005                    if (sr.app != null && sr.app.thread != null) {
3006                        // We always run in the foreground, since this is called as
3007                        // part of the "remove task" UI operation.
3008                        try {
3009                            sendServiceArgsLocked(sr, true, false);
3010                        } catch (TransactionTooLargeException e) {
3011                            // Ignore, keep going.
3012                        }
3013                    }
3014                }
3015            }
3016        }
3017    }
3018
3019    final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
3020        // Report disconnected services.
3021        if (false) {
3022            // XXX we are letting the client link to the service for
3023            // death notifications.
3024            if (app.services.size() > 0) {
3025                Iterator<ServiceRecord> it = app.services.iterator();
3026                while (it.hasNext()) {
3027                    ServiceRecord r = it.next();
3028                    for (int conni=r.connections.size()-1; conni>=0; conni--) {
3029                        ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
3030                        for (int i=0; i<cl.size(); i++) {
3031                            ConnectionRecord c = cl.get(i);
3032                            if (c.binding.client != app) {
3033                                try {
3034                                    //c.conn.connected(r.className, null);
3035                                } catch (Exception e) {
3036                                    // todo: this should be asynchronous!
3037                                    Slog.w(TAG, "Exception thrown disconnected servce "
3038                                          + r.shortName
3039                                          + " from app " + app.processName, e);
3040                                }
3041                            }
3042                        }
3043                    }
3044                }
3045            }
3046        }
3047
3048        // Clean up any connections this application has to other services.
3049        for (int i = app.connections.size() - 1; i >= 0; i--) {
3050            ConnectionRecord r = app.connections.valueAt(i);
3051            removeConnectionLocked(r, app, null);
3052        }
3053        updateServiceConnectionActivitiesLocked(app);
3054        app.connections.clear();
3055
3056        app.whitelistManager = false;
3057
3058        // Clear app state from services.
3059        for (int i = app.services.size() - 1; i >= 0; i--) {
3060            ServiceRecord sr = app.services.valueAt(i);
3061            synchronized (sr.stats.getBatteryStats()) {
3062                sr.stats.stopLaunchedLocked();
3063            }
3064            if (sr.app != app && sr.app != null && !sr.app.persistent) {
3065                sr.app.services.remove(sr);
3066            }
3067            sr.app = null;
3068            sr.isolatedProc = null;
3069            sr.executeNesting = 0;
3070            sr.forceClearTracker();
3071            if (mDestroyingServices.remove(sr)) {
3072                if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
3073            }
3074
3075            final int numClients = sr.bindings.size();
3076            for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
3077                IntentBindRecord b = sr.bindings.valueAt(bindingi);
3078                if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
3079                        + ": shouldUnbind=" + b.hasBound);
3080                b.binder = null;
3081                b.requested = b.received = b.hasBound = false;
3082                // If this binding is coming from a cached process and is asking to keep
3083                // the service created, then we'll kill the cached process as well -- we
3084                // don't want to be thrashing around restarting processes that are only
3085                // there to be cached.
3086                for (int appi=b.apps.size()-1; appi>=0; appi--) {
3087                    final ProcessRecord proc = b.apps.keyAt(appi);
3088                    // If the process is already gone, skip it.
3089                    if (proc.killedByAm || proc.thread == null) {
3090                        continue;
3091                    }
3092                    // Only do this for processes that have an auto-create binding;
3093                    // otherwise the binding can be left, because it won't cause the
3094                    // service to restart.
3095                    final AppBindRecord abind = b.apps.valueAt(appi);
3096                    boolean hasCreate = false;
3097                    for (int conni=abind.connections.size()-1; conni>=0; conni--) {
3098                        ConnectionRecord conn = abind.connections.valueAt(conni);
3099                        if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
3100                                |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
3101                            hasCreate = true;
3102                            break;
3103                        }
3104                    }
3105                    if (!hasCreate) {
3106                        continue;
3107                    }
3108                    // XXX turned off for now until we have more time to get a better policy.
3109                    if (false && proc != null && !proc.persistent && proc.thread != null
3110                            && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
3111                            && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
3112                        proc.kill("bound to service " + sr.name.flattenToShortString()
3113                                + " in dying proc " + (app != null ? app.processName : "??"), true);
3114                    }
3115                }
3116            }
3117        }
3118
3119        ServiceMap smap = getServiceMapLocked(app.userId);
3120
3121        // Now do remaining service cleanup.
3122        for (int i=app.services.size()-1; i>=0; i--) {
3123            ServiceRecord sr = app.services.valueAt(i);
3124
3125            // Unless the process is persistent, this process record is going away,
3126            // so make sure the service is cleaned out of it.
3127            if (!app.persistent) {
3128                app.services.removeAt(i);
3129            }
3130
3131            // Sanity check: if the service listed for the app is not one
3132            // we actually are maintaining, just let it drop.
3133            final ServiceRecord curRec = smap.mServicesByName.get(sr.name);
3134            if (curRec != sr) {
3135                if (curRec != null) {
3136                    Slog.wtf(TAG, "Service " + sr + " in process " + app
3137                            + " not same as in map: " + curRec);
3138                }
3139                continue;
3140            }
3141
3142            // Any services running in the application may need to be placed
3143            // back in the pending list.
3144            if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
3145                    && (sr.serviceInfo.applicationInfo.flags
3146                        &ApplicationInfo.FLAG_PERSISTENT) == 0) {
3147                Slog.w(TAG, "Service crashed " + sr.crashCount
3148                        + " times, stopping: " + sr);
3149                EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
3150                        sr.userId, sr.crashCount, sr.shortName, app.pid);
3151                bringDownServiceLocked(sr);
3152            } else if (!allowRestart
3153                    || !mAm.mUserController.isUserRunningLocked(sr.userId, 0)) {
3154                bringDownServiceLocked(sr);
3155            } else {
3156                boolean canceled = scheduleServiceRestartLocked(sr, true);
3157
3158                // Should the service remain running?  Note that in the
3159                // extreme case of so many attempts to deliver a command
3160                // that it failed we also will stop it here.
3161                if (sr.startRequested && (sr.stopIfKilled || canceled)) {
3162                    if (sr.pendingStarts.size() == 0) {
3163                        sr.startRequested = false;
3164                        if (sr.tracker != null) {
3165                            sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
3166                                    SystemClock.uptimeMillis());
3167                        }
3168                        if (!sr.hasAutoCreateConnections()) {
3169                            // Whoops, no reason to restart!
3170                            bringDownServiceLocked(sr);
3171                        }
3172                    }
3173                }
3174            }
3175        }
3176
3177        if (!allowRestart) {
3178            app.services.clear();
3179
3180            // Make sure there are no more restarting services for this process.
3181            for (int i=mRestartingServices.size()-1; i>=0; i--) {
3182                ServiceRecord r = mRestartingServices.get(i);
3183                if (r.processName.equals(app.processName) &&
3184                        r.serviceInfo.applicationInfo.uid == app.info.uid) {
3185                    mRestartingServices.remove(i);
3186                    clearRestartingIfNeededLocked(r);
3187                }
3188            }
3189            for (int i=mPendingServices.size()-1; i>=0; i--) {
3190                ServiceRecord r = mPendingServices.get(i);
3191                if (r.processName.equals(app.processName) &&
3192                        r.serviceInfo.applicationInfo.uid == app.info.uid) {
3193                    mPendingServices.remove(i);
3194                }
3195            }
3196        }
3197
3198        // Make sure we have no more records on the stopping list.
3199        int i = mDestroyingServices.size();
3200        while (i > 0) {
3201            i--;
3202            ServiceRecord sr = mDestroyingServices.get(i);
3203            if (sr.app == app) {
3204                sr.forceClearTracker();
3205                mDestroyingServices.remove(i);
3206                if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
3207            }
3208        }
3209
3210        app.executingServices.clear();
3211    }
3212
3213    ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
3214        ActivityManager.RunningServiceInfo info =
3215            new ActivityManager.RunningServiceInfo();
3216        info.service = r.name;
3217        if (r.app != null) {
3218            info.pid = r.app.pid;
3219        }
3220        info.uid = r.appInfo.uid;
3221        info.process = r.processName;
3222        info.foreground = r.isForeground;
3223        info.activeSince = r.createTime;
3224        info.started = r.startRequested;
3225        info.clientCount = r.connections.size();
3226        info.crashCount = r.crashCount;
3227        info.lastActivityTime = r.lastActivity;
3228        if (r.isForeground) {
3229            info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
3230        }
3231        if (r.startRequested) {
3232            info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
3233        }
3234        if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
3235            info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
3236        }
3237        if (r.app != null && r.app.persistent) {
3238            info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
3239        }
3240
3241        for (int conni=r.connections.size()-1; conni>=0; conni--) {
3242            ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
3243            for (int i=0; i<connl.size(); i++) {
3244                ConnectionRecord conn = connl.get(i);
3245                if (conn.clientLabel != 0) {
3246                    info.clientPackage = conn.binding.client.info.packageName;
3247                    info.clientLabel = conn.clientLabel;
3248                    return info;
3249                }
3250            }
3251        }
3252        return info;
3253    }
3254
3255    List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags,
3256        int callingUid, boolean allowed, boolean canInteractAcrossUsers) {
3257        ArrayList<ActivityManager.RunningServiceInfo> res
3258                = new ArrayList<ActivityManager.RunningServiceInfo>();
3259
3260        final long ident = Binder.clearCallingIdentity();
3261        try {
3262            if (canInteractAcrossUsers) {
3263                int[] users = mAm.mUserController.getUsers();
3264                for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
3265                    ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
3266                    for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3267                        ServiceRecord sr = alls.valueAt(i);
3268                        res.add(makeRunningServiceInfoLocked(sr));
3269                    }
3270                }
3271
3272                for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3273                    ServiceRecord r = mRestartingServices.get(i);
3274                    ActivityManager.RunningServiceInfo info =
3275                            makeRunningServiceInfoLocked(r);
3276                    info.restarting = r.nextRestartTime;
3277                    res.add(info);
3278                }
3279            } else {
3280                int userId = UserHandle.getUserId(callingUid);
3281                ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
3282                for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3283                    ServiceRecord sr = alls.valueAt(i);
3284
3285                    if (allowed || (sr.app != null && sr.app.uid == callingUid)) {
3286                        res.add(makeRunningServiceInfoLocked(sr));
3287                    }
3288                }
3289
3290                for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3291                    ServiceRecord r = mRestartingServices.get(i);
3292                    if (r.userId == userId
3293                        && (allowed || (r.app != null && r.app.uid == callingUid))) {
3294                        ActivityManager.RunningServiceInfo info =
3295                                makeRunningServiceInfoLocked(r);
3296                        info.restarting = r.nextRestartTime;
3297                        res.add(info);
3298                    }
3299                }
3300            }
3301        } finally {
3302            Binder.restoreCallingIdentity(ident);
3303        }
3304
3305        return res;
3306    }
3307
3308    public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
3309        int userId = UserHandle.getUserId(Binder.getCallingUid());
3310        ServiceRecord r = getServiceByNameLocked(name, userId);
3311        if (r != null) {
3312            for (int conni=r.connections.size()-1; conni>=0; conni--) {
3313                ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
3314                for (int i=0; i<conn.size(); i++) {
3315                    if (conn.get(i).clientIntent != null) {
3316                        return conn.get(i).clientIntent;
3317                    }
3318                }
3319            }
3320        }
3321        return null;
3322    }
3323
3324    void serviceTimeout(ProcessRecord proc) {
3325        String anrMessage = null;
3326
3327        synchronized(mAm) {
3328            if (proc.executingServices.size() == 0 || proc.thread == null) {
3329                return;
3330            }
3331            final long now = SystemClock.uptimeMillis();
3332            final long maxTime =  now -
3333                    (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
3334            ServiceRecord timeout = null;
3335            long nextTime = 0;
3336            for (int i=proc.executingServices.size()-1; i>=0; i--) {
3337                ServiceRecord sr = proc.executingServices.valueAt(i);
3338                if (sr.executingStart < maxTime) {
3339                    timeout = sr;
3340                    break;
3341                }
3342                if (sr.executingStart > nextTime) {
3343                    nextTime = sr.executingStart;
3344                }
3345            }
3346            if (timeout != null && mAm.mLruProcesses.contains(proc)) {
3347                Slog.w(TAG, "Timeout executing service: " + timeout);
3348                StringWriter sw = new StringWriter();
3349                PrintWriter pw = new FastPrintWriter(sw, false, 1024);
3350                pw.println(timeout);
3351                timeout.dump(pw, "    ");
3352                pw.close();
3353                mLastAnrDump = sw.toString();
3354                mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
3355                mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
3356                anrMessage = "executing service " + timeout.shortName;
3357            } else {
3358                Message msg = mAm.mHandler.obtainMessage(
3359                        ActivityManagerService.SERVICE_TIMEOUT_MSG);
3360                msg.obj = proc;
3361                mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
3362                        ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
3363            }
3364        }
3365
3366        if (anrMessage != null) {
3367            mAm.mAppErrors.appNotResponding(proc, null, null, false, anrMessage);
3368        }
3369    }
3370
3371    void serviceForegroundTimeout(ServiceRecord r) {
3372        ProcessRecord app;
3373        synchronized (mAm) {
3374            if (!r.fgRequired || r.destroying) {
3375                return;
3376            }
3377
3378            if (DEBUG_BACKGROUND_CHECK) {
3379                Slog.i(TAG, "Service foreground-required timeout for " + r);
3380            }
3381            app = r.app;
3382            r.fgWaiting = false;
3383            stopServiceLocked(r);
3384        }
3385
3386        if (app != null) {
3387            mAm.mAppErrors.appNotResponding(app, null, null, false,
3388                    "Context.startForegroundService() did not then call Service.startForeground()");
3389        }
3390    }
3391
3392    void serviceForegroundCrash(ProcessRecord app) {
3393        mAm.crashApplication(app.uid, app.pid, app.info.packageName, app.userId,
3394                "Context.startForegroundService() did not then call Service.startForeground()");
3395    }
3396
3397    void scheduleServiceTimeoutLocked(ProcessRecord proc) {
3398        if (proc.executingServices.size() == 0 || proc.thread == null) {
3399            return;
3400        }
3401        Message msg = mAm.mHandler.obtainMessage(
3402                ActivityManagerService.SERVICE_TIMEOUT_MSG);
3403        msg.obj = proc;
3404        mAm.mHandler.sendMessageDelayed(msg,
3405                proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
3406    }
3407
3408    void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
3409        if (r.app.executingServices.size() == 0 || r.app.thread == null) {
3410            return;
3411        }
3412        Message msg = mAm.mHandler.obtainMessage(
3413                ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG);
3414        msg.obj = r;
3415        r.fgWaiting = true;
3416        mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT);
3417    }
3418
3419    final class ServiceDumper {
3420        private final FileDescriptor fd;
3421        private final PrintWriter pw;
3422        private final String[] args;
3423        private final boolean dumpAll;
3424        private final String dumpPackage;
3425        private final ItemMatcher matcher;
3426        private final ArrayList<ServiceRecord> services = new ArrayList<>();
3427
3428        private final long nowReal = SystemClock.elapsedRealtime();
3429
3430        private boolean needSep = false;
3431        private boolean printedAnything = false;
3432        private boolean printed = false;
3433
3434        /**
3435         * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
3436         * must be called with the lock held).
3437         */
3438        ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
3439                int opti, boolean dumpAll, String dumpPackage) {
3440            this.fd = fd;
3441            this.pw = pw;
3442            this.args = args;
3443            this.dumpAll = dumpAll;
3444            this.dumpPackage = dumpPackage;
3445            matcher = new ItemMatcher();
3446            matcher.build(args, opti);
3447
3448            final int[] users = mAm.mUserController.getUsers();
3449            for (int user : users) {
3450                ServiceMap smap = getServiceMapLocked(user);
3451                if (smap.mServicesByName.size() > 0) {
3452                    for (int si=0; si<smap.mServicesByName.size(); si++) {
3453                        ServiceRecord r = smap.mServicesByName.valueAt(si);
3454                        if (!matcher.match(r, r.name)) {
3455                            continue;
3456                        }
3457                        if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3458                            continue;
3459                        }
3460                        services.add(r);
3461                    }
3462                }
3463            }
3464        }
3465
3466        private void dumpHeaderLocked() {
3467            pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
3468            if (mLastAnrDump != null) {
3469                pw.println("  Last ANR service:");
3470                pw.print(mLastAnrDump);
3471                pw.println();
3472            }
3473        }
3474
3475        void dumpLocked() {
3476            dumpHeaderLocked();
3477
3478            try {
3479                int[] users = mAm.mUserController.getUsers();
3480                for (int user : users) {
3481                    // Find the first service for this user.
3482                    int serviceIdx = 0;
3483                    while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3484                        serviceIdx++;
3485                    }
3486                    printed = false;
3487                    if (serviceIdx < services.size()) {
3488                        needSep = false;
3489                        while (serviceIdx < services.size()) {
3490                            ServiceRecord r = services.get(serviceIdx);
3491                            serviceIdx++;
3492                            if (r.userId != user) {
3493                                break;
3494                            }
3495                            dumpServiceLocalLocked(r);
3496                        }
3497                        needSep |= printed;
3498                    }
3499
3500                    dumpUserRemainsLocked(user);
3501                }
3502            } catch (Exception e) {
3503                Slog.w(TAG, "Exception in dumpServicesLocked", e);
3504            }
3505
3506            dumpRemainsLocked();
3507        }
3508
3509        void dumpWithClient() {
3510            synchronized(mAm) {
3511                dumpHeaderLocked();
3512            }
3513
3514            try {
3515                int[] users = mAm.mUserController.getUsers();
3516                for (int user : users) {
3517                    // Find the first service for this user.
3518                    int serviceIdx = 0;
3519                    while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3520                        serviceIdx++;
3521                    }
3522                    printed = false;
3523                    if (serviceIdx < services.size()) {
3524                        needSep = false;
3525                        while (serviceIdx < services.size()) {
3526                            ServiceRecord r = services.get(serviceIdx);
3527                            serviceIdx++;
3528                            if (r.userId != user) {
3529                                break;
3530                            }
3531                            synchronized(mAm) {
3532                                dumpServiceLocalLocked(r);
3533                            }
3534                            dumpServiceClient(r);
3535                        }
3536                        needSep |= printed;
3537                    }
3538
3539                    synchronized(mAm) {
3540                        dumpUserRemainsLocked(user);
3541                    }
3542                }
3543            } catch (Exception e) {
3544                Slog.w(TAG, "Exception in dumpServicesLocked", e);
3545            }
3546
3547            synchronized(mAm) {
3548                dumpRemainsLocked();
3549            }
3550        }
3551
3552        private void dumpUserHeaderLocked(int user) {
3553            if (!printed) {
3554                if (printedAnything) {
3555                    pw.println();
3556                }
3557                pw.println("  User " + user + " active services:");
3558                printed = true;
3559            }
3560            printedAnything = true;
3561            if (needSep) {
3562                pw.println();
3563            }
3564        }
3565
3566        private void dumpServiceLocalLocked(ServiceRecord r) {
3567            dumpUserHeaderLocked(r.userId);
3568            pw.print("  * ");
3569            pw.println(r);
3570            if (dumpAll) {
3571                r.dump(pw, "    ");
3572                needSep = true;
3573            } else {
3574                pw.print("    app=");
3575                pw.println(r.app);
3576                pw.print("    created=");
3577                TimeUtils.formatDuration(r.createTime, nowReal, pw);
3578                pw.print(" started=");
3579                pw.print(r.startRequested);
3580                pw.print(" connections=");
3581                pw.println(r.connections.size());
3582                if (r.connections.size() > 0) {
3583                    pw.println("    Connections:");
3584                    for (int conni=0; conni<r.connections.size(); conni++) {
3585                        ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
3586                        for (int i = 0; i < clist.size(); i++) {
3587                            ConnectionRecord conn = clist.get(i);
3588                            pw.print("      ");
3589                            pw.print(conn.binding.intent.intent.getIntent()
3590                                    .toShortString(false, false, false, false));
3591                            pw.print(" -> ");
3592                            ProcessRecord proc = conn.binding.client;
3593                            pw.println(proc != null ? proc.toShortString() : "null");
3594                        }
3595                    }
3596                }
3597            }
3598        }
3599
3600        private void dumpServiceClient(ServiceRecord r) {
3601            final ProcessRecord proc = r.app;
3602            if (proc == null) {
3603                return;
3604            }
3605            final IApplicationThread thread = proc.thread;
3606            if (thread == null) {
3607                return;
3608            }
3609            pw.println("    Client:");
3610            pw.flush();
3611            try {
3612                TransferPipe tp = new TransferPipe();
3613                try {
3614                    thread.dumpService(tp.getWriteFd(), r, args);
3615                    tp.setBufferPrefix("      ");
3616                    // Short timeout, since blocking here can
3617                    // deadlock with the application.
3618                    tp.go(fd, 2000);
3619                } finally {
3620                    tp.kill();
3621                }
3622            } catch (IOException e) {
3623                pw.println("      Failure while dumping the service: " + e);
3624            } catch (RemoteException e) {
3625                pw.println("      Got a RemoteException while dumping the service");
3626            }
3627            needSep = true;
3628        }
3629
3630        private void dumpUserRemainsLocked(int user) {
3631            ServiceMap smap = getServiceMapLocked(user);
3632            printed = false;
3633            for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
3634                ServiceRecord r = smap.mDelayedStartList.get(si);
3635                if (!matcher.match(r, r.name)) {
3636                    continue;
3637                }
3638                if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3639                    continue;
3640                }
3641                if (!printed) {
3642                    if (printedAnything) {
3643                        pw.println();
3644                    }
3645                    pw.println("  User " + user + " delayed start services:");
3646                    printed = true;
3647                }
3648                printedAnything = true;
3649                pw.print("  * Delayed start "); pw.println(r);
3650            }
3651            printed = false;
3652            for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
3653                ServiceRecord r = smap.mStartingBackground.get(si);
3654                if (!matcher.match(r, r.name)) {
3655                    continue;
3656                }
3657                if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3658                    continue;
3659                }
3660                if (!printed) {
3661                    if (printedAnything) {
3662                        pw.println();
3663                    }
3664                    pw.println("  User " + user + " starting in background:");
3665                    printed = true;
3666                }
3667                printedAnything = true;
3668                pw.print("  * Starting bg "); pw.println(r);
3669            }
3670        }
3671
3672        private void dumpRemainsLocked() {
3673            if (mPendingServices.size() > 0) {
3674                printed = false;
3675                for (int i=0; i<mPendingServices.size(); i++) {
3676                    ServiceRecord r = mPendingServices.get(i);
3677                    if (!matcher.match(r, r.name)) {
3678                        continue;
3679                    }
3680                    if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3681                        continue;
3682                    }
3683                    printedAnything = true;
3684                    if (!printed) {
3685                        if (needSep) pw.println();
3686                        needSep = true;
3687                        pw.println("  Pending services:");
3688                        printed = true;
3689                    }
3690                    pw.print("  * Pending "); pw.println(r);
3691                    r.dump(pw, "    ");
3692                }
3693                needSep = true;
3694            }
3695
3696            if (mRestartingServices.size() > 0) {
3697                printed = false;
3698                for (int i=0; i<mRestartingServices.size(); i++) {
3699                    ServiceRecord r = mRestartingServices.get(i);
3700                    if (!matcher.match(r, r.name)) {
3701                        continue;
3702                    }
3703                    if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3704                        continue;
3705                    }
3706                    printedAnything = true;
3707                    if (!printed) {
3708                        if (needSep) pw.println();
3709                        needSep = true;
3710                        pw.println("  Restarting services:");
3711                        printed = true;
3712                    }
3713                    pw.print("  * Restarting "); pw.println(r);
3714                    r.dump(pw, "    ");
3715                }
3716                needSep = true;
3717            }
3718
3719            if (mDestroyingServices.size() > 0) {
3720                printed = false;
3721                for (int i=0; i< mDestroyingServices.size(); i++) {
3722                    ServiceRecord r = mDestroyingServices.get(i);
3723                    if (!matcher.match(r, r.name)) {
3724                        continue;
3725                    }
3726                    if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3727                        continue;
3728                    }
3729                    printedAnything = true;
3730                    if (!printed) {
3731                        if (needSep) pw.println();
3732                        needSep = true;
3733                        pw.println("  Destroying services:");
3734                        printed = true;
3735                    }
3736                    pw.print("  * Destroy "); pw.println(r);
3737                    r.dump(pw, "    ");
3738                }
3739                needSep = true;
3740            }
3741
3742            if (dumpAll) {
3743                printed = false;
3744                for (int ic=0; ic<mServiceConnections.size(); ic++) {
3745                    ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
3746                    for (int i=0; i<r.size(); i++) {
3747                        ConnectionRecord cr = r.get(i);
3748                        if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
3749                            continue;
3750                        }
3751                        if (dumpPackage != null && (cr.binding.client == null
3752                                || !dumpPackage.equals(cr.binding.client.info.packageName))) {
3753                            continue;
3754                        }
3755                        printedAnything = true;
3756                        if (!printed) {
3757                            if (needSep) pw.println();
3758                            needSep = true;
3759                            pw.println("  Connection bindings to services:");
3760                            printed = true;
3761                        }
3762                        pw.print("  * "); pw.println(cr);
3763                        cr.dump(pw, "    ");
3764                    }
3765                }
3766            }
3767
3768            if (matcher.all) {
3769                final long nowElapsed = SystemClock.elapsedRealtime();
3770                final int[] users = mAm.mUserController.getUsers();
3771                for (int user : users) {
3772                    boolean printedUser = false;
3773                    ServiceMap smap = mServiceMap.get(user);
3774                    if (smap == null) {
3775                        continue;
3776                    }
3777                    for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) {
3778                        ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
3779                        if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) {
3780                            continue;
3781                        }
3782                        if (!printedUser) {
3783                            printedUser = true;
3784                            printedAnything = true;
3785                            if (needSep) pw.println();
3786                            needSep = true;
3787                            pw.print("Active foreground apps - user ");
3788                            pw.print(user);
3789                            pw.println(":");
3790                        }
3791                        pw.print("  #");
3792                        pw.print(i);
3793                        pw.print(": ");
3794                        pw.println(aa.mPackageName);
3795                        if (aa.mLabel != null) {
3796                            pw.print("    mLabel=");
3797                            pw.println(aa.mLabel);
3798                        }
3799                        pw.print("    mNumActive=");
3800                        pw.print(aa.mNumActive);
3801                        pw.print(" mAppOnTop=");
3802                        pw.print(aa.mAppOnTop);
3803                        pw.print(" mShownWhileTop=");
3804                        pw.print(aa.mShownWhileTop);
3805                        pw.print(" mShownWhileScreenOn=");
3806                        pw.println(aa.mShownWhileScreenOn);
3807                        pw.print("    mStartTime=");
3808                        TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw);
3809                        pw.print(" mStartVisibleTime=");
3810                        TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw);
3811                        pw.println();
3812                        if (aa.mEndTime != 0) {
3813                            pw.print("    mEndTime=");
3814                            TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw);
3815                            pw.println();
3816                        }
3817                    }
3818                    if (smap.hasMessagesOrCallbacks()) {
3819                        if (needSep) {
3820                            pw.println();
3821                        }
3822                        printedAnything = true;
3823                        needSep = true;
3824                        pw.print("  Handler - user ");
3825                        pw.print(user);
3826                        pw.println(":");
3827                        smap.dumpMine(new PrintWriterPrinter(pw), "    ");
3828                    }
3829                }
3830            }
3831
3832            if (!printedAnything) {
3833                pw.println("  (nothing)");
3834            }
3835        }
3836    }
3837
3838    ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
3839            int opti, boolean dumpAll, String dumpPackage) {
3840        return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
3841    }
3842
3843    /**
3844     * There are three ways to call this:
3845     *  - no service specified: dump all the services
3846     *  - a flattened component name that matched an existing service was specified as the
3847     *    first arg: dump that one service
3848     *  - the first arg isn't the flattened component name of an existing service:
3849     *    dump all services whose component contains the first arg as a substring
3850     */
3851    protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
3852            int opti, boolean dumpAll) {
3853        ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
3854
3855        synchronized (mAm) {
3856            int[] users = mAm.mUserController.getUsers();
3857            if ("all".equals(name)) {
3858                for (int user : users) {
3859                    ServiceMap smap = mServiceMap.get(user);
3860                    if (smap == null) {
3861                        continue;
3862                    }
3863                    ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
3864                    for (int i=0; i<alls.size(); i++) {
3865                        ServiceRecord r1 = alls.valueAt(i);
3866                        services.add(r1);
3867                    }
3868                }
3869            } else {
3870                ComponentName componentName = name != null
3871                        ? ComponentName.unflattenFromString(name) : null;
3872                int objectId = 0;
3873                if (componentName == null) {
3874                    // Not a '/' separated full component name; maybe an object ID?
3875                    try {
3876                        objectId = Integer.parseInt(name, 16);
3877                        name = null;
3878                        componentName = null;
3879                    } catch (RuntimeException e) {
3880                    }
3881                }
3882
3883                for (int user : users) {
3884                    ServiceMap smap = mServiceMap.get(user);
3885                    if (smap == null) {
3886                        continue;
3887                    }
3888                    ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
3889                    for (int i=0; i<alls.size(); i++) {
3890                        ServiceRecord r1 = alls.valueAt(i);
3891                        if (componentName != null) {
3892                            if (r1.name.equals(componentName)) {
3893                                services.add(r1);
3894                            }
3895                        } else if (name != null) {
3896                            if (r1.name.flattenToString().contains(name)) {
3897                                services.add(r1);
3898                            }
3899                        } else if (System.identityHashCode(r1) == objectId) {
3900                            services.add(r1);
3901                        }
3902                    }
3903                }
3904            }
3905        }
3906
3907        if (services.size() <= 0) {
3908            return false;
3909        }
3910
3911        boolean needSep = false;
3912        for (int i=0; i<services.size(); i++) {
3913            if (needSep) {
3914                pw.println();
3915            }
3916            needSep = true;
3917            dumpService("", fd, pw, services.get(i), args, dumpAll);
3918        }
3919        return true;
3920    }
3921
3922    /**
3923     * Invokes IApplicationThread.dumpService() on the thread of the specified service if
3924     * there is a thread associated with the service.
3925     */
3926    private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
3927            final ServiceRecord r, String[] args, boolean dumpAll) {
3928        String innerPrefix = prefix + "  ";
3929        synchronized (mAm) {
3930            pw.print(prefix); pw.print("SERVICE ");
3931                    pw.print(r.shortName); pw.print(" ");
3932                    pw.print(Integer.toHexString(System.identityHashCode(r)));
3933                    pw.print(" pid=");
3934                    if (r.app != null) pw.println(r.app.pid);
3935                    else pw.println("(not running)");
3936            if (dumpAll) {
3937                r.dump(pw, innerPrefix);
3938            }
3939        }
3940        if (r.app != null && r.app.thread != null) {
3941            pw.print(prefix); pw.println("  Client:");
3942            pw.flush();
3943            try {
3944                TransferPipe tp = new TransferPipe();
3945                try {
3946                    r.app.thread.dumpService(tp.getWriteFd(), r, args);
3947                    tp.setBufferPrefix(prefix + "    ");
3948                    tp.go(fd);
3949                } finally {
3950                    tp.kill();
3951                }
3952            } catch (IOException e) {
3953                pw.println(prefix + "    Failure while dumping the service: " + e);
3954            } catch (RemoteException e) {
3955                pw.println(prefix + "    Got a RemoteException while dumping the service");
3956            }
3957        }
3958    }
3959}
3960