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