blob: dcd0222fe8f119815b5fdc75100c78883eabafc5 [file] [log] [blame]
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
19import java.io.FileDescriptor;
20import java.io.IOException;
21import java.io.PrintWriter;
Dianne Hackborncff1bbf2015-01-20 13:43:32 -080022import java.io.StringWriter;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070023import java.util.ArrayList;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070024import java.util.HashSet;
25import java.util.Iterator;
26import java.util.List;
27
Dianne Hackborn455625e2015-01-21 09:55:13 -080028import android.app.ActivityThread;
Christoph Studer365e4c32014-09-18 20:35:36 +020029import android.os.Build;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -070030import android.os.DeadObjectException;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070031import android.os.Handler;
Dianne Hackborn13c590d2013-10-07 14:32:00 -070032import android.os.Looper;
Dianne Hackborn23037412013-11-04 18:11:29 -080033import android.os.SystemProperties;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070034import android.util.ArrayMap;
Dianne Hackborn465fa392014-09-14 14:21:18 -070035import android.util.ArraySet;
Dianne Hackbornd2932242013-08-05 18:18:42 -070036import com.android.internal.app.ProcessStats;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070037import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborncbfd23e2013-06-11 14:26:53 -070038import com.android.internal.os.TransferPipe;
Dianne Hackborncff1bbf2015-01-20 13:43:32 -080039import com.android.internal.util.FastPrintWriter;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070040import com.android.server.am.ActivityManagerService.ItemMatcher;
41import com.android.server.am.ActivityManagerService.NeededUriGrants;
42
43import android.app.ActivityManager;
44import android.app.AppGlobals;
45import android.app.IApplicationThread;
46import android.app.IServiceConnection;
47import android.app.Notification;
48import android.app.PendingIntent;
49import android.app.Service;
50import android.content.ComponentName;
51import android.content.Context;
52import android.content.Intent;
53import android.content.pm.ApplicationInfo;
54import android.content.pm.PackageManager;
55import android.content.pm.ResolveInfo;
56import android.content.pm.ServiceInfo;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070057import android.os.Binder;
58import android.os.IBinder;
59import android.os.Message;
60import android.os.Process;
61import android.os.RemoteException;
62import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070063import android.os.UserHandle;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070064import android.util.EventLog;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070065import android.util.Slog;
66import android.util.SparseArray;
67import android.util.TimeUtils;
68
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -070069public final class ActiveServices {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070070 static final boolean DEBUG_SERVICE = ActivityManagerService.DEBUG_SERVICE;
71 static final boolean DEBUG_SERVICE_EXECUTING = ActivityManagerService.DEBUG_SERVICE_EXECUTING;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070072 static final boolean DEBUG_DELAYED_SERVICE = ActivityManagerService.DEBUG_SERVICE;
Dianne Hackbornaa9875e2013-12-09 11:26:11 -080073 static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070074 static final boolean DEBUG_MU = ActivityManagerService.DEBUG_MU;
Craig Mautner9851d032015-01-26 14:33:39 -080075 static final boolean LOG_SERVICE_START_STOP = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070076 static final String TAG = ActivityManagerService.TAG;
77 static final String TAG_MU = ActivityManagerService.TAG_MU;
78
79 // How long we wait for a service to finish executing.
80 static final int SERVICE_TIMEOUT = 20*1000;
81
Dianne Hackbornbf36ee22013-07-26 18:24:10 -070082 // How long we wait for a service to finish executing.
83 static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
84
Dianne Hackborn599db5c2012-08-03 19:28:48 -070085 // How long a service needs to be running until restarting its process
86 // is no longer considered to be a relaunch of the service.
Dianne Hackborn7b492722013-11-01 09:58:45 -070087 static final int SERVICE_RESTART_DURATION = 1*1000;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070088
89 // How long a service needs to be running until it will start back at
90 // SERVICE_RESTART_DURATION after being killed.
91 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
92
93 // Multiplying factor to increase restart duration time by, for each time
94 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
95 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
96
97 // The minimum amount of time between restarting services that we allow.
98 // That is, when multiple services are restarting, we won't allow each
99 // to restart less than this amount of time from the last one.
100 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
101
102 // Maximum amount of time for there to be no activity on a service before
103 // we consider it non-essential and allow its process to go on the
104 // LRU background list.
105 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
106
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700107 // How long we wait for a background started service to stop itself before
108 // allowing the next pending start to run.
109 static final int BG_START_TIMEOUT = 15*1000;
110
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700111 final ActivityManagerService mAm;
112
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700113 // Maximum number of services that we allow to start in the background
114 // at the same time.
115 final int mMaxStartingBackground;
116
117 final SparseArray<ServiceMap> mServiceMap = new SparseArray<ServiceMap>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700118
119 /**
120 * All currently bound service connections. Keys are the IBinder of
121 * the client's IServiceConnection.
122 */
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700123 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
124 = new ArrayMap<IBinder, ArrayList<ConnectionRecord>>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700125
126 /**
127 * List of services that we have been asked to start,
128 * but haven't yet been able to. It is used to hold start requests
129 * while waiting for their corresponding application thread to get
130 * going.
131 */
132 final ArrayList<ServiceRecord> mPendingServices
133 = new ArrayList<ServiceRecord>();
134
135 /**
136 * List of services that are scheduled to restart following a crash.
137 */
138 final ArrayList<ServiceRecord> mRestartingServices
139 = new ArrayList<ServiceRecord>();
140
141 /**
Dianne Hackborn164371f2013-10-01 19:10:13 -0700142 * List of services that are in the process of being destroyed.
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700143 */
Dianne Hackborn164371f2013-10-01 19:10:13 -0700144 final ArrayList<ServiceRecord> mDestroyingServices
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700145 = new ArrayList<ServiceRecord>();
146
Dianne Hackborncff1bbf2015-01-20 13:43:32 -0800147 /** Amount of time to allow a last ANR message to exist before freeing the memory. */
148 static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
149
150 String mLastAnrDump;
151
152 final Runnable mLastAnrDumpClearer = new Runnable() {
153 @Override public void run() {
154 synchronized (mAm) {
155 mLastAnrDump = null;
156 }
157 }
158 };
159
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700160 static final class DelayingProcess extends ArrayList<ServiceRecord> {
161 long timeoout;
162 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700163
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700164 /**
165 * Information about services for a single user.
166 */
167 class ServiceMap extends Handler {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700168 final int mUserId;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700169 final ArrayMap<ComponentName, ServiceRecord> mServicesByName
170 = new ArrayMap<ComponentName, ServiceRecord>();
171 final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent
172 = new ArrayMap<Intent.FilterComparison, ServiceRecord>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700173
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700174 final ArrayList<ServiceRecord> mDelayedStartList
175 = new ArrayList<ServiceRecord>();
176 /* XXX eventually I'd like to have this based on processes instead of services.
177 * That is, if we try to start two services in a row both running in the same
178 * process, this should be one entry in mStartingBackground for that one process
179 * that remains until all services in it are done.
180 final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
181 = new ArrayMap<ProcessRecord, DelayingProcess>();
182 final ArrayList<DelayingProcess> mStartingProcessList
183 = new ArrayList<DelayingProcess>();
184 */
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700185
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700186 final ArrayList<ServiceRecord> mStartingBackground
187 = new ArrayList<ServiceRecord>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700188
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700189 static final int MSG_BG_START_TIMEOUT = 1;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700190
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700191 ServiceMap(Looper looper, int userId) {
192 super(looper);
Dianne Hackborn6285a322013-09-18 12:09:47 -0700193 mUserId = userId;
194 }
195
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700196 @Override
197 public void handleMessage(Message msg) {
198 switch (msg.what) {
199 case MSG_BG_START_TIMEOUT: {
200 synchronized (mAm) {
201 rescheduleDelayedStarts();
202 }
203 } break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700204 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700205 }
206
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700207 void ensureNotStartingBackground(ServiceRecord r) {
208 if (mStartingBackground.remove(r)) {
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800209 if (DEBUG_DELAYED_STARTS) Slog.v(TAG, "No longer background starting: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700210 rescheduleDelayedStarts();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700211 }
Dianne Hackborn2e46bb52013-09-13 17:01:26 -0700212 if (mDelayedStartList.remove(r)) {
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800213 if (DEBUG_DELAYED_STARTS) Slog.v(TAG, "No longer delaying start: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700214 }
215 }
216
217 void rescheduleDelayedStarts() {
218 removeMessages(MSG_BG_START_TIMEOUT);
219 final long now = SystemClock.uptimeMillis();
220 for (int i=0, N=mStartingBackground.size(); i<N; i++) {
221 ServiceRecord r = mStartingBackground.get(i);
222 if (r.startingBgTimeout <= now) {
223 Slog.i(TAG, "Waited long enough for: " + r);
224 mStartingBackground.remove(i);
225 N--;
Junu Kimfcb87362014-02-19 16:25:21 +0900226 i--;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700227 }
228 }
229 while (mDelayedStartList.size() > 0
230 && mStartingBackground.size() < mMaxStartingBackground) {
231 ServiceRecord r = mDelayedStartList.remove(0);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800232 if (DEBUG_DELAYED_STARTS) Slog.v(TAG, "REM FR DELAY LIST (exec next): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700233 if (r.pendingStarts.size() <= 0) {
234 Slog.w(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
235 + " delayedStop=" + r.delayedStop);
236 }
237 if (DEBUG_DELAYED_SERVICE) {
238 if (mDelayedStartList.size() > 0) {
239 Slog.v(TAG, "Remaining delayed list:");
240 for (int i=0; i<mDelayedStartList.size(); i++) {
241 Slog.v(TAG, " #" + i + ": " + mDelayedStartList.get(i));
242 }
243 }
244 }
245 r.delayed = false;
246 startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false, true);
247 }
248 if (mStartingBackground.size() > 0) {
249 ServiceRecord next = mStartingBackground.get(0);
250 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
251 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG, "Top bg start is " + next
252 + ", can delay others up to " + when);
253 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
254 sendMessageAtTime(msg, when);
255 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700256 if (mStartingBackground.size() < mMaxStartingBackground) {
257 mAm.backgroundServicesFinishedLocked(mUserId);
258 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700259 }
260 }
261
262 public ActiveServices(ActivityManagerService service) {
263 mAm = service;
Dianne Hackborn23037412013-11-04 18:11:29 -0800264 int maxBg = 0;
265 try {
266 maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
267 } catch(RuntimeException e) {
268 }
Dianne Hackborn20d94742014-05-29 18:35:45 -0700269 mMaxStartingBackground = maxBg > 0
270 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700271 }
272
273 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
274 // TODO: Deal with global services
275 if (DEBUG_MU)
276 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
277 return getServiceMap(callingUser).mServicesByName.get(name);
278 }
279
Dianne Hackborn6285a322013-09-18 12:09:47 -0700280 boolean hasBackgroundServices(int callingUser) {
281 ServiceMap smap = mServiceMap.get(callingUser);
282 return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
283 }
284
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700285 private ServiceMap getServiceMap(int callingUser) {
286 ServiceMap smap = mServiceMap.get(callingUser);
287 if (smap == null) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700288 smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700289 mServiceMap.put(callingUser, smap);
290 }
291 return smap;
292 }
293
294 ArrayMap<ComponentName, ServiceRecord> getServices(int callingUser) {
295 return getServiceMap(callingUser).mServicesByName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700296 }
297
298 ComponentName startServiceLocked(IApplicationThread caller,
299 Intent service, String resolvedType,
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700300 int callingPid, int callingUid, int userId) {
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800301 if (DEBUG_DELAYED_STARTS) Slog.v(TAG, "startService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700302 + " type=" + resolvedType + " args=" + service.getExtras());
303
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700304 final boolean callerFg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700305 if (caller != null) {
306 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
307 if (callerApp == null) {
308 throw new SecurityException(
309 "Unable to find app for caller " + caller
310 + " (pid=" + Binder.getCallingPid()
311 + ") when starting service " + service);
312 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700313 callerFg = callerApp.setSchedGroup != Process.THREAD_GROUP_BG_NONINTERACTIVE;
314 } else {
315 callerFg = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700316 }
317
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700318
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700319 ServiceLookupResult res =
320 retrieveServiceLocked(service, resolvedType,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700321 callingPid, callingUid, userId, true, callerFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700322 if (res == null) {
323 return null;
324 }
325 if (res.record == null) {
326 return new ComponentName("!", res.permission != null
327 ? res.permission : "private to package");
328 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700329
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700330 ServiceRecord r = res.record;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700331
332 if (!mAm.getUserManagerLocked().exists(r.userId)) {
333 Slog.d(TAG, "Trying to start service with non-existent user! " + r.userId);
334 return null;
335 }
336
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700337 NeededUriGrants neededGrants = mAm.checkGrantUriPermissionFromIntentLocked(
Nicolas Prevotc6cf95c2014-05-29 11:30:36 +0100338 callingUid, r.packageName, service, service.getFlags(), null, r.userId);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -0800339 if (unscheduleServiceRestartLocked(r, callingUid, false)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700340 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
341 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700342 r.lastActivity = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700343 r.startRequested = true;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700344 r.delayedStop = false;
345 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
346 service, neededGrants));
347
348 final ServiceMap smap = getServiceMap(r.userId);
349 boolean addToStarting = false;
350 if (!callerFg && r.app == null && mAm.mStartedUsers.get(r.userId) != null) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700351 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700352 if (proc == null || proc.curProcState > ActivityManager.PROCESS_STATE_RECEIVER) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700353 // If this is not coming from a foreground caller, then we may want
354 // to delay the start if there are already other background services
355 // that are starting. This is to avoid process start spam when lots
356 // of applications are all handling things like connectivity broadcasts.
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700357 // We only do this for cached processes, because otherwise an application
358 // can have assumptions about calling startService() for a service to run
359 // in its own process, and for that process to not be killed before the
360 // service is started. This is especially the case for receivers, which
361 // may start a service in onReceive() to do some additional work and have
362 // initialized some global state as part of that.
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700363 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG, "Potential start delay of " + r + " in "
364 + proc);
365 if (r.delayed) {
366 // This service is already scheduled for a delayed start; just leave
367 // it still waiting.
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800368 if (DEBUG_DELAYED_STARTS) Slog.v(TAG, "Continuing to delay: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700369 return r.name;
370 }
371 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
372 // Something else is starting, delay!
373 Slog.i(TAG, "Delaying start of: " + r);
374 smap.mDelayedStartList.add(r);
375 r.delayed = true;
376 return r.name;
377 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800378 if (DEBUG_DELAYED_STARTS) Slog.v(TAG, "Not delaying: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700379 addToStarting = true;
380 } else if (proc.curProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
381 // We slightly loosen when we will enqueue this new service as a background
382 // starting service we are waiting for, to also include processes that are
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700383 // currently running other services or receivers.
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700384 addToStarting = true;
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800385 if (DEBUG_DELAYED_STARTS) Slog.v(TAG, "Not delaying, but counting as bg: " + r);
386 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn8e692572013-09-10 19:06:15 -0700387 StringBuilder sb = new StringBuilder(128);
388 sb.append("Not potential delay (state=").append(proc.curProcState)
389 .append(' ').append(proc.adjType);
390 String reason = proc.makeAdjReason();
391 if (reason != null) {
392 sb.append(' ');
393 sb.append(reason);
394 }
395 sb.append("): ");
396 sb.append(r.toString());
397 Slog.v(TAG, sb.toString());
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700398 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800399 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700400 if (callerFg) {
401 Slog.v(TAG, "Not potential delay (callerFg=" + callerFg + " uid="
402 + callingUid + " pid=" + callingPid + "): " + r);
403 } else if (r.app != null) {
404 Slog.v(TAG, "Not potential delay (cur app=" + r.app + "): " + r);
405 } else {
406 Slog.v(TAG, "Not potential delay (user " + r.userId + " not started): " + r);
407 }
408 }
409
410 return startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
411 }
412
413 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service,
414 ServiceRecord r, boolean callerFg, boolean addToStarting) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700415 ProcessStats.ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700416 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700417 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700418 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700419 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700420 synchronized (r.stats.getBatteryStats()) {
421 r.stats.startRunningLocked();
422 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700423 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700424 if (error != null) {
425 return new ComponentName("!!", error);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700426 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700427
428 if (r.startRequested && addToStarting) {
429 boolean first = smap.mStartingBackground.size() == 0;
430 smap.mStartingBackground.add(r);
431 r.startingBgTimeout = SystemClock.uptimeMillis() + BG_START_TIMEOUT;
432 if (DEBUG_DELAYED_SERVICE) {
433 RuntimeException here = new RuntimeException("here");
434 here.fillInStackTrace();
435 Slog.v(TAG, "Starting background (first=" + first + "): " + r, here);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800436 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700437 Slog.v(TAG, "Starting background (first=" + first + "): " + r);
438 }
439 if (first) {
440 smap.rescheduleDelayedStarts();
441 }
442 } else if (callerFg) {
443 smap.ensureNotStartingBackground(r);
444 }
445
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700446 return r.name;
447 }
448
449 private void stopServiceLocked(ServiceRecord service) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700450 if (service.delayed) {
451 // If service isn't actually running, but is is being held in the
452 // delayed list, then we need to keep it started but note that it
453 // should be stopped once no longer delayed.
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800454 if (DEBUG_DELAYED_STARTS) Slog.v(TAG, "Delaying stop of pending: " + service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700455 service.delayedStop = true;
456 return;
457 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700458 synchronized (service.stats.getBatteryStats()) {
459 service.stats.stopRunningLocked();
460 }
461 service.startRequested = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700462 if (service.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700463 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700464 SystemClock.uptimeMillis());
465 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700466 service.callStart = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700467 bringDownServiceIfNeededLocked(service, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700468 }
469
470 int stopServiceLocked(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700471 String resolvedType, int userId) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700472 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
473 + " type=" + resolvedType);
474
475 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
476 if (caller != null && callerApp == null) {
477 throw new SecurityException(
478 "Unable to find app for caller " + caller
479 + " (pid=" + Binder.getCallingPid()
480 + ") when stopping service " + service);
481 }
482
483 // If this service is active, make sure it is stopped.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -0700484 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700485 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700486 if (r != null) {
487 if (r.record != null) {
488 final long origId = Binder.clearCallingIdentity();
489 try {
490 stopServiceLocked(r.record);
491 } finally {
492 Binder.restoreCallingIdentity(origId);
493 }
494 return 1;
495 }
496 return -1;
497 }
498
499 return 0;
500 }
501
502 IBinder peekServiceLocked(Intent service, String resolvedType) {
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -0700503 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType,
504 Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700505 UserHandle.getCallingUserId(), false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700506
507 IBinder ret = null;
508 if (r != null) {
509 // r.record is null if findServiceLocked() failed the caller permission check
510 if (r.record == null) {
511 throw new SecurityException(
512 "Permission Denial: Accessing service " + r.record.name
513 + " from pid=" + Binder.getCallingPid()
514 + ", uid=" + Binder.getCallingUid()
515 + " requires " + r.permission);
516 }
517 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
518 if (ib != null) {
519 ret = ib.binder;
520 }
521 }
522
523 return ret;
524 }
525
526 boolean stopServiceTokenLocked(ComponentName className, IBinder token,
527 int startId) {
528 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
529 + " " + token + " startId=" + startId);
Dianne Hackborn41203752012-08-31 14:05:51 -0700530 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700531 if (r != null) {
532 if (startId >= 0) {
533 // Asked to only stop if done with all work. Note that
534 // to avoid leaks, we will take this as dropping all
535 // start items up to and including this one.
536 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
537 if (si != null) {
538 while (r.deliveredStarts.size() > 0) {
539 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
540 cur.removeUriPermissionsLocked();
541 if (cur == si) {
542 break;
543 }
544 }
545 }
546
547 if (r.getLastStartId() != startId) {
548 return false;
549 }
550
551 if (r.deliveredStarts.size() > 0) {
552 Slog.w(TAG, "stopServiceToken startId " + startId
553 + " is last, but have " + r.deliveredStarts.size()
554 + " remaining args");
555 }
556 }
557
558 synchronized (r.stats.getBatteryStats()) {
559 r.stats.stopRunningLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700560 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700561 r.startRequested = false;
562 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700563 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700564 SystemClock.uptimeMillis());
565 }
566 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700567 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700568 bringDownServiceIfNeededLocked(r, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700569 Binder.restoreCallingIdentity(origId);
570 return true;
571 }
572 return false;
573 }
574
575 public void setServiceForegroundLocked(ComponentName className, IBinder token,
576 int id, Notification notification, boolean removeNotification) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700577 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700578 final long origId = Binder.clearCallingIdentity();
579 try {
Dianne Hackborn41203752012-08-31 14:05:51 -0700580 ServiceRecord r = findServiceLocked(className, token, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700581 if (r != null) {
582 if (id != 0) {
583 if (notification == null) {
584 throw new IllegalArgumentException("null notification");
585 }
586 if (r.foregroundId != id) {
587 r.cancelNotification();
588 r.foregroundId = id;
589 }
590 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
591 r.foregroundNoti = notification;
592 r.isForeground = true;
593 r.postNotification();
594 if (r.app != null) {
595 updateServiceForegroundLocked(r.app, true);
596 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700597 getServiceMap(r.userId).ensureNotStartingBackground(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700598 } else {
599 if (r.isForeground) {
600 r.isForeground = false;
601 if (r.app != null) {
Dianne Hackborndb926082013-10-31 16:32:44 -0700602 mAm.updateLruProcessLocked(r.app, false, null);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700603 updateServiceForegroundLocked(r.app, true);
604 }
605 }
606 if (removeNotification) {
607 r.cancelNotification();
608 r.foregroundId = 0;
609 r.foregroundNoti = null;
Dianne Hackborn955d8d62014-10-07 20:17:19 -0700610 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
Christoph Studer365e4c32014-09-18 20:35:36 +0200611 r.stripForegroundServiceFlagFromNotification();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700612 }
613 }
614 }
615 } finally {
616 Binder.restoreCallingIdentity(origId);
617 }
618 }
619
620 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
621 boolean anyForeground = false;
Dianne Hackbornc8230512013-07-13 21:32:12 -0700622 for (int i=proc.services.size()-1; i>=0; i--) {
623 ServiceRecord sr = proc.services.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700624 if (sr.isForeground) {
625 anyForeground = true;
626 break;
627 }
628 }
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800629 mAm.updateProcessForegroundLocked(proc, anyForeground, oomAdj);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700630 }
631
Dianne Hackborn465fa392014-09-14 14:21:18 -0700632 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
633 ArraySet<ProcessRecord> updatedProcesses = null;
634 for (int i=0; i<clientProc.connections.size(); i++) {
635 final ConnectionRecord conn = clientProc.connections.valueAt(i);
636 final ProcessRecord proc = conn.binding.service.app;
637 if (proc == null || proc == clientProc) {
638 continue;
639 } else if (updatedProcesses == null) {
640 updatedProcesses = new ArraySet<>();
641 } else if (updatedProcesses.contains(proc)) {
642 continue;
643 }
644 updatedProcesses.add(proc);
645 updateServiceClientActivitiesLocked(proc, null, false);
646 }
647 }
648
Dianne Hackborndb926082013-10-31 16:32:44 -0700649 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
Dianne Hackborn465fa392014-09-14 14:21:18 -0700650 ConnectionRecord modCr, boolean updateLru) {
Dianne Hackborndb926082013-10-31 16:32:44 -0700651 if (modCr != null && modCr.binding.client != null) {
652 if (modCr.binding.client.activities.size() <= 0) {
653 // This connection is from a client without activities, so adding
654 // and removing is not interesting.
655 return false;
656 }
657 }
658
659 boolean anyClientActivities = false;
660 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
661 ServiceRecord sr = proc.services.valueAt(i);
662 for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) {
663 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni);
664 for (int cri=clist.size()-1; cri>=0; cri--) {
665 ConnectionRecord cr = clist.get(cri);
666 if (cr.binding.client == null || cr.binding.client == proc) {
667 // Binding to ourself is not interesting.
668 continue;
669 }
670 if (cr.binding.client.activities.size() > 0) {
671 anyClientActivities = true;
672 break;
673 }
674 }
675 }
676 }
677 if (anyClientActivities != proc.hasClientActivities) {
678 proc.hasClientActivities = anyClientActivities;
Dianne Hackborn465fa392014-09-14 14:21:18 -0700679 if (updateLru) {
680 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
681 }
Dianne Hackborndb926082013-10-31 16:32:44 -0700682 return true;
683 }
684 return false;
685 }
686
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700687 int bindServiceLocked(IApplicationThread caller, IBinder token,
688 Intent service, String resolvedType,
689 IServiceConnection connection, int flags, int userId) {
690 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
691 + " type=" + resolvedType + " conn=" + connection.asBinder()
692 + " flags=0x" + Integer.toHexString(flags));
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700693 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
694 if (callerApp == null) {
695 throw new SecurityException(
696 "Unable to find app for caller " + caller
697 + " (pid=" + Binder.getCallingPid()
698 + ") when binding service " + service);
699 }
700
701 ActivityRecord activity = null;
702 if (token != null) {
Craig Mautnerd2328952013-03-05 12:46:26 -0800703 activity = ActivityRecord.isInStackLocked(token);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700704 if (activity == null) {
705 Slog.w(TAG, "Binding with unknown activity: " + token);
706 return 0;
707 }
708 }
709
710 int clientLabel = 0;
711 PendingIntent clientIntent = null;
712
713 if (callerApp.info.uid == Process.SYSTEM_UID) {
714 // Hacky kind of thing -- allow system stuff to tell us
715 // what they are, so we can report this elsewhere for
716 // others to know why certain services are running.
717 try {
Dianne Hackbornf0f94d12014-03-17 16:04:21 -0700718 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700719 } catch (RuntimeException e) {
720 }
721 if (clientIntent != null) {
722 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
723 if (clientLabel != 0) {
724 // There are no useful extras in the intent, trash them.
725 // System code calling with this stuff just needs to know
726 // this will happen.
727 service = service.cloneFilter();
728 }
729 }
730 }
731
Dianne Hackbornf0f94d12014-03-17 16:04:21 -0700732 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
733 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
734 "BIND_TREAT_LIKE_ACTIVITY");
735 }
736
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700737 final boolean callerFg = callerApp.setSchedGroup != Process.THREAD_GROUP_BG_NONINTERACTIVE;
738
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700739 ServiceLookupResult res =
740 retrieveServiceLocked(service, resolvedType,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700741 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, callerFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700742 if (res == null) {
743 return 0;
744 }
745 if (res.record == null) {
746 return -1;
747 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700748 ServiceRecord s = res.record;
749
750 final long origId = Binder.clearCallingIdentity();
751
752 try {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -0800753 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700754 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
755 + s);
756 }
757
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700758 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
759 s.lastActivity = SystemClock.uptimeMillis();
760 if (!s.hasAutoCreateConnections()) {
761 // This is the first binding, let the tracker know.
Dianne Hackbornd2932242013-08-05 18:18:42 -0700762 ProcessStats.ServiceState stracker = s.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700763 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700764 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700765 s.lastActivity);
766 }
767 }
768 }
769
Dianne Hackbornab2df062015-01-07 13:43:13 -0800770 mAm.startAssociationLocked(callerApp.uid, callerApp.processName,
771 s.appInfo.uid, s.name, s.processName);
772
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700773 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
774 ConnectionRecord c = new ConnectionRecord(b, activity,
775 connection, flags, clientLabel, clientIntent);
776
777 IBinder binder = connection.asBinder();
778 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
779 if (clist == null) {
780 clist = new ArrayList<ConnectionRecord>();
781 s.connections.put(binder, clist);
782 }
783 clist.add(c);
784 b.connections.add(c);
785 if (activity != null) {
786 if (activity.connections == null) {
787 activity.connections = new HashSet<ConnectionRecord>();
788 }
789 activity.connections.add(c);
790 }
791 b.client.connections.add(c);
792 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
793 b.client.hasAboveClient = true;
794 }
Dianne Hackborndb926082013-10-31 16:32:44 -0700795 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -0700796 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -0700797 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700798 clist = mServiceConnections.get(binder);
799 if (clist == null) {
800 clist = new ArrayList<ConnectionRecord>();
801 mServiceConnections.put(binder, clist);
802 }
803 clist.add(c);
804
805 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
806 s.lastActivity = SystemClock.uptimeMillis();
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700807 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false) != null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700808 return 0;
809 }
810 }
811
812 if (s.app != null) {
Dianne Hackbornf0f94d12014-03-17 16:04:21 -0700813 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
814 s.app.treatLikeActivity = true;
815 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700816 // This could have made the service more important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -0700817 mAm.updateLruProcessLocked(s.app, s.app.hasClientActivities
818 || s.app.treatLikeActivity, b.client);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700819 mAm.updateOomAdjLocked(s.app);
820 }
821
822 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
823 + ": received=" + b.intent.received
824 + " apps=" + b.intent.apps.size()
825 + " doRebind=" + b.intent.doRebind);
826
827 if (s.app != null && b.intent.received) {
828 // Service is already running, so we can immediately
829 // publish the connection.
830 try {
831 c.conn.connected(s.name, b.intent.binder);
832 } catch (Exception e) {
833 Slog.w(TAG, "Failure sending service " + s.shortName
834 + " to connection " + c.conn.asBinder()
835 + " (in " + c.binding.client.processName + ")", e);
836 }
837
838 // If this is the first app connected back to this binding,
839 // and the service had previously asked to be told when
840 // rebound, then do so.
841 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700842 requestServiceBindingLocked(s, b.intent, callerFg, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700843 }
844 } else if (!b.intent.requested) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700845 requestServiceBindingLocked(s, b.intent, callerFg, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700846 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700847
848 getServiceMap(s.userId).ensureNotStartingBackground(s);
849
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700850 } finally {
851 Binder.restoreCallingIdentity(origId);
852 }
853
854 return 1;
855 }
856
857 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
858 final long origId = Binder.clearCallingIdentity();
859 try {
860 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
861 + " " + intent + ": " + service);
862 if (r != null) {
863 Intent.FilterComparison filter
864 = new Intent.FilterComparison(intent);
865 IntentBindRecord b = r.bindings.get(filter);
866 if (b != null && !b.received) {
867 b.binder = service;
868 b.requested = true;
869 b.received = true;
Dianne Hackborn390517b2013-05-30 15:03:32 -0700870 for (int conni=r.connections.size()-1; conni>=0; conni--) {
871 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
872 for (int i=0; i<clist.size(); i++) {
873 ConnectionRecord c = clist.get(i);
874 if (!filter.equals(c.binding.intent.intent)) {
875 if (DEBUG_SERVICE) Slog.v(
876 TAG, "Not publishing to: " + c);
877 if (DEBUG_SERVICE) Slog.v(
878 TAG, "Bound intent: " + c.binding.intent.intent);
879 if (DEBUG_SERVICE) Slog.v(
880 TAG, "Published intent: " + intent);
881 continue;
882 }
883 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
884 try {
885 c.conn.connected(r.name, service);
886 } catch (Exception e) {
887 Slog.w(TAG, "Failure sending service " + r.name +
888 " to connection " + c.conn.asBinder() +
889 " (in " + c.binding.client.processName + ")", e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700890 }
891 }
892 }
893 }
894
Dianne Hackborn164371f2013-10-01 19:10:13 -0700895 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700896 }
897 } finally {
898 Binder.restoreCallingIdentity(origId);
899 }
900 }
901
902 boolean unbindServiceLocked(IServiceConnection connection) {
903 IBinder binder = connection.asBinder();
904 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
905 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
906 if (clist == null) {
907 Slog.w(TAG, "Unbind failed: could not find connection for "
908 + connection.asBinder());
909 return false;
910 }
911
912 final long origId = Binder.clearCallingIdentity();
913 try {
914 while (clist.size() > 0) {
915 ConnectionRecord r = clist.get(0);
916 removeConnectionLocked(r, null, null);
Dianne Hackborn25e1eca2014-09-23 10:13:13 -0700917 if (clist.size() > 0 && clist.get(0) == r) {
918 // In case it didn't get removed above, do it now.
919 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
920 clist.remove(0);
921 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700922
923 if (r.binding.service.app != null) {
924 // This could have made the service less important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -0700925 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
926 r.binding.service.app.treatLikeActivity = true;
927 mAm.updateLruProcessLocked(r.binding.service.app,
928 r.binding.service.app.hasClientActivities
929 || r.binding.service.app.treatLikeActivity, null);
930 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700931 mAm.updateOomAdjLocked(r.binding.service.app);
932 }
933 }
934 } finally {
935 Binder.restoreCallingIdentity(origId);
936 }
937
938 return true;
939 }
940
941 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
942 final long origId = Binder.clearCallingIdentity();
943 try {
944 if (r != null) {
945 Intent.FilterComparison filter
946 = new Intent.FilterComparison(intent);
947 IntentBindRecord b = r.bindings.get(filter);
948 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
949 + " at " + b + ": apps="
950 + (b != null ? b.apps.size() : 0));
951
Dianne Hackborn164371f2013-10-01 19:10:13 -0700952 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700953 if (b != null) {
Dianne Hackborn164371f2013-10-01 19:10:13 -0700954 if (b.apps.size() > 0 && !inDestroying) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700955 // Applications have already bound since the last
956 // unbind, so just rebind right here.
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700957 boolean inFg = false;
958 for (int i=b.apps.size()-1; i>=0; i--) {
959 ProcessRecord client = b.apps.valueAt(i).client;
960 if (client != null && client.setSchedGroup
961 != Process.THREAD_GROUP_BG_NONINTERACTIVE) {
962 inFg = true;
963 break;
964 }
965 }
966 requestServiceBindingLocked(r, b, inFg, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700967 } else {
968 // Note to tell the service the next time there is
969 // a new client.
970 b.doRebind = true;
971 }
972 }
973
Dianne Hackborn164371f2013-10-01 19:10:13 -0700974 serviceDoneExecutingLocked(r, inDestroying, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700975 }
976 } finally {
977 Binder.restoreCallingIdentity(origId);
978 }
979 }
980
981 private final ServiceRecord findServiceLocked(ComponentName name,
Dianne Hackborn41203752012-08-31 14:05:51 -0700982 IBinder token, int userId) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700983 ServiceRecord r = getServiceByName(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700984 return r == token ? r : null;
985 }
986
987 private final class ServiceLookupResult {
988 final ServiceRecord record;
989 final String permission;
990
991 ServiceLookupResult(ServiceRecord _record, String _permission) {
992 record = _record;
993 permission = _permission;
994 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700995 }
996
997 private class ServiceRestarter implements Runnable {
998 private ServiceRecord mService;
999
1000 void setService(ServiceRecord service) {
1001 mService = service;
1002 }
1003
1004 public void run() {
1005 synchronized(mAm) {
1006 performServiceRestartLocked(mService);
1007 }
1008 }
1009 }
1010
1011 private ServiceLookupResult retrieveServiceLocked(Intent service,
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001012 String resolvedType, int callingPid, int callingUid, int userId,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001013 boolean createIfNeeded, boolean callingFromFg) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001014 ServiceRecord r = null;
1015 if (DEBUG_SERVICE) Slog.v(TAG, "retrieveServiceLocked: " + service
1016 + " type=" + resolvedType + " callingUid=" + callingUid);
1017
Dianne Hackborn139748f2012-09-24 11:36:57 -07001018 userId = mAm.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn409297d2014-07-10 17:39:20 -07001019 false, ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE, "service", null);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001020
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001021 ServiceMap smap = getServiceMap(userId);
1022 final ComponentName comp = service.getComponent();
1023 if (comp != null) {
1024 r = smap.mServicesByName.get(comp);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001025 }
1026 if (r == null) {
1027 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001028 r = smap.mServicesByIntent.get(filter);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001029 }
1030 if (r == null) {
1031 try {
1032 ResolveInfo rInfo =
1033 AppGlobals.getPackageManager().resolveService(
1034 service, resolvedType,
1035 ActivityManagerService.STOCK_PM_FLAGS, userId);
1036 ServiceInfo sInfo =
1037 rInfo != null ? rInfo.serviceInfo : null;
1038 if (sInfo == null) {
Amith Yamasani2b914652012-08-27 12:04:40 -07001039 Slog.w(TAG, "Unable to start service " + service + " U=" + userId +
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001040 ": not found");
1041 return null;
1042 }
1043 ComponentName name = new ComponentName(
1044 sInfo.applicationInfo.packageName, sInfo.name);
1045 if (userId > 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001046 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
Amith Yamasani4b9d79c2014-05-21 19:14:21 -07001047 sInfo.name, sInfo.flags)
1048 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001049 userId = 0;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001050 smap = getServiceMap(0);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001051 }
1052 sInfo = new ServiceInfo(sInfo);
1053 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
1054 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001055 r = smap.mServicesByName.get(name);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001056 if (r == null && createIfNeeded) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001057 Intent.FilterComparison filter
1058 = new Intent.FilterComparison(service.cloneFilter());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001059 ServiceRestarter res = new ServiceRestarter();
1060 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
1061 BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
1062 synchronized (stats) {
1063 ss = stats.getServiceStatsLocked(
1064 sInfo.applicationInfo.uid, sInfo.packageName,
1065 sInfo.name);
1066 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001067 r = new ServiceRecord(mAm, ss, name, filter, sInfo, callingFromFg, res);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001068 res.setService(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001069 smap.mServicesByName.put(name, r);
1070 smap.mServicesByIntent.put(filter, r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001071
1072 // Make sure this component isn't in the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001073 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001074 ServiceRecord pr = mPendingServices.get(i);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001075 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
1076 && pr.name.equals(name)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001077 mPendingServices.remove(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001078 }
1079 }
1080 }
1081 } catch (RemoteException ex) {
1082 // pm is in same process, this will never happen.
1083 }
1084 }
1085 if (r != null) {
1086 if (mAm.checkComponentPermission(r.permission,
1087 callingPid, callingUid, r.appInfo.uid, r.exported)
1088 != PackageManager.PERMISSION_GRANTED) {
1089 if (!r.exported) {
1090 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1091 + " from pid=" + callingPid
1092 + ", uid=" + callingUid
1093 + " that is not exported from uid " + r.appInfo.uid);
1094 return new ServiceLookupResult(null, "not exported from uid "
1095 + r.appInfo.uid);
1096 }
1097 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1098 + " from pid=" + callingPid
1099 + ", uid=" + callingUid
1100 + " requires " + r.permission);
1101 return new ServiceLookupResult(null, r.permission);
1102 }
Ben Gruverf5323fe2013-07-31 15:09:51 -07001103 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
1104 resolvedType, r.appInfo)) {
Ben Gruverb6223792013-07-29 16:35:40 -07001105 return null;
1106 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001107 return new ServiceLookupResult(r, null);
1108 }
1109 return null;
1110 }
1111
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001112 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001113 if (DEBUG_SERVICE) Slog.v(TAG, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001114 + why + " of " + r + " in app " + r.app);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001115 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001116 + why + " of " + r.shortName);
1117 long now = SystemClock.uptimeMillis();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001118 if (r.executeNesting == 0) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001119 r.executeFg = fg;
Dianne Hackbornd2932242013-08-05 18:18:42 -07001120 ProcessStats.ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001121 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001122 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001123 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001124 if (r.app != null) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001125 r.app.executingServices.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001126 r.app.execServicesFg |= fg;
Dianne Hackborn2be00932013-09-22 16:46:00 -07001127 if (r.app.executingServices.size() == 1) {
1128 scheduleServiceTimeoutLocked(r.app);
1129 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001130 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001131 } else if (r.app != null && fg && !r.app.execServicesFg) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001132 r.app.execServicesFg = true;
Dianne Hackborn2be00932013-09-22 16:46:00 -07001133 scheduleServiceTimeoutLocked(r.app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001134 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001135 r.executeFg |= fg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001136 r.executeNesting++;
1137 r.executingStart = now;
1138 }
1139
1140 private final boolean requestServiceBindingLocked(ServiceRecord r,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001141 IntentBindRecord i, boolean execInFg, boolean rebind) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001142 if (r.app == null || r.app.thread == null) {
1143 // If service is not currently running, can't yet bind.
1144 return false;
1145 }
1146 if ((!i.requested || rebind) && i.apps.size() > 0) {
1147 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001148 bumpServiceExecutingLocked(r, execInFg, "bind");
Dianne Hackborna413dc02013-07-12 12:02:55 -07001149 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
1150 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
1151 r.app.repProcState);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001152 if (!rebind) {
1153 i.requested = true;
1154 }
1155 i.hasBound = true;
1156 i.doRebind = false;
1157 } catch (RemoteException e) {
1158 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
1159 return false;
1160 }
1161 }
1162 return true;
1163 }
1164
1165 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
1166 boolean allowCancel) {
1167 boolean canceled = false;
1168
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001169 ServiceMap smap = getServiceMap(r.userId);
1170 if (smap.mServicesByName.get(r.name) != r) {
1171 ServiceRecord cur = smap.mServicesByName.get(r.name);
1172 Slog.wtf(TAG, "Attempting to schedule restart of " + r
1173 + " when found in map: " + cur);
1174 return false;
1175 }
1176
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001177 final long now = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001178
1179 if ((r.serviceInfo.applicationInfo.flags
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001180 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
1181 long minDuration = SERVICE_RESTART_DURATION;
1182 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001183
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001184 // Any delivered but not yet finished starts should be put back
1185 // on the pending list.
1186 final int N = r.deliveredStarts.size();
1187 if (N > 0) {
1188 for (int i=N-1; i>=0; i--) {
1189 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
1190 si.removeUriPermissionsLocked();
1191 if (si.intent == null) {
1192 // We'll generate this again if needed.
1193 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
1194 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
1195 r.pendingStarts.add(0, si);
1196 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
1197 dur *= 2;
1198 if (minDuration < dur) minDuration = dur;
1199 if (resetTime < dur) resetTime = dur;
1200 } else {
1201 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
1202 + r.name);
1203 canceled = true;
1204 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001205 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001206 r.deliveredStarts.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001207 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001208
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001209 r.totalRestartCount++;
1210 if (r.restartDelay == 0) {
1211 r.restartCount++;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001212 r.restartDelay = minDuration;
1213 } else {
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001214 // If it has been a "reasonably long time" since the service
1215 // was started, then reset our restart duration back to
1216 // the beginning, so we don't infinitely increase the duration
1217 // on a service that just occasionally gets killed (which is
1218 // a normal case, due to process being killed to reclaim memory).
1219 if (now > (r.restartTime+resetTime)) {
1220 r.restartCount = 1;
1221 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001222 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07001223 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
1224 if (r.restartDelay < minDuration) {
1225 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001226 }
1227 }
1228 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001229
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001230 r.nextRestartTime = now + r.restartDelay;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001231
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001232 // Make sure that we don't end up restarting a bunch of services
1233 // all at the same time.
1234 boolean repeat;
1235 do {
1236 repeat = false;
1237 for (int i=mRestartingServices.size()-1; i>=0; i--) {
1238 ServiceRecord r2 = mRestartingServices.get(i);
1239 if (r2 != r && r.nextRestartTime
1240 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
1241 && r.nextRestartTime
1242 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
1243 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
1244 r.restartDelay = r.nextRestartTime - now;
1245 repeat = true;
1246 break;
1247 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001248 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001249 } while (repeat);
1250
1251 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07001252 // Persistent processes are immediately restarted, so there is no
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001253 // reason to hold of on restarting their services.
1254 r.totalRestartCount++;
1255 r.restartCount = 0;
1256 r.restartDelay = 0;
1257 r.nextRestartTime = now;
1258 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001259
1260 if (!mRestartingServices.contains(r)) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001261 r.createdFromFg = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001262 mRestartingServices.add(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001263 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001264 }
1265
1266 r.cancelNotification();
1267
1268 mAm.mHandler.removeCallbacks(r.restarter);
1269 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
1270 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
1271 Slog.w(TAG, "Scheduling restart of crashed service "
1272 + r.shortName + " in " + r.restartDelay + "ms");
1273 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001274 r.userId, r.shortName, r.restartDelay);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001275
1276 return canceled;
1277 }
1278
1279 final void performServiceRestartLocked(ServiceRecord r) {
1280 if (!mRestartingServices.contains(r)) {
1281 return;
1282 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001283 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001284 }
1285
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001286 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
1287 boolean force) {
1288 if (!force && r.restartDelay == 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001289 return false;
1290 }
Dianne Hackborn7b492722013-11-01 09:58:45 -07001291 // Remove from the restarting list; if the service is currently on the
1292 // restarting list, or the call is coming from another app, then this
1293 // service has become of much more interest so we reset the restart interval.
1294 boolean removed = mRestartingServices.remove(r);
1295 if (removed || callingUid != r.appInfo.uid) {
1296 r.resetRestartCounter();
1297 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001298 if (removed) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001299 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001300 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001301 mAm.mHandler.removeCallbacks(r.restarter);
1302 return true;
1303 }
1304
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001305 private void clearRestartingIfNeededLocked(ServiceRecord r) {
1306 if (r.restartTracker != null) {
1307 // If this is the last restarting record with this tracker, then clear
1308 // the tracker's restarting state.
1309 boolean stillTracking = false;
1310 for (int i=mRestartingServices.size()-1; i>=0; i--) {
1311 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
1312 stillTracking = true;
1313 break;
1314 }
1315 }
1316 if (!stillTracking) {
1317 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
1318 SystemClock.uptimeMillis());
1319 r.restartTracker = null;
1320 }
1321 }
1322 }
1323
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001324 private final String bringUpServiceLocked(ServiceRecord r,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001325 int intentFlags, boolean execInFg, boolean whileRestarting) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001326 //Slog.i(TAG, "Bring up service:");
1327 //r.dump(" ");
1328
1329 if (r.app != null && r.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001330 sendServiceArgsLocked(r, execInFg, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001331 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001332 }
1333
1334 if (!whileRestarting && r.restartDelay > 0) {
1335 // If waiting for a restart, then do nothing.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001336 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001337 }
1338
1339 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
1340
1341 // We are now bringing the service up, so no longer in the
1342 // restarting state.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001343 if (mRestartingServices.remove(r)) {
chad7158ea22014-12-21 15:43:01 +08001344 r.resetRestartCounter();
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001345 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001346 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001347
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001348 // Make sure this service is no longer considered delayed, we are starting it now.
1349 if (r.delayed) {
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08001350 if (DEBUG_DELAYED_STARTS) Slog.v(TAG, "REM FR DELAY LIST (bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001351 getServiceMap(r.userId).mDelayedStartList.remove(r);
1352 r.delayed = false;
1353 }
1354
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001355 // Make sure that the user who owns this service is started. If not,
1356 // we don't want to allow it to run.
1357 if (mAm.mStartedUsers.get(r.userId) == null) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001358 String msg = "Unable to launch app "
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001359 + r.appInfo.packageName + "/"
1360 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001361 + r.intent.getIntent() + ": user " + r.userId + " is stopped";
1362 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001363 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001364 return msg;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001365 }
1366
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001367 // Service is now being launched, its package can't be stopped.
1368 try {
1369 AppGlobals.getPackageManager().setPackageStoppedState(
1370 r.packageName, false, r.userId);
1371 } catch (RemoteException e) {
1372 } catch (IllegalArgumentException e) {
1373 Slog.w(TAG, "Failed trying to unstop package "
1374 + r.packageName + ": " + e);
1375 }
1376
1377 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
1378 final String procName = r.processName;
1379 ProcessRecord app;
1380
1381 if (!isolated) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001382 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
1383 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
1384 + " app=" + app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001385 if (app != null && app.thread != null) {
1386 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001387 app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001388 realStartServiceLocked(r, app, execInFg);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001389 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001390 } catch (RemoteException e) {
1391 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
1392 }
1393
1394 // If a dead object exception was thrown -- fall through to
1395 // restart the application.
1396 }
1397 } else {
1398 // If this service runs in an isolated process, then each time
1399 // we call startProcessLocked() we will get a new isolated
1400 // process, starting another process if we are currently waiting
1401 // for a previous process to come up. To deal with this, we store
1402 // in the service any current isolated process it is running in or
1403 // waiting to have come up.
1404 app = r.isolatedProc;
1405 }
1406
1407 // Not running -- get it started, and enqueue this service record
1408 // to be executed when the app comes up.
1409 if (app == null) {
1410 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001411 "service", r.name, false, isolated, false)) == null) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001412 String msg = "Unable to launch app "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001413 + r.appInfo.packageName + "/"
1414 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001415 + r.intent.getIntent() + ": process is bad";
1416 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001417 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001418 return msg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001419 }
1420 if (isolated) {
1421 r.isolatedProc = app;
1422 }
1423 }
1424
1425 if (!mPendingServices.contains(r)) {
1426 mPendingServices.add(r);
1427 }
1428
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001429 if (r.delayedStop) {
1430 // Oh and hey we've already been asked to stop!
1431 r.delayedStop = false;
1432 if (r.startRequested) {
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08001433 if (DEBUG_DELAYED_STARTS) Slog.v(TAG, "Applying delayed stop (in bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001434 stopServiceLocked(r);
1435 }
1436 }
1437
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001438 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001439 }
1440
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001441 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001442 for (int i=r.bindings.size()-1; i>=0; i--) {
1443 IntentBindRecord ibr = r.bindings.valueAt(i);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001444 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001445 break;
1446 }
1447 }
1448 }
1449
1450 private final void realStartServiceLocked(ServiceRecord r,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001451 ProcessRecord app, boolean execInFg) throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001452 if (app.thread == null) {
1453 throw new RemoteException();
1454 }
1455 if (DEBUG_MU)
1456 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
1457 + ", ProcessRecord.uid = " + app.uid);
1458 r.app = app;
1459 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
1460
1461 app.services.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001462 bumpServiceExecutingLocked(r, execInFg, "create");
Dianne Hackborndb926082013-10-31 16:32:44 -07001463 mAm.updateLruProcessLocked(app, false, null);
1464 mAm.updateOomAdjLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001465
1466 boolean created = false;
1467 try {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07001468 if (LOG_SERVICE_START_STOP) {
Dianne Hackbornab2df062015-01-07 13:43:13 -08001469 String nameTerm;
1470 int lastPeriod = r.shortName.lastIndexOf('.');
1471 nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07001472 EventLogTags.writeAmCreateService(
1473 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
1474 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001475 synchronized (r.stats.getBatteryStats()) {
1476 r.stats.startLaunchedLocked();
1477 }
1478 mAm.ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborna413dc02013-07-12 12:02:55 -07001479 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001480 app.thread.scheduleCreateService(r, r.serviceInfo,
Dianne Hackborna413dc02013-07-12 12:02:55 -07001481 mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
1482 app.repProcState);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001483 r.postNotification();
1484 created = true;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -07001485 } catch (DeadObjectException e) {
1486 Slog.w(TAG, "Application dead when creating service " + r);
1487 mAm.appDiedLocked(app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001488 } finally {
1489 if (!created) {
1490 app.services.remove(r);
Dianne Hackbornbc72dce2013-11-11 10:43:38 -08001491 r.app = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001492 scheduleServiceRestartLocked(r, false);
Dianne Hackborn7622a0f2014-09-30 14:31:42 -07001493 return;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001494 }
1495 }
1496
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001497 requestServiceBindingsLocked(r, execInFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001498
Dianne Hackborn465fa392014-09-14 14:21:18 -07001499 updateServiceClientActivitiesLocked(app, null, true);
1500
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001501 // If the service is in the started state, and there are no
1502 // pending arguments, then fake up one so its onStartCommand() will
1503 // be called.
1504 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
1505 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
1506 null, null));
1507 }
1508
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001509 sendServiceArgsLocked(r, execInFg, true);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001510
1511 if (r.delayed) {
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08001512 if (DEBUG_DELAYED_STARTS) Slog.v(TAG, "REM FR DELAY LIST (new proc): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001513 getServiceMap(r.userId).mDelayedStartList.remove(r);
1514 r.delayed = false;
1515 }
1516
1517 if (r.delayedStop) {
1518 // Oh and hey we've already been asked to stop!
1519 r.delayedStop = false;
1520 if (r.startRequested) {
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08001521 if (DEBUG_DELAYED_STARTS) Slog.v(TAG, "Applying delayed stop (from start): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001522 stopServiceLocked(r);
1523 }
1524 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001525 }
1526
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001527 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001528 boolean oomAdjusted) {
1529 final int N = r.pendingStarts.size();
1530 if (N == 0) {
1531 return;
1532 }
1533
1534 while (r.pendingStarts.size() > 0) {
1535 try {
1536 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
1537 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
1538 + r + " " + r.intent + " args=" + si.intent);
1539 if (si.intent == null && N > 1) {
1540 // If somehow we got a dummy null intent in the middle,
1541 // then skip it. DO NOT skip a null intent when it is
1542 // the only one in the list -- this is to support the
1543 // onStartCommand(null) case.
1544 continue;
1545 }
1546 si.deliveredTime = SystemClock.uptimeMillis();
1547 r.deliveredStarts.add(si);
1548 si.deliveryCount++;
1549 if (si.neededGrants != null) {
1550 mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
1551 si.getUriPermissionsLocked());
1552 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001553 bumpServiceExecutingLocked(r, execInFg, "start");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001554 if (!oomAdjusted) {
1555 oomAdjusted = true;
1556 mAm.updateOomAdjLocked(r.app);
1557 }
1558 int flags = 0;
1559 if (si.deliveryCount > 1) {
1560 flags |= Service.START_FLAG_RETRY;
1561 }
1562 if (si.doneExecutingCount > 0) {
1563 flags |= Service.START_FLAG_REDELIVERY;
1564 }
1565 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
1566 } catch (RemoteException e) {
1567 // Remote process gone... we'll let the normal cleanup take
1568 // care of this.
1569 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
1570 break;
1571 } catch (Exception e) {
1572 Slog.w(TAG, "Unexpected exception", e);
1573 break;
1574 }
1575 }
1576 }
1577
Dianne Hackborn164371f2013-10-01 19:10:13 -07001578 private final boolean isServiceNeeded(ServiceRecord r, boolean knowConn, boolean hasConn) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001579 // Are we still explicitly being asked to run?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001580 if (r.startRequested) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001581 return true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001582 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001583
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001584 // Is someone still bound to us keepign us running?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001585 if (!knowConn) {
1586 hasConn = r.hasAutoCreateConnections();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001587 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001588 if (hasConn) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001589 return true;
1590 }
1591
1592 return false;
1593 }
1594
1595 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
1596 boolean hasConn) {
1597 //Slog.i(TAG, "Bring down service:");
1598 //r.dump(" ");
1599
1600 if (isServiceNeeded(r, knowConn, hasConn)) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001601 return;
1602 }
1603
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001604 // Are we in the process of launching?
1605 if (mPendingServices.contains(r)) {
1606 return;
1607 }
1608
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001609 bringDownServiceLocked(r);
1610 }
1611
1612 private final void bringDownServiceLocked(ServiceRecord r) {
1613 //Slog.i(TAG, "Bring down service:");
1614 //r.dump(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001615
Dianne Hackborn390517b2013-05-30 15:03:32 -07001616 // Report to all of the connections that the service is no longer
1617 // available.
1618 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1619 ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
1620 for (int i=0; i<c.size(); i++) {
1621 ConnectionRecord cr = c.get(i);
1622 // There is still a connection to the service that is
1623 // being brought down. Mark it as dead.
1624 cr.serviceDead = true;
1625 try {
1626 cr.conn.connected(r.name, null);
1627 } catch (Exception e) {
1628 Slog.w(TAG, "Failure disconnecting service " + r.name +
1629 " to connection " + c.get(i).conn.asBinder() +
1630 " (in " + c.get(i).binding.client.processName + ")", e);
1631 }
1632 }
1633 }
1634
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001635 // Tell the service that it has been unbound.
Dianne Hackborn390517b2013-05-30 15:03:32 -07001636 if (r.app != null && r.app.thread != null) {
1637 for (int i=r.bindings.size()-1; i>=0; i--) {
1638 IntentBindRecord ibr = r.bindings.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001639 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
1640 + ": hasBound=" + ibr.hasBound);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001641 if (ibr.hasBound) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001642 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001643 bumpServiceExecutingLocked(r, false, "bring down unbind");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001644 mAm.updateOomAdjLocked(r.app);
1645 ibr.hasBound = false;
1646 r.app.thread.scheduleUnbindService(r,
1647 ibr.intent.getIntent());
1648 } catch (Exception e) {
1649 Slog.w(TAG, "Exception when unbinding service "
1650 + r.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07001651 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001652 }
1653 }
1654 }
1655 }
1656
1657 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Craig Mautner66c4a822015-01-16 12:48:16 -08001658 r.destroyTime = SystemClock.uptimeMillis();
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07001659 if (LOG_SERVICE_START_STOP) {
1660 EventLogTags.writeAmDestroyService(
1661 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
1662 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001663
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001664 final ServiceMap smap = getServiceMap(r.userId);
1665 smap.mServicesByName.remove(r.name);
1666 smap.mServicesByIntent.remove(r.intent);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001667 r.totalRestartCount = 0;
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001668 unscheduleServiceRestartLocked(r, 0, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001669
1670 // Also make sure it is not on the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001671 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001672 if (mPendingServices.get(i) == r) {
1673 mPendingServices.remove(i);
1674 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001675 }
1676 }
1677
1678 r.cancelNotification();
1679 r.isForeground = false;
1680 r.foregroundId = 0;
1681 r.foregroundNoti = null;
1682
1683 // Clear start entries.
1684 r.clearDeliveredStartsLocked();
1685 r.pendingStarts.clear();
1686
1687 if (r.app != null) {
1688 synchronized (r.stats.getBatteryStats()) {
1689 r.stats.stopLaunchedLocked();
1690 }
1691 r.app.services.remove(r);
1692 if (r.app.thread != null) {
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001693 updateServiceForegroundLocked(r.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001694 try {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001695 bumpServiceExecutingLocked(r, false, "destroy");
1696 mDestroyingServices.add(r);
Dianne Hackborn455625e2015-01-21 09:55:13 -08001697 r.destroying = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001698 mAm.updateOomAdjLocked(r.app);
1699 r.app.thread.scheduleStopService(r);
1700 } catch (Exception e) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001701 Slog.w(TAG, "Exception when destroying service "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001702 + r.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07001703 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001704 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001705 } else {
1706 if (DEBUG_SERVICE) Slog.v(
1707 TAG, "Removed service that has no process: " + r);
1708 }
1709 } else {
1710 if (DEBUG_SERVICE) Slog.v(
1711 TAG, "Removed service that is not running: " + r);
1712 }
1713
1714 if (r.bindings.size() > 0) {
1715 r.bindings.clear();
1716 }
1717
1718 if (r.restarter instanceof ServiceRestarter) {
1719 ((ServiceRestarter)r.restarter).setService(null);
1720 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001721
Dianne Hackbornd2932242013-08-05 18:18:42 -07001722 int memFactor = mAm.mProcessStats.getMemFactorLocked();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001723 long now = SystemClock.uptimeMillis();
1724 if (r.tracker != null) {
1725 r.tracker.setStarted(false, memFactor, now);
1726 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001727 if (r.executeNesting == 0) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07001728 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001729 r.tracker = null;
1730 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001731 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001732
1733 smap.ensureNotStartingBackground(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001734 }
1735
1736 void removeConnectionLocked(
1737 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
1738 IBinder binder = c.conn.asBinder();
1739 AppBindRecord b = c.binding;
1740 ServiceRecord s = b.service;
1741 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
1742 if (clist != null) {
1743 clist.remove(c);
1744 if (clist.size() == 0) {
1745 s.connections.remove(binder);
1746 }
1747 }
1748 b.connections.remove(c);
1749 if (c.activity != null && c.activity != skipAct) {
1750 if (c.activity.connections != null) {
1751 c.activity.connections.remove(c);
1752 }
1753 }
1754 if (b.client != skipApp) {
1755 b.client.connections.remove(c);
1756 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
1757 b.client.updateHasAboveClientLocked();
1758 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001759 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001760 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07001761 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001762 }
1763 clist = mServiceConnections.get(binder);
1764 if (clist != null) {
1765 clist.remove(c);
1766 if (clist.size() == 0) {
1767 mServiceConnections.remove(binder);
1768 }
1769 }
1770
Dianne Hackbornab2df062015-01-07 13:43:13 -08001771 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid, s.name);
1772
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001773 if (b.connections.size() == 0) {
1774 b.intent.apps.remove(b.client);
1775 }
1776
1777 if (!c.serviceDead) {
1778 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
1779 + ": shouldUnbind=" + b.intent.hasBound);
1780 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
1781 && b.intent.hasBound) {
1782 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001783 bumpServiceExecutingLocked(s, false, "unbind");
Dianne Hackborndb926082013-10-31 16:32:44 -07001784 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
1785 && s.app.setProcState <= ActivityManager.PROCESS_STATE_RECEIVER) {
1786 // If this service's process is not already in the cached list,
1787 // then update it in the LRU list here because this may be causing
1788 // it to go down there and we want it to start out near the top.
1789 mAm.updateLruProcessLocked(s.app, false, null);
1790 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001791 mAm.updateOomAdjLocked(s.app);
1792 b.intent.hasBound = false;
1793 // Assume the client doesn't want to know about a rebind;
1794 // we will deal with that later if it asks for one.
1795 b.intent.doRebind = false;
1796 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
1797 } catch (Exception e) {
1798 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07001799 serviceProcessGoneLocked(s);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001800 }
1801 }
1802
1803 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001804 boolean hasAutoCreate = s.hasAutoCreateConnections();
1805 if (!hasAutoCreate) {
1806 if (s.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001807 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001808 SystemClock.uptimeMillis());
1809 }
1810 }
1811 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001812 }
1813 }
1814 }
1815
1816 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001817 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001818 if (r != null) {
Dianne Hackborn455625e2015-01-21 09:55:13 -08001819 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001820 // This is a call from a service start... take care of
1821 // book-keeping.
1822 r.callStart = true;
1823 switch (res) {
1824 case Service.START_STICKY_COMPATIBILITY:
1825 case Service.START_STICKY: {
1826 // We are done with the associated start arguments.
1827 r.findDeliveredStart(startId, true);
1828 // Don't stop if killed.
1829 r.stopIfKilled = false;
1830 break;
1831 }
1832 case Service.START_NOT_STICKY: {
1833 // We are done with the associated start arguments.
1834 r.findDeliveredStart(startId, true);
1835 if (r.getLastStartId() == startId) {
1836 // There is no more work, and this service
1837 // doesn't want to hang around if killed.
1838 r.stopIfKilled = true;
1839 }
1840 break;
1841 }
1842 case Service.START_REDELIVER_INTENT: {
1843 // We'll keep this item until they explicitly
1844 // call stop for it, but keep track of the fact
1845 // that it was delivered.
1846 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
1847 if (si != null) {
1848 si.deliveryCount = 0;
1849 si.doneExecutingCount++;
1850 // Don't stop if killed.
1851 r.stopIfKilled = true;
1852 }
1853 break;
1854 }
1855 case Service.START_TASK_REMOVED_COMPLETE: {
1856 // Special processing for onTaskRemoved(). Don't
1857 // impact normal onStartCommand() processing.
1858 r.findDeliveredStart(startId, true);
1859 break;
1860 }
1861 default:
1862 throw new IllegalArgumentException(
1863 "Unknown service start result: " + res);
1864 }
1865 if (res == Service.START_STICKY_COMPATIBILITY) {
1866 r.callStart = false;
1867 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08001868 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
1869 // This is the final call from destroying the service... we should
1870 // actually be getting rid of the service at this point. Do some
1871 // validation of its state, and ensure it will be fully removed.
1872 if (!inDestroying) {
1873 // Not sure what else to do with this... if it is not actually in the
1874 // destroying list, we don't need to make sure to remove it from it.
1875 Slog.wtfStack(TAG, "Service done with onDestroy, but not inDestroying: "
1876 + r);
1877 } else if (r.executeNesting != 1) {
1878 Slog.wtfStack(TAG, "Service done with onDestroy, but executeNesting="
1879 + r.executeNesting + ": " + r);
1880 r.executeNesting = 1;
1881 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001882 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001883 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn164371f2013-10-01 19:10:13 -07001884 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001885 Binder.restoreCallingIdentity(origId);
1886 } else {
1887 Slog.w(TAG, "Done executing unknown service from pid "
1888 + Binder.getCallingPid());
1889 }
1890 }
1891
Dianne Hackborn878deb32013-10-14 16:55:09 -07001892 private void serviceProcessGoneLocked(ServiceRecord r) {
1893 if (r.tracker != null) {
1894 int memFactor = mAm.mProcessStats.getMemFactorLocked();
1895 long now = SystemClock.uptimeMillis();
1896 r.tracker.setExecuting(false, memFactor, now);
1897 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbc72dce2013-11-11 10:43:38 -08001898 r.tracker.setStarted(false, memFactor, now);
Dianne Hackborn878deb32013-10-14 16:55:09 -07001899 }
1900 serviceDoneExecutingLocked(r, true, true);
1901 }
1902
Dianne Hackborn164371f2013-10-01 19:10:13 -07001903 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
1904 boolean finishing) {
Craig Mautner66c4a822015-01-16 12:48:16 -08001905 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001906 + ": nesting=" + r.executeNesting
Dianne Hackborn164371f2013-10-01 19:10:13 -07001907 + ", inDestroying=" + inDestroying + ", app=" + r.app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001908 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
1909 r.executeNesting--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001910 if (r.executeNesting <= 0) {
1911 if (r.app != null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001912 if (DEBUG_SERVICE) Slog.v(TAG,
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001913 "Nesting at 0 of " + r.shortName);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001914 r.app.execServicesFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001915 r.app.executingServices.remove(r);
1916 if (r.app.executingServices.size() == 0) {
1917 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
1918 "No more executingServices of " + r.shortName);
1919 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001920 } else if (r.executeFg) {
1921 // Need to re-evaluate whether the app still needs to be in the foreground.
1922 for (int i=r.app.executingServices.size()-1; i>=0; i--) {
1923 if (r.app.executingServices.valueAt(i).executeFg) {
1924 r.app.execServicesFg = true;
1925 break;
1926 }
1927 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001928 }
Dianne Hackborn164371f2013-10-01 19:10:13 -07001929 if (inDestroying) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001930 if (DEBUG_SERVICE) Slog.v(TAG,
Dianne Hackborn164371f2013-10-01 19:10:13 -07001931 "doneExecuting remove destroying " + r);
1932 mDestroyingServices.remove(r);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001933 r.bindings.clear();
1934 }
1935 mAm.updateOomAdjLocked(r.app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001936 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001937 r.executeFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001938 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001939 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001940 SystemClock.uptimeMillis());
Dianne Hackborn164371f2013-10-01 19:10:13 -07001941 if (finishing) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07001942 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001943 r.tracker = null;
1944 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001945 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001946 if (finishing) {
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08001947 if (r.app != null && !r.app.persistent) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08001948 r.app.services.remove(r);
1949 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001950 r.app = null;
1951 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001952 }
1953 }
1954
Dianne Hackbornff072722014-09-24 10:56:28 -07001955 boolean attachApplicationLocked(ProcessRecord proc, String processName)
1956 throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001957 boolean didSomething = false;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001958 // Collect any services that are waiting for this process to come up.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001959 if (mPendingServices.size() > 0) {
1960 ServiceRecord sr = null;
1961 try {
1962 for (int i=0; i<mPendingServices.size(); i++) {
1963 sr = mPendingServices.get(i);
1964 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
1965 || !processName.equals(sr.processName))) {
1966 continue;
1967 }
1968
1969 mPendingServices.remove(i);
1970 i--;
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001971 proc.addPackage(sr.appInfo.packageName, sr.appInfo.versionCode,
1972 mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001973 realStartServiceLocked(sr, proc, sr.createdFromFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001974 didSomething = true;
1975 }
Dianne Hackbornff072722014-09-24 10:56:28 -07001976 } catch (RemoteException e) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001977 Slog.w(TAG, "Exception in new application when starting service "
1978 + sr.shortName, e);
1979 throw e;
1980 }
1981 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001982 // Also, if there are any services that are waiting to restart and
1983 // would run in this process, now is a good time to start them. It would
1984 // be weird to bring up the process but arbitrarily not let the services
1985 // run at this point just because their restart time hasn't come up.
1986 if (mRestartingServices.size() > 0) {
1987 ServiceRecord sr = null;
1988 for (int i=0; i<mRestartingServices.size(); i++) {
1989 sr = mRestartingServices.get(i);
1990 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
1991 || !processName.equals(sr.processName))) {
1992 continue;
1993 }
1994 mAm.mHandler.removeCallbacks(sr.restarter);
1995 mAm.mHandler.post(sr.restarter);
1996 }
1997 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001998 return didSomething;
1999 }
2000
2001 void processStartTimedOutLocked(ProcessRecord proc) {
2002 for (int i=0; i<mPendingServices.size(); i++) {
2003 ServiceRecord sr = mPendingServices.get(i);
2004 if ((proc.uid == sr.appInfo.uid
2005 && proc.processName.equals(sr.processName))
2006 || sr.isolatedProc == proc) {
2007 Slog.w(TAG, "Forcing bringing down service: " + sr);
2008 sr.isolatedProc = null;
2009 mPendingServices.remove(i);
2010 i--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002011 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002012 }
2013 }
2014 }
2015
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002016 private boolean collectForceStopServicesLocked(String name, int userId,
2017 boolean evenPersistent, boolean doit,
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002018 ArrayMap<ComponentName, ServiceRecord> services,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002019 ArrayList<ServiceRecord> result) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002020 boolean didSomething = false;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002021 for (int i=0; i<services.size(); i++) {
2022 ServiceRecord service = services.valueAt(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002023 if ((name == null || service.packageName.equals(name))
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002024 && (service.app == null || evenPersistent || !service.app.persistent)) {
2025 if (!doit) {
2026 return true;
2027 }
2028 didSomething = true;
2029 Slog.i(TAG, " Force stopping service " + service);
2030 if (service.app != null) {
2031 service.app.removed = true;
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08002032 if (!service.app.persistent) {
2033 service.app.services.remove(service);
2034 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002035 }
2036 service.app = null;
2037 service.isolatedProc = null;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002038 result.add(service);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002039 }
2040 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002041 return didSomething;
2042 }
2043
2044 boolean forceStopLocked(String name, int userId, boolean evenPersistent, boolean doit) {
2045 boolean didSomething = false;
2046 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
2047 if (userId == UserHandle.USER_ALL) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002048 for (int i=0; i<mServiceMap.size(); i++) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002049 didSomething |= collectForceStopServicesLocked(name, userId, evenPersistent,
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002050 doit, mServiceMap.valueAt(i).mServicesByName, services);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002051 if (!doit && didSomething) {
2052 return true;
2053 }
2054 }
2055 } else {
Amith Yamasani540b6592013-10-01 13:02:52 -07002056 ServiceMap smap = mServiceMap.get(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002057 if (smap != null) {
2058 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByName;
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002059 didSomething = collectForceStopServicesLocked(name, userId, evenPersistent,
2060 doit, items, services);
2061 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002062 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002063
2064 int N = services.size();
2065 for (int i=0; i<N; i++) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002066 bringDownServiceLocked(services.get(i));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002067 }
2068 return didSomething;
2069 }
2070
2071 void cleanUpRemovedTaskLocked(TaskRecord tr, ComponentName component, Intent baseIntent) {
2072 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002073 ArrayMap<ComponentName, ServiceRecord> alls = getServices(tr.userId);
2074 for (int i=0; i<alls.size(); i++) {
2075 ServiceRecord sr = alls.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002076 if (sr.packageName.equals(component.getPackageName())) {
2077 services.add(sr);
2078 }
2079 }
2080
2081 // Take care of any running services associated with the app.
2082 for (int i=0; i<services.size(); i++) {
2083 ServiceRecord sr = services.get(i);
2084 if (sr.startRequested) {
2085 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
2086 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
2087 stopServiceLocked(sr);
2088 } else {
2089 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
2090 sr.makeNextStartId(), baseIntent, null));
2091 if (sr.app != null && sr.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002092 // We always run in the foreground, since this is called as
2093 // part of the "remove task" UI operation.
2094 sendServiceArgsLocked(sr, true, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002095 }
2096 }
2097 }
2098 }
2099 }
2100
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002101 final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002102 // Report disconnected services.
2103 if (false) {
2104 // XXX we are letting the client link to the service for
2105 // death notifications.
2106 if (app.services.size() > 0) {
2107 Iterator<ServiceRecord> it = app.services.iterator();
2108 while (it.hasNext()) {
2109 ServiceRecord r = it.next();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002110 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2111 ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
2112 for (int i=0; i<cl.size(); i++) {
2113 ConnectionRecord c = cl.get(i);
2114 if (c.binding.client != app) {
2115 try {
2116 //c.conn.connected(r.className, null);
2117 } catch (Exception e) {
2118 // todo: this should be asynchronous!
2119 Slog.w(TAG, "Exception thrown disconnected servce "
2120 + r.shortName
2121 + " from app " + app.processName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002122 }
2123 }
2124 }
2125 }
2126 }
2127 }
2128 }
2129
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002130 // First clear app state from services.
Dianne Hackbornc8230512013-07-13 21:32:12 -07002131 for (int i=app.services.size()-1; i>=0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07002132 ServiceRecord sr = app.services.valueAt(i);
2133 synchronized (sr.stats.getBatteryStats()) {
2134 sr.stats.stopLaunchedLocked();
2135 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08002136 if (sr.app != app && sr.app != null && !sr.app.persistent) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002137 sr.app.services.remove(sr);
2138 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07002139 sr.app = null;
2140 sr.isolatedProc = null;
2141 sr.executeNesting = 0;
Dianne Hackborn164371f2013-10-01 19:10:13 -07002142 sr.forceClearTracker();
2143 if (mDestroyingServices.remove(sr)) {
2144 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove destroying " + sr);
Dianne Hackbornc8230512013-07-13 21:32:12 -07002145 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002146
Dianne Hackbornc8230512013-07-13 21:32:12 -07002147 final int numClients = sr.bindings.size();
2148 for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
2149 IntentBindRecord b = sr.bindings.valueAt(bindingi);
2150 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
2151 + ": shouldUnbind=" + b.hasBound);
2152 b.binder = null;
2153 b.requested = b.received = b.hasBound = false;
Dianne Hackborn465fa392014-09-14 14:21:18 -07002154 // If this binding is coming from a cached process and is asking to keep
2155 // the service created, then we'll kill the cached process as well -- we
2156 // don't want to be thrashing around restarting processes that are only
2157 // there to be cached.
2158 for (int appi=b.apps.size()-1; appi>=0; appi--) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07002159 final ProcessRecord proc = b.apps.keyAt(appi);
2160 // If the process is already gone, skip it.
2161 if (proc.killedByAm || proc.thread == null) {
2162 continue;
2163 }
2164 // Only do this for processes that have an auto-create binding;
2165 // otherwise the binding can be left, because it won't cause the
2166 // service to restart.
2167 final AppBindRecord abind = b.apps.valueAt(appi);
2168 boolean hasCreate = false;
2169 for (int conni=abind.connections.size()-1; conni>=0; conni--) {
2170 ConnectionRecord conn = abind.connections.valueAt(conni);
Dianne Hackborn0fe3c252014-09-19 15:09:39 -07002171 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
2172 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07002173 hasCreate = true;
2174 break;
2175 }
2176 }
2177 if (!hasCreate) {
2178 continue;
2179 }
Dianne Hackborncd97c962014-09-25 18:34:02 -07002180 // XXX turned off for now until we have more time to get a better policy.
2181 if (false && proc != null && !proc.persistent && proc.thread != null
Dianne Hackborn465fa392014-09-14 14:21:18 -07002182 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
2183 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
2184 proc.kill("bound to service " + sr.name.flattenToShortString()
2185 + " in dying proc " + (app != null ? app.processName : "??"), true);
2186 }
2187 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07002188 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002189 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002190
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002191 // Clean up any connections this application has to other services.
2192 for (int i=app.connections.size()-1; i>=0; i--) {
2193 ConnectionRecord r = app.connections.valueAt(i);
2194 removeConnectionLocked(r, app, null);
2195 }
Dianne Hackborn465fa392014-09-14 14:21:18 -07002196 updateServiceConnectionActivitiesLocked(app);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002197 app.connections.clear();
2198
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002199 ServiceMap smap = getServiceMap(app.userId);
2200
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002201 // Now do remaining service cleanup.
2202 for (int i=app.services.size()-1; i>=0; i--) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002203 ServiceRecord sr = app.services.valueAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08002204
2205 // Unless the process is persistent, this process record is going away,
2206 // so make sure the service is cleaned out of it.
2207 if (!app.persistent) {
Dianne Hackborn4190fc52013-12-09 18:20:16 -08002208 app.services.removeAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08002209 }
2210
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002211 // Sanity check: if the service listed for the app is not one
Dianne Hackborn4190fc52013-12-09 18:20:16 -08002212 // we actually are maintaining, just let it drop.
Dianne Hackborn40c87252014-03-19 16:55:40 -07002213 final ServiceRecord curRec = smap.mServicesByName.get(sr.name);
2214 if (curRec != sr) {
2215 if (curRec != null) {
2216 Slog.wtf(TAG, "Service " + sr + " in process " + app
2217 + " not same as in map: " + curRec);
2218 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002219 continue;
2220 }
2221
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002222 // Any services running in the application may need to be placed
2223 // back in the pending list.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002224 if (allowRestart && sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
Dianne Hackbornc8230512013-07-13 21:32:12 -07002225 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
2226 Slog.w(TAG, "Service crashed " + sr.crashCount
2227 + " times, stopping: " + sr);
2228 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
2229 sr.userId, sr.crashCount, sr.shortName, app.pid);
2230 bringDownServiceLocked(sr);
younghwan1.kimcd005eb2015-04-02 19:15:11 +09002231 } else if (!allowRestart || !mAm.isUserRunningLocked(sr.userId, false)) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07002232 bringDownServiceLocked(sr);
2233 } else {
2234 boolean canceled = scheduleServiceRestartLocked(sr, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002235
Dianne Hackbornc8230512013-07-13 21:32:12 -07002236 // Should the service remain running? Note that in the
2237 // extreme case of so many attempts to deliver a command
2238 // that it failed we also will stop it here.
2239 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
2240 if (sr.pendingStarts.size() == 0) {
2241 sr.startRequested = false;
2242 if (sr.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002243 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackbornc8230512013-07-13 21:32:12 -07002244 SystemClock.uptimeMillis());
2245 }
2246 if (!sr.hasAutoCreateConnections()) {
2247 // Whoops, no reason to restart!
2248 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002249 }
2250 }
2251 }
2252 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07002253 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002254
Dianne Hackbornc8230512013-07-13 21:32:12 -07002255 if (!allowRestart) {
2256 app.services.clear();
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002257
2258 // Make sure there are no more restarting services for this process.
2259 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2260 ServiceRecord r = mRestartingServices.get(i);
2261 if (r.processName.equals(app.processName) &&
2262 r.serviceInfo.applicationInfo.uid == app.info.uid) {
2263 mRestartingServices.remove(i);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002264 clearRestartingIfNeededLocked(r);
2265 }
2266 }
2267 for (int i=mPendingServices.size()-1; i>=0; i--) {
2268 ServiceRecord r = mPendingServices.get(i);
2269 if (r.processName.equals(app.processName) &&
2270 r.serviceInfo.applicationInfo.uid == app.info.uid) {
2271 mPendingServices.remove(i);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002272 }
2273 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002274 }
2275
2276 // Make sure we have no more records on the stopping list.
Dianne Hackborn164371f2013-10-01 19:10:13 -07002277 int i = mDestroyingServices.size();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002278 while (i > 0) {
2279 i--;
Dianne Hackborn164371f2013-10-01 19:10:13 -07002280 ServiceRecord sr = mDestroyingServices.get(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002281 if (sr.app == app) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002282 sr.forceClearTracker();
2283 mDestroyingServices.remove(i);
2284 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove destroying " + sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002285 }
2286 }
2287
2288 app.executingServices.clear();
2289 }
2290
2291 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
2292 ActivityManager.RunningServiceInfo info =
2293 new ActivityManager.RunningServiceInfo();
2294 info.service = r.name;
2295 if (r.app != null) {
2296 info.pid = r.app.pid;
2297 }
2298 info.uid = r.appInfo.uid;
2299 info.process = r.processName;
2300 info.foreground = r.isForeground;
2301 info.activeSince = r.createTime;
2302 info.started = r.startRequested;
2303 info.clientCount = r.connections.size();
2304 info.crashCount = r.crashCount;
2305 info.lastActivityTime = r.lastActivity;
2306 if (r.isForeground) {
2307 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
2308 }
2309 if (r.startRequested) {
2310 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
2311 }
2312 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
2313 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
2314 }
2315 if (r.app != null && r.app.persistent) {
2316 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
2317 }
2318
Dianne Hackborn390517b2013-05-30 15:03:32 -07002319 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2320 ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002321 for (int i=0; i<connl.size(); i++) {
2322 ConnectionRecord conn = connl.get(i);
2323 if (conn.clientLabel != 0) {
2324 info.clientPackage = conn.binding.client.info.packageName;
2325 info.clientLabel = conn.clientLabel;
2326 return info;
2327 }
2328 }
2329 }
2330 return info;
2331 }
2332
2333 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum,
2334 int flags) {
2335 ArrayList<ActivityManager.RunningServiceInfo> res
2336 = new ArrayList<ActivityManager.RunningServiceInfo>();
2337
Dianne Hackborn0c380492012-08-20 17:23:30 -07002338 final int uid = Binder.getCallingUid();
2339 final long ident = Binder.clearCallingIdentity();
2340 try {
2341 if (ActivityManager.checkUidPermission(
2342 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
2343 uid) == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07002344 int[] users = mAm.getUsersLocked();
2345 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002346 ArrayMap<ComponentName, ServiceRecord> alls = getServices(users[ui]);
2347 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
2348 ServiceRecord sr = alls.valueAt(i);
2349 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07002350 }
2351 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002352
Dianne Hackborn0c380492012-08-20 17:23:30 -07002353 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
2354 ServiceRecord r = mRestartingServices.get(i);
2355 ActivityManager.RunningServiceInfo info =
2356 makeRunningServiceInfoLocked(r);
2357 info.restarting = r.nextRestartTime;
2358 res.add(info);
2359 }
2360 } else {
2361 int userId = UserHandle.getUserId(uid);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002362 ArrayMap<ComponentName, ServiceRecord> alls = getServices(userId);
2363 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
2364 ServiceRecord sr = alls.valueAt(i);
2365 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07002366 }
2367
2368 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
2369 ServiceRecord r = mRestartingServices.get(i);
2370 if (r.userId == userId) {
2371 ActivityManager.RunningServiceInfo info =
2372 makeRunningServiceInfoLocked(r);
2373 info.restarting = r.nextRestartTime;
2374 res.add(info);
2375 }
2376 }
2377 }
2378 } finally {
2379 Binder.restoreCallingIdentity(ident);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002380 }
2381
2382 return res;
2383 }
2384
2385 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002386 int userId = UserHandle.getUserId(Binder.getCallingUid());
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002387 ServiceRecord r = getServiceByName(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002388 if (r != null) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002389 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2390 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002391 for (int i=0; i<conn.size(); i++) {
2392 if (conn.get(i).clientIntent != null) {
2393 return conn.get(i).clientIntent;
2394 }
2395 }
2396 }
2397 }
2398 return null;
2399 }
2400
2401 void serviceTimeout(ProcessRecord proc) {
2402 String anrMessage = null;
2403
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07002404 synchronized(mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002405 if (proc.executingServices.size() == 0 || proc.thread == null) {
2406 return;
2407 }
Dianne Hackbornab2df062015-01-07 13:43:13 -08002408 final long now = SystemClock.uptimeMillis();
2409 final long maxTime = now -
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002410 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002411 ServiceRecord timeout = null;
2412 long nextTime = 0;
Dianne Hackbornc8230512013-07-13 21:32:12 -07002413 for (int i=proc.executingServices.size()-1; i>=0; i--) {
2414 ServiceRecord sr = proc.executingServices.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002415 if (sr.executingStart < maxTime) {
2416 timeout = sr;
2417 break;
2418 }
2419 if (sr.executingStart > nextTime) {
2420 nextTime = sr.executingStart;
2421 }
2422 }
2423 if (timeout != null && mAm.mLruProcesses.contains(proc)) {
2424 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08002425 StringWriter sw = new StringWriter();
2426 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
2427 pw.println(timeout);
2428 timeout.dump(pw, " ");
2429 pw.close();
2430 mLastAnrDump = sw.toString();
2431 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
2432 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
2433 anrMessage = "executing service " + timeout.shortName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002434 } else {
2435 Message msg = mAm.mHandler.obtainMessage(
2436 ActivityManagerService.SERVICE_TIMEOUT_MSG);
2437 msg.obj = proc;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002438 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
Dianne Hackborn2be00932013-09-22 16:46:00 -07002439 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002440 }
2441 }
2442
2443 if (anrMessage != null) {
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07002444 mAm.appNotResponding(proc, null, null, false, anrMessage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002445 }
2446 }
2447
Dianne Hackborn2be00932013-09-22 16:46:00 -07002448 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
2449 if (proc.executingServices.size() == 0 || proc.thread == null) {
2450 return;
2451 }
2452 long now = SystemClock.uptimeMillis();
2453 Message msg = mAm.mHandler.obtainMessage(
2454 ActivityManagerService.SERVICE_TIMEOUT_MSG);
2455 msg.obj = proc;
2456 mAm.mHandler.sendMessageAtTime(msg,
2457 proc.execServicesFg ? (now+SERVICE_TIMEOUT) : (now+ SERVICE_BACKGROUND_TIMEOUT));
2458 }
2459
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002460 /**
2461 * Prints a list of ServiceRecords (dumpsys activity services)
2462 */
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002463 void dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002464 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
2465 boolean needSep = false;
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002466 boolean printedAnything = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002467
2468 ItemMatcher matcher = new ItemMatcher();
2469 matcher.build(args, opti);
2470
2471 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
2472 try {
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08002473 if (mLastAnrDump != null) {
2474 pw.println(" Last ANR service:");
2475 pw.print(mLastAnrDump);
2476 pw.println();
2477 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07002478 int[] users = mAm.getUsersLocked();
2479 for (int user : users) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002480 ServiceMap smap = getServiceMap(user);
2481 boolean printed = false;
2482 if (smap.mServicesByName.size() > 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002483 long nowReal = SystemClock.elapsedRealtime();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002484 needSep = false;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002485 for (int si=0; si<smap.mServicesByName.size(); si++) {
2486 ServiceRecord r = smap.mServicesByName.valueAt(si);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002487 if (!matcher.match(r, r.name)) {
2488 continue;
2489 }
2490 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2491 continue;
2492 }
2493 if (!printed) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002494 if (printedAnything) {
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002495 pw.println();
2496 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07002497 pw.println(" User " + user + " active services:");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002498 printed = true;
2499 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002500 printedAnything = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002501 if (needSep) {
2502 pw.println();
2503 }
2504 pw.print(" * ");
2505 pw.println(r);
2506 if (dumpAll) {
2507 r.dump(pw, " ");
2508 needSep = true;
2509 } else {
2510 pw.print(" app=");
2511 pw.println(r.app);
2512 pw.print(" created=");
2513 TimeUtils.formatDuration(r.createTime, nowReal, pw);
2514 pw.print(" started=");
2515 pw.print(r.startRequested);
2516 pw.print(" connections=");
2517 pw.println(r.connections.size());
2518 if (r.connections.size() > 0) {
2519 pw.println(" Connections:");
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002520 for (int conni=0; conni<r.connections.size(); conni++) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002521 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002522 for (int i = 0; i < clist.size(); i++) {
2523 ConnectionRecord conn = clist.get(i);
2524 pw.print(" ");
2525 pw.print(conn.binding.intent.intent.getIntent()
2526 .toShortString(false, false, false, false));
2527 pw.print(" -> ");
2528 ProcessRecord proc = conn.binding.client;
2529 pw.println(proc != null ? proc.toShortString() : "null");
2530 }
2531 }
2532 }
2533 }
2534 if (dumpClient && r.app != null && r.app.thread != null) {
2535 pw.println(" Client:");
2536 pw.flush();
2537 try {
2538 TransferPipe tp = new TransferPipe();
2539 try {
2540 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
2541 r, args);
2542 tp.setBufferPrefix(" ");
2543 // Short timeout, since blocking here can
2544 // deadlock with the application.
2545 tp.go(fd, 2000);
2546 } finally {
2547 tp.kill();
2548 }
2549 } catch (IOException e) {
2550 pw.println(" Failure while dumping the service: " + e);
2551 } catch (RemoteException e) {
2552 pw.println(" Got a RemoteException while dumping the service");
2553 }
2554 needSep = true;
2555 }
2556 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002557 needSep |= printed;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002558 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002559 printed = false;
2560 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
2561 ServiceRecord r = smap.mDelayedStartList.get(si);
2562 if (!matcher.match(r, r.name)) {
2563 continue;
2564 }
2565 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2566 continue;
2567 }
2568 if (!printed) {
2569 if (printedAnything) {
2570 pw.println();
2571 }
2572 pw.println(" User " + user + " delayed start services:");
2573 printed = true;
2574 }
2575 printedAnything = true;
2576 pw.print(" * Delayed start "); pw.println(r);
2577 }
2578 printed = false;
2579 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
2580 ServiceRecord r = smap.mStartingBackground.get(si);
2581 if (!matcher.match(r, r.name)) {
2582 continue;
2583 }
2584 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2585 continue;
2586 }
2587 if (!printed) {
2588 if (printedAnything) {
2589 pw.println();
2590 }
2591 pw.println(" User " + user + " starting in background:");
2592 printed = true;
2593 }
2594 printedAnything = true;
2595 pw.print(" * Starting bg "); pw.println(r);
2596 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002597 }
Amith Yamasani258848d2012-08-10 17:06:33 -07002598 } catch (Exception e) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002599 Slog.w(TAG, "Exception in dumpServicesLocked", e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002600 }
2601
2602 if (mPendingServices.size() > 0) {
2603 boolean printed = false;
2604 for (int i=0; i<mPendingServices.size(); i++) {
2605 ServiceRecord r = mPendingServices.get(i);
2606 if (!matcher.match(r, r.name)) {
2607 continue;
2608 }
2609 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2610 continue;
2611 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002612 printedAnything = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002613 if (!printed) {
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002614 if (needSep) pw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002615 needSep = true;
2616 pw.println(" Pending services:");
2617 printed = true;
2618 }
2619 pw.print(" * Pending "); pw.println(r);
2620 r.dump(pw, " ");
2621 }
2622 needSep = true;
2623 }
2624
2625 if (mRestartingServices.size() > 0) {
2626 boolean printed = false;
2627 for (int i=0; i<mRestartingServices.size(); i++) {
2628 ServiceRecord r = mRestartingServices.get(i);
2629 if (!matcher.match(r, r.name)) {
2630 continue;
2631 }
2632 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2633 continue;
2634 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002635 printedAnything = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002636 if (!printed) {
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002637 if (needSep) pw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002638 needSep = true;
2639 pw.println(" Restarting services:");
2640 printed = true;
2641 }
2642 pw.print(" * Restarting "); pw.println(r);
2643 r.dump(pw, " ");
2644 }
2645 needSep = true;
2646 }
2647
Dianne Hackborn164371f2013-10-01 19:10:13 -07002648 if (mDestroyingServices.size() > 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002649 boolean printed = false;
Dianne Hackborn164371f2013-10-01 19:10:13 -07002650 for (int i=0; i< mDestroyingServices.size(); i++) {
2651 ServiceRecord r = mDestroyingServices.get(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002652 if (!matcher.match(r, r.name)) {
2653 continue;
2654 }
2655 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2656 continue;
2657 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002658 printedAnything = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002659 if (!printed) {
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002660 if (needSep) pw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002661 needSep = true;
Dianne Hackborn164371f2013-10-01 19:10:13 -07002662 pw.println(" Destroying services:");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002663 printed = true;
2664 }
Dianne Hackborn164371f2013-10-01 19:10:13 -07002665 pw.print(" * Destroy "); pw.println(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002666 r.dump(pw, " ");
2667 }
2668 needSep = true;
2669 }
2670
2671 if (dumpAll) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002672 boolean printed = false;
2673 for (int ic=0; ic<mServiceConnections.size(); ic++) {
2674 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
2675 for (int i=0; i<r.size(); i++) {
2676 ConnectionRecord cr = r.get(i);
2677 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
2678 continue;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002679 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002680 if (dumpPackage != null && (cr.binding.client == null
2681 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
2682 continue;
2683 }
2684 printedAnything = true;
2685 if (!printed) {
2686 if (needSep) pw.println();
2687 needSep = true;
2688 pw.println(" Connection bindings to services:");
2689 printed = true;
2690 }
2691 pw.print(" * "); pw.println(cr);
2692 cr.dump(pw, " ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002693 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002694 }
2695 }
2696
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002697 if (!printedAnything) {
2698 pw.println(" (nothing)");
2699 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002700 }
2701
2702 /**
2703 * There are three ways to call this:
2704 * - no service specified: dump all the services
2705 * - a flattened component name that matched an existing service was specified as the
2706 * first arg: dump that one service
2707 * - the first arg isn't the flattened component name of an existing service:
2708 * dump all services whose component contains the first arg as a substring
2709 */
2710 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
2711 int opti, boolean dumpAll) {
2712 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
2713
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07002714 synchronized (mAm) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07002715 int[] users = mAm.getUsersLocked();
2716 if ("all".equals(name)) {
2717 for (int user : users) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -07002718 ServiceMap smap = mServiceMap.get(user);
2719 if (smap == null) {
2720 continue;
2721 }
2722 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002723 for (int i=0; i<alls.size(); i++) {
2724 ServiceRecord r1 = alls.valueAt(i);
Amith Yamasani258848d2012-08-10 17:06:33 -07002725 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002726 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002727 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07002728 } else {
2729 ComponentName componentName = name != null
2730 ? ComponentName.unflattenFromString(name) : null;
2731 int objectId = 0;
2732 if (componentName == null) {
2733 // Not a '/' separated full component name; maybe an object ID?
2734 try {
2735 objectId = Integer.parseInt(name, 16);
2736 name = null;
2737 componentName = null;
2738 } catch (RuntimeException e) {
2739 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002740 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002741
Dianne Hackborn1676c852012-09-10 14:52:30 -07002742 for (int user : users) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -07002743 ServiceMap smap = mServiceMap.get(user);
2744 if (smap == null) {
2745 continue;
2746 }
2747 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002748 for (int i=0; i<alls.size(); i++) {
2749 ServiceRecord r1 = alls.valueAt(i);
Amith Yamasani258848d2012-08-10 17:06:33 -07002750 if (componentName != null) {
2751 if (r1.name.equals(componentName)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002752 services.add(r1);
2753 }
Amith Yamasani258848d2012-08-10 17:06:33 -07002754 } else if (name != null) {
2755 if (r1.name.flattenToString().contains(name)) {
2756 services.add(r1);
2757 }
2758 } else if (System.identityHashCode(r1) == objectId) {
2759 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002760 }
2761 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002762 }
2763 }
2764 }
2765
2766 if (services.size() <= 0) {
2767 return false;
2768 }
2769
2770 boolean needSep = false;
2771 for (int i=0; i<services.size(); i++) {
2772 if (needSep) {
2773 pw.println();
2774 }
2775 needSep = true;
2776 dumpService("", fd, pw, services.get(i), args, dumpAll);
2777 }
2778 return true;
2779 }
2780
2781 /**
2782 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
2783 * there is a thread associated with the service.
2784 */
2785 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
2786 final ServiceRecord r, String[] args, boolean dumpAll) {
2787 String innerPrefix = prefix + " ";
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07002788 synchronized (mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002789 pw.print(prefix); pw.print("SERVICE ");
2790 pw.print(r.shortName); pw.print(" ");
2791 pw.print(Integer.toHexString(System.identityHashCode(r)));
2792 pw.print(" pid=");
2793 if (r.app != null) pw.println(r.app.pid);
2794 else pw.println("(not running)");
2795 if (dumpAll) {
2796 r.dump(pw, innerPrefix);
2797 }
2798 }
2799 if (r.app != null && r.app.thread != null) {
2800 pw.print(prefix); pw.println(" Client:");
2801 pw.flush();
2802 try {
2803 TransferPipe tp = new TransferPipe();
2804 try {
2805 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
2806 tp.setBufferPrefix(prefix + " ");
2807 tp.go(fd);
2808 } finally {
2809 tp.kill();
2810 }
2811 } catch (IOException e) {
2812 pw.println(prefix + " Failure while dumping the service: " + e);
2813 } catch (RemoteException e) {
2814 pw.println(prefix + " Got a RemoteException while dumping the service");
2815 }
2816 }
2817 }
2818
2819}