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