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