blob: 6a8c8b053ea741e8b68309f385f5b4af900cdc1a [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
Wale Ogunwaled57969f2014-11-15 19:37:29 -080019import static com.android.server.am.ActivityManagerDebugConfig.*;
20
Dianne Hackborn599db5c2012-08-03 19:28:48 -070021import java.io.FileDescriptor;
22import java.io.IOException;
23import java.io.PrintWriter;
Dianne Hackborncff1bbf2015-01-20 13:43:32 -080024import java.io.StringWriter;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070025import java.util.ArrayList;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070026import java.util.HashSet;
27import java.util.Iterator;
28import java.util.List;
Wale Ogunwale540e1232015-05-01 15:35:39 -070029import java.util.Set;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070030
Dianne Hackborn455625e2015-01-21 09:55:13 -080031import android.app.ActivityThread;
Svet Ganov99b60432015-06-27 13:15:22 -070032import android.app.AppOpsManager;
Svet Ganov9c165d72015-12-01 19:52:26 -080033import android.content.IIntentSender;
34import android.content.IntentSender;
Christoph Studer365e4c32014-09-18 20:35:36 +020035import android.os.Build;
Svet Ganov9c165d72015-12-01 19:52:26 -080036import android.os.Bundle;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -070037import android.os.DeadObjectException;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070038import android.os.Handler;
Dianne Hackborn13c590d2013-10-07 14:32:00 -070039import android.os.Looper;
Svet Ganov9c165d72015-12-01 19:52:26 -080040import android.os.RemoteCallback;
Dianne Hackborn23037412013-11-04 18:11:29 -080041import android.os.SystemProperties;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -070042import android.os.TransactionTooLargeException;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070043import android.util.ArrayMap;
Dianne Hackborn465fa392014-09-14 14:21:18 -070044import android.util.ArraySet;
Wale Ogunwaled57969f2014-11-15 19:37:29 -080045
Joe Onorato4eb64fd2016-03-21 15:30:09 -070046import com.android.internal.app.procstats.ProcessStats;
47import com.android.internal.app.procstats.ServiceState;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070048import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborncbfd23e2013-06-11 14:26:53 -070049import com.android.internal.os.TransferPipe;
Dianne Hackborncff1bbf2015-01-20 13:43:32 -080050import com.android.internal.util.FastPrintWriter;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070051import com.android.server.am.ActivityManagerService.ItemMatcher;
52import com.android.server.am.ActivityManagerService.NeededUriGrants;
53
54import android.app.ActivityManager;
55import android.app.AppGlobals;
56import android.app.IApplicationThread;
57import android.app.IServiceConnection;
58import android.app.Notification;
59import android.app.PendingIntent;
60import android.app.Service;
61import android.content.ComponentName;
62import android.content.Context;
63import android.content.Intent;
64import android.content.pm.ApplicationInfo;
65import android.content.pm.PackageManager;
66import android.content.pm.ResolveInfo;
67import android.content.pm.ServiceInfo;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070068import android.os.Binder;
69import android.os.IBinder;
70import android.os.Message;
71import android.os.Process;
72import android.os.RemoteException;
73import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070074import android.os.UserHandle;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070075import android.util.EventLog;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070076import android.util.Slog;
77import android.util.SparseArray;
78import android.util.TimeUtils;
79
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -070080public final class ActiveServices {
Wale Ogunwaled57969f2014-11-15 19:37:29 -080081 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM;
82 private static final String TAG_MU = TAG + POSTFIX_MU;
83 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
84 private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING;
85
86 private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE;
87 private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE;
88
89 private static final boolean LOG_SERVICE_START_STOP = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070090
91 // How long we wait for a service to finish executing.
92 static final int SERVICE_TIMEOUT = 20*1000;
93
Dianne Hackbornbf36ee22013-07-26 18:24:10 -070094 // How long we wait for a service to finish executing.
95 static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
96
Dianne Hackborn599db5c2012-08-03 19:28:48 -070097 // How long a service needs to be running until restarting its process
98 // is no longer considered to be a relaunch of the service.
Dianne Hackborn7b492722013-11-01 09:58:45 -070099 static final int SERVICE_RESTART_DURATION = 1*1000;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700100
101 // How long a service needs to be running until it will start back at
102 // SERVICE_RESTART_DURATION after being killed.
103 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
104
105 // Multiplying factor to increase restart duration time by, for each time
106 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
107 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
108
109 // The minimum amount of time between restarting services that we allow.
110 // That is, when multiple services are restarting, we won't allow each
111 // to restart less than this amount of time from the last one.
112 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
113
114 // Maximum amount of time for there to be no activity on a service before
115 // we consider it non-essential and allow its process to go on the
116 // LRU background list.
117 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
118
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700119 // How long we wait for a background started service to stop itself before
120 // allowing the next pending start to run.
121 static final int BG_START_TIMEOUT = 15*1000;
122
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700123 final ActivityManagerService mAm;
124
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700125 // Maximum number of services that we allow to start in the background
126 // at the same time.
127 final int mMaxStartingBackground;
128
Wale Ogunwale540e1232015-05-01 15:35:39 -0700129 final SparseArray<ServiceMap> mServiceMap = new SparseArray<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700130
131 /**
132 * All currently bound service connections. Keys are the IBinder of
133 * the client's IServiceConnection.
134 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700135 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700136
137 /**
138 * List of services that we have been asked to start,
139 * but haven't yet been able to. It is used to hold start requests
140 * while waiting for their corresponding application thread to get
141 * going.
142 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700143 final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700144
145 /**
146 * List of services that are scheduled to restart following a crash.
147 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700148 final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700149
150 /**
Dianne Hackborn164371f2013-10-01 19:10:13 -0700151 * List of services that are in the process of being destroyed.
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700152 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700153 final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>();
154
155 /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */
156 private ArrayList<ServiceRecord> mTmpCollectionResults = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700157
Dianne Hackborncff1bbf2015-01-20 13:43:32 -0800158 /** Amount of time to allow a last ANR message to exist before freeing the memory. */
159 static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
160
161 String mLastAnrDump;
162
163 final Runnable mLastAnrDumpClearer = new Runnable() {
164 @Override public void run() {
165 synchronized (mAm) {
166 mLastAnrDump = null;
167 }
168 }
169 };
170
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700171 /**
172 * Information about services for a single user.
173 */
174 class ServiceMap extends Handler {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700175 final int mUserId;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700176 final ArrayMap<ComponentName, ServiceRecord> mServicesByName = new ArrayMap<>();
177 final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700178
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700179 final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700180 /* XXX eventually I'd like to have this based on processes instead of services.
181 * That is, if we try to start two services in a row both running in the same
182 * process, this should be one entry in mStartingBackground for that one process
183 * that remains until all services in it are done.
184 final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
185 = new ArrayMap<ProcessRecord, DelayingProcess>();
186 final ArrayList<DelayingProcess> mStartingProcessList
187 = new ArrayList<DelayingProcess>();
188 */
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700189
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700190 final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700191
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700192 static final int MSG_BG_START_TIMEOUT = 1;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700193
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700194 ServiceMap(Looper looper, int userId) {
195 super(looper);
Dianne Hackborn6285a322013-09-18 12:09:47 -0700196 mUserId = userId;
197 }
198
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700199 @Override
200 public void handleMessage(Message msg) {
201 switch (msg.what) {
202 case MSG_BG_START_TIMEOUT: {
203 synchronized (mAm) {
204 rescheduleDelayedStarts();
205 }
206 } break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700207 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700208 }
209
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700210 void ensureNotStartingBackground(ServiceRecord r) {
211 if (mStartingBackground.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800212 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
213 "No longer background starting: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700214 rescheduleDelayedStarts();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700215 }
Dianne Hackborn2e46bb52013-09-13 17:01:26 -0700216 if (mDelayedStartList.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800217 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700218 }
219 }
220
221 void rescheduleDelayedStarts() {
222 removeMessages(MSG_BG_START_TIMEOUT);
223 final long now = SystemClock.uptimeMillis();
224 for (int i=0, N=mStartingBackground.size(); i<N; i++) {
225 ServiceRecord r = mStartingBackground.get(i);
226 if (r.startingBgTimeout <= now) {
227 Slog.i(TAG, "Waited long enough for: " + r);
228 mStartingBackground.remove(i);
229 N--;
Junu Kimfcb87362014-02-19 16:25:21 +0900230 i--;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700231 }
232 }
233 while (mDelayedStartList.size() > 0
234 && mStartingBackground.size() < mMaxStartingBackground) {
235 ServiceRecord r = mDelayedStartList.remove(0);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800236 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
237 "REM FR DELAY LIST (exec next): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700238 if (r.pendingStarts.size() <= 0) {
239 Slog.w(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
240 + " delayedStop=" + r.delayedStop);
241 }
242 if (DEBUG_DELAYED_SERVICE) {
243 if (mDelayedStartList.size() > 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800244 Slog.v(TAG_SERVICE, "Remaining delayed list:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700245 for (int i=0; i<mDelayedStartList.size(); i++) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800246 Slog.v(TAG_SERVICE, " #" + i + ": " + mDelayedStartList.get(i));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700247 }
248 }
249 }
250 r.delayed = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700251 try {
252 startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false, true);
253 } catch (TransactionTooLargeException e) {
254 // Ignore, nobody upstack cares.
255 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700256 }
257 if (mStartingBackground.size() > 0) {
258 ServiceRecord next = mStartingBackground.get(0);
259 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800260 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700261 + ", can delay others up to " + when);
262 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
263 sendMessageAtTime(msg, when);
264 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700265 if (mStartingBackground.size() < mMaxStartingBackground) {
266 mAm.backgroundServicesFinishedLocked(mUserId);
267 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700268 }
269 }
270
271 public ActiveServices(ActivityManagerService service) {
272 mAm = service;
Dianne Hackborn23037412013-11-04 18:11:29 -0800273 int maxBg = 0;
274 try {
275 maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
276 } catch(RuntimeException e) {
277 }
Dianne Hackborn20d94742014-05-29 18:35:45 -0700278 mMaxStartingBackground = maxBg > 0
279 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700280 }
281
282 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
283 // TODO: Deal with global services
284 if (DEBUG_MU)
285 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
286 return getServiceMap(callingUser).mServicesByName.get(name);
287 }
288
Dianne Hackborn6285a322013-09-18 12:09:47 -0700289 boolean hasBackgroundServices(int callingUser) {
290 ServiceMap smap = mServiceMap.get(callingUser);
291 return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
292 }
293
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700294 private ServiceMap getServiceMap(int callingUser) {
295 ServiceMap smap = mServiceMap.get(callingUser);
296 if (smap == null) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700297 smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700298 mServiceMap.put(callingUser, smap);
299 }
300 return smap;
301 }
302
303 ArrayMap<ComponentName, ServiceRecord> getServices(int callingUser) {
304 return getServiceMap(callingUser).mServicesByName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700305 }
306
Svet Ganov99b60432015-06-27 13:15:22 -0700307 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
Svet Ganov9c165d72015-12-01 19:52:26 -0800308 int callingPid, int callingUid, String callingPackage, final int userId)
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700309 throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800310 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700311 + " type=" + resolvedType + " args=" + service.getExtras());
312
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700313 final boolean callerFg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700314 if (caller != null) {
315 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
316 if (callerApp == null) {
317 throw new SecurityException(
318 "Unable to find app for caller " + caller
319 + " (pid=" + Binder.getCallingPid()
320 + ") when starting service " + service);
321 }
Dianne Hackborna49ad092016-03-03 13:39:10 -0800322 callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700323 } else {
324 callerFg = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700325 }
326
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700327
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700328 ServiceLookupResult res =
Svet Ganov99b60432015-06-27 13:15:22 -0700329 retrieveServiceLocked(service, resolvedType, callingPackage,
Robert Sesekb9a86662015-12-09 16:22:45 -0500330 callingPid, callingUid, userId, true, callerFg, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700331 if (res == null) {
332 return null;
333 }
334 if (res.record == null) {
335 return new ComponentName("!", res.permission != null
336 ? res.permission : "private to package");
337 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700338
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700339 ServiceRecord r = res.record;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700340
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700341 if (!mAm.mUserController.exists(r.userId)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700342 Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700343 return null;
344 }
345
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700346 if (!r.startRequested) {
347 final long token = Binder.clearCallingIdentity();
348 try {
349 // Before going further -- if this app is not allowed to run in the
350 // background, then at this point we aren't going to let it period.
351 final int allowed = mAm.checkAllowBackgroundLocked(
352 r.appInfo.uid, r.packageName, callingPid, true);
353 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
354 Slog.w(TAG, "Background start not allowed: service "
355 + service + " to " + r.name.flattenToShortString()
356 + " from pid=" + callingPid + " uid=" + callingUid
357 + " pkg=" + callingPackage);
358 return null;
359 }
360 } finally {
361 Binder.restoreCallingIdentity(token);
362 }
363 }
364
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700365 NeededUriGrants neededGrants = mAm.checkGrantUriPermissionFromIntentLocked(
Nicolas Prevotc6cf95c2014-05-29 11:30:36 +0100366 callingUid, r.packageName, service, service.getFlags(), null, r.userId);
Svet Ganov9c165d72015-12-01 19:52:26 -0800367
368 // If permissions need a review before any of the app components can run,
369 // we do not start the service and launch a review activity if the calling app
370 // is in the foreground passing it a pending intent to start the service when
371 // review is completed.
372 if (Build.PERMISSIONS_REVIEW_REQUIRED) {
373 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage,
374 callingUid, service, callerFg, userId)) {
375 return null;
376 }
377 }
378
Dianne Hackbornd6f5b622013-11-11 17:25:37 -0800379 if (unscheduleServiceRestartLocked(r, callingUid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800380 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700381 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700382 r.lastActivity = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700383 r.startRequested = true;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700384 r.delayedStop = false;
385 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
386 service, neededGrants));
387
388 final ServiceMap smap = getServiceMap(r.userId);
389 boolean addToStarting = false;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700390 if (!callerFg && r.app == null
391 && mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700392 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700393 if (proc == null || proc.curProcState > ActivityManager.PROCESS_STATE_RECEIVER) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700394 // If this is not coming from a foreground caller, then we may want
395 // to delay the start if there are already other background services
396 // that are starting. This is to avoid process start spam when lots
397 // of applications are all handling things like connectivity broadcasts.
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700398 // We only do this for cached processes, because otherwise an application
399 // can have assumptions about calling startService() for a service to run
400 // in its own process, and for that process to not be killed before the
401 // service is started. This is especially the case for receivers, which
402 // may start a service in onReceive() to do some additional work and have
403 // initialized some global state as part of that.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800404 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
405 + r + " in " + proc);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700406 if (r.delayed) {
407 // This service is already scheduled for a delayed start; just leave
408 // it still waiting.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800409 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700410 return r.name;
411 }
412 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
413 // Something else is starting, delay!
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800414 Slog.i(TAG_SERVICE, "Delaying start of: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700415 smap.mDelayedStartList.add(r);
416 r.delayed = true;
417 return r.name;
418 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800419 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700420 addToStarting = true;
421 } else if (proc.curProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
422 // We slightly loosen when we will enqueue this new service as a background
423 // starting service we are waiting for, to also include processes that are
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700424 // currently running other services or receivers.
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700425 addToStarting = true;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800426 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
427 "Not delaying, but counting as bg: " + r);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800428 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn8e692572013-09-10 19:06:15 -0700429 StringBuilder sb = new StringBuilder(128);
430 sb.append("Not potential delay (state=").append(proc.curProcState)
431 .append(' ').append(proc.adjType);
432 String reason = proc.makeAdjReason();
433 if (reason != null) {
434 sb.append(' ');
435 sb.append(reason);
436 }
437 sb.append("): ");
438 sb.append(r.toString());
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800439 Slog.v(TAG_SERVICE, sb.toString());
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700440 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800441 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700442 if (callerFg) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800443 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700444 + callingUid + " pid=" + callingPid + "): " + r);
445 } else if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800446 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700447 } else {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800448 Slog.v(TAG_SERVICE,
449 "Not potential delay (user " + r.userId + " not started): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700450 }
451 }
452
453 return startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
454 }
455
Svet Ganov9c165d72015-12-01 19:52:26 -0800456 private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
457 String callingPackage, int callingUid, Intent service, boolean callerFg,
458 final int userId) {
459 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
460 r.packageName, r.userId)) {
461
462 // Show a permission review UI only for starting from a foreground app
463 if (!callerFg) {
464 Slog.w(TAG, "u" + r.userId + " Starting a service in package"
465 + r.packageName + " requires a permissions review");
466 return false;
467 }
468
469 IIntentSender target = mAm.getIntentSenderLocked(
470 ActivityManager.INTENT_SENDER_SERVICE, callingPackage,
471 callingUid, userId, null, null, 0, new Intent[]{service},
472 new String[]{service.resolveType(mAm.mContext.getContentResolver())},
473 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
474 | PendingIntent.FLAG_IMMUTABLE, null);
475
476 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
477 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
478 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
479 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
480 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
481
482 if (DEBUG_PERMISSIONS_REVIEW) {
483 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
484 + r.packageName);
485 }
486
487 mAm.mHandler.post(new Runnable() {
488 @Override
489 public void run() {
490 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
491 }
492 });
493
494 return false;
495 }
496
497 return true;
498 }
499
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700500 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
501 boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
Joe Onorato4eb64fd2016-03-21 15:30:09 -0700502 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700503 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700504 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700505 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700506 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700507 synchronized (r.stats.getBatteryStats()) {
508 r.stats.startRunningLocked();
509 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800510 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700511 if (error != null) {
512 return new ComponentName("!!", error);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700513 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700514
515 if (r.startRequested && addToStarting) {
516 boolean first = smap.mStartingBackground.size() == 0;
517 smap.mStartingBackground.add(r);
518 r.startingBgTimeout = SystemClock.uptimeMillis() + BG_START_TIMEOUT;
519 if (DEBUG_DELAYED_SERVICE) {
520 RuntimeException here = new RuntimeException("here");
521 here.fillInStackTrace();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800522 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800523 } else if (DEBUG_DELAYED_STARTS) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800524 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700525 }
526 if (first) {
527 smap.rescheduleDelayedStarts();
528 }
529 } else if (callerFg) {
530 smap.ensureNotStartingBackground(r);
531 }
532
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700533 return r.name;
534 }
535
536 private void stopServiceLocked(ServiceRecord service) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700537 if (service.delayed) {
538 // If service isn't actually running, but is is being held in the
539 // delayed list, then we need to keep it started but note that it
540 // should be stopped once no longer delayed.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800541 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700542 service.delayedStop = true;
543 return;
544 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700545 synchronized (service.stats.getBatteryStats()) {
546 service.stats.stopRunningLocked();
547 }
548 service.startRequested = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700549 if (service.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700550 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700551 SystemClock.uptimeMillis());
552 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700553 service.callStart = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700554 bringDownServiceIfNeededLocked(service, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700555 }
556
557 int stopServiceLocked(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700558 String resolvedType, int userId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800559 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700560 + " type=" + resolvedType);
561
562 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
563 if (caller != null && callerApp == null) {
564 throw new SecurityException(
565 "Unable to find app for caller " + caller
566 + " (pid=" + Binder.getCallingPid()
567 + ") when stopping service " + service);
568 }
569
570 // If this service is active, make sure it is stopped.
Svet Ganov99b60432015-06-27 13:15:22 -0700571 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, null,
Robert Sesekb9a86662015-12-09 16:22:45 -0500572 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700573 if (r != null) {
574 if (r.record != null) {
575 final long origId = Binder.clearCallingIdentity();
576 try {
577 stopServiceLocked(r.record);
578 } finally {
579 Binder.restoreCallingIdentity(origId);
580 }
581 return 1;
582 }
583 return -1;
584 }
585
586 return 0;
587 }
588
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700589 void stopInBackgroundLocked(int uid) {
590 // Stop all services associated with this uid due to it going to the background
591 // stopped state.
592 ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
593 ArrayList<ServiceRecord> stopping = null;
594 if (services != null) {
595 for (int i=services.mServicesByName.size()-1; i>=0; i--) {
596 ServiceRecord service = services.mServicesByName.valueAt(i);
597 if (service.appInfo.uid == uid && service.startRequested) {
598 if (mAm.mAppOpsService.noteOperation(AppOpsManager.OP_RUN_IN_BACKGROUND,
599 uid, service.packageName) != AppOpsManager.MODE_ALLOWED) {
600 if (stopping == null) {
601 stopping = new ArrayList<>();
602 stopping.add(service);
603 }
604 }
605 }
606 }
607 if (stopping != null) {
608 for (int i=stopping.size()-1; i>=0; i--) {
609 ServiceRecord service = stopping.get(i);
610 service.delayed = false;
611 services.ensureNotStartingBackground(service);
612 stopServiceLocked(service);
613 }
614 }
615 }
616 }
617
Svet Ganov99b60432015-06-27 13:15:22 -0700618 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
619 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, callingPackage,
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -0700620 Binder.getCallingPid(), Binder.getCallingUid(),
Robert Sesekb9a86662015-12-09 16:22:45 -0500621 UserHandle.getCallingUserId(), false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700622
623 IBinder ret = null;
624 if (r != null) {
625 // r.record is null if findServiceLocked() failed the caller permission check
626 if (r.record == null) {
627 throw new SecurityException(
Christopher Desjardins5862c5f2015-05-19 11:25:40 +0000628 "Permission Denial: Accessing service"
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700629 + " from pid=" + Binder.getCallingPid()
630 + ", uid=" + Binder.getCallingUid()
631 + " requires " + r.permission);
632 }
633 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
634 if (ib != null) {
635 ret = ib.binder;
636 }
637 }
638
639 return ret;
640 }
641
642 boolean stopServiceTokenLocked(ComponentName className, IBinder token,
643 int startId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800644 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700645 + " " + token + " startId=" + startId);
Dianne Hackborn41203752012-08-31 14:05:51 -0700646 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700647 if (r != null) {
648 if (startId >= 0) {
649 // Asked to only stop if done with all work. Note that
650 // to avoid leaks, we will take this as dropping all
651 // start items up to and including this one.
652 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
653 if (si != null) {
654 while (r.deliveredStarts.size() > 0) {
655 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
656 cur.removeUriPermissionsLocked();
657 if (cur == si) {
658 break;
659 }
660 }
661 }
662
663 if (r.getLastStartId() != startId) {
664 return false;
665 }
666
667 if (r.deliveredStarts.size() > 0) {
668 Slog.w(TAG, "stopServiceToken startId " + startId
669 + " is last, but have " + r.deliveredStarts.size()
670 + " remaining args");
671 }
672 }
673
674 synchronized (r.stats.getBatteryStats()) {
675 r.stats.stopRunningLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700676 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700677 r.startRequested = false;
678 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700679 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700680 SystemClock.uptimeMillis());
681 }
682 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700683 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700684 bringDownServiceIfNeededLocked(r, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700685 Binder.restoreCallingIdentity(origId);
686 return true;
687 }
688 return false;
689 }
690
691 public void setServiceForegroundLocked(ComponentName className, IBinder token,
Dianne Hackborn67324c92016-04-18 13:55:25 -0700692 int id, Notification notification, int flags) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700693 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700694 final long origId = Binder.clearCallingIdentity();
695 try {
Dianne Hackborn41203752012-08-31 14:05:51 -0700696 ServiceRecord r = findServiceLocked(className, token, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700697 if (r != null) {
698 if (id != 0) {
699 if (notification == null) {
700 throw new IllegalArgumentException("null notification");
701 }
702 if (r.foregroundId != id) {
703 r.cancelNotification();
704 r.foregroundId = id;
705 }
706 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
707 r.foregroundNoti = notification;
708 r.isForeground = true;
709 r.postNotification();
710 if (r.app != null) {
711 updateServiceForegroundLocked(r.app, true);
712 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700713 getServiceMap(r.userId).ensureNotStartingBackground(r);
Brian Carlstromca82e612016-04-19 23:16:08 -0700714 mAm.notifyPackageUse(r.serviceInfo.packageName,
715 PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700716 } else {
717 if (r.isForeground) {
718 r.isForeground = false;
719 if (r.app != null) {
Dianne Hackborndb926082013-10-31 16:32:44 -0700720 mAm.updateLruProcessLocked(r.app, false, null);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700721 updateServiceForegroundLocked(r.app, true);
722 }
723 }
Dianne Hackborn67324c92016-04-18 13:55:25 -0700724 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700725 r.cancelNotification();
726 r.foregroundId = 0;
727 r.foregroundNoti = null;
Dianne Hackborn955d8d62014-10-07 20:17:19 -0700728 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
Christoph Studer365e4c32014-09-18 20:35:36 +0200729 r.stripForegroundServiceFlagFromNotification();
Dianne Hackborn67324c92016-04-18 13:55:25 -0700730 if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
731 r.foregroundId = 0;
732 r.foregroundNoti = null;
733 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700734 }
735 }
736 }
737 } finally {
738 Binder.restoreCallingIdentity(origId);
739 }
740 }
741
742 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
743 boolean anyForeground = false;
Dianne Hackbornc8230512013-07-13 21:32:12 -0700744 for (int i=proc.services.size()-1; i>=0; i--) {
745 ServiceRecord sr = proc.services.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700746 if (sr.isForeground) {
747 anyForeground = true;
748 break;
749 }
750 }
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800751 mAm.updateProcessForegroundLocked(proc, anyForeground, oomAdj);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700752 }
753
Dianne Hackborn465fa392014-09-14 14:21:18 -0700754 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
755 ArraySet<ProcessRecord> updatedProcesses = null;
Wale Ogunwaled6ac7622016-05-26 09:02:25 -0700756 for (int i = 0; i < clientProc.connections.size(); i++) {
Dianne Hackborn465fa392014-09-14 14:21:18 -0700757 final ConnectionRecord conn = clientProc.connections.valueAt(i);
758 final ProcessRecord proc = conn.binding.service.app;
759 if (proc == null || proc == clientProc) {
760 continue;
761 } else if (updatedProcesses == null) {
762 updatedProcesses = new ArraySet<>();
763 } else if (updatedProcesses.contains(proc)) {
764 continue;
765 }
766 updatedProcesses.add(proc);
767 updateServiceClientActivitiesLocked(proc, null, false);
768 }
769 }
770
Dianne Hackborndb926082013-10-31 16:32:44 -0700771 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
Dianne Hackborn465fa392014-09-14 14:21:18 -0700772 ConnectionRecord modCr, boolean updateLru) {
Dianne Hackborndb926082013-10-31 16:32:44 -0700773 if (modCr != null && modCr.binding.client != null) {
774 if (modCr.binding.client.activities.size() <= 0) {
775 // This connection is from a client without activities, so adding
776 // and removing is not interesting.
777 return false;
778 }
779 }
780
781 boolean anyClientActivities = false;
782 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
783 ServiceRecord sr = proc.services.valueAt(i);
784 for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) {
785 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni);
786 for (int cri=clist.size()-1; cri>=0; cri--) {
787 ConnectionRecord cr = clist.get(cri);
788 if (cr.binding.client == null || cr.binding.client == proc) {
789 // Binding to ourself is not interesting.
790 continue;
791 }
792 if (cr.binding.client.activities.size() > 0) {
793 anyClientActivities = true;
794 break;
795 }
796 }
797 }
798 }
799 if (anyClientActivities != proc.hasClientActivities) {
800 proc.hasClientActivities = anyClientActivities;
Dianne Hackborn465fa392014-09-14 14:21:18 -0700801 if (updateLru) {
802 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
803 }
Dianne Hackborndb926082013-10-31 16:32:44 -0700804 return true;
805 }
806 return false;
807 }
808
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700809 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
Svet Ganov9c165d72015-12-01 19:52:26 -0800810 String resolvedType, final IServiceConnection connection, int flags,
811 String callingPackage, final int userId) throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800812 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700813 + " type=" + resolvedType + " conn=" + connection.asBinder()
814 + " flags=0x" + Integer.toHexString(flags));
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700815 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
816 if (callerApp == null) {
817 throw new SecurityException(
818 "Unable to find app for caller " + caller
819 + " (pid=" + Binder.getCallingPid()
820 + ") when binding service " + service);
821 }
822
823 ActivityRecord activity = null;
824 if (token != null) {
Craig Mautnerd2328952013-03-05 12:46:26 -0800825 activity = ActivityRecord.isInStackLocked(token);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700826 if (activity == null) {
827 Slog.w(TAG, "Binding with unknown activity: " + token);
828 return 0;
829 }
830 }
831
832 int clientLabel = 0;
833 PendingIntent clientIntent = null;
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700834 final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700835
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700836 if (isCallerSystem) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700837 // Hacky kind of thing -- allow system stuff to tell us
838 // what they are, so we can report this elsewhere for
839 // others to know why certain services are running.
Jeff Sharkeyf0ec2e02016-03-21 12:37:54 -0600840 service.setDefusable(true);
841 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700842 if (clientIntent != null) {
843 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
844 if (clientLabel != 0) {
845 // There are no useful extras in the intent, trash them.
846 // System code calling with this stuff just needs to know
847 // this will happen.
848 service = service.cloneFilter();
849 }
850 }
851 }
852
Dianne Hackbornf0f94d12014-03-17 16:04:21 -0700853 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
854 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
855 "BIND_TREAT_LIKE_ACTIVITY");
856 }
857
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700858 if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
859 throw new SecurityException(
860 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
861 + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
862 }
863
Dianne Hackborna49ad092016-03-03 13:39:10 -0800864 final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Robert Sesekb9a86662015-12-09 16:22:45 -0500865 final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700866
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700867 ServiceLookupResult res =
Robert Sesekb9a86662015-12-09 16:22:45 -0500868 retrieveServiceLocked(service, resolvedType, callingPackage, Binder.getCallingPid(),
869 Binder.getCallingUid(), userId, true, callerFg, isBindExternal);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700870 if (res == null) {
871 return 0;
872 }
873 if (res.record == null) {
874 return -1;
875 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700876 ServiceRecord s = res.record;
877
Svet Ganov9c165d72015-12-01 19:52:26 -0800878 boolean permissionsReviewRequired = false;
879
880 // If permissions need a review before any of the app components can run,
881 // we schedule binding to the service but do not start its process, then
882 // we launch a review activity to which is passed a callback to invoke
883 // when done to start the bound service's process to completing the binding.
884 if (Build.PERMISSIONS_REVIEW_REQUIRED) {
885 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
886 s.packageName, s.userId)) {
887
888 permissionsReviewRequired = true;
889
890 // Show a permission review UI only for binding from a foreground app
891 if (!callerFg) {
892 Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
893 + s.packageName + " requires a permissions review");
894 return 0;
895 }
896
897 final ServiceRecord serviceRecord = s;
898 final Intent serviceIntent = service;
899
900 RemoteCallback callback = new RemoteCallback(
901 new RemoteCallback.OnResultListener() {
902 @Override
903 public void onResult(Bundle result) {
904 synchronized(mAm) {
905 final long identity = Binder.clearCallingIdentity();
906 try {
907 if (!mPendingServices.contains(serviceRecord)) {
908 return;
909 }
910 // If there is still a pending record, then the service
911 // binding request is still valid, so hook them up. We
912 // proceed only if the caller cleared the review requirement
913 // otherwise we unbind because the user didn't approve.
914 if (!mAm.getPackageManagerInternalLocked()
915 .isPermissionsReviewRequired(
916 serviceRecord.packageName,
917 serviceRecord.userId)) {
918 try {
919 bringUpServiceLocked(serviceRecord,
920 serviceIntent.getFlags(),
921 callerFg, false, false);
922 } catch (RemoteException e) {
923 /* ignore - local call */
924 }
925 } else {
926 unbindServiceLocked(connection);
927 }
928 } finally {
929 Binder.restoreCallingIdentity(identity);
930 }
931 }
932 }
933 });
934
935 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
936 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
937 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
938 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
939 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
940
941 if (DEBUG_PERMISSIONS_REVIEW) {
942 Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
943 + s.packageName);
944 }
945
946 mAm.mHandler.post(new Runnable() {
947 @Override
948 public void run() {
949 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
950 }
951 });
952 }
953 }
954
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700955 final long origId = Binder.clearCallingIdentity();
956
957 try {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -0800958 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800959 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700960 + s);
961 }
962
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700963 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
964 s.lastActivity = SystemClock.uptimeMillis();
965 if (!s.hasAutoCreateConnections()) {
966 // This is the first binding, let the tracker know.
Joe Onorato4eb64fd2016-03-21 15:30:09 -0700967 ServiceState stracker = s.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700968 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700969 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700970 s.lastActivity);
971 }
972 }
973 }
974
Joe Onorato05c9ecc2016-03-30 15:13:46 -0700975 mAm.startAssociationLocked(callerApp.uid, callerApp.processName, callerApp.curProcState,
Dianne Hackbornab2df062015-01-07 13:43:13 -0800976 s.appInfo.uid, s.name, s.processName);
977
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700978 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
979 ConnectionRecord c = new ConnectionRecord(b, activity,
980 connection, flags, clientLabel, clientIntent);
981
982 IBinder binder = connection.asBinder();
983 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
984 if (clist == null) {
985 clist = new ArrayList<ConnectionRecord>();
986 s.connections.put(binder, clist);
987 }
988 clist.add(c);
989 b.connections.add(c);
990 if (activity != null) {
991 if (activity.connections == null) {
992 activity.connections = new HashSet<ConnectionRecord>();
993 }
994 activity.connections.add(c);
995 }
996 b.client.connections.add(c);
997 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
998 b.client.hasAboveClient = true;
999 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001000 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001001 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07001002 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001003 clist = mServiceConnections.get(binder);
1004 if (clist == null) {
1005 clist = new ArrayList<ConnectionRecord>();
1006 mServiceConnections.put(binder, clist);
1007 }
1008 clist.add(c);
1009
1010 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1011 s.lastActivity = SystemClock.uptimeMillis();
Svet Ganov9c165d72015-12-01 19:52:26 -08001012 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
1013 permissionsReviewRequired) != null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001014 return 0;
1015 }
1016 }
1017
1018 if (s.app != null) {
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001019 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1020 s.app.treatLikeActivity = true;
1021 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001022 // This could have made the service more important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001023 mAm.updateLruProcessLocked(s.app, s.app.hasClientActivities
1024 || s.app.treatLikeActivity, b.client);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001025 mAm.updateOomAdjLocked(s.app);
1026 }
1027
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001028 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001029 + ": received=" + b.intent.received
1030 + " apps=" + b.intent.apps.size()
1031 + " doRebind=" + b.intent.doRebind);
1032
1033 if (s.app != null && b.intent.received) {
1034 // Service is already running, so we can immediately
1035 // publish the connection.
1036 try {
1037 c.conn.connected(s.name, b.intent.binder);
1038 } catch (Exception e) {
1039 Slog.w(TAG, "Failure sending service " + s.shortName
1040 + " to connection " + c.conn.asBinder()
1041 + " (in " + c.binding.client.processName + ")", e);
1042 }
1043
1044 // If this is the first app connected back to this binding,
1045 // and the service had previously asked to be told when
1046 // rebound, then do so.
1047 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001048 requestServiceBindingLocked(s, b.intent, callerFg, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001049 }
1050 } else if (!b.intent.requested) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001051 requestServiceBindingLocked(s, b.intent, callerFg, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001052 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001053
1054 getServiceMap(s.userId).ensureNotStartingBackground(s);
1055
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001056 } finally {
1057 Binder.restoreCallingIdentity(origId);
1058 }
1059
1060 return 1;
1061 }
1062
Svet Ganov9c165d72015-12-01 19:52:26 -08001063 private void foo() {
1064
1065 }
1066
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001067 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
1068 final long origId = Binder.clearCallingIdentity();
1069 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001070 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001071 + " " + intent + ": " + service);
1072 if (r != null) {
1073 Intent.FilterComparison filter
1074 = new Intent.FilterComparison(intent);
1075 IntentBindRecord b = r.bindings.get(filter);
1076 if (b != null && !b.received) {
1077 b.binder = service;
1078 b.requested = true;
1079 b.received = true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07001080 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1081 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
1082 for (int i=0; i<clist.size(); i++) {
1083 ConnectionRecord c = clist.get(i);
1084 if (!filter.equals(c.binding.intent.intent)) {
1085 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001086 TAG_SERVICE, "Not publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001087 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001088 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001089 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001090 TAG_SERVICE, "Published intent: " + intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001091 continue;
1092 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001093 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001094 try {
1095 c.conn.connected(r.name, service);
1096 } catch (Exception e) {
1097 Slog.w(TAG, "Failure sending service " + r.name +
1098 " to connection " + c.conn.asBinder() +
1099 " (in " + c.binding.client.processName + ")", e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001100 }
1101 }
1102 }
1103 }
1104
Dianne Hackborn164371f2013-10-01 19:10:13 -07001105 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001106 }
1107 } finally {
1108 Binder.restoreCallingIdentity(origId);
1109 }
1110 }
1111
1112 boolean unbindServiceLocked(IServiceConnection connection) {
1113 IBinder binder = connection.asBinder();
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001114 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001115 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1116 if (clist == null) {
1117 Slog.w(TAG, "Unbind failed: could not find connection for "
1118 + connection.asBinder());
1119 return false;
1120 }
1121
1122 final long origId = Binder.clearCallingIdentity();
1123 try {
1124 while (clist.size() > 0) {
1125 ConnectionRecord r = clist.get(0);
1126 removeConnectionLocked(r, null, null);
Dianne Hackborn25e1eca2014-09-23 10:13:13 -07001127 if (clist.size() > 0 && clist.get(0) == r) {
1128 // In case it didn't get removed above, do it now.
1129 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
1130 clist.remove(0);
1131 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001132
1133 if (r.binding.service.app != null) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001134 if (r.binding.service.app.whitelistManager) {
1135 // Must reset flag here because on computeOomAdjLocked() the service
1136 // connection will be gone...
1137 r.binding.service.app.whitelistManager = false;
1138 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001139 // This could have made the service less important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001140 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1141 r.binding.service.app.treatLikeActivity = true;
1142 mAm.updateLruProcessLocked(r.binding.service.app,
1143 r.binding.service.app.hasClientActivities
1144 || r.binding.service.app.treatLikeActivity, null);
1145 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001146 mAm.updateOomAdjLocked(r.binding.service.app);
1147 }
1148 }
1149 } finally {
1150 Binder.restoreCallingIdentity(origId);
1151 }
1152
1153 return true;
1154 }
1155
1156 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
1157 final long origId = Binder.clearCallingIdentity();
1158 try {
1159 if (r != null) {
1160 Intent.FilterComparison filter
1161 = new Intent.FilterComparison(intent);
1162 IntentBindRecord b = r.bindings.get(filter);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001163 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001164 + " at " + b + ": apps="
1165 + (b != null ? b.apps.size() : 0));
1166
Dianne Hackborn164371f2013-10-01 19:10:13 -07001167 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001168 if (b != null) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001169 if (b.apps.size() > 0 && !inDestroying) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001170 // Applications have already bound since the last
1171 // unbind, so just rebind right here.
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001172 boolean inFg = false;
1173 for (int i=b.apps.size()-1; i>=0; i--) {
1174 ProcessRecord client = b.apps.valueAt(i).client;
1175 if (client != null && client.setSchedGroup
Dianne Hackborna49ad092016-03-03 13:39:10 -08001176 != ProcessList.SCHED_GROUP_BACKGROUND) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001177 inFg = true;
1178 break;
1179 }
1180 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001181 try {
1182 requestServiceBindingLocked(r, b, inFg, true);
1183 } catch (TransactionTooLargeException e) {
1184 // Don't pass this back to ActivityThread, it's unrelated.
1185 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001186 } else {
1187 // Note to tell the service the next time there is
1188 // a new client.
1189 b.doRebind = true;
1190 }
1191 }
1192
Dianne Hackborn164371f2013-10-01 19:10:13 -07001193 serviceDoneExecutingLocked(r, inDestroying, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001194 }
1195 } finally {
1196 Binder.restoreCallingIdentity(origId);
1197 }
1198 }
1199
1200 private final ServiceRecord findServiceLocked(ComponentName name,
Dianne Hackborn41203752012-08-31 14:05:51 -07001201 IBinder token, int userId) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001202 ServiceRecord r = getServiceByName(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001203 return r == token ? r : null;
1204 }
1205
1206 private final class ServiceLookupResult {
1207 final ServiceRecord record;
1208 final String permission;
1209
1210 ServiceLookupResult(ServiceRecord _record, String _permission) {
1211 record = _record;
1212 permission = _permission;
1213 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001214 }
1215
1216 private class ServiceRestarter implements Runnable {
1217 private ServiceRecord mService;
1218
1219 void setService(ServiceRecord service) {
1220 mService = service;
1221 }
1222
1223 public void run() {
1224 synchronized(mAm) {
1225 performServiceRestartLocked(mService);
1226 }
1227 }
1228 }
1229
1230 private ServiceLookupResult retrieveServiceLocked(Intent service,
Svet Ganov99b60432015-06-27 13:15:22 -07001231 String resolvedType, String callingPackage, int callingPid, int callingUid, int userId,
Robert Sesekb9a86662015-12-09 16:22:45 -05001232 boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001233 ServiceRecord r = null;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001234 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001235 + " type=" + resolvedType + " callingUid=" + callingUid);
1236
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001237 userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
1238 ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE, "service", null);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001239
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001240 ServiceMap smap = getServiceMap(userId);
1241 final ComponentName comp = service.getComponent();
1242 if (comp != null) {
1243 r = smap.mServicesByName.get(comp);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001244 }
Robert Sesekb9a86662015-12-09 16:22:45 -05001245 if (r == null && !isBindExternal) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001246 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001247 r = smap.mServicesByIntent.get(filter);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001248 }
Robert Sesekb9a86662015-12-09 16:22:45 -05001249 if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
1250 && !callingPackage.equals(r.packageName)) {
1251 // If an external service is running within its own package, other packages
1252 // should not bind to that instance.
1253 r = null;
1254 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001255 if (r == null) {
1256 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001257 // TODO: come back and remove this assumption to triage all services
1258 ResolveInfo rInfo = AppGlobals.getPackageManager().resolveService(service,
1259 resolvedType, ActivityManagerService.STOCK_PM_FLAGS
1260 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1261 userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001262 ServiceInfo sInfo =
1263 rInfo != null ? rInfo.serviceInfo : null;
1264 if (sInfo == null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001265 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001266 ": not found");
1267 return null;
1268 }
1269 ComponentName name = new ComponentName(
1270 sInfo.applicationInfo.packageName, sInfo.name);
Robert Sesekb9a86662015-12-09 16:22:45 -05001271 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
1272 if (isBindExternal) {
1273 if (!sInfo.exported) {
1274 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1275 " is not exported");
1276 }
1277 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
1278 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1279 " is not an isolatedProcess");
1280 }
1281 // Run the service under the calling package's application.
1282 ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
1283 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
1284 if (aInfo == null) {
1285 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
1286 "could not resolve client package " + callingPackage);
1287 }
1288 sInfo = new ServiceInfo(sInfo);
1289 sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
1290 sInfo.applicationInfo.packageName = aInfo.packageName;
1291 sInfo.applicationInfo.uid = aInfo.uid;
1292 name = new ComponentName(aInfo.packageName, name.getClassName());
1293 service.setComponent(name);
1294 } else {
1295 throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
1296 name);
1297 }
1298 } else if (isBindExternal) {
1299 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1300 " is not an externalService");
1301 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001302 if (userId > 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001303 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
Amith Yamasani4b9d79c2014-05-21 19:14:21 -07001304 sInfo.name, sInfo.flags)
1305 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001306 userId = 0;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001307 smap = getServiceMap(0);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001308 }
1309 sInfo = new ServiceInfo(sInfo);
1310 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
1311 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001312 r = smap.mServicesByName.get(name);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001313 if (r == null && createIfNeeded) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001314 Intent.FilterComparison filter
1315 = new Intent.FilterComparison(service.cloneFilter());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001316 ServiceRestarter res = new ServiceRestarter();
1317 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
1318 BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
1319 synchronized (stats) {
1320 ss = stats.getServiceStatsLocked(
1321 sInfo.applicationInfo.uid, sInfo.packageName,
1322 sInfo.name);
1323 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001324 r = new ServiceRecord(mAm, ss, name, filter, sInfo, callingFromFg, res);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001325 res.setService(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001326 smap.mServicesByName.put(name, r);
1327 smap.mServicesByIntent.put(filter, r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001328
1329 // Make sure this component isn't in the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001330 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001331 ServiceRecord pr = mPendingServices.get(i);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001332 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
1333 && pr.name.equals(name)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001334 mPendingServices.remove(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001335 }
1336 }
1337 }
1338 } catch (RemoteException ex) {
1339 // pm is in same process, this will never happen.
1340 }
1341 }
1342 if (r != null) {
1343 if (mAm.checkComponentPermission(r.permission,
1344 callingPid, callingUid, r.appInfo.uid, r.exported)
1345 != PackageManager.PERMISSION_GRANTED) {
1346 if (!r.exported) {
1347 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1348 + " from pid=" + callingPid
1349 + ", uid=" + callingUid
1350 + " that is not exported from uid " + r.appInfo.uid);
1351 return new ServiceLookupResult(null, "not exported from uid "
1352 + r.appInfo.uid);
1353 }
1354 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1355 + " from pid=" + callingPid
1356 + ", uid=" + callingUid
1357 + " requires " + r.permission);
1358 return new ServiceLookupResult(null, r.permission);
Svet Ganov99b60432015-06-27 13:15:22 -07001359 } else if (r.permission != null && callingPackage != null) {
1360 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
1361 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation(
1362 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
1363 Slog.w(TAG, "Appop Denial: Accessing service " + r.name
1364 + " from pid=" + callingPid
1365 + ", uid=" + callingUid
1366 + " requires appop " + AppOpsManager.opToName(opCode));
1367 return null;
1368 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001369 }
Svet Ganov99b60432015-06-27 13:15:22 -07001370
Ben Gruverf5323fe2013-07-31 15:09:51 -07001371 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
1372 resolvedType, r.appInfo)) {
Ben Gruverb6223792013-07-29 16:35:40 -07001373 return null;
1374 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001375 return new ServiceLookupResult(r, null);
1376 }
1377 return null;
1378 }
1379
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001380 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001381 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001382 + why + " of " + r + " in app " + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001383 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001384 + why + " of " + r.shortName);
1385 long now = SystemClock.uptimeMillis();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001386 if (r.executeNesting == 0) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001387 r.executeFg = fg;
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001388 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001389 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001390 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001391 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001392 if (r.app != null) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001393 r.app.executingServices.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001394 r.app.execServicesFg |= fg;
Dianne Hackborn2be00932013-09-22 16:46:00 -07001395 if (r.app.executingServices.size() == 1) {
1396 scheduleServiceTimeoutLocked(r.app);
1397 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001398 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001399 } else if (r.app != null && fg && !r.app.execServicesFg) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001400 r.app.execServicesFg = true;
Dianne Hackborn2be00932013-09-22 16:46:00 -07001401 scheduleServiceTimeoutLocked(r.app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001402 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001403 r.executeFg |= fg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001404 r.executeNesting++;
1405 r.executingStart = now;
1406 }
1407
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001408 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
1409 boolean execInFg, boolean rebind) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001410 if (r.app == null || r.app.thread == null) {
1411 // If service is not currently running, can't yet bind.
1412 return false;
1413 }
1414 if ((!i.requested || rebind) && i.apps.size() > 0) {
1415 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001416 bumpServiceExecutingLocked(r, execInFg, "bind");
Dianne Hackborna413dc02013-07-12 12:02:55 -07001417 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
1418 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
1419 r.app.repProcState);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001420 if (!rebind) {
1421 i.requested = true;
1422 }
1423 i.hasBound = true;
1424 i.doRebind = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001425 } catch (TransactionTooLargeException e) {
1426 // Keep the executeNesting count accurate.
1427 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
1428 final boolean inDestroying = mDestroyingServices.contains(r);
1429 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
1430 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001431 } catch (RemoteException e) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001432 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001433 // Keep the executeNesting count accurate.
1434 final boolean inDestroying = mDestroyingServices.contains(r);
1435 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001436 return false;
1437 }
1438 }
1439 return true;
1440 }
1441
1442 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
1443 boolean allowCancel) {
1444 boolean canceled = false;
1445
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001446 ServiceMap smap = getServiceMap(r.userId);
1447 if (smap.mServicesByName.get(r.name) != r) {
1448 ServiceRecord cur = smap.mServicesByName.get(r.name);
1449 Slog.wtf(TAG, "Attempting to schedule restart of " + r
1450 + " when found in map: " + cur);
1451 return false;
1452 }
1453
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001454 final long now = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001455
1456 if ((r.serviceInfo.applicationInfo.flags
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001457 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
1458 long minDuration = SERVICE_RESTART_DURATION;
1459 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001460
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001461 // Any delivered but not yet finished starts should be put back
1462 // on the pending list.
1463 final int N = r.deliveredStarts.size();
1464 if (N > 0) {
1465 for (int i=N-1; i>=0; i--) {
1466 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
1467 si.removeUriPermissionsLocked();
1468 if (si.intent == null) {
1469 // We'll generate this again if needed.
1470 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
1471 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
1472 r.pendingStarts.add(0, si);
1473 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
1474 dur *= 2;
1475 if (minDuration < dur) minDuration = dur;
1476 if (resetTime < dur) resetTime = dur;
1477 } else {
1478 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
1479 + r.name);
1480 canceled = true;
1481 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001482 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001483 r.deliveredStarts.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001484 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001485
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001486 r.totalRestartCount++;
1487 if (r.restartDelay == 0) {
1488 r.restartCount++;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001489 r.restartDelay = minDuration;
1490 } else {
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001491 // If it has been a "reasonably long time" since the service
1492 // was started, then reset our restart duration back to
1493 // the beginning, so we don't infinitely increase the duration
1494 // on a service that just occasionally gets killed (which is
1495 // a normal case, due to process being killed to reclaim memory).
1496 if (now > (r.restartTime+resetTime)) {
1497 r.restartCount = 1;
1498 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001499 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07001500 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
1501 if (r.restartDelay < minDuration) {
1502 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001503 }
1504 }
1505 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001506
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001507 r.nextRestartTime = now + r.restartDelay;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001508
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001509 // Make sure that we don't end up restarting a bunch of services
1510 // all at the same time.
1511 boolean repeat;
1512 do {
1513 repeat = false;
1514 for (int i=mRestartingServices.size()-1; i>=0; i--) {
1515 ServiceRecord r2 = mRestartingServices.get(i);
1516 if (r2 != r && r.nextRestartTime
1517 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
1518 && r.nextRestartTime
1519 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
1520 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
1521 r.restartDelay = r.nextRestartTime - now;
1522 repeat = true;
1523 break;
1524 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001525 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001526 } while (repeat);
1527
1528 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07001529 // Persistent processes are immediately restarted, so there is no
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001530 // reason to hold of on restarting their services.
1531 r.totalRestartCount++;
1532 r.restartCount = 0;
1533 r.restartDelay = 0;
1534 r.nextRestartTime = now;
1535 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001536
1537 if (!mRestartingServices.contains(r)) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001538 r.createdFromFg = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001539 mRestartingServices.add(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001540 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001541 }
1542
1543 r.cancelNotification();
1544
1545 mAm.mHandler.removeCallbacks(r.restarter);
1546 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
1547 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
1548 Slog.w(TAG, "Scheduling restart of crashed service "
1549 + r.shortName + " in " + r.restartDelay + "ms");
1550 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001551 r.userId, r.shortName, r.restartDelay);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001552
1553 return canceled;
1554 }
1555
1556 final void performServiceRestartLocked(ServiceRecord r) {
1557 if (!mRestartingServices.contains(r)) {
1558 return;
1559 }
Dianne Hackborn865907d2015-10-21 17:12:53 -07001560 if (!isServiceNeeded(r, false, false)) {
1561 // Paranoia: is this service actually needed? In theory a service that is not
1562 // needed should never remain on the restart list. In practice... well, there
1563 // have been bugs where this happens, and bad things happen because the process
1564 // ends up just being cached, so quickly killed, then restarted again and again.
1565 // Let's not let that happen.
1566 Slog.wtf(TAG, "Restarting service that is not needed: " + r);
1567 return;
1568 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001569 try {
Svet Ganov9c165d72015-12-01 19:52:26 -08001570 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001571 } catch (TransactionTooLargeException e) {
1572 // Ignore, it's been logged and nothing upstack cares.
1573 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001574 }
1575
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001576 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
1577 boolean force) {
1578 if (!force && r.restartDelay == 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001579 return false;
1580 }
Dianne Hackborn7b492722013-11-01 09:58:45 -07001581 // Remove from the restarting list; if the service is currently on the
1582 // restarting list, or the call is coming from another app, then this
1583 // service has become of much more interest so we reset the restart interval.
1584 boolean removed = mRestartingServices.remove(r);
1585 if (removed || callingUid != r.appInfo.uid) {
1586 r.resetRestartCounter();
1587 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001588 if (removed) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001589 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001590 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001591 mAm.mHandler.removeCallbacks(r.restarter);
1592 return true;
1593 }
1594
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001595 private void clearRestartingIfNeededLocked(ServiceRecord r) {
1596 if (r.restartTracker != null) {
1597 // If this is the last restarting record with this tracker, then clear
1598 // the tracker's restarting state.
1599 boolean stillTracking = false;
1600 for (int i=mRestartingServices.size()-1; i>=0; i--) {
1601 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
1602 stillTracking = true;
1603 break;
1604 }
1605 }
1606 if (!stillTracking) {
1607 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
1608 SystemClock.uptimeMillis());
1609 r.restartTracker = null;
1610 }
1611 }
1612 }
1613
Svet Ganov9c165d72015-12-01 19:52:26 -08001614 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
1615 boolean whileRestarting, boolean permissionsReviewRequired)
1616 throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001617 //Slog.i(TAG, "Bring up service:");
1618 //r.dump(" ");
1619
1620 if (r.app != null && r.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001621 sendServiceArgsLocked(r, execInFg, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001622 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001623 }
1624
1625 if (!whileRestarting && r.restartDelay > 0) {
1626 // If waiting for a restart, then do nothing.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001627 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001628 }
1629
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001630 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001631
1632 // We are now bringing the service up, so no longer in the
1633 // restarting state.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001634 if (mRestartingServices.remove(r)) {
chad7158ea22014-12-21 15:43:01 +08001635 r.resetRestartCounter();
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001636 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001637 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001638
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001639 // Make sure this service is no longer considered delayed, we are starting it now.
1640 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001641 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001642 getServiceMap(r.userId).mDelayedStartList.remove(r);
1643 r.delayed = false;
1644 }
1645
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001646 // Make sure that the user who owns this service is started. If not,
1647 // we don't want to allow it to run.
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001648 if (!mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001649 String msg = "Unable to launch app "
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001650 + r.appInfo.packageName + "/"
1651 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001652 + r.intent.getIntent() + ": user " + r.userId + " is stopped";
1653 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001654 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001655 return msg;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001656 }
1657
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001658 // Service is now being launched, its package can't be stopped.
1659 try {
1660 AppGlobals.getPackageManager().setPackageStoppedState(
1661 r.packageName, false, r.userId);
1662 } catch (RemoteException e) {
1663 } catch (IllegalArgumentException e) {
1664 Slog.w(TAG, "Failed trying to unstop package "
1665 + r.packageName + ": " + e);
1666 }
1667
1668 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
1669 final String procName = r.processName;
1670 ProcessRecord app;
1671
1672 if (!isolated) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001673 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
1674 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
1675 + " app=" + app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001676 if (app != null && app.thread != null) {
1677 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001678 app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001679 realStartServiceLocked(r, app, execInFg);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001680 return null;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001681 } catch (TransactionTooLargeException e) {
1682 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001683 } catch (RemoteException e) {
1684 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
1685 }
1686
1687 // If a dead object exception was thrown -- fall through to
1688 // restart the application.
1689 }
1690 } else {
1691 // If this service runs in an isolated process, then each time
1692 // we call startProcessLocked() we will get a new isolated
1693 // process, starting another process if we are currently waiting
1694 // for a previous process to come up. To deal with this, we store
1695 // in the service any current isolated process it is running in or
1696 // waiting to have come up.
1697 app = r.isolatedProc;
1698 }
1699
1700 // Not running -- get it started, and enqueue this service record
1701 // to be executed when the app comes up.
Svet Ganov9c165d72015-12-01 19:52:26 -08001702 if (app == null && !permissionsReviewRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001703 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001704 "service", r.name, false, isolated, false)) == null) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001705 String msg = "Unable to launch app "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001706 + r.appInfo.packageName + "/"
1707 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001708 + r.intent.getIntent() + ": process is bad";
1709 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001710 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001711 return msg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001712 }
1713 if (isolated) {
1714 r.isolatedProc = app;
1715 }
1716 }
1717
1718 if (!mPendingServices.contains(r)) {
1719 mPendingServices.add(r);
1720 }
1721
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001722 if (r.delayedStop) {
1723 // Oh and hey we've already been asked to stop!
1724 r.delayedStop = false;
1725 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001726 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
1727 "Applying delayed stop (in bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001728 stopServiceLocked(r);
1729 }
1730 }
1731
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001732 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001733 }
1734
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001735 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
1736 throws TransactionTooLargeException {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001737 for (int i=r.bindings.size()-1; i>=0; i--) {
1738 IntentBindRecord ibr = r.bindings.valueAt(i);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001739 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001740 break;
1741 }
1742 }
1743 }
1744
1745 private final void realStartServiceLocked(ServiceRecord r,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001746 ProcessRecord app, boolean execInFg) throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001747 if (app.thread == null) {
1748 throw new RemoteException();
1749 }
1750 if (DEBUG_MU)
1751 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
1752 + ", ProcessRecord.uid = " + app.uid);
1753 r.app = app;
1754 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
1755
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001756 final boolean newService = app.services.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001757 bumpServiceExecutingLocked(r, execInFg, "create");
Dianne Hackborndb926082013-10-31 16:32:44 -07001758 mAm.updateLruProcessLocked(app, false, null);
1759 mAm.updateOomAdjLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001760
1761 boolean created = false;
1762 try {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07001763 if (LOG_SERVICE_START_STOP) {
Dianne Hackbornab2df062015-01-07 13:43:13 -08001764 String nameTerm;
1765 int lastPeriod = r.shortName.lastIndexOf('.');
1766 nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07001767 EventLogTags.writeAmCreateService(
1768 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
1769 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001770 synchronized (r.stats.getBatteryStats()) {
1771 r.stats.startLaunchedLocked();
1772 }
Brian Carlstromca82e612016-04-19 23:16:08 -07001773 mAm.notifyPackageUse(r.serviceInfo.packageName,
1774 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
Dianne Hackborna413dc02013-07-12 12:02:55 -07001775 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001776 app.thread.scheduleCreateService(r, r.serviceInfo,
Dianne Hackborna413dc02013-07-12 12:02:55 -07001777 mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
1778 app.repProcState);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001779 r.postNotification();
1780 created = true;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -07001781 } catch (DeadObjectException e) {
1782 Slog.w(TAG, "Application dead when creating service " + r);
1783 mAm.appDiedLocked(app);
Wale Ogunwalebfac4682015-04-08 14:33:21 -07001784 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001785 } finally {
1786 if (!created) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001787 // Keep the executeNesting count accurate.
1788 final boolean inDestroying = mDestroyingServices.contains(r);
1789 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
1790
1791 // Cleanup.
1792 if (newService) {
1793 app.services.remove(r);
1794 r.app = null;
1795 }
1796
1797 // Retry.
1798 if (!inDestroying) {
1799 scheduleServiceRestartLocked(r, false);
1800 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001801 }
1802 }
1803
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001804 requestServiceBindingsLocked(r, execInFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001805
Dianne Hackborn465fa392014-09-14 14:21:18 -07001806 updateServiceClientActivitiesLocked(app, null, true);
1807
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001808 // If the service is in the started state, and there are no
1809 // pending arguments, then fake up one so its onStartCommand() will
1810 // be called.
1811 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
1812 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
1813 null, null));
1814 }
1815
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001816 sendServiceArgsLocked(r, execInFg, true);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001817
1818 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001819 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001820 getServiceMap(r.userId).mDelayedStartList.remove(r);
1821 r.delayed = false;
1822 }
1823
1824 if (r.delayedStop) {
1825 // Oh and hey we've already been asked to stop!
1826 r.delayedStop = false;
1827 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001828 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
1829 "Applying delayed stop (from start): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001830 stopServiceLocked(r);
1831 }
1832 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001833 }
1834
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001835 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001836 boolean oomAdjusted) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001837 final int N = r.pendingStarts.size();
1838 if (N == 0) {
1839 return;
1840 }
1841
1842 while (r.pendingStarts.size() > 0) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001843 Exception caughtException = null;
Yasuhiro Matsuda8b5cd9f2015-07-10 15:35:47 +09001844 ServiceRecord.StartItem si = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001845 try {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001846 si = r.pendingStarts.remove(0);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001847 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Sending arguments to: "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001848 + r + " " + r.intent + " args=" + si.intent);
1849 if (si.intent == null && N > 1) {
1850 // If somehow we got a dummy null intent in the middle,
1851 // then skip it. DO NOT skip a null intent when it is
1852 // the only one in the list -- this is to support the
1853 // onStartCommand(null) case.
1854 continue;
1855 }
1856 si.deliveredTime = SystemClock.uptimeMillis();
1857 r.deliveredStarts.add(si);
1858 si.deliveryCount++;
1859 if (si.neededGrants != null) {
1860 mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
1861 si.getUriPermissionsLocked());
1862 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001863 bumpServiceExecutingLocked(r, execInFg, "start");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001864 if (!oomAdjusted) {
1865 oomAdjusted = true;
1866 mAm.updateOomAdjLocked(r.app);
1867 }
1868 int flags = 0;
1869 if (si.deliveryCount > 1) {
1870 flags |= Service.START_FLAG_RETRY;
1871 }
1872 if (si.doneExecutingCount > 0) {
1873 flags |= Service.START_FLAG_REDELIVERY;
1874 }
1875 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001876 } catch (TransactionTooLargeException e) {
1877 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large: intent="
1878 + si.intent);
1879 caughtException = e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001880 } catch (RemoteException e) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001881 // Remote process gone... we'll let the normal cleanup take care of this.
1882 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
1883 caughtException = e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001884 } catch (Exception e) {
1885 Slog.w(TAG, "Unexpected exception", e);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001886 caughtException = e;
1887 }
1888
1889 if (caughtException != null) {
1890 // Keep nesting count correct
1891 final boolean inDestroying = mDestroyingServices.contains(r);
1892 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
1893 if (caughtException instanceof TransactionTooLargeException) {
1894 throw (TransactionTooLargeException)caughtException;
1895 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001896 break;
1897 }
1898 }
1899 }
1900
Dianne Hackborn164371f2013-10-01 19:10:13 -07001901 private final boolean isServiceNeeded(ServiceRecord r, boolean knowConn, boolean hasConn) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001902 // Are we still explicitly being asked to run?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001903 if (r.startRequested) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001904 return true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001905 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001906
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001907 // Is someone still bound to us keepign us running?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001908 if (!knowConn) {
1909 hasConn = r.hasAutoCreateConnections();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001910 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001911 if (hasConn) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001912 return true;
1913 }
1914
1915 return false;
1916 }
1917
1918 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
1919 boolean hasConn) {
1920 //Slog.i(TAG, "Bring down service:");
1921 //r.dump(" ");
1922
1923 if (isServiceNeeded(r, knowConn, hasConn)) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001924 return;
1925 }
1926
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001927 // Are we in the process of launching?
1928 if (mPendingServices.contains(r)) {
1929 return;
1930 }
1931
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001932 bringDownServiceLocked(r);
1933 }
1934
1935 private final void bringDownServiceLocked(ServiceRecord r) {
1936 //Slog.i(TAG, "Bring down service:");
1937 //r.dump(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001938
Dianne Hackborn390517b2013-05-30 15:03:32 -07001939 // Report to all of the connections that the service is no longer
1940 // available.
1941 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1942 ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
1943 for (int i=0; i<c.size(); i++) {
1944 ConnectionRecord cr = c.get(i);
1945 // There is still a connection to the service that is
1946 // being brought down. Mark it as dead.
1947 cr.serviceDead = true;
1948 try {
1949 cr.conn.connected(r.name, null);
1950 } catch (Exception e) {
1951 Slog.w(TAG, "Failure disconnecting service " + r.name +
1952 " to connection " + c.get(i).conn.asBinder() +
1953 " (in " + c.get(i).binding.client.processName + ")", e);
1954 }
1955 }
1956 }
1957
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001958 // Tell the service that it has been unbound.
Dianne Hackborn390517b2013-05-30 15:03:32 -07001959 if (r.app != null && r.app.thread != null) {
1960 for (int i=r.bindings.size()-1; i>=0; i--) {
1961 IntentBindRecord ibr = r.bindings.valueAt(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001962 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001963 + ": hasBound=" + ibr.hasBound);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001964 if (ibr.hasBound) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001965 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001966 bumpServiceExecutingLocked(r, false, "bring down unbind");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001967 mAm.updateOomAdjLocked(r.app);
1968 ibr.hasBound = false;
1969 r.app.thread.scheduleUnbindService(r,
1970 ibr.intent.getIntent());
1971 } catch (Exception e) {
1972 Slog.w(TAG, "Exception when unbinding service "
1973 + r.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07001974 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001975 }
1976 }
1977 }
1978 }
1979
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001980 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent);
Craig Mautner66c4a822015-01-16 12:48:16 -08001981 r.destroyTime = SystemClock.uptimeMillis();
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07001982 if (LOG_SERVICE_START_STOP) {
1983 EventLogTags.writeAmDestroyService(
1984 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
1985 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001986
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001987 final ServiceMap smap = getServiceMap(r.userId);
1988 smap.mServicesByName.remove(r.name);
1989 smap.mServicesByIntent.remove(r.intent);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001990 r.totalRestartCount = 0;
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001991 unscheduleServiceRestartLocked(r, 0, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001992
1993 // Also make sure it is not on the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001994 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001995 if (mPendingServices.get(i) == r) {
1996 mPendingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001997 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001998 }
1999 }
2000
2001 r.cancelNotification();
2002 r.isForeground = false;
2003 r.foregroundId = 0;
2004 r.foregroundNoti = null;
2005
2006 // Clear start entries.
2007 r.clearDeliveredStartsLocked();
2008 r.pendingStarts.clear();
2009
2010 if (r.app != null) {
2011 synchronized (r.stats.getBatteryStats()) {
2012 r.stats.stopLaunchedLocked();
2013 }
2014 r.app.services.remove(r);
2015 if (r.app.thread != null) {
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002016 updateServiceForegroundLocked(r.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002017 try {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002018 bumpServiceExecutingLocked(r, false, "destroy");
2019 mDestroyingServices.add(r);
Dianne Hackborn455625e2015-01-21 09:55:13 -08002020 r.destroying = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002021 mAm.updateOomAdjLocked(r.app);
2022 r.app.thread.scheduleStopService(r);
2023 } catch (Exception e) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002024 Slog.w(TAG, "Exception when destroying service "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002025 + r.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002026 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002027 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002028 } else {
2029 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002030 TAG_SERVICE, "Removed service that has no process: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002031 }
2032 } else {
2033 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002034 TAG_SERVICE, "Removed service that is not running: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002035 }
2036
2037 if (r.bindings.size() > 0) {
2038 r.bindings.clear();
2039 }
2040
2041 if (r.restarter instanceof ServiceRestarter) {
2042 ((ServiceRestarter)r.restarter).setService(null);
2043 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002044
Dianne Hackbornd2932242013-08-05 18:18:42 -07002045 int memFactor = mAm.mProcessStats.getMemFactorLocked();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002046 long now = SystemClock.uptimeMillis();
2047 if (r.tracker != null) {
2048 r.tracker.setStarted(false, memFactor, now);
2049 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002050 if (r.executeNesting == 0) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07002051 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002052 r.tracker = null;
2053 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002054 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002055
2056 smap.ensureNotStartingBackground(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002057 }
2058
2059 void removeConnectionLocked(
2060 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
2061 IBinder binder = c.conn.asBinder();
2062 AppBindRecord b = c.binding;
2063 ServiceRecord s = b.service;
2064 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
2065 if (clist != null) {
2066 clist.remove(c);
2067 if (clist.size() == 0) {
2068 s.connections.remove(binder);
2069 }
2070 }
2071 b.connections.remove(c);
2072 if (c.activity != null && c.activity != skipAct) {
2073 if (c.activity.connections != null) {
2074 c.activity.connections.remove(c);
2075 }
2076 }
2077 if (b.client != skipApp) {
2078 b.client.connections.remove(c);
2079 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
2080 b.client.updateHasAboveClientLocked();
2081 }
Dianne Hackborndb926082013-10-31 16:32:44 -07002082 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07002083 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07002084 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002085 }
2086 clist = mServiceConnections.get(binder);
2087 if (clist != null) {
2088 clist.remove(c);
2089 if (clist.size() == 0) {
2090 mServiceConnections.remove(binder);
2091 }
2092 }
2093
Dianne Hackbornab2df062015-01-07 13:43:13 -08002094 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid, s.name);
2095
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002096 if (b.connections.size() == 0) {
2097 b.intent.apps.remove(b.client);
2098 }
2099
2100 if (!c.serviceDead) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002101 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002102 + ": shouldUnbind=" + b.intent.hasBound);
2103 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
2104 && b.intent.hasBound) {
2105 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002106 bumpServiceExecutingLocked(s, false, "unbind");
Dianne Hackborndb926082013-10-31 16:32:44 -07002107 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
2108 && s.app.setProcState <= ActivityManager.PROCESS_STATE_RECEIVER) {
2109 // If this service's process is not already in the cached list,
2110 // then update it in the LRU list here because this may be causing
2111 // it to go down there and we want it to start out near the top.
2112 mAm.updateLruProcessLocked(s.app, false, null);
2113 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002114 mAm.updateOomAdjLocked(s.app);
2115 b.intent.hasBound = false;
2116 // Assume the client doesn't want to know about a rebind;
2117 // we will deal with that later if it asks for one.
2118 b.intent.doRebind = false;
2119 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
2120 } catch (Exception e) {
2121 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002122 serviceProcessGoneLocked(s);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002123 }
2124 }
2125
Svet Ganov9c165d72015-12-01 19:52:26 -08002126 // If unbound while waiting to start, remove the pending service
2127 mPendingServices.remove(s);
2128
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002129 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002130 boolean hasAutoCreate = s.hasAutoCreateConnections();
2131 if (!hasAutoCreate) {
2132 if (s.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002133 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002134 SystemClock.uptimeMillis());
2135 }
2136 }
2137 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002138 }
2139 }
2140 }
2141
2142 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002143 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002144 if (r != null) {
Dianne Hackborn455625e2015-01-21 09:55:13 -08002145 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002146 // This is a call from a service start... take care of
2147 // book-keeping.
2148 r.callStart = true;
2149 switch (res) {
2150 case Service.START_STICKY_COMPATIBILITY:
2151 case Service.START_STICKY: {
2152 // We are done with the associated start arguments.
2153 r.findDeliveredStart(startId, true);
2154 // Don't stop if killed.
2155 r.stopIfKilled = false;
2156 break;
2157 }
2158 case Service.START_NOT_STICKY: {
2159 // We are done with the associated start arguments.
2160 r.findDeliveredStart(startId, true);
2161 if (r.getLastStartId() == startId) {
2162 // There is no more work, and this service
2163 // doesn't want to hang around if killed.
2164 r.stopIfKilled = true;
2165 }
2166 break;
2167 }
2168 case Service.START_REDELIVER_INTENT: {
2169 // We'll keep this item until they explicitly
2170 // call stop for it, but keep track of the fact
2171 // that it was delivered.
2172 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
2173 if (si != null) {
2174 si.deliveryCount = 0;
2175 si.doneExecutingCount++;
2176 // Don't stop if killed.
2177 r.stopIfKilled = true;
2178 }
2179 break;
2180 }
2181 case Service.START_TASK_REMOVED_COMPLETE: {
2182 // Special processing for onTaskRemoved(). Don't
2183 // impact normal onStartCommand() processing.
2184 r.findDeliveredStart(startId, true);
2185 break;
2186 }
2187 default:
2188 throw new IllegalArgumentException(
2189 "Unknown service start result: " + res);
2190 }
2191 if (res == Service.START_STICKY_COMPATIBILITY) {
2192 r.callStart = false;
2193 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08002194 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
2195 // This is the final call from destroying the service... we should
2196 // actually be getting rid of the service at this point. Do some
2197 // validation of its state, and ensure it will be fully removed.
2198 if (!inDestroying) {
2199 // Not sure what else to do with this... if it is not actually in the
2200 // destroying list, we don't need to make sure to remove it from it.
Amith Yamasanid0418222016-05-10 15:49:51 -07002201 // If the app is null, then it was probably removed because the process died,
2202 // otherwise wtf
2203 if (r.app != null) {
2204 Slog.wtfStack(TAG, "Service done with onDestroy, but not inDestroying: "
2205 + r + ", app=" + r.app);
2206 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08002207 } else if (r.executeNesting != 1) {
2208 Slog.wtfStack(TAG, "Service done with onDestroy, but executeNesting="
2209 + r.executeNesting + ": " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002210 // Fake it to keep from ANR due to orphaned entry.
Dianne Hackborn455625e2015-01-21 09:55:13 -08002211 r.executeNesting = 1;
2212 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002213 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002214 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn164371f2013-10-01 19:10:13 -07002215 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002216 Binder.restoreCallingIdentity(origId);
2217 } else {
2218 Slog.w(TAG, "Done executing unknown service from pid "
2219 + Binder.getCallingPid());
2220 }
2221 }
2222
Dianne Hackborn878deb32013-10-14 16:55:09 -07002223 private void serviceProcessGoneLocked(ServiceRecord r) {
2224 if (r.tracker != null) {
2225 int memFactor = mAm.mProcessStats.getMemFactorLocked();
2226 long now = SystemClock.uptimeMillis();
2227 r.tracker.setExecuting(false, memFactor, now);
2228 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbc72dce2013-11-11 10:43:38 -08002229 r.tracker.setStarted(false, memFactor, now);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002230 }
2231 serviceDoneExecutingLocked(r, true, true);
2232 }
2233
Dianne Hackborn164371f2013-10-01 19:10:13 -07002234 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
2235 boolean finishing) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002236 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002237 + ": nesting=" + r.executeNesting
Dianne Hackborn164371f2013-10-01 19:10:13 -07002238 + ", inDestroying=" + inDestroying + ", app=" + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002239 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
2240 "<<< DONE EXECUTING " + r.shortName);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002241 r.executeNesting--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002242 if (r.executeNesting <= 0) {
2243 if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002244 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002245 "Nesting at 0 of " + r.shortName);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002246 r.app.execServicesFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002247 r.app.executingServices.remove(r);
2248 if (r.app.executingServices.size() == 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002249 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002250 "No more executingServices of " + r.shortName);
2251 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002252 } else if (r.executeFg) {
2253 // Need to re-evaluate whether the app still needs to be in the foreground.
2254 for (int i=r.app.executingServices.size()-1; i>=0; i--) {
2255 if (r.app.executingServices.valueAt(i).executeFg) {
2256 r.app.execServicesFg = true;
2257 break;
2258 }
2259 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002260 }
Dianne Hackborn164371f2013-10-01 19:10:13 -07002261 if (inDestroying) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002262 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn164371f2013-10-01 19:10:13 -07002263 "doneExecuting remove destroying " + r);
2264 mDestroyingServices.remove(r);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002265 r.bindings.clear();
2266 }
2267 mAm.updateOomAdjLocked(r.app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002268 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002269 r.executeFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002270 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002271 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002272 SystemClock.uptimeMillis());
Dianne Hackborn164371f2013-10-01 19:10:13 -07002273 if (finishing) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07002274 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002275 r.tracker = null;
2276 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002277 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002278 if (finishing) {
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08002279 if (r.app != null && !r.app.persistent) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002280 r.app.services.remove(r);
2281 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002282 r.app = null;
2283 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002284 }
2285 }
2286
Dianne Hackbornff072722014-09-24 10:56:28 -07002287 boolean attachApplicationLocked(ProcessRecord proc, String processName)
2288 throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002289 boolean didSomething = false;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002290 // Collect any services that are waiting for this process to come up.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002291 if (mPendingServices.size() > 0) {
2292 ServiceRecord sr = null;
2293 try {
2294 for (int i=0; i<mPendingServices.size(); i++) {
2295 sr = mPendingServices.get(i);
2296 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
2297 || !processName.equals(sr.processName))) {
2298 continue;
2299 }
2300
2301 mPendingServices.remove(i);
2302 i--;
Dianne Hackbornf7097a52014-05-13 09:56:14 -07002303 proc.addPackage(sr.appInfo.packageName, sr.appInfo.versionCode,
2304 mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002305 realStartServiceLocked(sr, proc, sr.createdFromFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002306 didSomething = true;
Dianne Hackborn865907d2015-10-21 17:12:53 -07002307 if (!isServiceNeeded(sr, false, false)) {
2308 // We were waiting for this service to start, but it is actually no
2309 // longer needed. This could happen because bringDownServiceIfNeeded
2310 // won't bring down a service that is pending... so now the pending
2311 // is done, so let's drop it.
2312 bringDownServiceLocked(sr);
2313 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002314 }
Dianne Hackbornff072722014-09-24 10:56:28 -07002315 } catch (RemoteException e) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002316 Slog.w(TAG, "Exception in new application when starting service "
2317 + sr.shortName, e);
2318 throw e;
2319 }
2320 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002321 // Also, if there are any services that are waiting to restart and
2322 // would run in this process, now is a good time to start them. It would
2323 // be weird to bring up the process but arbitrarily not let the services
2324 // run at this point just because their restart time hasn't come up.
2325 if (mRestartingServices.size() > 0) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002326 ServiceRecord sr;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002327 for (int i=0; i<mRestartingServices.size(); i++) {
2328 sr = mRestartingServices.get(i);
2329 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
2330 || !processName.equals(sr.processName))) {
2331 continue;
2332 }
2333 mAm.mHandler.removeCallbacks(sr.restarter);
2334 mAm.mHandler.post(sr.restarter);
2335 }
2336 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002337 return didSomething;
2338 }
2339
2340 void processStartTimedOutLocked(ProcessRecord proc) {
2341 for (int i=0; i<mPendingServices.size(); i++) {
2342 ServiceRecord sr = mPendingServices.get(i);
2343 if ((proc.uid == sr.appInfo.uid
2344 && proc.processName.equals(sr.processName))
2345 || sr.isolatedProc == proc) {
2346 Slog.w(TAG, "Forcing bringing down service: " + sr);
2347 sr.isolatedProc = null;
2348 mPendingServices.remove(i);
2349 i--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002350 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002351 }
2352 }
2353 }
2354
Wale Ogunwale540e1232015-05-01 15:35:39 -07002355 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002356 boolean evenPersistent, boolean doit, boolean killProcess,
2357 ArrayMap<ComponentName, ServiceRecord> services) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002358 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002359 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002360 ServiceRecord service = services.valueAt(i);
Wale Ogunwale540e1232015-05-01 15:35:39 -07002361 final boolean sameComponent = packageName == null
2362 || (service.packageName.equals(packageName)
2363 && (filterByClasses == null
2364 || filterByClasses.contains(service.name.getClassName())));
2365 if (sameComponent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002366 && (service.app == null || evenPersistent || !service.app.persistent)) {
2367 if (!doit) {
2368 return true;
2369 }
2370 didSomething = true;
2371 Slog.i(TAG, " Force stopping service " + service);
2372 if (service.app != null) {
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002373 service.app.removed = killProcess;
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08002374 if (!service.app.persistent) {
2375 service.app.services.remove(service);
2376 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002377 }
2378 service.app = null;
2379 service.isolatedProc = null;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002380 if (mTmpCollectionResults == null) {
2381 mTmpCollectionResults = new ArrayList<>();
2382 }
2383 mTmpCollectionResults.add(service);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002384 }
2385 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002386 return didSomething;
2387 }
2388
Wale Ogunwale540e1232015-05-01 15:35:39 -07002389 boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002390 int userId, boolean evenPersistent, boolean killProcess, boolean doit) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002391 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002392
2393 if (mTmpCollectionResults != null) {
2394 mTmpCollectionResults.clear();
2395 }
2396
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002397 if (userId == UserHandle.USER_ALL) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07002398 for (int i = mServiceMap.size() - 1; i >= 0; i--) {
2399 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002400 evenPersistent, doit, killProcess, mServiceMap.valueAt(i).mServicesByName);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002401 if (!doit && didSomething) {
2402 return true;
2403 }
2404 }
2405 } else {
Amith Yamasani540b6592013-10-01 13:02:52 -07002406 ServiceMap smap = mServiceMap.get(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002407 if (smap != null) {
2408 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByName;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002409 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002410 evenPersistent, doit, killProcess, items);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002411 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002412 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002413
Wale Ogunwale540e1232015-05-01 15:35:39 -07002414 if (mTmpCollectionResults != null) {
2415 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
2416 bringDownServiceLocked(mTmpCollectionResults.get(i));
2417 }
2418 mTmpCollectionResults.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002419 }
2420 return didSomething;
2421 }
2422
2423 void cleanUpRemovedTaskLocked(TaskRecord tr, ComponentName component, Intent baseIntent) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07002424 ArrayList<ServiceRecord> services = new ArrayList<>();
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002425 ArrayMap<ComponentName, ServiceRecord> alls = getServices(tr.userId);
Wale Ogunwale540e1232015-05-01 15:35:39 -07002426 for (int i = alls.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002427 ServiceRecord sr = alls.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002428 if (sr.packageName.equals(component.getPackageName())) {
2429 services.add(sr);
2430 }
2431 }
2432
2433 // Take care of any running services associated with the app.
Wale Ogunwale540e1232015-05-01 15:35:39 -07002434 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002435 ServiceRecord sr = services.get(i);
2436 if (sr.startRequested) {
2437 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
2438 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
2439 stopServiceLocked(sr);
2440 } else {
2441 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
2442 sr.makeNextStartId(), baseIntent, null));
2443 if (sr.app != null && sr.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002444 // We always run in the foreground, since this is called as
2445 // part of the "remove task" UI operation.
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002446 try {
2447 sendServiceArgsLocked(sr, true, false);
2448 } catch (TransactionTooLargeException e) {
2449 // Ignore, keep going.
2450 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002451 }
2452 }
2453 }
2454 }
2455 }
2456
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002457 final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002458 // Report disconnected services.
2459 if (false) {
2460 // XXX we are letting the client link to the service for
2461 // death notifications.
2462 if (app.services.size() > 0) {
2463 Iterator<ServiceRecord> it = app.services.iterator();
2464 while (it.hasNext()) {
2465 ServiceRecord r = it.next();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002466 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2467 ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
2468 for (int i=0; i<cl.size(); i++) {
2469 ConnectionRecord c = cl.get(i);
2470 if (c.binding.client != app) {
2471 try {
2472 //c.conn.connected(r.className, null);
2473 } catch (Exception e) {
2474 // todo: this should be asynchronous!
2475 Slog.w(TAG, "Exception thrown disconnected servce "
2476 + r.shortName
2477 + " from app " + app.processName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002478 }
2479 }
2480 }
2481 }
2482 }
2483 }
2484 }
2485
louis_chang40e259c2015-03-26 13:31:14 +08002486 // Clean up any connections this application has to other services.
2487 for (int i = app.connections.size() - 1; i >= 0; i--) {
2488 ConnectionRecord r = app.connections.valueAt(i);
2489 removeConnectionLocked(r, app, null);
2490 }
2491 updateServiceConnectionActivitiesLocked(app);
2492 app.connections.clear();
2493
2494 // Clear app state from services.
2495 for (int i = app.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07002496 ServiceRecord sr = app.services.valueAt(i);
2497 synchronized (sr.stats.getBatteryStats()) {
2498 sr.stats.stopLaunchedLocked();
2499 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08002500 if (sr.app != app && sr.app != null && !sr.app.persistent) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002501 sr.app.services.remove(sr);
2502 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07002503 sr.app = null;
2504 sr.isolatedProc = null;
2505 sr.executeNesting = 0;
Dianne Hackborn164371f2013-10-01 19:10:13 -07002506 sr.forceClearTracker();
2507 if (mDestroyingServices.remove(sr)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002508 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackbornc8230512013-07-13 21:32:12 -07002509 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002510
Dianne Hackbornc8230512013-07-13 21:32:12 -07002511 final int numClients = sr.bindings.size();
2512 for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
2513 IntentBindRecord b = sr.bindings.valueAt(bindingi);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002514 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
Dianne Hackbornc8230512013-07-13 21:32:12 -07002515 + ": shouldUnbind=" + b.hasBound);
2516 b.binder = null;
2517 b.requested = b.received = b.hasBound = false;
Dianne Hackborn465fa392014-09-14 14:21:18 -07002518 // If this binding is coming from a cached process and is asking to keep
2519 // the service created, then we'll kill the cached process as well -- we
2520 // don't want to be thrashing around restarting processes that are only
2521 // there to be cached.
2522 for (int appi=b.apps.size()-1; appi>=0; appi--) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07002523 final ProcessRecord proc = b.apps.keyAt(appi);
2524 // If the process is already gone, skip it.
2525 if (proc.killedByAm || proc.thread == null) {
2526 continue;
2527 }
2528 // Only do this for processes that have an auto-create binding;
2529 // otherwise the binding can be left, because it won't cause the
2530 // service to restart.
2531 final AppBindRecord abind = b.apps.valueAt(appi);
2532 boolean hasCreate = false;
2533 for (int conni=abind.connections.size()-1; conni>=0; conni--) {
2534 ConnectionRecord conn = abind.connections.valueAt(conni);
Dianne Hackborn0fe3c252014-09-19 15:09:39 -07002535 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
2536 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07002537 hasCreate = true;
2538 break;
2539 }
2540 }
2541 if (!hasCreate) {
2542 continue;
2543 }
Dianne Hackborncd97c962014-09-25 18:34:02 -07002544 // XXX turned off for now until we have more time to get a better policy.
2545 if (false && proc != null && !proc.persistent && proc.thread != null
Dianne Hackborn465fa392014-09-14 14:21:18 -07002546 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
2547 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
2548 proc.kill("bound to service " + sr.name.flattenToShortString()
2549 + " in dying proc " + (app != null ? app.processName : "??"), true);
2550 }
2551 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07002552 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002553 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002554
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002555 ServiceMap smap = getServiceMap(app.userId);
2556
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002557 // Now do remaining service cleanup.
2558 for (int i=app.services.size()-1; i>=0; i--) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002559 ServiceRecord sr = app.services.valueAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08002560
2561 // Unless the process is persistent, this process record is going away,
2562 // so make sure the service is cleaned out of it.
2563 if (!app.persistent) {
Dianne Hackborn4190fc52013-12-09 18:20:16 -08002564 app.services.removeAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08002565 }
2566
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002567 // Sanity check: if the service listed for the app is not one
Dianne Hackborn4190fc52013-12-09 18:20:16 -08002568 // we actually are maintaining, just let it drop.
Dianne Hackborn40c87252014-03-19 16:55:40 -07002569 final ServiceRecord curRec = smap.mServicesByName.get(sr.name);
2570 if (curRec != sr) {
2571 if (curRec != null) {
2572 Slog.wtf(TAG, "Service " + sr + " in process " + app
2573 + " not same as in map: " + curRec);
2574 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002575 continue;
2576 }
2577
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002578 // Any services running in the application may need to be placed
2579 // back in the pending list.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002580 if (allowRestart && sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
Dianne Hackbornc8230512013-07-13 21:32:12 -07002581 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
2582 Slog.w(TAG, "Service crashed " + sr.crashCount
2583 + " times, stopping: " + sr);
2584 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
2585 sr.userId, sr.crashCount, sr.shortName, app.pid);
2586 bringDownServiceLocked(sr);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07002587 } else if (!allowRestart
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002588 || !mAm.mUserController.isUserRunningLocked(sr.userId, 0)) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07002589 bringDownServiceLocked(sr);
2590 } else {
2591 boolean canceled = scheduleServiceRestartLocked(sr, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002592
Dianne Hackbornc8230512013-07-13 21:32:12 -07002593 // Should the service remain running? Note that in the
2594 // extreme case of so many attempts to deliver a command
2595 // that it failed we also will stop it here.
2596 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
2597 if (sr.pendingStarts.size() == 0) {
2598 sr.startRequested = false;
2599 if (sr.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002600 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackbornc8230512013-07-13 21:32:12 -07002601 SystemClock.uptimeMillis());
2602 }
2603 if (!sr.hasAutoCreateConnections()) {
2604 // Whoops, no reason to restart!
2605 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002606 }
2607 }
2608 }
2609 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07002610 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002611
Dianne Hackbornc8230512013-07-13 21:32:12 -07002612 if (!allowRestart) {
2613 app.services.clear();
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002614
2615 // Make sure there are no more restarting services for this process.
2616 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2617 ServiceRecord r = mRestartingServices.get(i);
2618 if (r.processName.equals(app.processName) &&
2619 r.serviceInfo.applicationInfo.uid == app.info.uid) {
2620 mRestartingServices.remove(i);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002621 clearRestartingIfNeededLocked(r);
2622 }
2623 }
2624 for (int i=mPendingServices.size()-1; i>=0; i--) {
2625 ServiceRecord r = mPendingServices.get(i);
2626 if (r.processName.equals(app.processName) &&
2627 r.serviceInfo.applicationInfo.uid == app.info.uid) {
2628 mPendingServices.remove(i);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002629 }
2630 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002631 }
2632
2633 // Make sure we have no more records on the stopping list.
Dianne Hackborn164371f2013-10-01 19:10:13 -07002634 int i = mDestroyingServices.size();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002635 while (i > 0) {
2636 i--;
Dianne Hackborn164371f2013-10-01 19:10:13 -07002637 ServiceRecord sr = mDestroyingServices.get(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002638 if (sr.app == app) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002639 sr.forceClearTracker();
2640 mDestroyingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002641 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002642 }
2643 }
2644
2645 app.executingServices.clear();
2646 }
2647
2648 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
2649 ActivityManager.RunningServiceInfo info =
2650 new ActivityManager.RunningServiceInfo();
2651 info.service = r.name;
2652 if (r.app != null) {
2653 info.pid = r.app.pid;
2654 }
2655 info.uid = r.appInfo.uid;
2656 info.process = r.processName;
2657 info.foreground = r.isForeground;
2658 info.activeSince = r.createTime;
2659 info.started = r.startRequested;
2660 info.clientCount = r.connections.size();
2661 info.crashCount = r.crashCount;
2662 info.lastActivityTime = r.lastActivity;
2663 if (r.isForeground) {
2664 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
2665 }
2666 if (r.startRequested) {
2667 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
2668 }
2669 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
2670 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
2671 }
2672 if (r.app != null && r.app.persistent) {
2673 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
2674 }
2675
Dianne Hackborn390517b2013-05-30 15:03:32 -07002676 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2677 ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002678 for (int i=0; i<connl.size(); i++) {
2679 ConnectionRecord conn = connl.get(i);
2680 if (conn.clientLabel != 0) {
2681 info.clientPackage = conn.binding.client.info.packageName;
2682 info.clientLabel = conn.clientLabel;
2683 return info;
2684 }
2685 }
2686 }
2687 return info;
2688 }
2689
2690 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum,
2691 int flags) {
2692 ArrayList<ActivityManager.RunningServiceInfo> res
2693 = new ArrayList<ActivityManager.RunningServiceInfo>();
2694
Dianne Hackborn0c380492012-08-20 17:23:30 -07002695 final int uid = Binder.getCallingUid();
2696 final long ident = Binder.clearCallingIdentity();
2697 try {
2698 if (ActivityManager.checkUidPermission(
2699 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
2700 uid) == PackageManager.PERMISSION_GRANTED) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07002701 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07002702 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002703 ArrayMap<ComponentName, ServiceRecord> alls = getServices(users[ui]);
2704 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
2705 ServiceRecord sr = alls.valueAt(i);
2706 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07002707 }
2708 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002709
Dianne Hackborn0c380492012-08-20 17:23:30 -07002710 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
2711 ServiceRecord r = mRestartingServices.get(i);
2712 ActivityManager.RunningServiceInfo info =
2713 makeRunningServiceInfoLocked(r);
2714 info.restarting = r.nextRestartTime;
2715 res.add(info);
2716 }
2717 } else {
2718 int userId = UserHandle.getUserId(uid);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002719 ArrayMap<ComponentName, ServiceRecord> alls = getServices(userId);
2720 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
2721 ServiceRecord sr = alls.valueAt(i);
2722 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07002723 }
2724
2725 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
2726 ServiceRecord r = mRestartingServices.get(i);
2727 if (r.userId == userId) {
2728 ActivityManager.RunningServiceInfo info =
2729 makeRunningServiceInfoLocked(r);
2730 info.restarting = r.nextRestartTime;
2731 res.add(info);
2732 }
2733 }
2734 }
2735 } finally {
2736 Binder.restoreCallingIdentity(ident);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002737 }
2738
2739 return res;
2740 }
2741
2742 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002743 int userId = UserHandle.getUserId(Binder.getCallingUid());
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002744 ServiceRecord r = getServiceByName(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002745 if (r != null) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002746 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2747 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002748 for (int i=0; i<conn.size(); i++) {
2749 if (conn.get(i).clientIntent != null) {
2750 return conn.get(i).clientIntent;
2751 }
2752 }
2753 }
2754 }
2755 return null;
2756 }
2757
2758 void serviceTimeout(ProcessRecord proc) {
2759 String anrMessage = null;
2760
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07002761 synchronized(mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002762 if (proc.executingServices.size() == 0 || proc.thread == null) {
2763 return;
2764 }
Dianne Hackbornab2df062015-01-07 13:43:13 -08002765 final long now = SystemClock.uptimeMillis();
2766 final long maxTime = now -
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002767 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002768 ServiceRecord timeout = null;
2769 long nextTime = 0;
Dianne Hackbornc8230512013-07-13 21:32:12 -07002770 for (int i=proc.executingServices.size()-1; i>=0; i--) {
2771 ServiceRecord sr = proc.executingServices.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002772 if (sr.executingStart < maxTime) {
2773 timeout = sr;
2774 break;
2775 }
2776 if (sr.executingStart > nextTime) {
2777 nextTime = sr.executingStart;
2778 }
2779 }
2780 if (timeout != null && mAm.mLruProcesses.contains(proc)) {
2781 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08002782 StringWriter sw = new StringWriter();
2783 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
2784 pw.println(timeout);
2785 timeout.dump(pw, " ");
2786 pw.close();
2787 mLastAnrDump = sw.toString();
2788 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
2789 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
2790 anrMessage = "executing service " + timeout.shortName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002791 } else {
2792 Message msg = mAm.mHandler.obtainMessage(
2793 ActivityManagerService.SERVICE_TIMEOUT_MSG);
2794 msg.obj = proc;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002795 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
Dianne Hackborn2be00932013-09-22 16:46:00 -07002796 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002797 }
2798 }
2799
2800 if (anrMessage != null) {
Adrian Roos20d7df32016-01-12 18:59:43 +01002801 mAm.mAppErrors.appNotResponding(proc, null, null, false, anrMessage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002802 }
2803 }
2804
Dianne Hackborn2be00932013-09-22 16:46:00 -07002805 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
2806 if (proc.executingServices.size() == 0 || proc.thread == null) {
2807 return;
2808 }
2809 long now = SystemClock.uptimeMillis();
2810 Message msg = mAm.mHandler.obtainMessage(
2811 ActivityManagerService.SERVICE_TIMEOUT_MSG);
2812 msg.obj = proc;
2813 mAm.mHandler.sendMessageAtTime(msg,
2814 proc.execServicesFg ? (now+SERVICE_TIMEOUT) : (now+ SERVICE_BACKGROUND_TIMEOUT));
2815 }
2816
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002817 /**
2818 * Prints a list of ServiceRecords (dumpsys activity services)
2819 */
Dianne Hackborn777a06d2016-05-16 17:36:15 -07002820 List<ServiceRecord> collectServicesToDumpLocked(ItemMatcher matcher, String dumpPackage) {
2821 final ArrayList<ServiceRecord> services = new ArrayList<>();
2822 final int[] users = mAm.mUserController.getUsers();
2823 for (int user : users) {
2824 ServiceMap smap = getServiceMap(user);
2825 if (smap.mServicesByName.size() > 0) {
2826 for (int si=0; si<smap.mServicesByName.size(); si++) {
2827 ServiceRecord r = smap.mServicesByName.valueAt(si);
2828 if (!matcher.match(r, r.name)) {
2829 continue;
2830 }
2831 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2832 continue;
2833 }
2834 services.add(r);
2835 }
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08002836 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07002837 }
2838
2839 return services;
2840 }
2841
2842 final class ServiceDumper {
2843 private final FileDescriptor fd;
2844 private final PrintWriter pw;
2845 private final String[] args;
2846 private final int opti;
2847 private final boolean dumpAll;
2848 private final String dumpPackage;
2849 private final ItemMatcher matcher;
2850 private final ArrayList<ServiceRecord> services = new ArrayList<>();
2851
2852 private final long nowReal = SystemClock.elapsedRealtime();
2853
2854 private boolean needSep = false;
2855 private boolean printedAnything = false;
2856 private boolean printed = false;
2857
2858 /**
2859 * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
2860 * must be called with the lock held).
2861 */
2862 ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
2863 int opti, boolean dumpAll, String dumpPackage) {
2864 this.fd = fd;
2865 this.pw = pw;
2866 this.args = args;
2867 this.opti = opti;
2868 this.dumpAll = dumpAll;
2869 this.dumpPackage = dumpPackage;
2870 matcher = new ItemMatcher();
2871 matcher.build(args, opti);
2872
2873 final int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07002874 for (int user : users) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002875 ServiceMap smap = getServiceMap(user);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002876 if (smap.mServicesByName.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002877 for (int si=0; si<smap.mServicesByName.size(); si++) {
2878 ServiceRecord r = smap.mServicesByName.valueAt(si);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002879 if (!matcher.match(r, r.name)) {
2880 continue;
2881 }
2882 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2883 continue;
2884 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07002885 services.add(r);
2886 }
2887 }
2888 }
2889 }
2890
2891 private void dumpHeaderLocked() {
2892 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
2893 if (mLastAnrDump != null) {
2894 pw.println(" Last ANR service:");
2895 pw.print(mLastAnrDump);
2896 pw.println();
2897 }
2898 }
2899
2900 void dumpLocked() {
2901 dumpHeaderLocked();
2902
2903 try {
2904 int[] users = mAm.mUserController.getUsers();
2905 for (int user : users) {
2906 // Find the first service for this user.
2907 int serviceIdx = 0;
2908 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
2909 serviceIdx++;
2910 }
2911 printed = false;
2912 if (serviceIdx < services.size()) {
2913 needSep = false;
2914 while (serviceIdx < services.size()) {
2915 ServiceRecord r = services.get(serviceIdx);
2916 serviceIdx++;
2917 if (r.userId != user) {
2918 break;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002919 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07002920 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002921 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07002922 needSep |= printed;
2923 }
2924
2925 dumpUserRemainsLocked(user);
2926 }
2927 } catch (Exception e) {
2928 Slog.w(TAG, "Exception in dumpServicesLocked", e);
2929 }
2930
2931 dumpRemainsLocked();
2932 }
2933
2934 void dumpWithClient() {
2935 synchronized(mAm) {
2936 dumpHeaderLocked();
2937 }
2938
2939 try {
2940 int[] users = mAm.mUserController.getUsers();
2941 for (int user : users) {
2942 // Find the first service for this user.
2943 int serviceIdx = 0;
2944 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
2945 serviceIdx++;
2946 }
2947 printed = false;
2948 if (serviceIdx < services.size()) {
2949 needSep = false;
2950 while (serviceIdx < services.size()) {
2951 ServiceRecord r = services.get(serviceIdx);
2952 serviceIdx++;
2953 if (r.userId != user) {
2954 break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002955 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07002956 synchronized(mAm) {
2957 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002958 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07002959 dumpServiceClient(r);
2960 }
2961 needSep |= printed;
2962 }
2963
2964 synchronized(mAm) {
2965 dumpUserRemainsLocked(user);
2966 }
2967 }
2968 } catch (Exception e) {
2969 Slog.w(TAG, "Exception in dumpServicesLocked", e);
2970 }
2971
2972 synchronized(mAm) {
2973 dumpRemainsLocked();
2974 }
2975 }
2976
2977 private void dumpUserHeaderLocked(int user) {
2978 if (!printed) {
2979 if (printedAnything) {
2980 pw.println();
2981 }
2982 pw.println(" User " + user + " active services:");
2983 printed = true;
2984 }
2985 printedAnything = true;
2986 if (needSep) {
2987 pw.println();
2988 }
2989 }
2990
2991 private void dumpServiceLocalLocked(ServiceRecord r) {
2992 dumpUserHeaderLocked(r.userId);
2993 pw.print(" * ");
2994 pw.println(r);
2995 if (dumpAll) {
2996 r.dump(pw, " ");
2997 needSep = true;
2998 } else {
2999 pw.print(" app=");
3000 pw.println(r.app);
3001 pw.print(" created=");
3002 TimeUtils.formatDuration(r.createTime, nowReal, pw);
3003 pw.print(" started=");
3004 pw.print(r.startRequested);
3005 pw.print(" connections=");
3006 pw.println(r.connections.size());
3007 if (r.connections.size() > 0) {
3008 pw.println(" Connections:");
3009 for (int conni=0; conni<r.connections.size(); conni++) {
3010 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
3011 for (int i = 0; i < clist.size(); i++) {
3012 ConnectionRecord conn = clist.get(i);
3013 pw.print(" ");
3014 pw.print(conn.binding.intent.intent.getIntent()
3015 .toShortString(false, false, false, false));
3016 pw.print(" -> ");
3017 ProcessRecord proc = conn.binding.client;
3018 pw.println(proc != null ? proc.toShortString() : "null");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003019 }
3020 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003021 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003022 }
3023 }
3024
3025 private void dumpServiceClient(ServiceRecord r) {
3026 final ProcessRecord proc = r.app;
3027 if (proc == null) {
3028 return;
3029 }
3030 final IApplicationThread thread = proc.thread;
3031 if (thread == null) {
3032 return;
3033 }
3034 pw.println(" Client:");
3035 pw.flush();
3036 try {
3037 TransferPipe tp = new TransferPipe();
3038 try {
3039 thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
3040 tp.setBufferPrefix(" ");
3041 // Short timeout, since blocking here can
3042 // deadlock with the application.
3043 tp.go(fd, 2000);
3044 } finally {
3045 tp.kill();
3046 }
3047 } catch (IOException e) {
3048 pw.println(" Failure while dumping the service: " + e);
3049 } catch (RemoteException e) {
3050 pw.println(" Got a RemoteException while dumping the service");
3051 }
3052 needSep = true;
3053 }
3054
3055 private void dumpUserRemainsLocked(int user) {
3056 ServiceMap smap = getServiceMap(user);
3057 printed = false;
3058 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
3059 ServiceRecord r = smap.mDelayedStartList.get(si);
3060 if (!matcher.match(r, r.name)) {
3061 continue;
3062 }
3063 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3064 continue;
3065 }
3066 if (!printed) {
3067 if (printedAnything) {
3068 pw.println();
3069 }
3070 pw.println(" User " + user + " delayed start services:");
3071 printed = true;
3072 }
3073 printedAnything = true;
3074 pw.print(" * Delayed start "); pw.println(r);
3075 }
3076 printed = false;
3077 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
3078 ServiceRecord r = smap.mStartingBackground.get(si);
3079 if (!matcher.match(r, r.name)) {
3080 continue;
3081 }
3082 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3083 continue;
3084 }
3085 if (!printed) {
3086 if (printedAnything) {
3087 pw.println();
3088 }
3089 pw.println(" User " + user + " starting in background:");
3090 printed = true;
3091 }
3092 printedAnything = true;
3093 pw.print(" * Starting bg "); pw.println(r);
3094 }
3095 }
3096
3097 private void dumpRemainsLocked() {
3098 if (mPendingServices.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003099 printed = false;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003100 for (int i=0; i<mPendingServices.size(); i++) {
3101 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003102 if (!matcher.match(r, r.name)) {
3103 continue;
3104 }
3105 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3106 continue;
3107 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003108 printedAnything = true;
3109 if (!printed) {
3110 if (needSep) pw.println();
3111 needSep = true;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003112 pw.println(" Pending services:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003113 printed = true;
3114 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003115 pw.print(" * Pending "); pw.println(r);
3116 r.dump(pw, " ");
3117 }
3118 needSep = true;
3119 }
3120
3121 if (mRestartingServices.size() > 0) {
3122 printed = false;
3123 for (int i=0; i<mRestartingServices.size(); i++) {
3124 ServiceRecord r = mRestartingServices.get(i);
3125 if (!matcher.match(r, r.name)) {
3126 continue;
3127 }
3128 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3129 continue;
3130 }
3131 printedAnything = true;
3132 if (!printed) {
3133 if (needSep) pw.println();
3134 needSep = true;
3135 pw.println(" Restarting services:");
3136 printed = true;
3137 }
3138 pw.print(" * Restarting "); pw.println(r);
3139 r.dump(pw, " ");
3140 }
3141 needSep = true;
3142 }
3143
3144 if (mDestroyingServices.size() > 0) {
3145 printed = false;
3146 for (int i=0; i< mDestroyingServices.size(); i++) {
3147 ServiceRecord r = mDestroyingServices.get(i);
3148 if (!matcher.match(r, r.name)) {
3149 continue;
3150 }
3151 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3152 continue;
3153 }
3154 printedAnything = true;
3155 if (!printed) {
3156 if (needSep) pw.println();
3157 needSep = true;
3158 pw.println(" Destroying services:");
3159 printed = true;
3160 }
3161 pw.print(" * Destroy "); pw.println(r);
3162 r.dump(pw, " ");
3163 }
3164 needSep = true;
3165 }
3166
3167 if (dumpAll) {
3168 printed = false;
3169 for (int ic=0; ic<mServiceConnections.size(); ic++) {
3170 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
3171 for (int i=0; i<r.size(); i++) {
3172 ConnectionRecord cr = r.get(i);
3173 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
3174 continue;
3175 }
3176 if (dumpPackage != null && (cr.binding.client == null
3177 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
3178 continue;
3179 }
3180 printedAnything = true;
3181 if (!printed) {
3182 if (needSep) pw.println();
3183 needSep = true;
3184 pw.println(" Connection bindings to services:");
3185 printed = true;
3186 }
3187 pw.print(" * "); pw.println(cr);
3188 cr.dump(pw, " ");
3189 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003190 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003191 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003192
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003193 if (!printedAnything) {
3194 pw.println(" (nothing)");
3195 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003196 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003197 }
3198
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003199 ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
3200 int opti, boolean dumpAll, String dumpPackage) {
3201 return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
3202 }
3203
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003204 /**
3205 * There are three ways to call this:
3206 * - no service specified: dump all the services
3207 * - a flattened component name that matched an existing service was specified as the
3208 * first arg: dump that one service
3209 * - the first arg isn't the flattened component name of an existing service:
3210 * dump all services whose component contains the first arg as a substring
3211 */
3212 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
3213 int opti, boolean dumpAll) {
3214 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
3215
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003216 synchronized (mAm) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003217 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003218 if ("all".equals(name)) {
3219 for (int user : users) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -07003220 ServiceMap smap = mServiceMap.get(user);
3221 if (smap == null) {
3222 continue;
3223 }
3224 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003225 for (int i=0; i<alls.size(); i++) {
3226 ServiceRecord r1 = alls.valueAt(i);
Amith Yamasani258848d2012-08-10 17:06:33 -07003227 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003228 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003229 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003230 } else {
3231 ComponentName componentName = name != null
3232 ? ComponentName.unflattenFromString(name) : null;
3233 int objectId = 0;
3234 if (componentName == null) {
3235 // Not a '/' separated full component name; maybe an object ID?
3236 try {
3237 objectId = Integer.parseInt(name, 16);
3238 name = null;
3239 componentName = null;
3240 } catch (RuntimeException e) {
3241 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003242 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003243
Dianne Hackborn1676c852012-09-10 14:52:30 -07003244 for (int user : users) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -07003245 ServiceMap smap = mServiceMap.get(user);
3246 if (smap == null) {
3247 continue;
3248 }
3249 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003250 for (int i=0; i<alls.size(); i++) {
3251 ServiceRecord r1 = alls.valueAt(i);
Amith Yamasani258848d2012-08-10 17:06:33 -07003252 if (componentName != null) {
3253 if (r1.name.equals(componentName)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003254 services.add(r1);
3255 }
Amith Yamasani258848d2012-08-10 17:06:33 -07003256 } else if (name != null) {
3257 if (r1.name.flattenToString().contains(name)) {
3258 services.add(r1);
3259 }
3260 } else if (System.identityHashCode(r1) == objectId) {
3261 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003262 }
3263 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003264 }
3265 }
3266 }
3267
3268 if (services.size() <= 0) {
3269 return false;
3270 }
3271
3272 boolean needSep = false;
3273 for (int i=0; i<services.size(); i++) {
3274 if (needSep) {
3275 pw.println();
3276 }
3277 needSep = true;
3278 dumpService("", fd, pw, services.get(i), args, dumpAll);
3279 }
3280 return true;
3281 }
3282
3283 /**
3284 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
3285 * there is a thread associated with the service.
3286 */
3287 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
3288 final ServiceRecord r, String[] args, boolean dumpAll) {
3289 String innerPrefix = prefix + " ";
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003290 synchronized (mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003291 pw.print(prefix); pw.print("SERVICE ");
3292 pw.print(r.shortName); pw.print(" ");
3293 pw.print(Integer.toHexString(System.identityHashCode(r)));
3294 pw.print(" pid=");
3295 if (r.app != null) pw.println(r.app.pid);
3296 else pw.println("(not running)");
3297 if (dumpAll) {
3298 r.dump(pw, innerPrefix);
3299 }
3300 }
3301 if (r.app != null && r.app.thread != null) {
3302 pw.print(prefix); pw.println(" Client:");
3303 pw.flush();
3304 try {
3305 TransferPipe tp = new TransferPipe();
3306 try {
3307 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
3308 tp.setBufferPrefix(prefix + " ");
3309 tp.go(fd);
3310 } finally {
3311 tp.kill();
3312 }
3313 } catch (IOException e) {
3314 pw.println(prefix + " Failure while dumping the service: " + e);
3315 } catch (RemoteException e) {
3316 pw.println(prefix + " Got a RemoteException while dumping the service");
3317 }
3318 }
3319 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003320}