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