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