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