blob: d741c494828060d7ae4680b74e88f9b50e6c9eaf [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 Hackborn599db5c2012-08-03 19:28:48 -0700346 NeededUriGrants neededGrants = mAm.checkGrantUriPermissionFromIntentLocked(
Nicolas Prevotc6cf95c2014-05-29 11:30:36 +0100347 callingUid, r.packageName, service, service.getFlags(), null, r.userId);
Svet Ganov9c165d72015-12-01 19:52:26 -0800348
349 // If permissions need a review before any of the app components can run,
350 // we do not start the service and launch a review activity if the calling app
351 // is in the foreground passing it a pending intent to start the service when
352 // review is completed.
353 if (Build.PERMISSIONS_REVIEW_REQUIRED) {
354 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage,
355 callingUid, service, callerFg, userId)) {
356 return null;
357 }
358 }
359
Dianne Hackbornd6f5b622013-11-11 17:25:37 -0800360 if (unscheduleServiceRestartLocked(r, callingUid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800361 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700362 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700363 r.lastActivity = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700364 r.startRequested = true;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700365 r.delayedStop = false;
366 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
367 service, neededGrants));
368
369 final ServiceMap smap = getServiceMap(r.userId);
370 boolean addToStarting = false;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700371 if (!callerFg && r.app == null
372 && mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700373 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700374 if (proc == null || proc.curProcState > ActivityManager.PROCESS_STATE_RECEIVER) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700375 // If this is not coming from a foreground caller, then we may want
376 // to delay the start if there are already other background services
377 // that are starting. This is to avoid process start spam when lots
378 // of applications are all handling things like connectivity broadcasts.
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700379 // We only do this for cached processes, because otherwise an application
380 // can have assumptions about calling startService() for a service to run
381 // in its own process, and for that process to not be killed before the
382 // service is started. This is especially the case for receivers, which
383 // may start a service in onReceive() to do some additional work and have
384 // initialized some global state as part of that.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800385 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
386 + r + " in " + proc);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700387 if (r.delayed) {
388 // This service is already scheduled for a delayed start; just leave
389 // it still waiting.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800390 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700391 return r.name;
392 }
393 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
394 // Something else is starting, delay!
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800395 Slog.i(TAG_SERVICE, "Delaying start of: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700396 smap.mDelayedStartList.add(r);
397 r.delayed = true;
398 return r.name;
399 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800400 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700401 addToStarting = true;
402 } else if (proc.curProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
403 // We slightly loosen when we will enqueue this new service as a background
404 // starting service we are waiting for, to also include processes that are
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700405 // currently running other services or receivers.
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700406 addToStarting = true;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800407 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
408 "Not delaying, but counting as bg: " + r);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800409 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn8e692572013-09-10 19:06:15 -0700410 StringBuilder sb = new StringBuilder(128);
411 sb.append("Not potential delay (state=").append(proc.curProcState)
412 .append(' ').append(proc.adjType);
413 String reason = proc.makeAdjReason();
414 if (reason != null) {
415 sb.append(' ');
416 sb.append(reason);
417 }
418 sb.append("): ");
419 sb.append(r.toString());
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800420 Slog.v(TAG_SERVICE, sb.toString());
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700421 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800422 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700423 if (callerFg) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800424 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700425 + callingUid + " pid=" + callingPid + "): " + r);
426 } else if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800427 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700428 } else {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800429 Slog.v(TAG_SERVICE,
430 "Not potential delay (user " + r.userId + " not started): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700431 }
432 }
433
434 return startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
435 }
436
Svet Ganov9c165d72015-12-01 19:52:26 -0800437 private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
438 String callingPackage, int callingUid, Intent service, boolean callerFg,
439 final int userId) {
440 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
441 r.packageName, r.userId)) {
442
443 // Show a permission review UI only for starting from a foreground app
444 if (!callerFg) {
445 Slog.w(TAG, "u" + r.userId + " Starting a service in package"
446 + r.packageName + " requires a permissions review");
447 return false;
448 }
449
450 IIntentSender target = mAm.getIntentSenderLocked(
451 ActivityManager.INTENT_SENDER_SERVICE, callingPackage,
452 callingUid, userId, null, null, 0, new Intent[]{service},
453 new String[]{service.resolveType(mAm.mContext.getContentResolver())},
454 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
455 | PendingIntent.FLAG_IMMUTABLE, null);
456
457 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
458 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
459 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
460 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
461 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
462
463 if (DEBUG_PERMISSIONS_REVIEW) {
464 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
465 + r.packageName);
466 }
467
468 mAm.mHandler.post(new Runnable() {
469 @Override
470 public void run() {
471 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
472 }
473 });
474
475 return false;
476 }
477
478 return true;
479 }
480
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700481 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
482 boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
Joe Onorato4eb64fd2016-03-21 15:30:09 -0700483 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700484 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700485 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700486 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700487 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700488 synchronized (r.stats.getBatteryStats()) {
489 r.stats.startRunningLocked();
490 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800491 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700492 if (error != null) {
493 return new ComponentName("!!", error);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700494 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700495
496 if (r.startRequested && addToStarting) {
497 boolean first = smap.mStartingBackground.size() == 0;
498 smap.mStartingBackground.add(r);
499 r.startingBgTimeout = SystemClock.uptimeMillis() + BG_START_TIMEOUT;
500 if (DEBUG_DELAYED_SERVICE) {
501 RuntimeException here = new RuntimeException("here");
502 here.fillInStackTrace();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800503 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800504 } else if (DEBUG_DELAYED_STARTS) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800505 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700506 }
507 if (first) {
508 smap.rescheduleDelayedStarts();
509 }
510 } else if (callerFg) {
511 smap.ensureNotStartingBackground(r);
512 }
513
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700514 return r.name;
515 }
516
517 private void stopServiceLocked(ServiceRecord service) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700518 if (service.delayed) {
519 // If service isn't actually running, but is is being held in the
520 // delayed list, then we need to keep it started but note that it
521 // should be stopped once no longer delayed.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800522 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700523 service.delayedStop = true;
524 return;
525 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700526 synchronized (service.stats.getBatteryStats()) {
527 service.stats.stopRunningLocked();
528 }
529 service.startRequested = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700530 if (service.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700531 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700532 SystemClock.uptimeMillis());
533 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700534 service.callStart = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700535 bringDownServiceIfNeededLocked(service, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700536 }
537
538 int stopServiceLocked(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700539 String resolvedType, int userId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800540 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700541 + " type=" + resolvedType);
542
543 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
544 if (caller != null && callerApp == null) {
545 throw new SecurityException(
546 "Unable to find app for caller " + caller
547 + " (pid=" + Binder.getCallingPid()
548 + ") when stopping service " + service);
549 }
550
551 // If this service is active, make sure it is stopped.
Svet Ganov99b60432015-06-27 13:15:22 -0700552 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, null,
Robert Sesekb9a86662015-12-09 16:22:45 -0500553 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700554 if (r != null) {
555 if (r.record != null) {
556 final long origId = Binder.clearCallingIdentity();
557 try {
558 stopServiceLocked(r.record);
559 } finally {
560 Binder.restoreCallingIdentity(origId);
561 }
562 return 1;
563 }
564 return -1;
565 }
566
567 return 0;
568 }
569
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700570 void stopInBackgroundLocked(int uid) {
571 // Stop all services associated with this uid due to it going to the background
572 // stopped state.
573 ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
574 ArrayList<ServiceRecord> stopping = null;
575 if (services != null) {
576 for (int i=services.mServicesByName.size()-1; i>=0; i--) {
577 ServiceRecord service = services.mServicesByName.valueAt(i);
578 if (service.appInfo.uid == uid && service.startRequested) {
579 if (mAm.mAppOpsService.noteOperation(AppOpsManager.OP_RUN_IN_BACKGROUND,
580 uid, service.packageName) != AppOpsManager.MODE_ALLOWED) {
581 if (stopping == null) {
582 stopping = new ArrayList<>();
583 stopping.add(service);
584 }
585 }
586 }
587 }
588 if (stopping != null) {
589 for (int i=stopping.size()-1; i>=0; i--) {
590 ServiceRecord service = stopping.get(i);
591 service.delayed = false;
592 services.ensureNotStartingBackground(service);
593 stopServiceLocked(service);
594 }
595 }
596 }
597 }
598
Svet Ganov99b60432015-06-27 13:15:22 -0700599 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
600 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, callingPackage,
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -0700601 Binder.getCallingPid(), Binder.getCallingUid(),
Robert Sesekb9a86662015-12-09 16:22:45 -0500602 UserHandle.getCallingUserId(), false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700603
604 IBinder ret = null;
605 if (r != null) {
606 // r.record is null if findServiceLocked() failed the caller permission check
607 if (r.record == null) {
608 throw new SecurityException(
Christopher Desjardins5862c5f2015-05-19 11:25:40 +0000609 "Permission Denial: Accessing service"
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700610 + " from pid=" + Binder.getCallingPid()
611 + ", uid=" + Binder.getCallingUid()
612 + " requires " + r.permission);
613 }
614 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
615 if (ib != null) {
616 ret = ib.binder;
617 }
618 }
619
620 return ret;
621 }
622
623 boolean stopServiceTokenLocked(ComponentName className, IBinder token,
624 int startId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800625 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700626 + " " + token + " startId=" + startId);
Dianne Hackborn41203752012-08-31 14:05:51 -0700627 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700628 if (r != null) {
629 if (startId >= 0) {
630 // Asked to only stop if done with all work. Note that
631 // to avoid leaks, we will take this as dropping all
632 // start items up to and including this one.
633 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
634 if (si != null) {
635 while (r.deliveredStarts.size() > 0) {
636 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
637 cur.removeUriPermissionsLocked();
638 if (cur == si) {
639 break;
640 }
641 }
642 }
643
644 if (r.getLastStartId() != startId) {
645 return false;
646 }
647
648 if (r.deliveredStarts.size() > 0) {
649 Slog.w(TAG, "stopServiceToken startId " + startId
650 + " is last, but have " + r.deliveredStarts.size()
651 + " remaining args");
652 }
653 }
654
655 synchronized (r.stats.getBatteryStats()) {
656 r.stats.stopRunningLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700657 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700658 r.startRequested = false;
659 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700660 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700661 SystemClock.uptimeMillis());
662 }
663 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700664 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700665 bringDownServiceIfNeededLocked(r, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700666 Binder.restoreCallingIdentity(origId);
667 return true;
668 }
669 return false;
670 }
671
672 public void setServiceForegroundLocked(ComponentName className, IBinder token,
673 int id, Notification notification, boolean removeNotification) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700674 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700675 final long origId = Binder.clearCallingIdentity();
676 try {
Dianne Hackborn41203752012-08-31 14:05:51 -0700677 ServiceRecord r = findServiceLocked(className, token, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700678 if (r != null) {
679 if (id != 0) {
680 if (notification == null) {
681 throw new IllegalArgumentException("null notification");
682 }
683 if (r.foregroundId != id) {
684 r.cancelNotification();
685 r.foregroundId = id;
686 }
687 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
688 r.foregroundNoti = notification;
689 r.isForeground = true;
690 r.postNotification();
691 if (r.app != null) {
692 updateServiceForegroundLocked(r.app, true);
693 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700694 getServiceMap(r.userId).ensureNotStartingBackground(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700695 } else {
696 if (r.isForeground) {
697 r.isForeground = false;
698 if (r.app != null) {
Dianne Hackborndb926082013-10-31 16:32:44 -0700699 mAm.updateLruProcessLocked(r.app, false, null);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700700 updateServiceForegroundLocked(r.app, true);
701 }
702 }
703 if (removeNotification) {
704 r.cancelNotification();
705 r.foregroundId = 0;
706 r.foregroundNoti = null;
Dianne Hackborn955d8d62014-10-07 20:17:19 -0700707 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
Christoph Studer365e4c32014-09-18 20:35:36 +0200708 r.stripForegroundServiceFlagFromNotification();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700709 }
710 }
711 }
712 } finally {
713 Binder.restoreCallingIdentity(origId);
714 }
715 }
716
717 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
718 boolean anyForeground = false;
Dianne Hackbornc8230512013-07-13 21:32:12 -0700719 for (int i=proc.services.size()-1; i>=0; i--) {
720 ServiceRecord sr = proc.services.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700721 if (sr.isForeground) {
722 anyForeground = true;
723 break;
724 }
725 }
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800726 mAm.updateProcessForegroundLocked(proc, anyForeground, oomAdj);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700727 }
728
Dianne Hackborn465fa392014-09-14 14:21:18 -0700729 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
730 ArraySet<ProcessRecord> updatedProcesses = null;
731 for (int i=0; i<clientProc.connections.size(); i++) {
732 final ConnectionRecord conn = clientProc.connections.valueAt(i);
733 final ProcessRecord proc = conn.binding.service.app;
734 if (proc == null || proc == clientProc) {
735 continue;
736 } else if (updatedProcesses == null) {
737 updatedProcesses = new ArraySet<>();
738 } else if (updatedProcesses.contains(proc)) {
739 continue;
740 }
741 updatedProcesses.add(proc);
742 updateServiceClientActivitiesLocked(proc, null, false);
743 }
744 }
745
Dianne Hackborndb926082013-10-31 16:32:44 -0700746 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
Dianne Hackborn465fa392014-09-14 14:21:18 -0700747 ConnectionRecord modCr, boolean updateLru) {
Dianne Hackborndb926082013-10-31 16:32:44 -0700748 if (modCr != null && modCr.binding.client != null) {
749 if (modCr.binding.client.activities.size() <= 0) {
750 // This connection is from a client without activities, so adding
751 // and removing is not interesting.
752 return false;
753 }
754 }
755
756 boolean anyClientActivities = false;
757 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
758 ServiceRecord sr = proc.services.valueAt(i);
759 for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) {
760 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni);
761 for (int cri=clist.size()-1; cri>=0; cri--) {
762 ConnectionRecord cr = clist.get(cri);
763 if (cr.binding.client == null || cr.binding.client == proc) {
764 // Binding to ourself is not interesting.
765 continue;
766 }
767 if (cr.binding.client.activities.size() > 0) {
768 anyClientActivities = true;
769 break;
770 }
771 }
772 }
773 }
774 if (anyClientActivities != proc.hasClientActivities) {
775 proc.hasClientActivities = anyClientActivities;
Dianne Hackborn465fa392014-09-14 14:21:18 -0700776 if (updateLru) {
777 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
778 }
Dianne Hackborndb926082013-10-31 16:32:44 -0700779 return true;
780 }
781 return false;
782 }
783
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700784 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
Svet Ganov9c165d72015-12-01 19:52:26 -0800785 String resolvedType, final IServiceConnection connection, int flags,
786 String callingPackage, final int userId) throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800787 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700788 + " type=" + resolvedType + " conn=" + connection.asBinder()
789 + " flags=0x" + Integer.toHexString(flags));
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700790 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
791 if (callerApp == null) {
792 throw new SecurityException(
793 "Unable to find app for caller " + caller
794 + " (pid=" + Binder.getCallingPid()
795 + ") when binding service " + service);
796 }
797
798 ActivityRecord activity = null;
799 if (token != null) {
Craig Mautnerd2328952013-03-05 12:46:26 -0800800 activity = ActivityRecord.isInStackLocked(token);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700801 if (activity == null) {
802 Slog.w(TAG, "Binding with unknown activity: " + token);
803 return 0;
804 }
805 }
806
807 int clientLabel = 0;
808 PendingIntent clientIntent = null;
809
810 if (callerApp.info.uid == Process.SYSTEM_UID) {
811 // Hacky kind of thing -- allow system stuff to tell us
812 // what they are, so we can report this elsewhere for
813 // others to know why certain services are running.
Jeff Sharkeyf0ec2e02016-03-21 12:37:54 -0600814 service.setDefusable(true);
815 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700816 if (clientIntent != null) {
817 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
818 if (clientLabel != 0) {
819 // There are no useful extras in the intent, trash them.
820 // System code calling with this stuff just needs to know
821 // this will happen.
822 service = service.cloneFilter();
823 }
824 }
825 }
826
Dianne Hackbornf0f94d12014-03-17 16:04:21 -0700827 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
828 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
829 "BIND_TREAT_LIKE_ACTIVITY");
830 }
831
Dianne Hackborna49ad092016-03-03 13:39:10 -0800832 final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Robert Sesekb9a86662015-12-09 16:22:45 -0500833 final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700834
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700835 ServiceLookupResult res =
Robert Sesekb9a86662015-12-09 16:22:45 -0500836 retrieveServiceLocked(service, resolvedType, callingPackage, Binder.getCallingPid(),
837 Binder.getCallingUid(), userId, true, callerFg, isBindExternal);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700838 if (res == null) {
839 return 0;
840 }
841 if (res.record == null) {
842 return -1;
843 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700844 ServiceRecord s = res.record;
845
Svet Ganov9c165d72015-12-01 19:52:26 -0800846 boolean permissionsReviewRequired = false;
847
848 // If permissions need a review before any of the app components can run,
849 // we schedule binding to the service but do not start its process, then
850 // we launch a review activity to which is passed a callback to invoke
851 // when done to start the bound service's process to completing the binding.
852 if (Build.PERMISSIONS_REVIEW_REQUIRED) {
853 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
854 s.packageName, s.userId)) {
855
856 permissionsReviewRequired = true;
857
858 // Show a permission review UI only for binding from a foreground app
859 if (!callerFg) {
860 Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
861 + s.packageName + " requires a permissions review");
862 return 0;
863 }
864
865 final ServiceRecord serviceRecord = s;
866 final Intent serviceIntent = service;
867
868 RemoteCallback callback = new RemoteCallback(
869 new RemoteCallback.OnResultListener() {
870 @Override
871 public void onResult(Bundle result) {
872 synchronized(mAm) {
873 final long identity = Binder.clearCallingIdentity();
874 try {
875 if (!mPendingServices.contains(serviceRecord)) {
876 return;
877 }
878 // If there is still a pending record, then the service
879 // binding request is still valid, so hook them up. We
880 // proceed only if the caller cleared the review requirement
881 // otherwise we unbind because the user didn't approve.
882 if (!mAm.getPackageManagerInternalLocked()
883 .isPermissionsReviewRequired(
884 serviceRecord.packageName,
885 serviceRecord.userId)) {
886 try {
887 bringUpServiceLocked(serviceRecord,
888 serviceIntent.getFlags(),
889 callerFg, false, false);
890 } catch (RemoteException e) {
891 /* ignore - local call */
892 }
893 } else {
894 unbindServiceLocked(connection);
895 }
896 } finally {
897 Binder.restoreCallingIdentity(identity);
898 }
899 }
900 }
901 });
902
903 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
904 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
905 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
906 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
907 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
908
909 if (DEBUG_PERMISSIONS_REVIEW) {
910 Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
911 + s.packageName);
912 }
913
914 mAm.mHandler.post(new Runnable() {
915 @Override
916 public void run() {
917 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
918 }
919 });
920 }
921 }
922
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700923 final long origId = Binder.clearCallingIdentity();
924
925 try {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -0800926 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800927 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700928 + s);
929 }
930
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700931 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
932 s.lastActivity = SystemClock.uptimeMillis();
933 if (!s.hasAutoCreateConnections()) {
934 // This is the first binding, let the tracker know.
Joe Onorato4eb64fd2016-03-21 15:30:09 -0700935 ServiceState stracker = s.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700936 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700937 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700938 s.lastActivity);
939 }
940 }
941 }
942
Joe Onorato05c9ecc2016-03-30 15:13:46 -0700943 mAm.startAssociationLocked(callerApp.uid, callerApp.processName, callerApp.curProcState,
Dianne Hackbornab2df062015-01-07 13:43:13 -0800944 s.appInfo.uid, s.name, s.processName);
945
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700946 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
947 ConnectionRecord c = new ConnectionRecord(b, activity,
948 connection, flags, clientLabel, clientIntent);
949
950 IBinder binder = connection.asBinder();
951 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
952 if (clist == null) {
953 clist = new ArrayList<ConnectionRecord>();
954 s.connections.put(binder, clist);
955 }
956 clist.add(c);
957 b.connections.add(c);
958 if (activity != null) {
959 if (activity.connections == null) {
960 activity.connections = new HashSet<ConnectionRecord>();
961 }
962 activity.connections.add(c);
963 }
964 b.client.connections.add(c);
965 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
966 b.client.hasAboveClient = true;
967 }
Dianne Hackborndb926082013-10-31 16:32:44 -0700968 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -0700969 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -0700970 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700971 clist = mServiceConnections.get(binder);
972 if (clist == null) {
973 clist = new ArrayList<ConnectionRecord>();
974 mServiceConnections.put(binder, clist);
975 }
976 clist.add(c);
977
978 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
979 s.lastActivity = SystemClock.uptimeMillis();
Svet Ganov9c165d72015-12-01 19:52:26 -0800980 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
981 permissionsReviewRequired) != null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700982 return 0;
983 }
984 }
985
986 if (s.app != null) {
Dianne Hackbornf0f94d12014-03-17 16:04:21 -0700987 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
988 s.app.treatLikeActivity = true;
989 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700990 // This could have made the service more important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -0700991 mAm.updateLruProcessLocked(s.app, s.app.hasClientActivities
992 || s.app.treatLikeActivity, b.client);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700993 mAm.updateOomAdjLocked(s.app);
994 }
995
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800996 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700997 + ": received=" + b.intent.received
998 + " apps=" + b.intent.apps.size()
999 + " doRebind=" + b.intent.doRebind);
1000
1001 if (s.app != null && b.intent.received) {
1002 // Service is already running, so we can immediately
1003 // publish the connection.
1004 try {
1005 c.conn.connected(s.name, b.intent.binder);
1006 } catch (Exception e) {
1007 Slog.w(TAG, "Failure sending service " + s.shortName
1008 + " to connection " + c.conn.asBinder()
1009 + " (in " + c.binding.client.processName + ")", e);
1010 }
1011
1012 // If this is the first app connected back to this binding,
1013 // and the service had previously asked to be told when
1014 // rebound, then do so.
1015 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001016 requestServiceBindingLocked(s, b.intent, callerFg, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001017 }
1018 } else if (!b.intent.requested) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001019 requestServiceBindingLocked(s, b.intent, callerFg, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001020 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001021
1022 getServiceMap(s.userId).ensureNotStartingBackground(s);
1023
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001024 } finally {
1025 Binder.restoreCallingIdentity(origId);
1026 }
1027
1028 return 1;
1029 }
1030
Svet Ganov9c165d72015-12-01 19:52:26 -08001031 private void foo() {
1032
1033 }
1034
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001035 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
1036 final long origId = Binder.clearCallingIdentity();
1037 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001038 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001039 + " " + intent + ": " + service);
1040 if (r != null) {
1041 Intent.FilterComparison filter
1042 = new Intent.FilterComparison(intent);
1043 IntentBindRecord b = r.bindings.get(filter);
1044 if (b != null && !b.received) {
1045 b.binder = service;
1046 b.requested = true;
1047 b.received = true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07001048 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1049 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
1050 for (int i=0; i<clist.size(); i++) {
1051 ConnectionRecord c = clist.get(i);
1052 if (!filter.equals(c.binding.intent.intent)) {
1053 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001054 TAG_SERVICE, "Not publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001055 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001056 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001057 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001058 TAG_SERVICE, "Published intent: " + intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001059 continue;
1060 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001061 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001062 try {
1063 c.conn.connected(r.name, service);
1064 } catch (Exception e) {
1065 Slog.w(TAG, "Failure sending service " + r.name +
1066 " to connection " + c.conn.asBinder() +
1067 " (in " + c.binding.client.processName + ")", e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001068 }
1069 }
1070 }
1071 }
1072
Dianne Hackborn164371f2013-10-01 19:10:13 -07001073 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001074 }
1075 } finally {
1076 Binder.restoreCallingIdentity(origId);
1077 }
1078 }
1079
1080 boolean unbindServiceLocked(IServiceConnection connection) {
1081 IBinder binder = connection.asBinder();
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001082 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001083 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1084 if (clist == null) {
1085 Slog.w(TAG, "Unbind failed: could not find connection for "
1086 + connection.asBinder());
1087 return false;
1088 }
1089
1090 final long origId = Binder.clearCallingIdentity();
1091 try {
1092 while (clist.size() > 0) {
1093 ConnectionRecord r = clist.get(0);
1094 removeConnectionLocked(r, null, null);
Dianne Hackborn25e1eca2014-09-23 10:13:13 -07001095 if (clist.size() > 0 && clist.get(0) == r) {
1096 // In case it didn't get removed above, do it now.
1097 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
1098 clist.remove(0);
1099 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001100
1101 if (r.binding.service.app != null) {
1102 // This could have made the service less important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001103 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1104 r.binding.service.app.treatLikeActivity = true;
1105 mAm.updateLruProcessLocked(r.binding.service.app,
1106 r.binding.service.app.hasClientActivities
1107 || r.binding.service.app.treatLikeActivity, null);
1108 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001109 mAm.updateOomAdjLocked(r.binding.service.app);
1110 }
1111 }
1112 } finally {
1113 Binder.restoreCallingIdentity(origId);
1114 }
1115
1116 return true;
1117 }
1118
1119 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
1120 final long origId = Binder.clearCallingIdentity();
1121 try {
1122 if (r != null) {
1123 Intent.FilterComparison filter
1124 = new Intent.FilterComparison(intent);
1125 IntentBindRecord b = r.bindings.get(filter);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001126 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001127 + " at " + b + ": apps="
1128 + (b != null ? b.apps.size() : 0));
1129
Dianne Hackborn164371f2013-10-01 19:10:13 -07001130 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001131 if (b != null) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001132 if (b.apps.size() > 0 && !inDestroying) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001133 // Applications have already bound since the last
1134 // unbind, so just rebind right here.
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001135 boolean inFg = false;
1136 for (int i=b.apps.size()-1; i>=0; i--) {
1137 ProcessRecord client = b.apps.valueAt(i).client;
1138 if (client != null && client.setSchedGroup
Dianne Hackborna49ad092016-03-03 13:39:10 -08001139 != ProcessList.SCHED_GROUP_BACKGROUND) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001140 inFg = true;
1141 break;
1142 }
1143 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001144 try {
1145 requestServiceBindingLocked(r, b, inFg, true);
1146 } catch (TransactionTooLargeException e) {
1147 // Don't pass this back to ActivityThread, it's unrelated.
1148 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001149 } else {
1150 // Note to tell the service the next time there is
1151 // a new client.
1152 b.doRebind = true;
1153 }
1154 }
1155
Dianne Hackborn164371f2013-10-01 19:10:13 -07001156 serviceDoneExecutingLocked(r, inDestroying, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001157 }
1158 } finally {
1159 Binder.restoreCallingIdentity(origId);
1160 }
1161 }
1162
1163 private final ServiceRecord findServiceLocked(ComponentName name,
Dianne Hackborn41203752012-08-31 14:05:51 -07001164 IBinder token, int userId) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001165 ServiceRecord r = getServiceByName(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001166 return r == token ? r : null;
1167 }
1168
1169 private final class ServiceLookupResult {
1170 final ServiceRecord record;
1171 final String permission;
1172
1173 ServiceLookupResult(ServiceRecord _record, String _permission) {
1174 record = _record;
1175 permission = _permission;
1176 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001177 }
1178
1179 private class ServiceRestarter implements Runnable {
1180 private ServiceRecord mService;
1181
1182 void setService(ServiceRecord service) {
1183 mService = service;
1184 }
1185
1186 public void run() {
1187 synchronized(mAm) {
1188 performServiceRestartLocked(mService);
1189 }
1190 }
1191 }
1192
1193 private ServiceLookupResult retrieveServiceLocked(Intent service,
Svet Ganov99b60432015-06-27 13:15:22 -07001194 String resolvedType, String callingPackage, int callingPid, int callingUid, int userId,
Robert Sesekb9a86662015-12-09 16:22:45 -05001195 boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001196 ServiceRecord r = null;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001197 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001198 + " type=" + resolvedType + " callingUid=" + callingUid);
1199
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001200 userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
1201 ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE, "service", null);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001202
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001203 ServiceMap smap = getServiceMap(userId);
1204 final ComponentName comp = service.getComponent();
1205 if (comp != null) {
1206 r = smap.mServicesByName.get(comp);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001207 }
Robert Sesekb9a86662015-12-09 16:22:45 -05001208 if (r == null && !isBindExternal) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001209 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001210 r = smap.mServicesByIntent.get(filter);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001211 }
Robert Sesekb9a86662015-12-09 16:22:45 -05001212 if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
1213 && !callingPackage.equals(r.packageName)) {
1214 // If an external service is running within its own package, other packages
1215 // should not bind to that instance.
1216 r = null;
1217 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001218 if (r == null) {
1219 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001220 // TODO: come back and remove this assumption to triage all services
1221 ResolveInfo rInfo = AppGlobals.getPackageManager().resolveService(service,
1222 resolvedType, ActivityManagerService.STOCK_PM_FLAGS
1223 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1224 userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001225 ServiceInfo sInfo =
1226 rInfo != null ? rInfo.serviceInfo : null;
1227 if (sInfo == null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001228 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001229 ": not found");
1230 return null;
1231 }
1232 ComponentName name = new ComponentName(
1233 sInfo.applicationInfo.packageName, sInfo.name);
Robert Sesekb9a86662015-12-09 16:22:45 -05001234 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
1235 if (isBindExternal) {
1236 if (!sInfo.exported) {
1237 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1238 " is not exported");
1239 }
1240 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
1241 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1242 " is not an isolatedProcess");
1243 }
1244 // Run the service under the calling package's application.
1245 ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
1246 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
1247 if (aInfo == null) {
1248 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
1249 "could not resolve client package " + callingPackage);
1250 }
1251 sInfo = new ServiceInfo(sInfo);
1252 sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
1253 sInfo.applicationInfo.packageName = aInfo.packageName;
1254 sInfo.applicationInfo.uid = aInfo.uid;
1255 name = new ComponentName(aInfo.packageName, name.getClassName());
1256 service.setComponent(name);
1257 } else {
1258 throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
1259 name);
1260 }
1261 } else if (isBindExternal) {
1262 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1263 " is not an externalService");
1264 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001265 if (userId > 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001266 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
Amith Yamasani4b9d79c2014-05-21 19:14:21 -07001267 sInfo.name, sInfo.flags)
1268 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001269 userId = 0;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001270 smap = getServiceMap(0);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001271 }
1272 sInfo = new ServiceInfo(sInfo);
1273 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
1274 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001275 r = smap.mServicesByName.get(name);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001276 if (r == null && createIfNeeded) {
Amith Yamasani8fb0e192015-11-18 10:56:04 -08001277 final long token = Binder.clearCallingIdentity();
1278 try {
1279 // Before going further -- if this app is not allowed to run in the
1280 // background, then at this point we aren't going to let it period.
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001281 final int allowed = mAm.checkAllowBackgroundLocked(
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001282 sInfo.applicationInfo.uid, sInfo.packageName, callingPid, true);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001283 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
Amith Yamasani8fb0e192015-11-18 10:56:04 -08001284 Slog.w(TAG, "Background execution not allowed: service "
Dianne Hackborn03a25bd2016-01-06 17:52:05 -08001285 + service + " to " + name.flattenToShortString()
Amith Yamasani8fb0e192015-11-18 10:56:04 -08001286 + " from pid=" + callingPid + " uid=" + callingUid
1287 + " pkg=" + callingPackage);
1288 return null;
1289 }
1290 } finally {
1291 Binder.restoreCallingIdentity(token);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001292 }
1293
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001294 Intent.FilterComparison filter
1295 = new Intent.FilterComparison(service.cloneFilter());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001296 ServiceRestarter res = new ServiceRestarter();
1297 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
1298 BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
1299 synchronized (stats) {
1300 ss = stats.getServiceStatsLocked(
1301 sInfo.applicationInfo.uid, sInfo.packageName,
1302 sInfo.name);
1303 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001304 r = new ServiceRecord(mAm, ss, name, filter, sInfo, callingFromFg, res);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001305 res.setService(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001306 smap.mServicesByName.put(name, r);
1307 smap.mServicesByIntent.put(filter, r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001308
1309 // Make sure this component isn't in the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001310 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001311 ServiceRecord pr = mPendingServices.get(i);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001312 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
1313 && pr.name.equals(name)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001314 mPendingServices.remove(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001315 }
1316 }
1317 }
1318 } catch (RemoteException ex) {
1319 // pm is in same process, this will never happen.
1320 }
1321 }
1322 if (r != null) {
1323 if (mAm.checkComponentPermission(r.permission,
1324 callingPid, callingUid, r.appInfo.uid, r.exported)
1325 != PackageManager.PERMISSION_GRANTED) {
1326 if (!r.exported) {
1327 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1328 + " from pid=" + callingPid
1329 + ", uid=" + callingUid
1330 + " that is not exported from uid " + r.appInfo.uid);
1331 return new ServiceLookupResult(null, "not exported from uid "
1332 + r.appInfo.uid);
1333 }
1334 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1335 + " from pid=" + callingPid
1336 + ", uid=" + callingUid
1337 + " requires " + r.permission);
1338 return new ServiceLookupResult(null, r.permission);
Svet Ganov99b60432015-06-27 13:15:22 -07001339 } else if (r.permission != null && callingPackage != null) {
1340 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
1341 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation(
1342 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
1343 Slog.w(TAG, "Appop Denial: Accessing service " + r.name
1344 + " from pid=" + callingPid
1345 + ", uid=" + callingUid
1346 + " requires appop " + AppOpsManager.opToName(opCode));
1347 return null;
1348 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001349 }
Svet Ganov99b60432015-06-27 13:15:22 -07001350
Ben Gruverf5323fe2013-07-31 15:09:51 -07001351 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
1352 resolvedType, r.appInfo)) {
Ben Gruverb6223792013-07-29 16:35:40 -07001353 return null;
1354 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001355 return new ServiceLookupResult(r, null);
1356 }
1357 return null;
1358 }
1359
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001360 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001361 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001362 + why + " of " + r + " in app " + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001363 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001364 + why + " of " + r.shortName);
1365 long now = SystemClock.uptimeMillis();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001366 if (r.executeNesting == 0) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001367 r.executeFg = fg;
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001368 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001369 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001370 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001371 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001372 if (r.app != null) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001373 r.app.executingServices.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001374 r.app.execServicesFg |= fg;
Dianne Hackborn2be00932013-09-22 16:46:00 -07001375 if (r.app.executingServices.size() == 1) {
1376 scheduleServiceTimeoutLocked(r.app);
1377 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001378 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001379 } else if (r.app != null && fg && !r.app.execServicesFg) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001380 r.app.execServicesFg = true;
Dianne Hackborn2be00932013-09-22 16:46:00 -07001381 scheduleServiceTimeoutLocked(r.app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001382 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001383 r.executeFg |= fg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001384 r.executeNesting++;
1385 r.executingStart = now;
1386 }
1387
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001388 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
1389 boolean execInFg, boolean rebind) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001390 if (r.app == null || r.app.thread == null) {
1391 // If service is not currently running, can't yet bind.
1392 return false;
1393 }
1394 if ((!i.requested || rebind) && i.apps.size() > 0) {
1395 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001396 bumpServiceExecutingLocked(r, execInFg, "bind");
Dianne Hackborna413dc02013-07-12 12:02:55 -07001397 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
1398 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
1399 r.app.repProcState);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001400 if (!rebind) {
1401 i.requested = true;
1402 }
1403 i.hasBound = true;
1404 i.doRebind = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001405 } catch (TransactionTooLargeException e) {
1406 // Keep the executeNesting count accurate.
1407 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
1408 final boolean inDestroying = mDestroyingServices.contains(r);
1409 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
1410 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001411 } catch (RemoteException e) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001412 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001413 // Keep the executeNesting count accurate.
1414 final boolean inDestroying = mDestroyingServices.contains(r);
1415 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001416 return false;
1417 }
1418 }
1419 return true;
1420 }
1421
1422 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
1423 boolean allowCancel) {
1424 boolean canceled = false;
1425
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001426 ServiceMap smap = getServiceMap(r.userId);
1427 if (smap.mServicesByName.get(r.name) != r) {
1428 ServiceRecord cur = smap.mServicesByName.get(r.name);
1429 Slog.wtf(TAG, "Attempting to schedule restart of " + r
1430 + " when found in map: " + cur);
1431 return false;
1432 }
1433
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001434 final long now = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001435
1436 if ((r.serviceInfo.applicationInfo.flags
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001437 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
1438 long minDuration = SERVICE_RESTART_DURATION;
1439 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001440
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001441 // Any delivered but not yet finished starts should be put back
1442 // on the pending list.
1443 final int N = r.deliveredStarts.size();
1444 if (N > 0) {
1445 for (int i=N-1; i>=0; i--) {
1446 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
1447 si.removeUriPermissionsLocked();
1448 if (si.intent == null) {
1449 // We'll generate this again if needed.
1450 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
1451 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
1452 r.pendingStarts.add(0, si);
1453 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
1454 dur *= 2;
1455 if (minDuration < dur) minDuration = dur;
1456 if (resetTime < dur) resetTime = dur;
1457 } else {
1458 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
1459 + r.name);
1460 canceled = true;
1461 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001462 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001463 r.deliveredStarts.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001464 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001465
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001466 r.totalRestartCount++;
1467 if (r.restartDelay == 0) {
1468 r.restartCount++;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001469 r.restartDelay = minDuration;
1470 } else {
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001471 // If it has been a "reasonably long time" since the service
1472 // was started, then reset our restart duration back to
1473 // the beginning, so we don't infinitely increase the duration
1474 // on a service that just occasionally gets killed (which is
1475 // a normal case, due to process being killed to reclaim memory).
1476 if (now > (r.restartTime+resetTime)) {
1477 r.restartCount = 1;
1478 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001479 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07001480 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
1481 if (r.restartDelay < minDuration) {
1482 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001483 }
1484 }
1485 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001486
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001487 r.nextRestartTime = now + r.restartDelay;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001488
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001489 // Make sure that we don't end up restarting a bunch of services
1490 // all at the same time.
1491 boolean repeat;
1492 do {
1493 repeat = false;
1494 for (int i=mRestartingServices.size()-1; i>=0; i--) {
1495 ServiceRecord r2 = mRestartingServices.get(i);
1496 if (r2 != r && r.nextRestartTime
1497 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
1498 && r.nextRestartTime
1499 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
1500 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
1501 r.restartDelay = r.nextRestartTime - now;
1502 repeat = true;
1503 break;
1504 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001505 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001506 } while (repeat);
1507
1508 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07001509 // Persistent processes are immediately restarted, so there is no
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001510 // reason to hold of on restarting their services.
1511 r.totalRestartCount++;
1512 r.restartCount = 0;
1513 r.restartDelay = 0;
1514 r.nextRestartTime = now;
1515 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001516
1517 if (!mRestartingServices.contains(r)) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001518 r.createdFromFg = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001519 mRestartingServices.add(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001520 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001521 }
1522
1523 r.cancelNotification();
1524
1525 mAm.mHandler.removeCallbacks(r.restarter);
1526 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
1527 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
1528 Slog.w(TAG, "Scheduling restart of crashed service "
1529 + r.shortName + " in " + r.restartDelay + "ms");
1530 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001531 r.userId, r.shortName, r.restartDelay);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001532
1533 return canceled;
1534 }
1535
1536 final void performServiceRestartLocked(ServiceRecord r) {
1537 if (!mRestartingServices.contains(r)) {
1538 return;
1539 }
Dianne Hackborn865907d2015-10-21 17:12:53 -07001540 if (!isServiceNeeded(r, false, false)) {
1541 // Paranoia: is this service actually needed? In theory a service that is not
1542 // needed should never remain on the restart list. In practice... well, there
1543 // have been bugs where this happens, and bad things happen because the process
1544 // ends up just being cached, so quickly killed, then restarted again and again.
1545 // Let's not let that happen.
1546 Slog.wtf(TAG, "Restarting service that is not needed: " + r);
1547 return;
1548 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001549 try {
Svet Ganov9c165d72015-12-01 19:52:26 -08001550 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001551 } catch (TransactionTooLargeException e) {
1552 // Ignore, it's been logged and nothing upstack cares.
1553 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001554 }
1555
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001556 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
1557 boolean force) {
1558 if (!force && r.restartDelay == 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001559 return false;
1560 }
Dianne Hackborn7b492722013-11-01 09:58:45 -07001561 // Remove from the restarting list; if the service is currently on the
1562 // restarting list, or the call is coming from another app, then this
1563 // service has become of much more interest so we reset the restart interval.
1564 boolean removed = mRestartingServices.remove(r);
1565 if (removed || callingUid != r.appInfo.uid) {
1566 r.resetRestartCounter();
1567 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001568 if (removed) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001569 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001570 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001571 mAm.mHandler.removeCallbacks(r.restarter);
1572 return true;
1573 }
1574
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001575 private void clearRestartingIfNeededLocked(ServiceRecord r) {
1576 if (r.restartTracker != null) {
1577 // If this is the last restarting record with this tracker, then clear
1578 // the tracker's restarting state.
1579 boolean stillTracking = false;
1580 for (int i=mRestartingServices.size()-1; i>=0; i--) {
1581 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
1582 stillTracking = true;
1583 break;
1584 }
1585 }
1586 if (!stillTracking) {
1587 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
1588 SystemClock.uptimeMillis());
1589 r.restartTracker = null;
1590 }
1591 }
1592 }
1593
Svet Ganov9c165d72015-12-01 19:52:26 -08001594 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
1595 boolean whileRestarting, boolean permissionsReviewRequired)
1596 throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001597 //Slog.i(TAG, "Bring up service:");
1598 //r.dump(" ");
1599
1600 if (r.app != null && r.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001601 sendServiceArgsLocked(r, execInFg, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001602 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001603 }
1604
1605 if (!whileRestarting && r.restartDelay > 0) {
1606 // If waiting for a restart, then do nothing.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001607 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001608 }
1609
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001610 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001611
1612 // We are now bringing the service up, so no longer in the
1613 // restarting state.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001614 if (mRestartingServices.remove(r)) {
chad7158ea22014-12-21 15:43:01 +08001615 r.resetRestartCounter();
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001616 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001617 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001618
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001619 // Make sure this service is no longer considered delayed, we are starting it now.
1620 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001621 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001622 getServiceMap(r.userId).mDelayedStartList.remove(r);
1623 r.delayed = false;
1624 }
1625
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001626 // Make sure that the user who owns this service is started. If not,
1627 // we don't want to allow it to run.
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001628 if (!mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001629 String msg = "Unable to launch app "
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001630 + r.appInfo.packageName + "/"
1631 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001632 + r.intent.getIntent() + ": user " + r.userId + " is stopped";
1633 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001634 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001635 return msg;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001636 }
1637
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001638 // Service is now being launched, its package can't be stopped.
1639 try {
1640 AppGlobals.getPackageManager().setPackageStoppedState(
1641 r.packageName, false, r.userId);
1642 } catch (RemoteException e) {
1643 } catch (IllegalArgumentException e) {
1644 Slog.w(TAG, "Failed trying to unstop package "
1645 + r.packageName + ": " + e);
1646 }
1647
1648 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
1649 final String procName = r.processName;
1650 ProcessRecord app;
1651
1652 if (!isolated) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001653 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
1654 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
1655 + " app=" + app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001656 if (app != null && app.thread != null) {
1657 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001658 app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001659 realStartServiceLocked(r, app, execInFg);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001660 return null;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001661 } catch (TransactionTooLargeException e) {
1662 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001663 } catch (RemoteException e) {
1664 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
1665 }
1666
1667 // If a dead object exception was thrown -- fall through to
1668 // restart the application.
1669 }
1670 } else {
1671 // If this service runs in an isolated process, then each time
1672 // we call startProcessLocked() we will get a new isolated
1673 // process, starting another process if we are currently waiting
1674 // for a previous process to come up. To deal with this, we store
1675 // in the service any current isolated process it is running in or
1676 // waiting to have come up.
1677 app = r.isolatedProc;
1678 }
1679
1680 // Not running -- get it started, and enqueue this service record
1681 // to be executed when the app comes up.
Svet Ganov9c165d72015-12-01 19:52:26 -08001682 if (app == null && !permissionsReviewRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001683 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001684 "service", r.name, false, isolated, false)) == null) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001685 String msg = "Unable to launch app "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001686 + r.appInfo.packageName + "/"
1687 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001688 + r.intent.getIntent() + ": process is bad";
1689 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001690 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001691 return msg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001692 }
1693 if (isolated) {
1694 r.isolatedProc = app;
1695 }
1696 }
1697
1698 if (!mPendingServices.contains(r)) {
1699 mPendingServices.add(r);
1700 }
1701
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001702 if (r.delayedStop) {
1703 // Oh and hey we've already been asked to stop!
1704 r.delayedStop = false;
1705 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001706 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
1707 "Applying delayed stop (in bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001708 stopServiceLocked(r);
1709 }
1710 }
1711
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001712 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001713 }
1714
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001715 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
1716 throws TransactionTooLargeException {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001717 for (int i=r.bindings.size()-1; i>=0; i--) {
1718 IntentBindRecord ibr = r.bindings.valueAt(i);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001719 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001720 break;
1721 }
1722 }
1723 }
1724
1725 private final void realStartServiceLocked(ServiceRecord r,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001726 ProcessRecord app, boolean execInFg) throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001727 if (app.thread == null) {
1728 throw new RemoteException();
1729 }
1730 if (DEBUG_MU)
1731 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
1732 + ", ProcessRecord.uid = " + app.uid);
1733 r.app = app;
1734 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
1735
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001736 final boolean newService = app.services.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001737 bumpServiceExecutingLocked(r, execInFg, "create");
Dianne Hackborndb926082013-10-31 16:32:44 -07001738 mAm.updateLruProcessLocked(app, false, null);
1739 mAm.updateOomAdjLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001740
1741 boolean created = false;
1742 try {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07001743 if (LOG_SERVICE_START_STOP) {
Dianne Hackbornab2df062015-01-07 13:43:13 -08001744 String nameTerm;
1745 int lastPeriod = r.shortName.lastIndexOf('.');
1746 nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07001747 EventLogTags.writeAmCreateService(
1748 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
1749 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001750 synchronized (r.stats.getBatteryStats()) {
1751 r.stats.startLaunchedLocked();
1752 }
Nicolas Geoffray27c07372015-11-05 16:54:09 +00001753 mAm.notifyPackageUse(r.serviceInfo.packageName);
Dianne Hackborna413dc02013-07-12 12:02:55 -07001754 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001755 app.thread.scheduleCreateService(r, r.serviceInfo,
Dianne Hackborna413dc02013-07-12 12:02:55 -07001756 mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
1757 app.repProcState);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001758 r.postNotification();
1759 created = true;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -07001760 } catch (DeadObjectException e) {
1761 Slog.w(TAG, "Application dead when creating service " + r);
1762 mAm.appDiedLocked(app);
Wale Ogunwalebfac4682015-04-08 14:33:21 -07001763 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001764 } finally {
1765 if (!created) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001766 // Keep the executeNesting count accurate.
1767 final boolean inDestroying = mDestroyingServices.contains(r);
1768 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
1769
1770 // Cleanup.
1771 if (newService) {
1772 app.services.remove(r);
1773 r.app = null;
1774 }
1775
1776 // Retry.
1777 if (!inDestroying) {
1778 scheduleServiceRestartLocked(r, false);
1779 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001780 }
1781 }
1782
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001783 requestServiceBindingsLocked(r, execInFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001784
Dianne Hackborn465fa392014-09-14 14:21:18 -07001785 updateServiceClientActivitiesLocked(app, null, true);
1786
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001787 // If the service is in the started state, and there are no
1788 // pending arguments, then fake up one so its onStartCommand() will
1789 // be called.
1790 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
1791 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
1792 null, null));
1793 }
1794
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001795 sendServiceArgsLocked(r, execInFg, true);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001796
1797 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001798 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001799 getServiceMap(r.userId).mDelayedStartList.remove(r);
1800 r.delayed = false;
1801 }
1802
1803 if (r.delayedStop) {
1804 // Oh and hey we've already been asked to stop!
1805 r.delayedStop = false;
1806 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001807 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
1808 "Applying delayed stop (from start): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001809 stopServiceLocked(r);
1810 }
1811 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001812 }
1813
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001814 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001815 boolean oomAdjusted) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001816 final int N = r.pendingStarts.size();
1817 if (N == 0) {
1818 return;
1819 }
1820
1821 while (r.pendingStarts.size() > 0) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001822 Exception caughtException = null;
Yasuhiro Matsuda8b5cd9f2015-07-10 15:35:47 +09001823 ServiceRecord.StartItem si = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001824 try {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001825 si = r.pendingStarts.remove(0);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001826 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Sending arguments to: "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001827 + r + " " + r.intent + " args=" + si.intent);
1828 if (si.intent == null && N > 1) {
1829 // If somehow we got a dummy null intent in the middle,
1830 // then skip it. DO NOT skip a null intent when it is
1831 // the only one in the list -- this is to support the
1832 // onStartCommand(null) case.
1833 continue;
1834 }
1835 si.deliveredTime = SystemClock.uptimeMillis();
1836 r.deliveredStarts.add(si);
1837 si.deliveryCount++;
1838 if (si.neededGrants != null) {
1839 mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
1840 si.getUriPermissionsLocked());
1841 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001842 bumpServiceExecutingLocked(r, execInFg, "start");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001843 if (!oomAdjusted) {
1844 oomAdjusted = true;
1845 mAm.updateOomAdjLocked(r.app);
1846 }
1847 int flags = 0;
1848 if (si.deliveryCount > 1) {
1849 flags |= Service.START_FLAG_RETRY;
1850 }
1851 if (si.doneExecutingCount > 0) {
1852 flags |= Service.START_FLAG_REDELIVERY;
1853 }
1854 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001855 } catch (TransactionTooLargeException e) {
1856 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large: intent="
1857 + si.intent);
1858 caughtException = e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001859 } catch (RemoteException e) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001860 // Remote process gone... we'll let the normal cleanup take care of this.
1861 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
1862 caughtException = e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001863 } catch (Exception e) {
1864 Slog.w(TAG, "Unexpected exception", e);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001865 caughtException = e;
1866 }
1867
1868 if (caughtException != null) {
1869 // Keep nesting count correct
1870 final boolean inDestroying = mDestroyingServices.contains(r);
1871 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
1872 if (caughtException instanceof TransactionTooLargeException) {
1873 throw (TransactionTooLargeException)caughtException;
1874 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001875 break;
1876 }
1877 }
1878 }
1879
Dianne Hackborn164371f2013-10-01 19:10:13 -07001880 private final boolean isServiceNeeded(ServiceRecord r, boolean knowConn, boolean hasConn) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001881 // Are we still explicitly being asked to run?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001882 if (r.startRequested) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001883 return true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001884 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001885
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001886 // Is someone still bound to us keepign us running?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001887 if (!knowConn) {
1888 hasConn = r.hasAutoCreateConnections();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001889 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001890 if (hasConn) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001891 return true;
1892 }
1893
1894 return false;
1895 }
1896
1897 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
1898 boolean hasConn) {
1899 //Slog.i(TAG, "Bring down service:");
1900 //r.dump(" ");
1901
1902 if (isServiceNeeded(r, knowConn, hasConn)) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001903 return;
1904 }
1905
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001906 // Are we in the process of launching?
1907 if (mPendingServices.contains(r)) {
1908 return;
1909 }
1910
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001911 bringDownServiceLocked(r);
1912 }
1913
1914 private final void bringDownServiceLocked(ServiceRecord r) {
1915 //Slog.i(TAG, "Bring down service:");
1916 //r.dump(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001917
Dianne Hackborn390517b2013-05-30 15:03:32 -07001918 // Report to all of the connections that the service is no longer
1919 // available.
1920 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1921 ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
1922 for (int i=0; i<c.size(); i++) {
1923 ConnectionRecord cr = c.get(i);
1924 // There is still a connection to the service that is
1925 // being brought down. Mark it as dead.
1926 cr.serviceDead = true;
1927 try {
1928 cr.conn.connected(r.name, null);
1929 } catch (Exception e) {
1930 Slog.w(TAG, "Failure disconnecting service " + r.name +
1931 " to connection " + c.get(i).conn.asBinder() +
1932 " (in " + c.get(i).binding.client.processName + ")", e);
1933 }
1934 }
1935 }
1936
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001937 // Tell the service that it has been unbound.
Dianne Hackborn390517b2013-05-30 15:03:32 -07001938 if (r.app != null && r.app.thread != null) {
1939 for (int i=r.bindings.size()-1; i>=0; i--) {
1940 IntentBindRecord ibr = r.bindings.valueAt(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001941 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001942 + ": hasBound=" + ibr.hasBound);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001943 if (ibr.hasBound) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001944 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001945 bumpServiceExecutingLocked(r, false, "bring down unbind");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001946 mAm.updateOomAdjLocked(r.app);
1947 ibr.hasBound = false;
1948 r.app.thread.scheduleUnbindService(r,
1949 ibr.intent.getIntent());
1950 } catch (Exception e) {
1951 Slog.w(TAG, "Exception when unbinding service "
1952 + r.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07001953 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001954 }
1955 }
1956 }
1957 }
1958
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001959 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent);
Craig Mautner66c4a822015-01-16 12:48:16 -08001960 r.destroyTime = SystemClock.uptimeMillis();
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07001961 if (LOG_SERVICE_START_STOP) {
1962 EventLogTags.writeAmDestroyService(
1963 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
1964 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001965
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001966 final ServiceMap smap = getServiceMap(r.userId);
1967 smap.mServicesByName.remove(r.name);
1968 smap.mServicesByIntent.remove(r.intent);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001969 r.totalRestartCount = 0;
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001970 unscheduleServiceRestartLocked(r, 0, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001971
1972 // Also make sure it is not on the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001973 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001974 if (mPendingServices.get(i) == r) {
1975 mPendingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001976 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001977 }
1978 }
1979
1980 r.cancelNotification();
1981 r.isForeground = false;
1982 r.foregroundId = 0;
1983 r.foregroundNoti = null;
1984
1985 // Clear start entries.
1986 r.clearDeliveredStartsLocked();
1987 r.pendingStarts.clear();
1988
1989 if (r.app != null) {
1990 synchronized (r.stats.getBatteryStats()) {
1991 r.stats.stopLaunchedLocked();
1992 }
1993 r.app.services.remove(r);
1994 if (r.app.thread != null) {
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001995 updateServiceForegroundLocked(r.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001996 try {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001997 bumpServiceExecutingLocked(r, false, "destroy");
1998 mDestroyingServices.add(r);
Dianne Hackborn455625e2015-01-21 09:55:13 -08001999 r.destroying = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002000 mAm.updateOomAdjLocked(r.app);
2001 r.app.thread.scheduleStopService(r);
2002 } catch (Exception e) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002003 Slog.w(TAG, "Exception when destroying service "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002004 + r.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002005 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002006 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002007 } else {
2008 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002009 TAG_SERVICE, "Removed service that has no process: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002010 }
2011 } else {
2012 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002013 TAG_SERVICE, "Removed service that is not running: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002014 }
2015
2016 if (r.bindings.size() > 0) {
2017 r.bindings.clear();
2018 }
2019
2020 if (r.restarter instanceof ServiceRestarter) {
2021 ((ServiceRestarter)r.restarter).setService(null);
2022 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002023
Dianne Hackbornd2932242013-08-05 18:18:42 -07002024 int memFactor = mAm.mProcessStats.getMemFactorLocked();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002025 long now = SystemClock.uptimeMillis();
2026 if (r.tracker != null) {
2027 r.tracker.setStarted(false, memFactor, now);
2028 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002029 if (r.executeNesting == 0) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07002030 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002031 r.tracker = null;
2032 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002033 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002034
2035 smap.ensureNotStartingBackground(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002036 }
2037
2038 void removeConnectionLocked(
2039 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
2040 IBinder binder = c.conn.asBinder();
2041 AppBindRecord b = c.binding;
2042 ServiceRecord s = b.service;
2043 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
2044 if (clist != null) {
2045 clist.remove(c);
2046 if (clist.size() == 0) {
2047 s.connections.remove(binder);
2048 }
2049 }
2050 b.connections.remove(c);
2051 if (c.activity != null && c.activity != skipAct) {
2052 if (c.activity.connections != null) {
2053 c.activity.connections.remove(c);
2054 }
2055 }
2056 if (b.client != skipApp) {
2057 b.client.connections.remove(c);
2058 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
2059 b.client.updateHasAboveClientLocked();
2060 }
Dianne Hackborndb926082013-10-31 16:32:44 -07002061 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07002062 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07002063 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002064 }
2065 clist = mServiceConnections.get(binder);
2066 if (clist != null) {
2067 clist.remove(c);
2068 if (clist.size() == 0) {
2069 mServiceConnections.remove(binder);
2070 }
2071 }
2072
Dianne Hackbornab2df062015-01-07 13:43:13 -08002073 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid, s.name);
2074
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002075 if (b.connections.size() == 0) {
2076 b.intent.apps.remove(b.client);
2077 }
2078
2079 if (!c.serviceDead) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002080 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002081 + ": shouldUnbind=" + b.intent.hasBound);
2082 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
2083 && b.intent.hasBound) {
2084 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002085 bumpServiceExecutingLocked(s, false, "unbind");
Dianne Hackborndb926082013-10-31 16:32:44 -07002086 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
2087 && s.app.setProcState <= ActivityManager.PROCESS_STATE_RECEIVER) {
2088 // If this service's process is not already in the cached list,
2089 // then update it in the LRU list here because this may be causing
2090 // it to go down there and we want it to start out near the top.
2091 mAm.updateLruProcessLocked(s.app, false, null);
2092 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002093 mAm.updateOomAdjLocked(s.app);
2094 b.intent.hasBound = false;
2095 // Assume the client doesn't want to know about a rebind;
2096 // we will deal with that later if it asks for one.
2097 b.intent.doRebind = false;
2098 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
2099 } catch (Exception e) {
2100 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002101 serviceProcessGoneLocked(s);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002102 }
2103 }
2104
Svet Ganov9c165d72015-12-01 19:52:26 -08002105 // If unbound while waiting to start, remove the pending service
2106 mPendingServices.remove(s);
2107
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002108 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002109 boolean hasAutoCreate = s.hasAutoCreateConnections();
2110 if (!hasAutoCreate) {
2111 if (s.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002112 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002113 SystemClock.uptimeMillis());
2114 }
2115 }
2116 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002117 }
2118 }
2119 }
2120
2121 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002122 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002123 if (r != null) {
Dianne Hackborn455625e2015-01-21 09:55:13 -08002124 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002125 // This is a call from a service start... take care of
2126 // book-keeping.
2127 r.callStart = true;
2128 switch (res) {
2129 case Service.START_STICKY_COMPATIBILITY:
2130 case Service.START_STICKY: {
2131 // We are done with the associated start arguments.
2132 r.findDeliveredStart(startId, true);
2133 // Don't stop if killed.
2134 r.stopIfKilled = false;
2135 break;
2136 }
2137 case Service.START_NOT_STICKY: {
2138 // We are done with the associated start arguments.
2139 r.findDeliveredStart(startId, true);
2140 if (r.getLastStartId() == startId) {
2141 // There is no more work, and this service
2142 // doesn't want to hang around if killed.
2143 r.stopIfKilled = true;
2144 }
2145 break;
2146 }
2147 case Service.START_REDELIVER_INTENT: {
2148 // We'll keep this item until they explicitly
2149 // call stop for it, but keep track of the fact
2150 // that it was delivered.
2151 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
2152 if (si != null) {
2153 si.deliveryCount = 0;
2154 si.doneExecutingCount++;
2155 // Don't stop if killed.
2156 r.stopIfKilled = true;
2157 }
2158 break;
2159 }
2160 case Service.START_TASK_REMOVED_COMPLETE: {
2161 // Special processing for onTaskRemoved(). Don't
2162 // impact normal onStartCommand() processing.
2163 r.findDeliveredStart(startId, true);
2164 break;
2165 }
2166 default:
2167 throw new IllegalArgumentException(
2168 "Unknown service start result: " + res);
2169 }
2170 if (res == Service.START_STICKY_COMPATIBILITY) {
2171 r.callStart = false;
2172 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08002173 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
2174 // This is the final call from destroying the service... we should
2175 // actually be getting rid of the service at this point. Do some
2176 // validation of its state, and ensure it will be fully removed.
2177 if (!inDestroying) {
2178 // Not sure what else to do with this... if it is not actually in the
2179 // destroying list, we don't need to make sure to remove it from it.
2180 Slog.wtfStack(TAG, "Service done with onDestroy, but not inDestroying: "
2181 + r);
2182 } else if (r.executeNesting != 1) {
2183 Slog.wtfStack(TAG, "Service done with onDestroy, but executeNesting="
2184 + r.executeNesting + ": " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002185 // Fake it to keep from ANR due to orphaned entry.
Dianne Hackborn455625e2015-01-21 09:55:13 -08002186 r.executeNesting = 1;
2187 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002188 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002189 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn164371f2013-10-01 19:10:13 -07002190 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002191 Binder.restoreCallingIdentity(origId);
2192 } else {
2193 Slog.w(TAG, "Done executing unknown service from pid "
2194 + Binder.getCallingPid());
2195 }
2196 }
2197
Dianne Hackborn878deb32013-10-14 16:55:09 -07002198 private void serviceProcessGoneLocked(ServiceRecord r) {
2199 if (r.tracker != null) {
2200 int memFactor = mAm.mProcessStats.getMemFactorLocked();
2201 long now = SystemClock.uptimeMillis();
2202 r.tracker.setExecuting(false, memFactor, now);
2203 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbc72dce2013-11-11 10:43:38 -08002204 r.tracker.setStarted(false, memFactor, now);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002205 }
2206 serviceDoneExecutingLocked(r, true, true);
2207 }
2208
Dianne Hackborn164371f2013-10-01 19:10:13 -07002209 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
2210 boolean finishing) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002211 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002212 + ": nesting=" + r.executeNesting
Dianne Hackborn164371f2013-10-01 19:10:13 -07002213 + ", inDestroying=" + inDestroying + ", app=" + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002214 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
2215 "<<< DONE EXECUTING " + r.shortName);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002216 r.executeNesting--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002217 if (r.executeNesting <= 0) {
2218 if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002219 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002220 "Nesting at 0 of " + r.shortName);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002221 r.app.execServicesFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002222 r.app.executingServices.remove(r);
2223 if (r.app.executingServices.size() == 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002224 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002225 "No more executingServices of " + r.shortName);
2226 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002227 } else if (r.executeFg) {
2228 // Need to re-evaluate whether the app still needs to be in the foreground.
2229 for (int i=r.app.executingServices.size()-1; i>=0; i--) {
2230 if (r.app.executingServices.valueAt(i).executeFg) {
2231 r.app.execServicesFg = true;
2232 break;
2233 }
2234 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002235 }
Dianne Hackborn164371f2013-10-01 19:10:13 -07002236 if (inDestroying) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002237 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn164371f2013-10-01 19:10:13 -07002238 "doneExecuting remove destroying " + r);
2239 mDestroyingServices.remove(r);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002240 r.bindings.clear();
2241 }
2242 mAm.updateOomAdjLocked(r.app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002243 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002244 r.executeFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002245 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002246 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002247 SystemClock.uptimeMillis());
Dianne Hackborn164371f2013-10-01 19:10:13 -07002248 if (finishing) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07002249 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002250 r.tracker = null;
2251 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002252 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002253 if (finishing) {
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08002254 if (r.app != null && !r.app.persistent) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002255 r.app.services.remove(r);
2256 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002257 r.app = null;
2258 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002259 }
2260 }
2261
Dianne Hackbornff072722014-09-24 10:56:28 -07002262 boolean attachApplicationLocked(ProcessRecord proc, String processName)
2263 throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002264 boolean didSomething = false;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002265 // Collect any services that are waiting for this process to come up.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002266 if (mPendingServices.size() > 0) {
2267 ServiceRecord sr = null;
2268 try {
2269 for (int i=0; i<mPendingServices.size(); i++) {
2270 sr = mPendingServices.get(i);
2271 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
2272 || !processName.equals(sr.processName))) {
2273 continue;
2274 }
2275
2276 mPendingServices.remove(i);
2277 i--;
Dianne Hackbornf7097a52014-05-13 09:56:14 -07002278 proc.addPackage(sr.appInfo.packageName, sr.appInfo.versionCode,
2279 mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002280 realStartServiceLocked(sr, proc, sr.createdFromFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002281 didSomething = true;
Dianne Hackborn865907d2015-10-21 17:12:53 -07002282 if (!isServiceNeeded(sr, false, false)) {
2283 // We were waiting for this service to start, but it is actually no
2284 // longer needed. This could happen because bringDownServiceIfNeeded
2285 // won't bring down a service that is pending... so now the pending
2286 // is done, so let's drop it.
2287 bringDownServiceLocked(sr);
2288 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002289 }
Dianne Hackbornff072722014-09-24 10:56:28 -07002290 } catch (RemoteException e) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002291 Slog.w(TAG, "Exception in new application when starting service "
2292 + sr.shortName, e);
2293 throw e;
2294 }
2295 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002296 // Also, if there are any services that are waiting to restart and
2297 // would run in this process, now is a good time to start them. It would
2298 // be weird to bring up the process but arbitrarily not let the services
2299 // run at this point just because their restart time hasn't come up.
2300 if (mRestartingServices.size() > 0) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002301 ServiceRecord sr;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002302 for (int i=0; i<mRestartingServices.size(); i++) {
2303 sr = mRestartingServices.get(i);
2304 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
2305 || !processName.equals(sr.processName))) {
2306 continue;
2307 }
2308 mAm.mHandler.removeCallbacks(sr.restarter);
2309 mAm.mHandler.post(sr.restarter);
2310 }
2311 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002312 return didSomething;
2313 }
2314
2315 void processStartTimedOutLocked(ProcessRecord proc) {
2316 for (int i=0; i<mPendingServices.size(); i++) {
2317 ServiceRecord sr = mPendingServices.get(i);
2318 if ((proc.uid == sr.appInfo.uid
2319 && proc.processName.equals(sr.processName))
2320 || sr.isolatedProc == proc) {
2321 Slog.w(TAG, "Forcing bringing down service: " + sr);
2322 sr.isolatedProc = null;
2323 mPendingServices.remove(i);
2324 i--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002325 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002326 }
2327 }
2328 }
2329
Wale Ogunwale540e1232015-05-01 15:35:39 -07002330 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002331 boolean evenPersistent, boolean doit, boolean killProcess,
2332 ArrayMap<ComponentName, ServiceRecord> services) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002333 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002334 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002335 ServiceRecord service = services.valueAt(i);
Wale Ogunwale540e1232015-05-01 15:35:39 -07002336 final boolean sameComponent = packageName == null
2337 || (service.packageName.equals(packageName)
2338 && (filterByClasses == null
2339 || filterByClasses.contains(service.name.getClassName())));
2340 if (sameComponent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002341 && (service.app == null || evenPersistent || !service.app.persistent)) {
2342 if (!doit) {
2343 return true;
2344 }
2345 didSomething = true;
2346 Slog.i(TAG, " Force stopping service " + service);
2347 if (service.app != null) {
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002348 service.app.removed = killProcess;
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08002349 if (!service.app.persistent) {
2350 service.app.services.remove(service);
2351 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002352 }
2353 service.app = null;
2354 service.isolatedProc = null;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002355 if (mTmpCollectionResults == null) {
2356 mTmpCollectionResults = new ArrayList<>();
2357 }
2358 mTmpCollectionResults.add(service);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002359 }
2360 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002361 return didSomething;
2362 }
2363
Wale Ogunwale540e1232015-05-01 15:35:39 -07002364 boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002365 int userId, boolean evenPersistent, boolean killProcess, boolean doit) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002366 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002367
2368 if (mTmpCollectionResults != null) {
2369 mTmpCollectionResults.clear();
2370 }
2371
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002372 if (userId == UserHandle.USER_ALL) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07002373 for (int i = mServiceMap.size() - 1; i >= 0; i--) {
2374 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002375 evenPersistent, doit, killProcess, mServiceMap.valueAt(i).mServicesByName);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002376 if (!doit && didSomething) {
2377 return true;
2378 }
2379 }
2380 } else {
Amith Yamasani540b6592013-10-01 13:02:52 -07002381 ServiceMap smap = mServiceMap.get(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002382 if (smap != null) {
2383 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByName;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002384 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002385 evenPersistent, doit, killProcess, items);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002386 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002387 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002388
Wale Ogunwale540e1232015-05-01 15:35:39 -07002389 if (mTmpCollectionResults != null) {
2390 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
2391 bringDownServiceLocked(mTmpCollectionResults.get(i));
2392 }
2393 mTmpCollectionResults.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002394 }
2395 return didSomething;
2396 }
2397
2398 void cleanUpRemovedTaskLocked(TaskRecord tr, ComponentName component, Intent baseIntent) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07002399 ArrayList<ServiceRecord> services = new ArrayList<>();
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002400 ArrayMap<ComponentName, ServiceRecord> alls = getServices(tr.userId);
Wale Ogunwale540e1232015-05-01 15:35:39 -07002401 for (int i = alls.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002402 ServiceRecord sr = alls.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002403 if (sr.packageName.equals(component.getPackageName())) {
2404 services.add(sr);
2405 }
2406 }
2407
2408 // Take care of any running services associated with the app.
Wale Ogunwale540e1232015-05-01 15:35:39 -07002409 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002410 ServiceRecord sr = services.get(i);
2411 if (sr.startRequested) {
2412 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
2413 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
2414 stopServiceLocked(sr);
2415 } else {
2416 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
2417 sr.makeNextStartId(), baseIntent, null));
2418 if (sr.app != null && sr.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002419 // We always run in the foreground, since this is called as
2420 // part of the "remove task" UI operation.
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002421 try {
2422 sendServiceArgsLocked(sr, true, false);
2423 } catch (TransactionTooLargeException e) {
2424 // Ignore, keep going.
2425 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002426 }
2427 }
2428 }
2429 }
2430 }
2431
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002432 final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002433 // Report disconnected services.
2434 if (false) {
2435 // XXX we are letting the client link to the service for
2436 // death notifications.
2437 if (app.services.size() > 0) {
2438 Iterator<ServiceRecord> it = app.services.iterator();
2439 while (it.hasNext()) {
2440 ServiceRecord r = it.next();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002441 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2442 ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
2443 for (int i=0; i<cl.size(); i++) {
2444 ConnectionRecord c = cl.get(i);
2445 if (c.binding.client != app) {
2446 try {
2447 //c.conn.connected(r.className, null);
2448 } catch (Exception e) {
2449 // todo: this should be asynchronous!
2450 Slog.w(TAG, "Exception thrown disconnected servce "
2451 + r.shortName
2452 + " from app " + app.processName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002453 }
2454 }
2455 }
2456 }
2457 }
2458 }
2459 }
2460
louis_chang40e259c2015-03-26 13:31:14 +08002461 // Clean up any connections this application has to other services.
2462 for (int i = app.connections.size() - 1; i >= 0; i--) {
2463 ConnectionRecord r = app.connections.valueAt(i);
2464 removeConnectionLocked(r, app, null);
2465 }
2466 updateServiceConnectionActivitiesLocked(app);
2467 app.connections.clear();
2468
2469 // Clear app state from services.
2470 for (int i = app.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07002471 ServiceRecord sr = app.services.valueAt(i);
2472 synchronized (sr.stats.getBatteryStats()) {
2473 sr.stats.stopLaunchedLocked();
2474 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08002475 if (sr.app != app && sr.app != null && !sr.app.persistent) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002476 sr.app.services.remove(sr);
2477 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07002478 sr.app = null;
2479 sr.isolatedProc = null;
2480 sr.executeNesting = 0;
Dianne Hackborn164371f2013-10-01 19:10:13 -07002481 sr.forceClearTracker();
2482 if (mDestroyingServices.remove(sr)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002483 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackbornc8230512013-07-13 21:32:12 -07002484 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002485
Dianne Hackbornc8230512013-07-13 21:32:12 -07002486 final int numClients = sr.bindings.size();
2487 for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
2488 IntentBindRecord b = sr.bindings.valueAt(bindingi);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002489 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
Dianne Hackbornc8230512013-07-13 21:32:12 -07002490 + ": shouldUnbind=" + b.hasBound);
2491 b.binder = null;
2492 b.requested = b.received = b.hasBound = false;
Dianne Hackborn465fa392014-09-14 14:21:18 -07002493 // If this binding is coming from a cached process and is asking to keep
2494 // the service created, then we'll kill the cached process as well -- we
2495 // don't want to be thrashing around restarting processes that are only
2496 // there to be cached.
2497 for (int appi=b.apps.size()-1; appi>=0; appi--) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07002498 final ProcessRecord proc = b.apps.keyAt(appi);
2499 // If the process is already gone, skip it.
2500 if (proc.killedByAm || proc.thread == null) {
2501 continue;
2502 }
2503 // Only do this for processes that have an auto-create binding;
2504 // otherwise the binding can be left, because it won't cause the
2505 // service to restart.
2506 final AppBindRecord abind = b.apps.valueAt(appi);
2507 boolean hasCreate = false;
2508 for (int conni=abind.connections.size()-1; conni>=0; conni--) {
2509 ConnectionRecord conn = abind.connections.valueAt(conni);
Dianne Hackborn0fe3c252014-09-19 15:09:39 -07002510 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
2511 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07002512 hasCreate = true;
2513 break;
2514 }
2515 }
2516 if (!hasCreate) {
2517 continue;
2518 }
Dianne Hackborncd97c962014-09-25 18:34:02 -07002519 // XXX turned off for now until we have more time to get a better policy.
2520 if (false && proc != null && !proc.persistent && proc.thread != null
Dianne Hackborn465fa392014-09-14 14:21:18 -07002521 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
2522 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
2523 proc.kill("bound to service " + sr.name.flattenToShortString()
2524 + " in dying proc " + (app != null ? app.processName : "??"), true);
2525 }
2526 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07002527 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002528 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002529
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002530 ServiceMap smap = getServiceMap(app.userId);
2531
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002532 // Now do remaining service cleanup.
2533 for (int i=app.services.size()-1; i>=0; i--) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002534 ServiceRecord sr = app.services.valueAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08002535
2536 // Unless the process is persistent, this process record is going away,
2537 // so make sure the service is cleaned out of it.
2538 if (!app.persistent) {
Dianne Hackborn4190fc52013-12-09 18:20:16 -08002539 app.services.removeAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08002540 }
2541
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002542 // Sanity check: if the service listed for the app is not one
Dianne Hackborn4190fc52013-12-09 18:20:16 -08002543 // we actually are maintaining, just let it drop.
Dianne Hackborn40c87252014-03-19 16:55:40 -07002544 final ServiceRecord curRec = smap.mServicesByName.get(sr.name);
2545 if (curRec != sr) {
2546 if (curRec != null) {
2547 Slog.wtf(TAG, "Service " + sr + " in process " + app
2548 + " not same as in map: " + curRec);
2549 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002550 continue;
2551 }
2552
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002553 // Any services running in the application may need to be placed
2554 // back in the pending list.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002555 if (allowRestart && sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
Dianne Hackbornc8230512013-07-13 21:32:12 -07002556 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
2557 Slog.w(TAG, "Service crashed " + sr.crashCount
2558 + " times, stopping: " + sr);
2559 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
2560 sr.userId, sr.crashCount, sr.shortName, app.pid);
2561 bringDownServiceLocked(sr);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07002562 } else if (!allowRestart
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002563 || !mAm.mUserController.isUserRunningLocked(sr.userId, 0)) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07002564 bringDownServiceLocked(sr);
2565 } else {
2566 boolean canceled = scheduleServiceRestartLocked(sr, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002567
Dianne Hackbornc8230512013-07-13 21:32:12 -07002568 // Should the service remain running? Note that in the
2569 // extreme case of so many attempts to deliver a command
2570 // that it failed we also will stop it here.
2571 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
2572 if (sr.pendingStarts.size() == 0) {
2573 sr.startRequested = false;
2574 if (sr.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002575 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackbornc8230512013-07-13 21:32:12 -07002576 SystemClock.uptimeMillis());
2577 }
2578 if (!sr.hasAutoCreateConnections()) {
2579 // Whoops, no reason to restart!
2580 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002581 }
2582 }
2583 }
2584 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07002585 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002586
Dianne Hackbornc8230512013-07-13 21:32:12 -07002587 if (!allowRestart) {
2588 app.services.clear();
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002589
2590 // Make sure there are no more restarting services for this process.
2591 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2592 ServiceRecord r = mRestartingServices.get(i);
2593 if (r.processName.equals(app.processName) &&
2594 r.serviceInfo.applicationInfo.uid == app.info.uid) {
2595 mRestartingServices.remove(i);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002596 clearRestartingIfNeededLocked(r);
2597 }
2598 }
2599 for (int i=mPendingServices.size()-1; i>=0; i--) {
2600 ServiceRecord r = mPendingServices.get(i);
2601 if (r.processName.equals(app.processName) &&
2602 r.serviceInfo.applicationInfo.uid == app.info.uid) {
2603 mPendingServices.remove(i);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002604 }
2605 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002606 }
2607
2608 // Make sure we have no more records on the stopping list.
Dianne Hackborn164371f2013-10-01 19:10:13 -07002609 int i = mDestroyingServices.size();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002610 while (i > 0) {
2611 i--;
Dianne Hackborn164371f2013-10-01 19:10:13 -07002612 ServiceRecord sr = mDestroyingServices.get(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002613 if (sr.app == app) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002614 sr.forceClearTracker();
2615 mDestroyingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002616 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002617 }
2618 }
2619
2620 app.executingServices.clear();
2621 }
2622
2623 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
2624 ActivityManager.RunningServiceInfo info =
2625 new ActivityManager.RunningServiceInfo();
2626 info.service = r.name;
2627 if (r.app != null) {
2628 info.pid = r.app.pid;
2629 }
2630 info.uid = r.appInfo.uid;
2631 info.process = r.processName;
2632 info.foreground = r.isForeground;
2633 info.activeSince = r.createTime;
2634 info.started = r.startRequested;
2635 info.clientCount = r.connections.size();
2636 info.crashCount = r.crashCount;
2637 info.lastActivityTime = r.lastActivity;
2638 if (r.isForeground) {
2639 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
2640 }
2641 if (r.startRequested) {
2642 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
2643 }
2644 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
2645 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
2646 }
2647 if (r.app != null && r.app.persistent) {
2648 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
2649 }
2650
Dianne Hackborn390517b2013-05-30 15:03:32 -07002651 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2652 ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002653 for (int i=0; i<connl.size(); i++) {
2654 ConnectionRecord conn = connl.get(i);
2655 if (conn.clientLabel != 0) {
2656 info.clientPackage = conn.binding.client.info.packageName;
2657 info.clientLabel = conn.clientLabel;
2658 return info;
2659 }
2660 }
2661 }
2662 return info;
2663 }
2664
2665 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum,
2666 int flags) {
2667 ArrayList<ActivityManager.RunningServiceInfo> res
2668 = new ArrayList<ActivityManager.RunningServiceInfo>();
2669
Dianne Hackborn0c380492012-08-20 17:23:30 -07002670 final int uid = Binder.getCallingUid();
2671 final long ident = Binder.clearCallingIdentity();
2672 try {
2673 if (ActivityManager.checkUidPermission(
2674 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
2675 uid) == PackageManager.PERMISSION_GRANTED) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07002676 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07002677 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002678 ArrayMap<ComponentName, ServiceRecord> alls = getServices(users[ui]);
2679 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
2680 ServiceRecord sr = alls.valueAt(i);
2681 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07002682 }
2683 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002684
Dianne Hackborn0c380492012-08-20 17:23:30 -07002685 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
2686 ServiceRecord r = mRestartingServices.get(i);
2687 ActivityManager.RunningServiceInfo info =
2688 makeRunningServiceInfoLocked(r);
2689 info.restarting = r.nextRestartTime;
2690 res.add(info);
2691 }
2692 } else {
2693 int userId = UserHandle.getUserId(uid);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002694 ArrayMap<ComponentName, ServiceRecord> alls = getServices(userId);
2695 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
2696 ServiceRecord sr = alls.valueAt(i);
2697 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07002698 }
2699
2700 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
2701 ServiceRecord r = mRestartingServices.get(i);
2702 if (r.userId == userId) {
2703 ActivityManager.RunningServiceInfo info =
2704 makeRunningServiceInfoLocked(r);
2705 info.restarting = r.nextRestartTime;
2706 res.add(info);
2707 }
2708 }
2709 }
2710 } finally {
2711 Binder.restoreCallingIdentity(ident);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002712 }
2713
2714 return res;
2715 }
2716
2717 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002718 int userId = UserHandle.getUserId(Binder.getCallingUid());
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002719 ServiceRecord r = getServiceByName(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002720 if (r != null) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002721 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2722 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002723 for (int i=0; i<conn.size(); i++) {
2724 if (conn.get(i).clientIntent != null) {
2725 return conn.get(i).clientIntent;
2726 }
2727 }
2728 }
2729 }
2730 return null;
2731 }
2732
2733 void serviceTimeout(ProcessRecord proc) {
2734 String anrMessage = null;
2735
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07002736 synchronized(mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002737 if (proc.executingServices.size() == 0 || proc.thread == null) {
2738 return;
2739 }
Dianne Hackbornab2df062015-01-07 13:43:13 -08002740 final long now = SystemClock.uptimeMillis();
2741 final long maxTime = now -
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002742 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002743 ServiceRecord timeout = null;
2744 long nextTime = 0;
Dianne Hackbornc8230512013-07-13 21:32:12 -07002745 for (int i=proc.executingServices.size()-1; i>=0; i--) {
2746 ServiceRecord sr = proc.executingServices.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002747 if (sr.executingStart < maxTime) {
2748 timeout = sr;
2749 break;
2750 }
2751 if (sr.executingStart > nextTime) {
2752 nextTime = sr.executingStart;
2753 }
2754 }
2755 if (timeout != null && mAm.mLruProcesses.contains(proc)) {
2756 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08002757 StringWriter sw = new StringWriter();
2758 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
2759 pw.println(timeout);
2760 timeout.dump(pw, " ");
2761 pw.close();
2762 mLastAnrDump = sw.toString();
2763 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
2764 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
2765 anrMessage = "executing service " + timeout.shortName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002766 } else {
2767 Message msg = mAm.mHandler.obtainMessage(
2768 ActivityManagerService.SERVICE_TIMEOUT_MSG);
2769 msg.obj = proc;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002770 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
Dianne Hackborn2be00932013-09-22 16:46:00 -07002771 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002772 }
2773 }
2774
2775 if (anrMessage != null) {
Adrian Roos20d7df32016-01-12 18:59:43 +01002776 mAm.mAppErrors.appNotResponding(proc, null, null, false, anrMessage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002777 }
2778 }
2779
Dianne Hackborn2be00932013-09-22 16:46:00 -07002780 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
2781 if (proc.executingServices.size() == 0 || proc.thread == null) {
2782 return;
2783 }
2784 long now = SystemClock.uptimeMillis();
2785 Message msg = mAm.mHandler.obtainMessage(
2786 ActivityManagerService.SERVICE_TIMEOUT_MSG);
2787 msg.obj = proc;
2788 mAm.mHandler.sendMessageAtTime(msg,
2789 proc.execServicesFg ? (now+SERVICE_TIMEOUT) : (now+ SERVICE_BACKGROUND_TIMEOUT));
2790 }
2791
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002792 /**
2793 * Prints a list of ServiceRecords (dumpsys activity services)
2794 */
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002795 void dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002796 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
2797 boolean needSep = false;
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002798 boolean printedAnything = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002799
2800 ItemMatcher matcher = new ItemMatcher();
2801 matcher.build(args, opti);
2802
2803 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
2804 try {
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08002805 if (mLastAnrDump != null) {
2806 pw.println(" Last ANR service:");
2807 pw.print(mLastAnrDump);
2808 pw.println();
2809 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07002810 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07002811 for (int user : users) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002812 ServiceMap smap = getServiceMap(user);
2813 boolean printed = false;
2814 if (smap.mServicesByName.size() > 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002815 long nowReal = SystemClock.elapsedRealtime();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002816 needSep = false;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002817 for (int si=0; si<smap.mServicesByName.size(); si++) {
2818 ServiceRecord r = smap.mServicesByName.valueAt(si);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002819 if (!matcher.match(r, r.name)) {
2820 continue;
2821 }
2822 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2823 continue;
2824 }
2825 if (!printed) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002826 if (printedAnything) {
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002827 pw.println();
2828 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07002829 pw.println(" User " + user + " active services:");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002830 printed = true;
2831 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002832 printedAnything = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002833 if (needSep) {
2834 pw.println();
2835 }
2836 pw.print(" * ");
2837 pw.println(r);
2838 if (dumpAll) {
2839 r.dump(pw, " ");
2840 needSep = true;
2841 } else {
2842 pw.print(" app=");
2843 pw.println(r.app);
2844 pw.print(" created=");
2845 TimeUtils.formatDuration(r.createTime, nowReal, pw);
2846 pw.print(" started=");
2847 pw.print(r.startRequested);
2848 pw.print(" connections=");
2849 pw.println(r.connections.size());
2850 if (r.connections.size() > 0) {
2851 pw.println(" Connections:");
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002852 for (int conni=0; conni<r.connections.size(); conni++) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002853 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002854 for (int i = 0; i < clist.size(); i++) {
2855 ConnectionRecord conn = clist.get(i);
2856 pw.print(" ");
2857 pw.print(conn.binding.intent.intent.getIntent()
2858 .toShortString(false, false, false, false));
2859 pw.print(" -> ");
2860 ProcessRecord proc = conn.binding.client;
2861 pw.println(proc != null ? proc.toShortString() : "null");
2862 }
2863 }
2864 }
2865 }
2866 if (dumpClient && r.app != null && r.app.thread != null) {
2867 pw.println(" Client:");
2868 pw.flush();
2869 try {
2870 TransferPipe tp = new TransferPipe();
2871 try {
2872 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
2873 r, args);
2874 tp.setBufferPrefix(" ");
2875 // Short timeout, since blocking here can
2876 // deadlock with the application.
2877 tp.go(fd, 2000);
2878 } finally {
2879 tp.kill();
2880 }
2881 } catch (IOException e) {
2882 pw.println(" Failure while dumping the service: " + e);
2883 } catch (RemoteException e) {
2884 pw.println(" Got a RemoteException while dumping the service");
2885 }
2886 needSep = true;
2887 }
2888 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002889 needSep |= printed;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002890 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002891 printed = false;
2892 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
2893 ServiceRecord r = smap.mDelayedStartList.get(si);
2894 if (!matcher.match(r, r.name)) {
2895 continue;
2896 }
2897 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2898 continue;
2899 }
2900 if (!printed) {
2901 if (printedAnything) {
2902 pw.println();
2903 }
2904 pw.println(" User " + user + " delayed start services:");
2905 printed = true;
2906 }
2907 printedAnything = true;
2908 pw.print(" * Delayed start "); pw.println(r);
2909 }
2910 printed = false;
2911 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
2912 ServiceRecord r = smap.mStartingBackground.get(si);
2913 if (!matcher.match(r, r.name)) {
2914 continue;
2915 }
2916 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2917 continue;
2918 }
2919 if (!printed) {
2920 if (printedAnything) {
2921 pw.println();
2922 }
2923 pw.println(" User " + user + " starting in background:");
2924 printed = true;
2925 }
2926 printedAnything = true;
2927 pw.print(" * Starting bg "); pw.println(r);
2928 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002929 }
Amith Yamasani258848d2012-08-10 17:06:33 -07002930 } catch (Exception e) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002931 Slog.w(TAG, "Exception in dumpServicesLocked", e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002932 }
2933
2934 if (mPendingServices.size() > 0) {
2935 boolean printed = false;
2936 for (int i=0; i<mPendingServices.size(); i++) {
2937 ServiceRecord r = mPendingServices.get(i);
2938 if (!matcher.match(r, r.name)) {
2939 continue;
2940 }
2941 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2942 continue;
2943 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002944 printedAnything = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002945 if (!printed) {
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002946 if (needSep) pw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002947 needSep = true;
2948 pw.println(" Pending services:");
2949 printed = true;
2950 }
2951 pw.print(" * Pending "); pw.println(r);
2952 r.dump(pw, " ");
2953 }
2954 needSep = true;
2955 }
2956
2957 if (mRestartingServices.size() > 0) {
2958 boolean printed = false;
2959 for (int i=0; i<mRestartingServices.size(); i++) {
2960 ServiceRecord r = mRestartingServices.get(i);
2961 if (!matcher.match(r, r.name)) {
2962 continue;
2963 }
2964 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2965 continue;
2966 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002967 printedAnything = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002968 if (!printed) {
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002969 if (needSep) pw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002970 needSep = true;
2971 pw.println(" Restarting services:");
2972 printed = true;
2973 }
2974 pw.print(" * Restarting "); pw.println(r);
2975 r.dump(pw, " ");
2976 }
2977 needSep = true;
2978 }
2979
Dianne Hackborn164371f2013-10-01 19:10:13 -07002980 if (mDestroyingServices.size() > 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002981 boolean printed = false;
Dianne Hackborn164371f2013-10-01 19:10:13 -07002982 for (int i=0; i< mDestroyingServices.size(); i++) {
2983 ServiceRecord r = mDestroyingServices.get(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002984 if (!matcher.match(r, r.name)) {
2985 continue;
2986 }
2987 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2988 continue;
2989 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002990 printedAnything = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002991 if (!printed) {
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07002992 if (needSep) pw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002993 needSep = true;
Dianne Hackborn164371f2013-10-01 19:10:13 -07002994 pw.println(" Destroying services:");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002995 printed = true;
2996 }
Dianne Hackborn164371f2013-10-01 19:10:13 -07002997 pw.print(" * Destroy "); pw.println(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002998 r.dump(pw, " ");
2999 }
3000 needSep = true;
3001 }
3002
3003 if (dumpAll) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003004 boolean printed = false;
3005 for (int ic=0; ic<mServiceConnections.size(); ic++) {
3006 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
3007 for (int i=0; i<r.size(); i++) {
3008 ConnectionRecord cr = r.get(i);
3009 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
3010 continue;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003011 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003012 if (dumpPackage != null && (cr.binding.client == null
3013 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
3014 continue;
3015 }
3016 printedAnything = true;
3017 if (!printed) {
3018 if (needSep) pw.println();
3019 needSep = true;
3020 pw.println(" Connection bindings to services:");
3021 printed = true;
3022 }
3023 pw.print(" * "); pw.println(cr);
3024 cr.dump(pw, " ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003025 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003026 }
3027 }
3028
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003029 if (!printedAnything) {
3030 pw.println(" (nothing)");
3031 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003032 }
3033
3034 /**
3035 * There are three ways to call this:
3036 * - no service specified: dump all the services
3037 * - a flattened component name that matched an existing service was specified as the
3038 * first arg: dump that one service
3039 * - the first arg isn't the flattened component name of an existing service:
3040 * dump all services whose component contains the first arg as a substring
3041 */
3042 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
3043 int opti, boolean dumpAll) {
3044 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
3045
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003046 synchronized (mAm) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003047 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003048 if ("all".equals(name)) {
3049 for (int user : users) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -07003050 ServiceMap smap = mServiceMap.get(user);
3051 if (smap == null) {
3052 continue;
3053 }
3054 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003055 for (int i=0; i<alls.size(); i++) {
3056 ServiceRecord r1 = alls.valueAt(i);
Amith Yamasani258848d2012-08-10 17:06:33 -07003057 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003058 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003059 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003060 } else {
3061 ComponentName componentName = name != null
3062 ? ComponentName.unflattenFromString(name) : null;
3063 int objectId = 0;
3064 if (componentName == null) {
3065 // Not a '/' separated full component name; maybe an object ID?
3066 try {
3067 objectId = Integer.parseInt(name, 16);
3068 name = null;
3069 componentName = null;
3070 } catch (RuntimeException e) {
3071 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003072 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003073
Dianne Hackborn1676c852012-09-10 14:52:30 -07003074 for (int user : users) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -07003075 ServiceMap smap = mServiceMap.get(user);
3076 if (smap == null) {
3077 continue;
3078 }
3079 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003080 for (int i=0; i<alls.size(); i++) {
3081 ServiceRecord r1 = alls.valueAt(i);
Amith Yamasani258848d2012-08-10 17:06:33 -07003082 if (componentName != null) {
3083 if (r1.name.equals(componentName)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003084 services.add(r1);
3085 }
Amith Yamasani258848d2012-08-10 17:06:33 -07003086 } else if (name != null) {
3087 if (r1.name.flattenToString().contains(name)) {
3088 services.add(r1);
3089 }
3090 } else if (System.identityHashCode(r1) == objectId) {
3091 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003092 }
3093 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003094 }
3095 }
3096 }
3097
3098 if (services.size() <= 0) {
3099 return false;
3100 }
3101
3102 boolean needSep = false;
3103 for (int i=0; i<services.size(); i++) {
3104 if (needSep) {
3105 pw.println();
3106 }
3107 needSep = true;
3108 dumpService("", fd, pw, services.get(i), args, dumpAll);
3109 }
3110 return true;
3111 }
3112
3113 /**
3114 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
3115 * there is a thread associated with the service.
3116 */
3117 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
3118 final ServiceRecord r, String[] args, boolean dumpAll) {
3119 String innerPrefix = prefix + " ";
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003120 synchronized (mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003121 pw.print(prefix); pw.print("SERVICE ");
3122 pw.print(r.shortName); pw.print(" ");
3123 pw.print(Integer.toHexString(System.identityHashCode(r)));
3124 pw.print(" pid=");
3125 if (r.app != null) pw.println(r.app.pid);
3126 else pw.println("(not running)");
3127 if (dumpAll) {
3128 r.dump(pw, innerPrefix);
3129 }
3130 }
3131 if (r.app != null && r.app.thread != null) {
3132 pw.print(prefix); pw.println(" Client:");
3133 pw.flush();
3134 try {
3135 TransferPipe tp = new TransferPipe();
3136 try {
3137 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
3138 tp.setBufferPrefix(prefix + " ");
3139 tp.go(fd);
3140 } finally {
3141 tp.kill();
3142 }
3143 } catch (IOException e) {
3144 pw.println(prefix + " Failure while dumping the service: " + e);
3145 } catch (RemoteException e) {
3146 pw.println(prefix + " Got a RemoteException while dumping the service");
3147 }
3148 }
3149 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003150}