blob: 2f7d4c1ec6342f5d931264494f7b40563fb7afd6 [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
Bryce Lee290e5782017-02-01 16:41:20 -080019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwaled57969f2014-11-15 19:37:29 -080020import static com.android.server.am.ActivityManagerDebugConfig.*;
21
Dianne Hackborn599db5c2012-08-03 19:28:48 -070022import java.io.FileDescriptor;
23import java.io.IOException;
24import java.io.PrintWriter;
Dianne Hackborncff1bbf2015-01-20 13:43:32 -080025import java.io.StringWriter;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070026import java.util.ArrayList;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070027import java.util.HashSet;
28import java.util.Iterator;
29import java.util.List;
Wale Ogunwale540e1232015-05-01 15:35:39 -070030import java.util.Set;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070031
Dianne Hackborn455625e2015-01-21 09:55:13 -080032import android.app.ActivityThread;
Svet Ganov99b60432015-06-27 13:15:22 -070033import android.app.AppOpsManager;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070034import android.app.NotificationManager;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070035import android.app.ServiceStartArgs;
Svet Ganov9c165d72015-12-01 19:52:26 -080036import android.content.IIntentSender;
37import android.content.IntentSender;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070038import android.content.pm.ParceledListSlice;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070039import android.net.Uri;
Christoph Studer365e4c32014-09-18 20:35:36 +020040import android.os.Build;
Svet Ganov9c165d72015-12-01 19:52:26 -080041import android.os.Bundle;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -070042import android.os.DeadObjectException;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070043import android.os.Handler;
Dianne Hackborn13c590d2013-10-07 14:32:00 -070044import android.os.Looper;
Svet Ganov9c165d72015-12-01 19:52:26 -080045import android.os.RemoteCallback;
Dianne Hackborn23037412013-11-04 18:11:29 -080046import android.os.SystemProperties;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -070047import android.os.TransactionTooLargeException;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070048import android.provider.Settings;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070049import android.util.ArrayMap;
Dianne Hackborn465fa392014-09-14 14:21:18 -070050import android.util.ArraySet;
Wale Ogunwaled57969f2014-11-15 19:37:29 -080051
Dianne Hackborn83b40f62017-04-26 13:59:47 -070052import com.android.internal.R;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070053import com.android.internal.app.procstats.ServiceState;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070054import com.android.internal.messages.nano.SystemMessageProto;
55import com.android.internal.notification.SystemNotificationChannels;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070056import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborncbfd23e2013-06-11 14:26:53 -070057import com.android.internal.os.TransferPipe;
Dianne Hackborncff1bbf2015-01-20 13:43:32 -080058import com.android.internal.util.FastPrintWriter;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070059import com.android.server.am.ActivityManagerService.ItemMatcher;
60import com.android.server.am.ActivityManagerService.NeededUriGrants;
Yi Jin6b514142017-10-30 14:54:12 -070061import com.android.server.am.proto.ActiveServicesProto;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070062
63import android.app.ActivityManager;
64import android.app.AppGlobals;
65import android.app.IApplicationThread;
66import android.app.IServiceConnection;
67import android.app.Notification;
68import android.app.PendingIntent;
69import android.app.Service;
70import android.content.ComponentName;
71import android.content.Context;
72import android.content.Intent;
73import android.content.pm.ApplicationInfo;
74import android.content.pm.PackageManager;
75import android.content.pm.ResolveInfo;
76import android.content.pm.ServiceInfo;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070077import android.os.Binder;
78import android.os.IBinder;
79import android.os.Message;
80import android.os.Process;
81import android.os.RemoteException;
82import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070083import android.os.UserHandle;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070084import android.util.EventLog;
Dianne Hackborncb015632017-06-14 17:30:15 -070085import android.util.PrintWriterPrinter;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070086import android.util.Slog;
87import android.util.SparseArray;
88import android.util.TimeUtils;
Yi Jin6b514142017-10-30 14:54:12 -070089import android.util.proto.ProtoOutputStream;
Robert Sesekc5f86642016-11-04 10:20:38 -040090import android.webkit.WebViewZygote;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070091
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -070092public final class ActiveServices {
Wale Ogunwaled57969f2014-11-15 19:37:29 -080093 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM;
94 private static final String TAG_MU = TAG + POSTFIX_MU;
95 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
96 private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING;
97
98 private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE;
99 private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE;
100
101 private static final boolean LOG_SERVICE_START_STOP = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700102
103 // How long we wait for a service to finish executing.
104 static final int SERVICE_TIMEOUT = 20*1000;
105
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700106 // How long we wait for a service to finish executing.
107 static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
108
Christopher Tate08992ac2017-03-21 11:37:06 -0700109 // How long the startForegroundService() grace period is to get around to
110 // calling startForeground() before we ANR + stop it.
111 static final int SERVICE_START_FOREGROUND_TIMEOUT = 5*1000;
112
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700113 final ActivityManagerService mAm;
114
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700115 // Maximum number of services that we allow to start in the background
116 // at the same time.
117 final int mMaxStartingBackground;
118
Wale Ogunwale540e1232015-05-01 15:35:39 -0700119 final SparseArray<ServiceMap> mServiceMap = new SparseArray<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700120
121 /**
122 * All currently bound service connections. Keys are the IBinder of
123 * the client's IServiceConnection.
124 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700125 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700126
127 /**
128 * List of services that we have been asked to start,
129 * but haven't yet been able to. It is used to hold start requests
130 * while waiting for their corresponding application thread to get
131 * going.
132 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700133 final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700134
135 /**
136 * List of services that are scheduled to restart following a crash.
137 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700138 final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700139
140 /**
Dianne Hackborn164371f2013-10-01 19:10:13 -0700141 * List of services that are in the process of being destroyed.
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700142 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700143 final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>();
144
145 /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */
146 private ArrayList<ServiceRecord> mTmpCollectionResults = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700147
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700148 /**
149 * For keeping ActiveForegroundApps retaining state while the screen is off.
150 */
151 boolean mScreenOn = true;
152
Dianne Hackborncff1bbf2015-01-20 13:43:32 -0800153 /** Amount of time to allow a last ANR message to exist before freeing the memory. */
154 static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
155
156 String mLastAnrDump;
157
158 final Runnable mLastAnrDumpClearer = new Runnable() {
159 @Override public void run() {
160 synchronized (mAm) {
161 mLastAnrDump = null;
162 }
163 }
164 };
165
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700166 /**
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700167 * Information about an app that is currently running one or more foreground services.
Dan Sandler2f36ab82017-05-25 00:15:49 -0400168 * (This maps directly to the running apps we show in the notification.)
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700169 */
170 static final class ActiveForegroundApp {
171 String mPackageName;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700172 int mUid;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700173 CharSequence mLabel;
174 boolean mShownWhileScreenOn;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700175 boolean mAppOnTop;
176 boolean mShownWhileTop;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700177 long mStartTime;
178 long mStartVisibleTime;
179 long mEndTime;
180 int mNumActive;
Dianne Hackborncb015632017-06-14 17:30:15 -0700181
182 // Temp output of foregroundAppShownEnoughLocked
183 long mHideTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700184 }
185
186 /**
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700187 * Information about services for a single user.
188 */
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700189 final class ServiceMap extends Handler {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700190 final int mUserId;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700191 final ArrayMap<ComponentName, ServiceRecord> mServicesByName = new ArrayMap<>();
192 final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700193
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700194 final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700195 /* XXX eventually I'd like to have this based on processes instead of services.
196 * That is, if we try to start two services in a row both running in the same
197 * process, this should be one entry in mStartingBackground for that one process
198 * that remains until all services in it are done.
199 final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
200 = new ArrayMap<ProcessRecord, DelayingProcess>();
201 final ArrayList<DelayingProcess> mStartingProcessList
202 = new ArrayList<DelayingProcess>();
203 */
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700204
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700205 final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700206
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700207 final ArrayMap<String, ActiveForegroundApp> mActiveForegroundApps = new ArrayMap<>();
208 boolean mActiveForegroundAppsChanged;
209
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700210 static final int MSG_BG_START_TIMEOUT = 1;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700211 static final int MSG_UPDATE_FOREGROUND_APPS = 2;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700212
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700213 ServiceMap(Looper looper, int userId) {
214 super(looper);
Dianne Hackborn6285a322013-09-18 12:09:47 -0700215 mUserId = userId;
216 }
217
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700218 @Override
219 public void handleMessage(Message msg) {
220 switch (msg.what) {
221 case MSG_BG_START_TIMEOUT: {
222 synchronized (mAm) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700223 rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700224 }
225 } break;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700226 case MSG_UPDATE_FOREGROUND_APPS: {
227 updateForegroundApps(this);
228 } break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700229 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700230 }
231
Dianne Hackbornad51be92016-08-16 16:27:36 -0700232 void ensureNotStartingBackgroundLocked(ServiceRecord r) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700233 if (mStartingBackground.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800234 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
235 "No longer background starting: " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -0700236 rescheduleDelayedStartsLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700237 }
Dianne Hackborn2e46bb52013-09-13 17:01:26 -0700238 if (mDelayedStartList.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800239 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700240 }
241 }
242
Dianne Hackbornad51be92016-08-16 16:27:36 -0700243 void rescheduleDelayedStartsLocked() {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700244 removeMessages(MSG_BG_START_TIMEOUT);
245 final long now = SystemClock.uptimeMillis();
246 for (int i=0, N=mStartingBackground.size(); i<N; i++) {
247 ServiceRecord r = mStartingBackground.get(i);
248 if (r.startingBgTimeout <= now) {
249 Slog.i(TAG, "Waited long enough for: " + r);
250 mStartingBackground.remove(i);
251 N--;
Junu Kimfcb87362014-02-19 16:25:21 +0900252 i--;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700253 }
254 }
255 while (mDelayedStartList.size() > 0
256 && mStartingBackground.size() < mMaxStartingBackground) {
257 ServiceRecord r = mDelayedStartList.remove(0);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800258 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
259 "REM FR DELAY LIST (exec next): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700260 if (r.pendingStarts.size() <= 0) {
261 Slog.w(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
262 + " delayedStop=" + r.delayedStop);
263 }
264 if (DEBUG_DELAYED_SERVICE) {
265 if (mDelayedStartList.size() > 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800266 Slog.v(TAG_SERVICE, "Remaining delayed list:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700267 for (int i=0; i<mDelayedStartList.size(); i++) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800268 Slog.v(TAG_SERVICE, " #" + i + ": " + mDelayedStartList.get(i));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700269 }
270 }
271 }
272 r.delayed = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700273 try {
274 startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false, true);
275 } catch (TransactionTooLargeException e) {
276 // Ignore, nobody upstack cares.
277 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700278 }
279 if (mStartingBackground.size() > 0) {
280 ServiceRecord next = mStartingBackground.get(0);
281 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800282 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700283 + ", can delay others up to " + when);
284 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
285 sendMessageAtTime(msg, when);
286 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700287 if (mStartingBackground.size() < mMaxStartingBackground) {
288 mAm.backgroundServicesFinishedLocked(mUserId);
289 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700290 }
291 }
292
293 public ActiveServices(ActivityManagerService service) {
294 mAm = service;
Dianne Hackborn23037412013-11-04 18:11:29 -0800295 int maxBg = 0;
296 try {
297 maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
298 } catch(RuntimeException e) {
299 }
Dianne Hackborn20d94742014-05-29 18:35:45 -0700300 mMaxStartingBackground = maxBg > 0
301 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700302 }
303
Dianne Hackbornad51be92016-08-16 16:27:36 -0700304 ServiceRecord getServiceByNameLocked(ComponentName name, int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700305 // TODO: Deal with global services
306 if (DEBUG_MU)
Dianne Hackbornad51be92016-08-16 16:27:36 -0700307 Slog.v(TAG_MU, "getServiceByNameLocked(" + name + "), callingUser = " + callingUser);
308 return getServiceMapLocked(callingUser).mServicesByName.get(name);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700309 }
310
Dianne Hackbornad51be92016-08-16 16:27:36 -0700311 boolean hasBackgroundServicesLocked(int callingUser) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700312 ServiceMap smap = mServiceMap.get(callingUser);
313 return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
314 }
315
Dianne Hackbornad51be92016-08-16 16:27:36 -0700316 private ServiceMap getServiceMapLocked(int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700317 ServiceMap smap = mServiceMap.get(callingUser);
318 if (smap == null) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700319 smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700320 mServiceMap.put(callingUser, smap);
321 }
322 return smap;
323 }
324
Dianne Hackbornad51be92016-08-16 16:27:36 -0700325 ArrayMap<ComponentName, ServiceRecord> getServicesLocked(int callingUser) {
326 return getServiceMapLocked(callingUser).mServicesByName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700327 }
328
Svet Ganov99b60432015-06-27 13:15:22 -0700329 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
Christopher Tate242ba3e92017-04-14 15:07:06 -0700330 int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700331 throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800332 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700333 + " type=" + resolvedType + " args=" + service.getExtras());
334
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700335 final boolean callerFg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700336 if (caller != null) {
337 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
338 if (callerApp == null) {
339 throw new SecurityException(
340 "Unable to find app for caller " + caller
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700341 + " (pid=" + callingPid
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700342 + ") when starting service " + service);
343 }
Dianne Hackborna49ad092016-03-03 13:39:10 -0800344 callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700345 } else {
346 callerFg = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700347 }
348
349 ServiceLookupResult res =
Svet Ganov99b60432015-06-27 13:15:22 -0700350 retrieveServiceLocked(service, resolvedType, callingPackage,
Svet Ganovd223db32017-12-22 09:43:48 -0800351 callingPid, callingUid, userId, true, callerFg, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700352 if (res == null) {
353 return null;
354 }
355 if (res.record == null) {
356 return new ComponentName("!", res.permission != null
357 ? res.permission : "private to package");
358 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700359
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700360 ServiceRecord r = res.record;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700361
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700362 if (!mAm.mUserController.exists(r.userId)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700363 Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700364 return null;
365 }
366
Christopher Tate08992ac2017-03-21 11:37:06 -0700367 // If this isn't a direct-to-foreground start, check our ability to kick off an
368 // arbitrary service
369 if (!r.startRequested && !fgRequired) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700370 // Before going further -- if this app is not allowed to start services in the
371 // background, then at this point we aren't going to let it period.
372 final int allowed = mAm.getAppStartModeLocked(r.appInfo.uid, r.packageName,
373 r.appInfo.targetSdkVersion, callingPid, false, false);
374 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
375 Slog.w(TAG, "Background start not allowed: service "
376 + service + " to " + r.name.flattenToShortString()
377 + " from pid=" + callingPid + " uid=" + callingUid
378 + " pkg=" + callingPackage);
379 if (allowed == ActivityManager.APP_START_MODE_DELAYED) {
380 // In this case we are silently disabling the app, to disrupt as
381 // little as possible existing apps.
382 return null;
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700383 }
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700384 // This app knows it is in the new model where this operation is not
385 // allowed, so tell it what has happened.
386 UidRecord uidRec = mAm.mActiveUids.get(r.appInfo.uid);
387 return new ComponentName("?", "app is in background uid " + uidRec);
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700388 }
389 }
390
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700391 NeededUriGrants neededGrants = mAm.checkGrantUriPermissionFromIntentLocked(
Nicolas Prevotc6cf95c2014-05-29 11:30:36 +0100392 callingUid, r.packageName, service, service.getFlags(), null, r.userId);
Svet Ganov9c165d72015-12-01 19:52:26 -0800393
394 // If permissions need a review before any of the app components can run,
395 // we do not start the service and launch a review activity if the calling app
396 // is in the foreground passing it a pending intent to start the service when
397 // review is completed.
Svet Ganov77df6f32016-08-17 11:46:34 -0700398 if (mAm.mPermissionReviewRequired) {
Svet Ganov9c165d72015-12-01 19:52:26 -0800399 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage,
400 callingUid, service, callerFg, userId)) {
401 return null;
402 }
403 }
404
Dianne Hackbornd6f5b622013-11-11 17:25:37 -0800405 if (unscheduleServiceRestartLocked(r, callingUid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800406 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700407 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700408 r.lastActivity = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700409 r.startRequested = true;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700410 r.delayedStop = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700411 r.fgRequired = fgRequired;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700412 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -0700413 service, neededGrants, callingUid));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700414
Dianne Hackbornad51be92016-08-16 16:27:36 -0700415 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700416 boolean addToStarting = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700417 if (!callerFg && !fgRequired && r.app == null
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700418 && mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700419 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700420 if (proc == null || proc.curProcState > ActivityManager.PROCESS_STATE_RECEIVER) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700421 // If this is not coming from a foreground caller, then we may want
422 // to delay the start if there are already other background services
423 // that are starting. This is to avoid process start spam when lots
424 // of applications are all handling things like connectivity broadcasts.
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700425 // We only do this for cached processes, because otherwise an application
426 // can have assumptions about calling startService() for a service to run
427 // in its own process, and for that process to not be killed before the
428 // service is started. This is especially the case for receivers, which
429 // may start a service in onReceive() to do some additional work and have
430 // initialized some global state as part of that.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800431 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
432 + r + " in " + proc);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700433 if (r.delayed) {
434 // This service is already scheduled for a delayed start; just leave
435 // it still waiting.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800436 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700437 return r.name;
438 }
439 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
440 // Something else is starting, delay!
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800441 Slog.i(TAG_SERVICE, "Delaying start of: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700442 smap.mDelayedStartList.add(r);
443 r.delayed = true;
444 return r.name;
445 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800446 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700447 addToStarting = true;
448 } else if (proc.curProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
449 // We slightly loosen when we will enqueue this new service as a background
450 // starting service we are waiting for, to also include processes that are
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700451 // currently running other services or receivers.
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700452 addToStarting = true;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800453 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
454 "Not delaying, but counting as bg: " + r);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800455 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn8e692572013-09-10 19:06:15 -0700456 StringBuilder sb = new StringBuilder(128);
457 sb.append("Not potential delay (state=").append(proc.curProcState)
458 .append(' ').append(proc.adjType);
459 String reason = proc.makeAdjReason();
460 if (reason != null) {
461 sb.append(' ');
462 sb.append(reason);
463 }
464 sb.append("): ");
465 sb.append(r.toString());
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800466 Slog.v(TAG_SERVICE, sb.toString());
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700467 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800468 } else if (DEBUG_DELAYED_STARTS) {
Christopher Tate08992ac2017-03-21 11:37:06 -0700469 if (callerFg || fgRequired) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800470 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
Christopher Tate08992ac2017-03-21 11:37:06 -0700471 + callingUid + " pid=" + callingPid + " fgRequired=" + fgRequired + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700472 } else if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800473 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700474 } else {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800475 Slog.v(TAG_SERVICE,
476 "Not potential delay (user " + r.userId + " not started): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700477 }
478 }
479
Christopher Tate42a386b2016-11-07 12:21:21 -0800480 ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
Christopher Tate42a386b2016-11-07 12:21:21 -0800481 return cmp;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700482 }
483
Svet Ganov9c165d72015-12-01 19:52:26 -0800484 private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
485 String callingPackage, int callingUid, Intent service, boolean callerFg,
486 final int userId) {
487 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
488 r.packageName, r.userId)) {
489
490 // Show a permission review UI only for starting from a foreground app
491 if (!callerFg) {
492 Slog.w(TAG, "u" + r.userId + " Starting a service in package"
493 + r.packageName + " requires a permissions review");
494 return false;
495 }
496
497 IIntentSender target = mAm.getIntentSenderLocked(
498 ActivityManager.INTENT_SENDER_SERVICE, callingPackage,
499 callingUid, userId, null, null, 0, new Intent[]{service},
500 new String[]{service.resolveType(mAm.mContext.getContentResolver())},
501 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
502 | PendingIntent.FLAG_IMMUTABLE, null);
503
504 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
505 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
506 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
507 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
508 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
509
510 if (DEBUG_PERMISSIONS_REVIEW) {
511 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
512 + r.packageName);
513 }
514
515 mAm.mHandler.post(new Runnable() {
516 @Override
517 public void run() {
518 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
519 }
520 });
521
522 return false;
523 }
524
525 return true;
526 }
527
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700528 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
529 boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
Joe Onorato4eb64fd2016-03-21 15:30:09 -0700530 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700531 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700532 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700533 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700534 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700535 synchronized (r.stats.getBatteryStats()) {
536 r.stats.startRunningLocked();
537 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800538 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700539 if (error != null) {
540 return new ComponentName("!!", error);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700541 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700542
543 if (r.startRequested && addToStarting) {
544 boolean first = smap.mStartingBackground.size() == 0;
545 smap.mStartingBackground.add(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700546 r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700547 if (DEBUG_DELAYED_SERVICE) {
548 RuntimeException here = new RuntimeException("here");
549 here.fillInStackTrace();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800550 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800551 } else if (DEBUG_DELAYED_STARTS) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800552 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700553 }
554 if (first) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700555 smap.rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700556 }
Christopher Tate08992ac2017-03-21 11:37:06 -0700557 } else if (callerFg || r.fgRequired) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700558 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700559 }
560
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700561 return r.name;
562 }
563
564 private void stopServiceLocked(ServiceRecord service) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700565 if (service.delayed) {
566 // If service isn't actually running, but is is being held in the
567 // delayed list, then we need to keep it started but note that it
568 // should be stopped once no longer delayed.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800569 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700570 service.delayedStop = true;
571 return;
572 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700573 synchronized (service.stats.getBatteryStats()) {
574 service.stats.stopRunningLocked();
575 }
576 service.startRequested = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700577 if (service.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700578 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700579 SystemClock.uptimeMillis());
580 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700581 service.callStart = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700582 bringDownServiceIfNeededLocked(service, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700583 }
584
585 int stopServiceLocked(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700586 String resolvedType, int userId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800587 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700588 + " type=" + resolvedType);
589
590 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
591 if (caller != null && callerApp == null) {
592 throw new SecurityException(
593 "Unable to find app for caller " + caller
594 + " (pid=" + Binder.getCallingPid()
595 + ") when stopping service " + service);
596 }
597
598 // If this service is active, make sure it is stopped.
Svet Ganov99b60432015-06-27 13:15:22 -0700599 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, null,
Svet Ganovd223db32017-12-22 09:43:48 -0800600 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700601 if (r != null) {
602 if (r.record != null) {
603 final long origId = Binder.clearCallingIdentity();
604 try {
605 stopServiceLocked(r.record);
606 } finally {
607 Binder.restoreCallingIdentity(origId);
608 }
609 return 1;
610 }
611 return -1;
612 }
613
614 return 0;
615 }
616
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700617 void stopInBackgroundLocked(int uid) {
618 // Stop all services associated with this uid due to it going to the background
619 // stopped state.
620 ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
621 ArrayList<ServiceRecord> stopping = null;
622 if (services != null) {
623 for (int i=services.mServicesByName.size()-1; i>=0; i--) {
624 ServiceRecord service = services.mServicesByName.valueAt(i);
625 if (service.appInfo.uid == uid && service.startRequested) {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800626 if (mAm.getAppStartModeLocked(service.appInfo.uid, service.packageName,
627 service.appInfo.targetSdkVersion, -1, false, false)
628 != ActivityManager.APP_START_MODE_NORMAL) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700629 if (stopping == null) {
630 stopping = new ArrayList<>();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700631 }
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700632 String compName = service.name.flattenToShortString();
633 EventLogTags.writeAmStopIdleService(service.appInfo.uid, compName);
634 StringBuilder sb = new StringBuilder(64);
635 sb.append("Stopping service due to app idle: ");
636 UserHandle.formatUid(sb, service.appInfo.uid);
637 sb.append(" ");
Yi Jin6b514142017-10-30 14:54:12 -0700638 TimeUtils.formatDuration(service.createRealTime
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700639 - SystemClock.elapsedRealtime(), sb);
640 sb.append(" ");
641 sb.append(compName);
642 Slog.w(TAG, sb.toString());
643 stopping.add(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700644 }
645 }
646 }
647 if (stopping != null) {
648 for (int i=stopping.size()-1; i>=0; i--) {
649 ServiceRecord service = stopping.get(i);
650 service.delayed = false;
Dianne Hackbornad51be92016-08-16 16:27:36 -0700651 services.ensureNotStartingBackgroundLocked(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700652 stopServiceLocked(service);
653 }
654 }
655 }
656 }
657
Svet Ganov99b60432015-06-27 13:15:22 -0700658 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
659 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, callingPackage,
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -0700660 Binder.getCallingPid(), Binder.getCallingUid(),
Svet Ganovd223db32017-12-22 09:43:48 -0800661 UserHandle.getCallingUserId(), false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700662
663 IBinder ret = null;
664 if (r != null) {
665 // r.record is null if findServiceLocked() failed the caller permission check
666 if (r.record == null) {
667 throw new SecurityException(
Christopher Desjardins5862c5f2015-05-19 11:25:40 +0000668 "Permission Denial: Accessing service"
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700669 + " from pid=" + Binder.getCallingPid()
670 + ", uid=" + Binder.getCallingUid()
671 + " requires " + r.permission);
672 }
673 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
674 if (ib != null) {
675 ret = ib.binder;
676 }
677 }
678
679 return ret;
680 }
681
682 boolean stopServiceTokenLocked(ComponentName className, IBinder token,
683 int startId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800684 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700685 + " " + token + " startId=" + startId);
Dianne Hackborn41203752012-08-31 14:05:51 -0700686 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700687 if (r != null) {
688 if (startId >= 0) {
689 // Asked to only stop if done with all work. Note that
690 // to avoid leaks, we will take this as dropping all
691 // start items up to and including this one.
692 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
693 if (si != null) {
694 while (r.deliveredStarts.size() > 0) {
695 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
696 cur.removeUriPermissionsLocked();
697 if (cur == si) {
698 break;
699 }
700 }
701 }
702
703 if (r.getLastStartId() != startId) {
704 return false;
705 }
706
707 if (r.deliveredStarts.size() > 0) {
708 Slog.w(TAG, "stopServiceToken startId " + startId
709 + " is last, but have " + r.deliveredStarts.size()
710 + " remaining args");
711 }
712 }
713
714 synchronized (r.stats.getBatteryStats()) {
715 r.stats.stopRunningLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700716 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700717 r.startRequested = false;
718 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700719 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700720 SystemClock.uptimeMillis());
721 }
722 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700723 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700724 bringDownServiceIfNeededLocked(r, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700725 Binder.restoreCallingIdentity(origId);
726 return true;
727 }
728 return false;
729 }
730
Sudheer Shankac9d94072017-02-22 22:13:55 +0000731 public void setServiceForegroundLocked(ComponentName className, IBinder token,
Dianne Hackborn67324c92016-04-18 13:55:25 -0700732 int id, Notification notification, int flags) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700733 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700734 final long origId = Binder.clearCallingIdentity();
735 try {
Dianne Hackborn41203752012-08-31 14:05:51 -0700736 ServiceRecord r = findServiceLocked(className, token, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700737 if (r != null) {
Sudheer Shankac9d94072017-02-22 22:13:55 +0000738 setServiceForegroundInnerLocked(r, id, notification, flags);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700739 }
740 } finally {
741 Binder.restoreCallingIdentity(origId);
742 }
743 }
744
Dianne Hackborncb015632017-06-14 17:30:15 -0700745 boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) {
746 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid="
747 + aa.mUid);
748 boolean canRemove = false;
749 aa.mHideTime = Long.MAX_VALUE;
750 if (aa.mShownWhileTop) {
751 // If the app was ever at the top of the screen while the foreground
752 // service was running, then we can always just immediately remove it.
753 canRemove = true;
754 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown while on top");
755 } else if (mScreenOn || aa.mShownWhileScreenOn) {
756 final long minTime = aa.mStartVisibleTime
757 + (aa.mStartTime != aa.mStartVisibleTime
758 ? mAm.mConstants.FGSERVICE_SCREEN_ON_AFTER_TIME
759 : mAm.mConstants.FGSERVICE_MIN_SHOWN_TIME);
760 if (nowElapsed >= minTime) {
761 // If shown while the screen is on, and it has been shown for
762 // at least the minimum show time, then we can now remove it.
763 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown long enough with screen on");
764 canRemove = true;
765 } else {
766 // This is when we will be okay to stop telling the user.
767 long reportTime = nowElapsed + mAm.mConstants.FGSERVICE_MIN_REPORT_TIME;
768 aa.mHideTime = reportTime > minTime ? reportTime : minTime;
769 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
770 + " with screen on");
771 }
772 } else {
773 final long minTime = aa.mEndTime
774 + mAm.mConstants.FGSERVICE_SCREEN_ON_BEFORE_TIME;
775 if (nowElapsed >= minTime) {
776 // If the foreground service has only run while the screen is
777 // off, but it has been gone now for long enough that we won't
778 // care to tell the user about it when the screen comes back on,
779 // then we can remove it now.
780 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - gone long enough with screen off");
781 canRemove = true;
782 } else {
783 // This is when we won't care about this old fg service.
784 aa.mHideTime = minTime;
785 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
786 + " with screen off");
787 }
788 }
789 return canRemove;
790 }
791
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700792 void updateForegroundApps(ServiceMap smap) {
793 // This is called from the handler without the lock held.
794 ArrayList<ActiveForegroundApp> active = null;
795 synchronized (mAm) {
796 final long now = SystemClock.elapsedRealtime();
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700797 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700798 if (smap != null) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700799 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Updating foreground apps for user "
800 + smap.mUserId);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700801 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
802 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -0700803 if (aa.mEndTime != 0) {
804 boolean canRemove = foregroundAppShownEnoughLocked(aa, now);
805 if (canRemove) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700806 // This was up for longer than the timeout, so just remove immediately.
807 smap.mActiveForegroundApps.removeAt(i);
808 smap.mActiveForegroundAppsChanged = true;
809 continue;
810 }
Dianne Hackborncb015632017-06-14 17:30:15 -0700811 if (aa.mHideTime < nextUpdateTime) {
812 nextUpdateTime = aa.mHideTime;
813 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700814 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700815 if (!aa.mAppOnTop) {
816 if (active == null) {
817 active = new ArrayList<>();
818 }
Dianne Hackborncb015632017-06-14 17:30:15 -0700819 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
820 + aa.mPackageName + ", uid=" + aa.mUid);
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700821 active.add(aa);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700822 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700823 }
824 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
825 if (nextUpdateTime < Long.MAX_VALUE) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700826 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Next update time in: "
827 + (nextUpdateTime-now));
828 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700829 smap.sendMessageAtTime(msg, nextUpdateTime
830 + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700831 }
832 }
833 if (!smap.mActiveForegroundAppsChanged) {
834 return;
835 }
836 smap.mActiveForegroundAppsChanged = false;
837 }
838
839 final NotificationManager nm = (NotificationManager) mAm.mContext.getSystemService(
840 Context.NOTIFICATION_SERVICE);
841 final Context context = mAm.mContext;
842
843 if (active != null) {
844 for (int i = 0; i < active.size(); i++) {
845 ActiveForegroundApp aa = active.get(i);
846 if (aa.mLabel == null) {
847 PackageManager pm = context.getPackageManager();
848 try {
849 ApplicationInfo ai = pm.getApplicationInfoAsUser(aa.mPackageName,
850 PackageManager.MATCH_KNOWN_PACKAGES, smap.mUserId);
851 aa.mLabel = ai.loadLabel(pm);
852 } catch (PackageManager.NameNotFoundException e) {
853 aa.mLabel = aa.mPackageName;
854 }
855 }
856 }
857
858 Intent intent;
859 String title;
860 String msg;
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700861 String[] pkgs;
Dan Sandler886e0162017-06-06 14:23:43 -0400862 final long nowElapsed = SystemClock.elapsedRealtime();
863 long oldestStartTime = nowElapsed;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700864 if (active.size() == 1) {
865 intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
866 intent.setData(Uri.fromParts("package", active.get(0).mPackageName, null));
867 title = context.getString(
868 R.string.foreground_service_app_in_background, active.get(0).mLabel);
869 msg = context.getString(R.string.foreground_service_tap_for_details);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700870 pkgs = new String[] { active.get(0).mPackageName };
Dan Sandler2f36ab82017-05-25 00:15:49 -0400871 oldestStartTime = active.get(0).mStartTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700872 } else {
873 intent = new Intent(Settings.ACTION_FOREGROUND_SERVICES_SETTINGS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700874 pkgs = new String[active.size()];
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700875 for (int i = 0; i < active.size(); i++) {
876 pkgs[i] = active.get(i).mPackageName;
Dan Sandler2f36ab82017-05-25 00:15:49 -0400877 oldestStartTime = Math.min(oldestStartTime, active.get(i).mStartTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700878 }
879 intent.putExtra("packages", pkgs);
880 title = context.getString(
881 R.string.foreground_service_apps_in_background, active.size());
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700882 msg = active.get(0).mLabel.toString();
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700883 for (int i = 1; i < active.size(); i++) {
884 msg = context.getString(R.string.foreground_service_multiple_separator,
885 msg, active.get(i).mLabel);
886 }
887 }
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700888 Bundle notificationBundle = new Bundle();
889 notificationBundle.putStringArray(Notification.EXTRA_FOREGROUND_APPS, pkgs);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700890 Notification.Builder n =
891 new Notification.Builder(context,
892 SystemNotificationChannels.FOREGROUND_SERVICE)
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700893 .addExtras(notificationBundle)
Dan Sandler2f36ab82017-05-25 00:15:49 -0400894 .setSmallIcon(R.drawable.stat_sys_vitals)
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700895 .setOngoing(true)
Dan Sandler886e0162017-06-06 14:23:43 -0400896 .setShowWhen(oldestStartTime < nowElapsed)
897 .setWhen(System.currentTimeMillis() - (nowElapsed - oldestStartTime))
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700898 .setColor(context.getColor(
899 com.android.internal.R.color.system_notification_accent_color))
900 .setContentTitle(title)
901 .setContentText(msg)
902 .setContentIntent(
903 PendingIntent.getActivityAsUser(context, 0, intent,
904 PendingIntent.FLAG_UPDATE_CURRENT,
905 null, new UserHandle(smap.mUserId)));
906 nm.notifyAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
907 n.build(), new UserHandle(smap.mUserId));
908 } else {
909 nm.cancelAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
910 new UserHandle(smap.mUserId));
911 }
912 }
913
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700914 private void requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700915 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700916 if (timeElapsed != 0) {
917 smap.sendMessageAtTime(msg,
918 timeElapsed + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700919 } else {
920 smap.mActiveForegroundAppsChanged = true;
921 smap.sendMessage(msg);
922 }
923 }
924
925 private void decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r) {
926 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
927 if (active != null) {
928 active.mNumActive--;
929 if (active.mNumActive <= 0) {
930 active.mEndTime = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -0700931 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Ended running of service");
932 if (foregroundAppShownEnoughLocked(active, active.mEndTime)) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700933 // Have been active for long enough that we will remove it immediately.
934 smap.mActiveForegroundApps.remove(r.packageName);
935 smap.mActiveForegroundAppsChanged = true;
936 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -0700937 } else if (active.mHideTime < Long.MAX_VALUE){
938 requestUpdateActiveForegroundAppsLocked(smap, active.mHideTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700939 }
940 }
941 }
942 }
943
944 void updateScreenStateLocked(boolean screenOn) {
945 if (mScreenOn != screenOn) {
946 mScreenOn = screenOn;
947
948 // If screen is turning on, then we now reset the start time of any foreground
949 // services that were started while the screen was off.
950 if (screenOn) {
951 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -0700952 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Screen turned on");
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700953 for (int i = mServiceMap.size()-1; i >= 0; i--) {
954 ServiceMap smap = mServiceMap.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -0700955 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700956 boolean changed = false;
957 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
958 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
Dianne Hackborncb015632017-06-14 17:30:15 -0700959 if (active.mEndTime == 0) {
960 if (!active.mShownWhileScreenOn) {
961 active.mShownWhileScreenOn = true;
962 active.mStartVisibleTime = nowElapsed;
963 }
964 } else {
965 if (!active.mShownWhileScreenOn
966 && active.mStartVisibleTime == active.mStartTime) {
967 // If this was never shown while the screen was on, then we will
968 // count the time it started being visible as now, to tell the user
969 // about it now that they have a screen to look at.
970 active.mEndTime = active.mStartVisibleTime = nowElapsed;
971 }
972 if (foregroundAppShownEnoughLocked(active, nowElapsed)) {
973 // Have been active for long enough that we will remove it
974 // immediately.
975 smap.mActiveForegroundApps.remove(active.mPackageName);
976 smap.mActiveForegroundAppsChanged = true;
977 changed = true;
978 } else {
979 if (active.mHideTime < nextUpdateTime) {
980 nextUpdateTime = active.mHideTime;
981 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700982 }
983 }
984 }
985 if (changed) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700986 // Need to immediately update.
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700987 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -0700988 } else if (nextUpdateTime < Long.MAX_VALUE) {
989 requestUpdateActiveForegroundAppsLocked(smap, nextUpdateTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700990 }
991 }
992 }
993 }
994 }
995
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700996 void foregroundServiceProcStateChangedLocked(UidRecord uidRec) {
997 ServiceMap smap = mServiceMap.get(UserHandle.getUserId(uidRec.uid));
998 if (smap != null) {
999 boolean changed = false;
1000 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1001 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
1002 if (active.mUid == uidRec.uid) {
1003 if (uidRec.curProcState <= ActivityManager.PROCESS_STATE_TOP) {
1004 if (!active.mAppOnTop) {
1005 active.mAppOnTop = true;
1006 changed = true;
1007 }
1008 active.mShownWhileTop = true;
1009 } else if (active.mAppOnTop) {
1010 active.mAppOnTop = false;
1011 changed = true;
1012 }
1013 }
1014 }
1015 if (changed) {
1016 requestUpdateActiveForegroundAppsLocked(smap, 0);
1017 }
1018 }
1019 }
1020
Sudheer Shankac9d94072017-02-22 22:13:55 +00001021 private void setServiceForegroundInnerLocked(ServiceRecord r, int id,
Christopher Tate42a386b2016-11-07 12:21:21 -08001022 Notification notification, int flags) {
1023 if (id != 0) {
1024 if (notification == null) {
1025 throw new IllegalArgumentException("null notification");
1026 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001027 // Instant apps need permission to create foreground services.
1028 if (r.appInfo.isInstantApp()) {
1029 final int mode = mAm.mAppOpsService.checkOperation(
1030 AppOpsManager.OP_INSTANT_APP_START_FOREGROUND,
1031 r.appInfo.uid,
1032 r.appInfo.packageName);
1033 switch (mode) {
1034 case AppOpsManager.MODE_ALLOWED:
1035 break;
1036 case AppOpsManager.MODE_IGNORED:
1037 Slog.w(TAG, "Instant app " + r.appInfo.packageName
1038 + " does not have permission to create foreground services"
1039 + ", ignoring.");
Sudheer Shankac9d94072017-02-22 22:13:55 +00001040 return;
Chad Brubaker97b383f2017-02-02 15:04:35 -08001041 case AppOpsManager.MODE_ERRORED:
1042 throw new SecurityException("Instant app " + r.appInfo.packageName
1043 + " does not have permission to create foreground services");
1044 default:
1045 try {
1046 if (AppGlobals.getPackageManager().checkPermission(
1047 android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
Svet Ganov2c935912017-11-14 17:36:20 -08001048 r.appInfo.packageName, UserHandle.getUserId(r.appInfo.uid))
1049 != PackageManager.PERMISSION_GRANTED) {
Chad Brubaker97b383f2017-02-02 15:04:35 -08001050 throw new SecurityException("Instant app " + r.appInfo.packageName
1051 + " does not have permission to create foreground"
1052 + "services");
1053 }
1054 } catch (RemoteException e) {
1055 throw new SecurityException("Failed to check instant app permission." ,
1056 e);
1057 }
1058 }
1059 }
Christopher Tate08992ac2017-03-21 11:37:06 -07001060 if (r.fgRequired) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001061 if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001062 Slog.i(TAG, "Service called startForeground() as required: " + r);
1063 }
1064 r.fgRequired = false;
1065 r.fgWaiting = false;
1066 mAm.mHandler.removeMessages(
1067 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
1068 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001069 if (r.foregroundId != id) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001070 cancelForegroundNotificationLocked(r);
Christopher Tate42a386b2016-11-07 12:21:21 -08001071 r.foregroundId = id;
1072 }
1073 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
1074 r.foregroundNoti = notification;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001075 if (!r.isForeground) {
1076 final ServiceMap smap = getServiceMapLocked(r.userId);
1077 if (smap != null) {
1078 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1079 if (active == null) {
1080 active = new ActiveForegroundApp();
1081 active.mPackageName = r.packageName;
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001082 active.mUid = r.appInfo.uid;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001083 active.mShownWhileScreenOn = mScreenOn;
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001084 if (r.app != null) {
1085 active.mAppOnTop = active.mShownWhileTop =
1086 r.app.uidRecord.curProcState
1087 <= ActivityManager.PROCESS_STATE_TOP;
1088 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001089 active.mStartTime = active.mStartVisibleTime
1090 = SystemClock.elapsedRealtime();
1091 smap.mActiveForegroundApps.put(r.packageName, active);
1092 requestUpdateActiveForegroundAppsLocked(smap, 0);
1093 }
1094 active.mNumActive++;
1095 }
1096 r.isForeground = true;
1097 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001098 r.postNotification();
1099 if (r.app != null) {
1100 updateServiceForegroundLocked(r.app, true);
1101 }
1102 getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
1103 mAm.notifyPackageUse(r.serviceInfo.packageName,
1104 PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
1105 } else {
1106 if (r.isForeground) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001107 final ServiceMap smap = getServiceMapLocked(r.userId);
1108 if (smap != null) {
1109 decActiveForegroundAppLocked(smap, r);
1110 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001111 r.isForeground = false;
1112 if (r.app != null) {
1113 mAm.updateLruProcessLocked(r.app, false, null);
1114 updateServiceForegroundLocked(r.app, true);
1115 }
1116 }
1117 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001118 cancelForegroundNotificationLocked(r);
Christopher Tate42a386b2016-11-07 12:21:21 -08001119 r.foregroundId = 0;
1120 r.foregroundNoti = null;
1121 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1122 r.stripForegroundServiceFlagFromNotification();
1123 if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
1124 r.foregroundId = 0;
1125 r.foregroundNoti = null;
1126 }
1127 }
1128 }
1129 }
1130
Christopher Tate08992ac2017-03-21 11:37:06 -07001131 private void cancelForegroundNotificationLocked(ServiceRecord r) {
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001132 if (r.foregroundId != 0) {
1133 // First check to see if this app has any other active foreground services
1134 // with the same notification ID. If so, we shouldn't actually cancel it,
1135 // because that would wipe away the notification that still needs to be shown
1136 // due the other service.
Dianne Hackbornad51be92016-08-16 16:27:36 -07001137 ServiceMap sm = getServiceMapLocked(r.userId);
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001138 if (sm != null) {
1139 for (int i = sm.mServicesByName.size()-1; i >= 0; i--) {
1140 ServiceRecord other = sm.mServicesByName.valueAt(i);
Dianne Hackborn569a4582016-08-04 14:00:22 -07001141 if (other != r && other.foregroundId == r.foregroundId
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001142 && other.packageName.equals(r.packageName)) {
1143 // Found one! Abort the cancel.
1144 return;
1145 }
1146 }
1147 }
1148 r.cancelNotification();
1149 }
1150 }
1151
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001152 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
1153 boolean anyForeground = false;
Dianne Hackbornc8230512013-07-13 21:32:12 -07001154 for (int i=proc.services.size()-1; i>=0; i--) {
1155 ServiceRecord sr = proc.services.valueAt(i);
Christopher Tatee23fa2b2017-04-20 14:48:13 -07001156 if (sr.isForeground || sr.fgRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001157 anyForeground = true;
1158 break;
1159 }
1160 }
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08001161 mAm.updateProcessForegroundLocked(proc, anyForeground, oomAdj);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001162 }
1163
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001164 private void updateWhitelistManagerLocked(ProcessRecord proc) {
1165 proc.whitelistManager = false;
1166 for (int i=proc.services.size()-1; i>=0; i--) {
1167 ServiceRecord sr = proc.services.valueAt(i);
1168 if (sr.whitelistManager) {
1169 proc.whitelistManager = true;
1170 break;
1171 }
1172 }
1173 }
1174
Dianne Hackborn465fa392014-09-14 14:21:18 -07001175 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
1176 ArraySet<ProcessRecord> updatedProcesses = null;
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001177 for (int i = 0; i < clientProc.connections.size(); i++) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001178 final ConnectionRecord conn = clientProc.connections.valueAt(i);
1179 final ProcessRecord proc = conn.binding.service.app;
1180 if (proc == null || proc == clientProc) {
1181 continue;
1182 } else if (updatedProcesses == null) {
1183 updatedProcesses = new ArraySet<>();
1184 } else if (updatedProcesses.contains(proc)) {
1185 continue;
1186 }
1187 updatedProcesses.add(proc);
1188 updateServiceClientActivitiesLocked(proc, null, false);
1189 }
1190 }
1191
Dianne Hackborndb926082013-10-31 16:32:44 -07001192 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
Dianne Hackborn465fa392014-09-14 14:21:18 -07001193 ConnectionRecord modCr, boolean updateLru) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001194 if (modCr != null && modCr.binding.client != null) {
1195 if (modCr.binding.client.activities.size() <= 0) {
1196 // This connection is from a client without activities, so adding
1197 // and removing is not interesting.
1198 return false;
1199 }
1200 }
1201
1202 boolean anyClientActivities = false;
1203 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
1204 ServiceRecord sr = proc.services.valueAt(i);
1205 for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) {
1206 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni);
1207 for (int cri=clist.size()-1; cri>=0; cri--) {
1208 ConnectionRecord cr = clist.get(cri);
1209 if (cr.binding.client == null || cr.binding.client == proc) {
1210 // Binding to ourself is not interesting.
1211 continue;
1212 }
1213 if (cr.binding.client.activities.size() > 0) {
1214 anyClientActivities = true;
1215 break;
1216 }
1217 }
1218 }
1219 }
1220 if (anyClientActivities != proc.hasClientActivities) {
1221 proc.hasClientActivities = anyClientActivities;
Dianne Hackborn465fa392014-09-14 14:21:18 -07001222 if (updateLru) {
1223 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
1224 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001225 return true;
1226 }
1227 return false;
1228 }
1229
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001230 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
Svet Ganov9c165d72015-12-01 19:52:26 -08001231 String resolvedType, final IServiceConnection connection, int flags,
1232 String callingPackage, final int userId) throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001233 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001234 + " type=" + resolvedType + " conn=" + connection.asBinder()
1235 + " flags=0x" + Integer.toHexString(flags));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001236 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
1237 if (callerApp == null) {
1238 throw new SecurityException(
1239 "Unable to find app for caller " + caller
1240 + " (pid=" + Binder.getCallingPid()
1241 + ") when binding service " + service);
1242 }
1243
1244 ActivityRecord activity = null;
1245 if (token != null) {
Craig Mautnerd2328952013-03-05 12:46:26 -08001246 activity = ActivityRecord.isInStackLocked(token);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001247 if (activity == null) {
1248 Slog.w(TAG, "Binding with unknown activity: " + token);
1249 return 0;
1250 }
1251 }
1252
1253 int clientLabel = 0;
1254 PendingIntent clientIntent = null;
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001255 final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001256
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001257 if (isCallerSystem) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001258 // Hacky kind of thing -- allow system stuff to tell us
1259 // what they are, so we can report this elsewhere for
1260 // others to know why certain services are running.
Jeff Sharkeyf0ec2e02016-03-21 12:37:54 -06001261 service.setDefusable(true);
1262 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001263 if (clientIntent != null) {
1264 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
1265 if (clientLabel != 0) {
1266 // There are no useful extras in the intent, trash them.
1267 // System code calling with this stuff just needs to know
1268 // this will happen.
1269 service = service.cloneFilter();
1270 }
1271 }
1272 }
1273
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001274 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1275 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
1276 "BIND_TREAT_LIKE_ACTIVITY");
1277 }
1278
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001279 if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
1280 throw new SecurityException(
1281 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1282 + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
1283 }
1284
Svet Ganovd223db32017-12-22 09:43:48 -08001285 if ((flags & Context.BIND_ALLOW_INSTANT) != 0 && !isCallerSystem) {
1286 throw new SecurityException(
1287 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1288 + ") set BIND_ALLOW_INSTANT when binding service " + service);
1289 }
1290
Dianne Hackborna49ad092016-03-03 13:39:10 -08001291 final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Robert Sesekb9a86662015-12-09 16:22:45 -05001292 final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
Svet Ganovd223db32017-12-22 09:43:48 -08001293 final boolean allowInstant = (flags & Context.BIND_ALLOW_INSTANT) != 0;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001294
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001295 ServiceLookupResult res =
Robert Sesekb9a86662015-12-09 16:22:45 -05001296 retrieveServiceLocked(service, resolvedType, callingPackage, Binder.getCallingPid(),
Svet Ganovd223db32017-12-22 09:43:48 -08001297 Binder.getCallingUid(), userId, true, callerFg, isBindExternal, allowInstant);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001298 if (res == null) {
1299 return 0;
1300 }
1301 if (res.record == null) {
1302 return -1;
1303 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001304 ServiceRecord s = res.record;
1305
Svet Ganov9c165d72015-12-01 19:52:26 -08001306 boolean permissionsReviewRequired = false;
1307
1308 // If permissions need a review before any of the app components can run,
1309 // we schedule binding to the service but do not start its process, then
1310 // we launch a review activity to which is passed a callback to invoke
1311 // when done to start the bound service's process to completing the binding.
Svet Ganov77df6f32016-08-17 11:46:34 -07001312 if (mAm.mPermissionReviewRequired) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001313 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
1314 s.packageName, s.userId)) {
1315
1316 permissionsReviewRequired = true;
1317
1318 // Show a permission review UI only for binding from a foreground app
1319 if (!callerFg) {
1320 Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
1321 + s.packageName + " requires a permissions review");
1322 return 0;
1323 }
1324
1325 final ServiceRecord serviceRecord = s;
1326 final Intent serviceIntent = service;
1327
1328 RemoteCallback callback = new RemoteCallback(
1329 new RemoteCallback.OnResultListener() {
1330 @Override
1331 public void onResult(Bundle result) {
1332 synchronized(mAm) {
1333 final long identity = Binder.clearCallingIdentity();
1334 try {
1335 if (!mPendingServices.contains(serviceRecord)) {
1336 return;
1337 }
1338 // If there is still a pending record, then the service
1339 // binding request is still valid, so hook them up. We
1340 // proceed only if the caller cleared the review requirement
1341 // otherwise we unbind because the user didn't approve.
1342 if (!mAm.getPackageManagerInternalLocked()
1343 .isPermissionsReviewRequired(
1344 serviceRecord.packageName,
1345 serviceRecord.userId)) {
1346 try {
1347 bringUpServiceLocked(serviceRecord,
1348 serviceIntent.getFlags(),
1349 callerFg, false, false);
1350 } catch (RemoteException e) {
1351 /* ignore - local call */
1352 }
1353 } else {
1354 unbindServiceLocked(connection);
1355 }
1356 } finally {
1357 Binder.restoreCallingIdentity(identity);
1358 }
1359 }
1360 }
1361 });
1362
1363 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
1364 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1365 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1366 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
1367 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
1368
1369 if (DEBUG_PERMISSIONS_REVIEW) {
1370 Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
1371 + s.packageName);
1372 }
1373
1374 mAm.mHandler.post(new Runnable() {
1375 @Override
1376 public void run() {
1377 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
1378 }
1379 });
1380 }
1381 }
1382
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001383 final long origId = Binder.clearCallingIdentity();
1384
1385 try {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001386 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001387 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001388 + s);
1389 }
1390
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001391 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1392 s.lastActivity = SystemClock.uptimeMillis();
1393 if (!s.hasAutoCreateConnections()) {
1394 // This is the first binding, let the tracker know.
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001395 ServiceState stracker = s.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001396 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001397 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001398 s.lastActivity);
1399 }
1400 }
1401 }
1402
Joe Onorato05c9ecc2016-03-30 15:13:46 -07001403 mAm.startAssociationLocked(callerApp.uid, callerApp.processName, callerApp.curProcState,
Dianne Hackbornab2df062015-01-07 13:43:13 -08001404 s.appInfo.uid, s.name, s.processName);
Jesse Evans02af3ea2017-05-03 09:57:16 -07001405 // Once the apps have become associated, if one of them is caller is ephemeral
1406 // the target app should now be able to see the calling app
1407 mAm.grantEphemeralAccessLocked(callerApp.userId, service,
1408 s.appInfo.uid, UserHandle.getAppId(callerApp.uid));
Dianne Hackbornab2df062015-01-07 13:43:13 -08001409
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001410 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
1411 ConnectionRecord c = new ConnectionRecord(b, activity,
1412 connection, flags, clientLabel, clientIntent);
1413
1414 IBinder binder = connection.asBinder();
1415 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
1416 if (clist == null) {
1417 clist = new ArrayList<ConnectionRecord>();
1418 s.connections.put(binder, clist);
1419 }
1420 clist.add(c);
1421 b.connections.add(c);
1422 if (activity != null) {
1423 if (activity.connections == null) {
1424 activity.connections = new HashSet<ConnectionRecord>();
1425 }
1426 activity.connections.add(c);
1427 }
1428 b.client.connections.add(c);
1429 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
1430 b.client.hasAboveClient = true;
1431 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001432 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
1433 s.whitelistManager = true;
1434 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001435 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001436 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07001437 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001438 clist = mServiceConnections.get(binder);
1439 if (clist == null) {
1440 clist = new ArrayList<ConnectionRecord>();
1441 mServiceConnections.put(binder, clist);
1442 }
1443 clist.add(c);
1444
1445 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1446 s.lastActivity = SystemClock.uptimeMillis();
Svet Ganov9c165d72015-12-01 19:52:26 -08001447 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
1448 permissionsReviewRequired) != null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001449 return 0;
1450 }
1451 }
1452
1453 if (s.app != null) {
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001454 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1455 s.app.treatLikeActivity = true;
1456 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001457 if (s.whitelistManager) {
1458 s.app.whitelistManager = true;
1459 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001460 // This could have made the service more important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001461 mAm.updateLruProcessLocked(s.app, s.app.hasClientActivities
1462 || s.app.treatLikeActivity, b.client);
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001463 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001464 }
1465
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001466 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001467 + ": received=" + b.intent.received
1468 + " apps=" + b.intent.apps.size()
1469 + " doRebind=" + b.intent.doRebind);
1470
1471 if (s.app != null && b.intent.received) {
1472 // Service is already running, so we can immediately
1473 // publish the connection.
1474 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001475 c.conn.connected(s.name, b.intent.binder, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001476 } catch (Exception e) {
1477 Slog.w(TAG, "Failure sending service " + s.shortName
1478 + " to connection " + c.conn.asBinder()
1479 + " (in " + c.binding.client.processName + ")", e);
1480 }
1481
1482 // If this is the first app connected back to this binding,
1483 // and the service had previously asked to be told when
1484 // rebound, then do so.
1485 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001486 requestServiceBindingLocked(s, b.intent, callerFg, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001487 }
1488 } else if (!b.intent.requested) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001489 requestServiceBindingLocked(s, b.intent, callerFg, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001490 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001491
Dianne Hackbornad51be92016-08-16 16:27:36 -07001492 getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001493
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001494 } finally {
1495 Binder.restoreCallingIdentity(origId);
1496 }
1497
1498 return 1;
1499 }
1500
1501 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
1502 final long origId = Binder.clearCallingIdentity();
1503 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001504 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001505 + " " + intent + ": " + service);
1506 if (r != null) {
1507 Intent.FilterComparison filter
1508 = new Intent.FilterComparison(intent);
1509 IntentBindRecord b = r.bindings.get(filter);
1510 if (b != null && !b.received) {
1511 b.binder = service;
1512 b.requested = true;
1513 b.received = true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07001514 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1515 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
1516 for (int i=0; i<clist.size(); i++) {
1517 ConnectionRecord c = clist.get(i);
1518 if (!filter.equals(c.binding.intent.intent)) {
1519 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001520 TAG_SERVICE, "Not publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001521 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001522 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001523 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001524 TAG_SERVICE, "Published intent: " + intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001525 continue;
1526 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001527 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001528 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001529 c.conn.connected(r.name, service, false);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001530 } catch (Exception e) {
1531 Slog.w(TAG, "Failure sending service " + r.name +
1532 " to connection " + c.conn.asBinder() +
1533 " (in " + c.binding.client.processName + ")", e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001534 }
1535 }
1536 }
1537 }
1538
Dianne Hackborn164371f2013-10-01 19:10:13 -07001539 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001540 }
1541 } finally {
1542 Binder.restoreCallingIdentity(origId);
1543 }
1544 }
1545
1546 boolean unbindServiceLocked(IServiceConnection connection) {
1547 IBinder binder = connection.asBinder();
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001548 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001549 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1550 if (clist == null) {
1551 Slog.w(TAG, "Unbind failed: could not find connection for "
1552 + connection.asBinder());
1553 return false;
1554 }
1555
1556 final long origId = Binder.clearCallingIdentity();
1557 try {
1558 while (clist.size() > 0) {
1559 ConnectionRecord r = clist.get(0);
1560 removeConnectionLocked(r, null, null);
Dianne Hackborn25e1eca2014-09-23 10:13:13 -07001561 if (clist.size() > 0 && clist.get(0) == r) {
1562 // In case it didn't get removed above, do it now.
1563 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
1564 clist.remove(0);
1565 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001566
1567 if (r.binding.service.app != null) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001568 if (r.binding.service.app.whitelistManager) {
Felipe Lemea7778b02016-06-28 10:38:59 -07001569 updateWhitelistManagerLocked(r.binding.service.app);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001570 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001571 // This could have made the service less important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001572 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1573 r.binding.service.app.treatLikeActivity = true;
1574 mAm.updateLruProcessLocked(r.binding.service.app,
1575 r.binding.service.app.hasClientActivities
1576 || r.binding.service.app.treatLikeActivity, null);
1577 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001578 mAm.updateOomAdjLocked(r.binding.service.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001579 }
1580 }
Amith Yamasanib2926b12017-05-11 11:13:52 -07001581
1582 mAm.updateOomAdjLocked();
1583
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001584 } finally {
1585 Binder.restoreCallingIdentity(origId);
1586 }
1587
1588 return true;
1589 }
1590
1591 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
1592 final long origId = Binder.clearCallingIdentity();
1593 try {
1594 if (r != null) {
1595 Intent.FilterComparison filter
1596 = new Intent.FilterComparison(intent);
1597 IntentBindRecord b = r.bindings.get(filter);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001598 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001599 + " at " + b + ": apps="
1600 + (b != null ? b.apps.size() : 0));
1601
Dianne Hackborn164371f2013-10-01 19:10:13 -07001602 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001603 if (b != null) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001604 if (b.apps.size() > 0 && !inDestroying) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001605 // Applications have already bound since the last
1606 // unbind, so just rebind right here.
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001607 boolean inFg = false;
1608 for (int i=b.apps.size()-1; i>=0; i--) {
1609 ProcessRecord client = b.apps.valueAt(i).client;
1610 if (client != null && client.setSchedGroup
Dianne Hackborna49ad092016-03-03 13:39:10 -08001611 != ProcessList.SCHED_GROUP_BACKGROUND) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001612 inFg = true;
1613 break;
1614 }
1615 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001616 try {
1617 requestServiceBindingLocked(r, b, inFg, true);
1618 } catch (TransactionTooLargeException e) {
1619 // Don't pass this back to ActivityThread, it's unrelated.
1620 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001621 } else {
1622 // Note to tell the service the next time there is
1623 // a new client.
1624 b.doRebind = true;
1625 }
1626 }
1627
Dianne Hackborn164371f2013-10-01 19:10:13 -07001628 serviceDoneExecutingLocked(r, inDestroying, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001629 }
1630 } finally {
1631 Binder.restoreCallingIdentity(origId);
1632 }
1633 }
1634
1635 private final ServiceRecord findServiceLocked(ComponentName name,
Dianne Hackborn41203752012-08-31 14:05:51 -07001636 IBinder token, int userId) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07001637 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001638 return r == token ? r : null;
1639 }
1640
1641 private final class ServiceLookupResult {
1642 final ServiceRecord record;
1643 final String permission;
1644
1645 ServiceLookupResult(ServiceRecord _record, String _permission) {
1646 record = _record;
1647 permission = _permission;
1648 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001649 }
1650
1651 private class ServiceRestarter implements Runnable {
1652 private ServiceRecord mService;
1653
1654 void setService(ServiceRecord service) {
1655 mService = service;
1656 }
1657
1658 public void run() {
1659 synchronized(mAm) {
1660 performServiceRestartLocked(mService);
1661 }
1662 }
1663 }
1664
1665 private ServiceLookupResult retrieveServiceLocked(Intent service,
Svet Ganov99b60432015-06-27 13:15:22 -07001666 String resolvedType, String callingPackage, int callingPid, int callingUid, int userId,
Svet Ganovd223db32017-12-22 09:43:48 -08001667 boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
1668 boolean allowInstant) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001669 ServiceRecord r = null;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001670 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001671 + " type=" + resolvedType + " callingUid=" + callingUid);
1672
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001673 userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
1674 ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE, "service", null);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001675
Dianne Hackbornad51be92016-08-16 16:27:36 -07001676 ServiceMap smap = getServiceMapLocked(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001677 final ComponentName comp = service.getComponent();
1678 if (comp != null) {
1679 r = smap.mServicesByName.get(comp);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001680 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001681 }
Robert Sesekb9a86662015-12-09 16:22:45 -05001682 if (r == null && !isBindExternal) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001683 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001684 r = smap.mServicesByIntent.get(filter);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001685 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001686 }
Robert Sesekb9a86662015-12-09 16:22:45 -05001687 if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
1688 && !callingPackage.equals(r.packageName)) {
1689 // If an external service is running within its own package, other packages
1690 // should not bind to that instance.
1691 r = null;
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001692 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Whoops, can't use existing external service");
Robert Sesekb9a86662015-12-09 16:22:45 -05001693 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001694 if (r == null) {
1695 try {
Svet Ganovd223db32017-12-22 09:43:48 -08001696 int flags = ActivityManagerService.STOCK_PM_FLAGS
1697 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
1698 if (allowInstant) {
1699 flags |= PackageManager.MATCH_INSTANT;
1700 }
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001701 // TODO: come back and remove this assumption to triage all services
Todd Kennedy51b3aac2017-03-30 17:50:42 -07001702 ResolveInfo rInfo = mAm.getPackageManagerInternalLocked().resolveService(service,
Svet Ganovd223db32017-12-22 09:43:48 -08001703 resolvedType, flags, userId, callingUid);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001704 ServiceInfo sInfo =
1705 rInfo != null ? rInfo.serviceInfo : null;
1706 if (sInfo == null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001707 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001708 ": not found");
1709 return null;
1710 }
1711 ComponentName name = new ComponentName(
1712 sInfo.applicationInfo.packageName, sInfo.name);
Robert Sesekb9a86662015-12-09 16:22:45 -05001713 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
1714 if (isBindExternal) {
1715 if (!sInfo.exported) {
1716 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1717 " is not exported");
1718 }
1719 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
1720 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1721 " is not an isolatedProcess");
1722 }
1723 // Run the service under the calling package's application.
1724 ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
1725 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
1726 if (aInfo == null) {
1727 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
1728 "could not resolve client package " + callingPackage);
1729 }
1730 sInfo = new ServiceInfo(sInfo);
1731 sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
1732 sInfo.applicationInfo.packageName = aInfo.packageName;
1733 sInfo.applicationInfo.uid = aInfo.uid;
1734 name = new ComponentName(aInfo.packageName, name.getClassName());
1735 service.setComponent(name);
1736 } else {
1737 throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
1738 name);
1739 }
1740 } else if (isBindExternal) {
1741 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1742 " is not an externalService");
1743 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001744 if (userId > 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001745 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
Amith Yamasani4b9d79c2014-05-21 19:14:21 -07001746 sInfo.name, sInfo.flags)
1747 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001748 userId = 0;
Dianne Hackbornad51be92016-08-16 16:27:36 -07001749 smap = getServiceMapLocked(0);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001750 }
1751 sInfo = new ServiceInfo(sInfo);
1752 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
1753 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001754 r = smap.mServicesByName.get(name);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001755 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE,
1756 "Retrieved via pm by intent: " + r);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001757 if (r == null && createIfNeeded) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001758 final Intent.FilterComparison filter
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001759 = new Intent.FilterComparison(service.cloneFilter());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001760 final ServiceRestarter res = new ServiceRestarter();
1761 final BatteryStatsImpl.Uid.Pkg.Serv ss;
1762 final BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001763 synchronized (stats) {
1764 ss = stats.getServiceStatsLocked(
1765 sInfo.applicationInfo.uid, sInfo.packageName,
1766 sInfo.name);
1767 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001768 r = new ServiceRecord(mAm, ss, name, filter, sInfo, callingFromFg, res);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001769 res.setService(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001770 smap.mServicesByName.put(name, r);
1771 smap.mServicesByIntent.put(filter, r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001772
1773 // Make sure this component isn't in the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001774 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001775 final ServiceRecord pr = mPendingServices.get(i);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001776 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
1777 && pr.name.equals(name)) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001778 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001779 mPendingServices.remove(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001780 }
1781 }
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001782 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001783 }
1784 } catch (RemoteException ex) {
1785 // pm is in same process, this will never happen.
1786 }
1787 }
1788 if (r != null) {
1789 if (mAm.checkComponentPermission(r.permission,
Bryce Lee290e5782017-02-01 16:41:20 -08001790 callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001791 if (!r.exported) {
1792 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1793 + " from pid=" + callingPid
1794 + ", uid=" + callingUid
1795 + " that is not exported from uid " + r.appInfo.uid);
1796 return new ServiceLookupResult(null, "not exported from uid "
1797 + r.appInfo.uid);
1798 }
1799 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1800 + " from pid=" + callingPid
1801 + ", uid=" + callingUid
1802 + " requires " + r.permission);
1803 return new ServiceLookupResult(null, r.permission);
Svet Ganov99b60432015-06-27 13:15:22 -07001804 } else if (r.permission != null && callingPackage != null) {
1805 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
1806 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation(
1807 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
1808 Slog.w(TAG, "Appop Denial: Accessing service " + r.name
1809 + " from pid=" + callingPid
1810 + ", uid=" + callingUid
1811 + " requires appop " + AppOpsManager.opToName(opCode));
1812 return null;
1813 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001814 }
Svet Ganov99b60432015-06-27 13:15:22 -07001815
Ben Gruverf5323fe2013-07-31 15:09:51 -07001816 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
1817 resolvedType, r.appInfo)) {
Ben Gruverb6223792013-07-29 16:35:40 -07001818 return null;
1819 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001820 return new ServiceLookupResult(r, null);
1821 }
1822 return null;
1823 }
1824
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001825 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001826 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001827 + why + " of " + r + " in app " + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001828 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001829 + why + " of " + r.shortName);
1830 long now = SystemClock.uptimeMillis();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001831 if (r.executeNesting == 0) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001832 r.executeFg = fg;
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001833 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001834 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001835 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001836 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001837 if (r.app != null) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001838 r.app.executingServices.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001839 r.app.execServicesFg |= fg;
Dianne Hackborn2be00932013-09-22 16:46:00 -07001840 if (r.app.executingServices.size() == 1) {
1841 scheduleServiceTimeoutLocked(r.app);
1842 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001843 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001844 } else if (r.app != null && fg && !r.app.execServicesFg) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001845 r.app.execServicesFg = true;
Dianne Hackborn2be00932013-09-22 16:46:00 -07001846 scheduleServiceTimeoutLocked(r.app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001847 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001848 r.executeFg |= fg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001849 r.executeNesting++;
1850 r.executingStart = now;
1851 }
1852
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001853 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
1854 boolean execInFg, boolean rebind) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001855 if (r.app == null || r.app.thread == null) {
1856 // If service is not currently running, can't yet bind.
1857 return false;
1858 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08001859 if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
1860 + " rebind=" + rebind);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001861 if ((!i.requested || rebind) && i.apps.size() > 0) {
1862 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001863 bumpServiceExecutingLocked(r, execInFg, "bind");
Dianne Hackborna413dc02013-07-12 12:02:55 -07001864 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
1865 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
1866 r.app.repProcState);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001867 if (!rebind) {
1868 i.requested = true;
1869 }
1870 i.hasBound = true;
1871 i.doRebind = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001872 } catch (TransactionTooLargeException e) {
1873 // Keep the executeNesting count accurate.
1874 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
1875 final boolean inDestroying = mDestroyingServices.contains(r);
1876 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
1877 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001878 } catch (RemoteException e) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001879 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001880 // Keep the executeNesting count accurate.
1881 final boolean inDestroying = mDestroyingServices.contains(r);
1882 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001883 return false;
1884 }
1885 }
1886 return true;
1887 }
1888
Dianne Hackbornad51be92016-08-16 16:27:36 -07001889 private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001890 boolean canceled = false;
1891
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07001892 if (mAm.isShuttingDownLocked()) {
1893 Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortName
1894 + " - system is shutting down");
1895 return false;
1896 }
1897
Dianne Hackbornad51be92016-08-16 16:27:36 -07001898 ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001899 if (smap.mServicesByName.get(r.name) != r) {
1900 ServiceRecord cur = smap.mServicesByName.get(r.name);
1901 Slog.wtf(TAG, "Attempting to schedule restart of " + r
1902 + " when found in map: " + cur);
1903 return false;
1904 }
1905
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001906 final long now = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001907
1908 if ((r.serviceInfo.applicationInfo.flags
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001909 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001910 long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION;
1911 long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001912
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001913 // Any delivered but not yet finished starts should be put back
1914 // on the pending list.
1915 final int N = r.deliveredStarts.size();
1916 if (N > 0) {
1917 for (int i=N-1; i>=0; i--) {
1918 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
1919 si.removeUriPermissionsLocked();
1920 if (si.intent == null) {
1921 // We'll generate this again if needed.
1922 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
1923 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
1924 r.pendingStarts.add(0, si);
1925 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
1926 dur *= 2;
1927 if (minDuration < dur) minDuration = dur;
1928 if (resetTime < dur) resetTime = dur;
1929 } else {
1930 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
1931 + r.name);
1932 canceled = true;
1933 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001934 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001935 r.deliveredStarts.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001936 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001937
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001938 r.totalRestartCount++;
1939 if (r.restartDelay == 0) {
1940 r.restartCount++;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001941 r.restartDelay = minDuration;
Amith Yamasanib0c8a882017-08-28 09:36:42 -07001942 } else if (r.crashCount > 1) {
1943 r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
1944 * (r.crashCount - 1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001945 } else {
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001946 // If it has been a "reasonably long time" since the service
1947 // was started, then reset our restart duration back to
1948 // the beginning, so we don't infinitely increase the duration
1949 // on a service that just occasionally gets killed (which is
1950 // a normal case, due to process being killed to reclaim memory).
1951 if (now > (r.restartTime+resetTime)) {
1952 r.restartCount = 1;
1953 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001954 } else {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001955 r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
Dianne Hackborn7b492722013-11-01 09:58:45 -07001956 if (r.restartDelay < minDuration) {
1957 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001958 }
1959 }
1960 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001961
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001962 r.nextRestartTime = now + r.restartDelay;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001963
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001964 // Make sure that we don't end up restarting a bunch of services
1965 // all at the same time.
1966 boolean repeat;
1967 do {
1968 repeat = false;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001969 final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001970 for (int i=mRestartingServices.size()-1; i>=0; i--) {
1971 ServiceRecord r2 = mRestartingServices.get(i);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001972 if (r2 != r && r.nextRestartTime >= (r2.nextRestartTime-restartTimeBetween)
1973 && r.nextRestartTime < (r2.nextRestartTime+restartTimeBetween)) {
1974 r.nextRestartTime = r2.nextRestartTime + restartTimeBetween;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001975 r.restartDelay = r.nextRestartTime - now;
1976 repeat = true;
1977 break;
1978 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001979 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001980 } while (repeat);
1981
1982 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07001983 // Persistent processes are immediately restarted, so there is no
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001984 // reason to hold of on restarting their services.
1985 r.totalRestartCount++;
1986 r.restartCount = 0;
1987 r.restartDelay = 0;
1988 r.nextRestartTime = now;
1989 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001990
1991 if (!mRestartingServices.contains(r)) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001992 r.createdFromFg = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001993 mRestartingServices.add(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001994 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001995 }
1996
Christopher Tate08992ac2017-03-21 11:37:06 -07001997 cancelForegroundNotificationLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001998
1999 mAm.mHandler.removeCallbacks(r.restarter);
2000 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
2001 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
2002 Slog.w(TAG, "Scheduling restart of crashed service "
2003 + r.shortName + " in " + r.restartDelay + "ms");
2004 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002005 r.userId, r.shortName, r.restartDelay);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002006
2007 return canceled;
2008 }
2009
2010 final void performServiceRestartLocked(ServiceRecord r) {
2011 if (!mRestartingServices.contains(r)) {
2012 return;
2013 }
Dianne Hackbornad51be92016-08-16 16:27:36 -07002014 if (!isServiceNeededLocked(r, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002015 // Paranoia: is this service actually needed? In theory a service that is not
2016 // needed should never remain on the restart list. In practice... well, there
2017 // have been bugs where this happens, and bad things happen because the process
2018 // ends up just being cached, so quickly killed, then restarted again and again.
2019 // Let's not let that happen.
2020 Slog.wtf(TAG, "Restarting service that is not needed: " + r);
2021 return;
2022 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002023 try {
Svet Ganov9c165d72015-12-01 19:52:26 -08002024 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002025 } catch (TransactionTooLargeException e) {
2026 // Ignore, it's been logged and nothing upstack cares.
2027 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002028 }
2029
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002030 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
2031 boolean force) {
2032 if (!force && r.restartDelay == 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002033 return false;
2034 }
Dianne Hackborn7b492722013-11-01 09:58:45 -07002035 // Remove from the restarting list; if the service is currently on the
2036 // restarting list, or the call is coming from another app, then this
2037 // service has become of much more interest so we reset the restart interval.
2038 boolean removed = mRestartingServices.remove(r);
2039 if (removed || callingUid != r.appInfo.uid) {
2040 r.resetRestartCounter();
2041 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002042 if (removed) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002043 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002044 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002045 mAm.mHandler.removeCallbacks(r.restarter);
2046 return true;
2047 }
2048
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002049 private void clearRestartingIfNeededLocked(ServiceRecord r) {
2050 if (r.restartTracker != null) {
2051 // If this is the last restarting record with this tracker, then clear
2052 // the tracker's restarting state.
2053 boolean stillTracking = false;
2054 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2055 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
2056 stillTracking = true;
2057 break;
2058 }
2059 }
2060 if (!stillTracking) {
2061 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
2062 SystemClock.uptimeMillis());
2063 r.restartTracker = null;
2064 }
2065 }
2066 }
2067
Svet Ganov9c165d72015-12-01 19:52:26 -08002068 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
2069 boolean whileRestarting, boolean permissionsReviewRequired)
2070 throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002071 //Slog.i(TAG, "Bring up service:");
2072 //r.dump(" ");
2073
2074 if (r.app != null && r.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002075 sendServiceArgsLocked(r, execInFg, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002076 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002077 }
2078
Sudheer Shanka03d0f812017-04-20 16:57:50 -07002079 if (!whileRestarting && mRestartingServices.contains(r)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002080 // If waiting for a restart, then do nothing.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002081 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002082 }
2083
Christopher Tate08992ac2017-03-21 11:37:06 -07002084 if (DEBUG_SERVICE) {
2085 Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
2086 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002087
2088 // We are now bringing the service up, so no longer in the
2089 // restarting state.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002090 if (mRestartingServices.remove(r)) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002091 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002092 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002093
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002094 // Make sure this service is no longer considered delayed, we are starting it now.
2095 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002096 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002097 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002098 r.delayed = false;
2099 }
2100
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002101 // Make sure that the user who owns this service is started. If not,
2102 // we don't want to allow it to run.
Fyodor Kupolov610acda2015-10-19 18:44:07 -07002103 if (!mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002104 String msg = "Unable to launch app "
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002105 + r.appInfo.packageName + "/"
2106 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002107 + r.intent.getIntent() + ": user " + r.userId + " is stopped";
2108 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002109 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002110 return msg;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002111 }
2112
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002113 // Service is now being launched, its package can't be stopped.
2114 try {
2115 AppGlobals.getPackageManager().setPackageStoppedState(
2116 r.packageName, false, r.userId);
2117 } catch (RemoteException e) {
2118 } catch (IllegalArgumentException e) {
2119 Slog.w(TAG, "Failed trying to unstop package "
2120 + r.packageName + ": " + e);
2121 }
2122
2123 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
2124 final String procName = r.processName;
Robert Sesekc5f86642016-11-04 10:20:38 -04002125 String hostingType = "service";
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002126 ProcessRecord app;
2127
2128 if (!isolated) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07002129 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
2130 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
2131 + " app=" + app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002132 if (app != null && app.thread != null) {
2133 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07002134 app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002135 realStartServiceLocked(r, app, execInFg);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002136 return null;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002137 } catch (TransactionTooLargeException e) {
2138 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002139 } catch (RemoteException e) {
2140 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
2141 }
2142
2143 // If a dead object exception was thrown -- fall through to
2144 // restart the application.
2145 }
2146 } else {
2147 // If this service runs in an isolated process, then each time
2148 // we call startProcessLocked() we will get a new isolated
2149 // process, starting another process if we are currently waiting
2150 // for a previous process to come up. To deal with this, we store
2151 // in the service any current isolated process it is running in or
2152 // waiting to have come up.
2153 app = r.isolatedProc;
Robert Sesekc5f86642016-11-04 10:20:38 -04002154 if (WebViewZygote.isMultiprocessEnabled()
2155 && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
2156 hostingType = "webview_service";
2157 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002158 }
2159
2160 // Not running -- get it started, and enqueue this service record
2161 // to be executed when the app comes up.
Svet Ganov9c165d72015-12-01 19:52:26 -08002162 if (app == null && !permissionsReviewRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002163 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
Robert Sesekc5f86642016-11-04 10:20:38 -04002164 hostingType, r.name, false, isolated, false)) == null) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002165 String msg = "Unable to launch app "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002166 + r.appInfo.packageName + "/"
2167 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002168 + r.intent.getIntent() + ": process is bad";
2169 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002170 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002171 return msg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002172 }
2173 if (isolated) {
2174 r.isolatedProc = app;
2175 }
2176 }
2177
Christopher Tate1536cc22017-09-18 16:43:30 -07002178 if (r.fgRequired) {
2179 if (DEBUG_FOREGROUND_SERVICE) {
2180 Slog.v(TAG, "Whitelisting " + UserHandle.formatUid(r.appInfo.uid)
2181 + " for fg-service launch");
2182 }
2183 mAm.tempWhitelistUidLocked(r.appInfo.uid,
2184 SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch");
2185 }
2186
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002187 if (!mPendingServices.contains(r)) {
2188 mPendingServices.add(r);
2189 }
2190
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002191 if (r.delayedStop) {
2192 // Oh and hey we've already been asked to stop!
2193 r.delayedStop = false;
2194 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002195 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2196 "Applying delayed stop (in bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002197 stopServiceLocked(r);
2198 }
2199 }
2200
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002201 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002202 }
2203
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002204 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
2205 throws TransactionTooLargeException {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002206 for (int i=r.bindings.size()-1; i>=0; i--) {
2207 IntentBindRecord ibr = r.bindings.valueAt(i);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002208 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002209 break;
2210 }
2211 }
2212 }
2213
2214 private final void realStartServiceLocked(ServiceRecord r,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002215 ProcessRecord app, boolean execInFg) throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002216 if (app.thread == null) {
2217 throw new RemoteException();
2218 }
2219 if (DEBUG_MU)
2220 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
2221 + ", ProcessRecord.uid = " + app.uid);
2222 r.app = app;
2223 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
2224
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002225 final boolean newService = app.services.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002226 bumpServiceExecutingLocked(r, execInFg, "create");
Dianne Hackborndb926082013-10-31 16:32:44 -07002227 mAm.updateLruProcessLocked(app, false, null);
Makoto Onuki0f421292017-04-28 15:03:33 -07002228 updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
2229 mAm.updateOomAdjLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002230
2231 boolean created = false;
2232 try {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002233 if (LOG_SERVICE_START_STOP) {
Dianne Hackbornab2df062015-01-07 13:43:13 -08002234 String nameTerm;
2235 int lastPeriod = r.shortName.lastIndexOf('.');
2236 nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002237 EventLogTags.writeAmCreateService(
2238 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
2239 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002240 synchronized (r.stats.getBatteryStats()) {
2241 r.stats.startLaunchedLocked();
2242 }
Brian Carlstromca82e612016-04-19 23:16:08 -07002243 mAm.notifyPackageUse(r.serviceInfo.packageName,
2244 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
Dianne Hackborna413dc02013-07-12 12:02:55 -07002245 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002246 app.thread.scheduleCreateService(r, r.serviceInfo,
Dianne Hackborna413dc02013-07-12 12:02:55 -07002247 mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
2248 app.repProcState);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002249 r.postNotification();
2250 created = true;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -07002251 } catch (DeadObjectException e) {
2252 Slog.w(TAG, "Application dead when creating service " + r);
2253 mAm.appDiedLocked(app);
Wale Ogunwalebfac4682015-04-08 14:33:21 -07002254 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002255 } finally {
2256 if (!created) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002257 // Keep the executeNesting count accurate.
2258 final boolean inDestroying = mDestroyingServices.contains(r);
2259 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2260
2261 // Cleanup.
2262 if (newService) {
2263 app.services.remove(r);
2264 r.app = null;
2265 }
2266
2267 // Retry.
2268 if (!inDestroying) {
2269 scheduleServiceRestartLocked(r, false);
2270 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002271 }
2272 }
2273
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002274 if (r.whitelistManager) {
2275 app.whitelistManager = true;
2276 }
2277
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002278 requestServiceBindingsLocked(r, execInFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002279
Dianne Hackborn465fa392014-09-14 14:21:18 -07002280 updateServiceClientActivitiesLocked(app, null, true);
2281
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002282 // If the service is in the started state, and there are no
2283 // pending arguments, then fake up one so its onStartCommand() will
2284 // be called.
2285 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
2286 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002287 null, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002288 }
2289
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002290 sendServiceArgsLocked(r, execInFg, true);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002291
2292 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002293 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002294 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002295 r.delayed = false;
2296 }
2297
2298 if (r.delayedStop) {
2299 // Oh and hey we've already been asked to stop!
2300 r.delayedStop = false;
2301 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002302 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2303 "Applying delayed stop (from start): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002304 stopServiceLocked(r);
2305 }
2306 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002307 }
2308
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002309 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002310 boolean oomAdjusted) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002311 final int N = r.pendingStarts.size();
2312 if (N == 0) {
2313 return;
2314 }
2315
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002316 ArrayList<ServiceStartArgs> args = new ArrayList<>();
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002317
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002318 while (r.pendingStarts.size() > 0) {
2319 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
2320 if (DEBUG_SERVICE) {
2321 Slog.v(TAG_SERVICE, "Sending arguments to: "
2322 + r + " " + r.intent + " args=" + si.intent);
2323 }
2324 if (si.intent == null && N > 1) {
2325 // If somehow we got a dummy null intent in the middle,
2326 // then skip it. DO NOT skip a null intent when it is
2327 // the only one in the list -- this is to support the
2328 // onStartCommand(null) case.
2329 continue;
2330 }
2331 si.deliveredTime = SystemClock.uptimeMillis();
2332 r.deliveredStarts.add(si);
2333 si.deliveryCount++;
2334 if (si.neededGrants != null) {
2335 mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
2336 si.getUriPermissionsLocked());
2337 }
2338 mAm.grantEphemeralAccessLocked(r.userId, si.intent,
2339 r.appInfo.uid, UserHandle.getAppId(si.callingId));
2340 bumpServiceExecutingLocked(r, execInFg, "start");
2341 if (!oomAdjusted) {
2342 oomAdjusted = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002343 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002344 }
2345 if (r.fgRequired && !r.fgWaiting) {
2346 if (!r.isForeground) {
2347 if (DEBUG_BACKGROUND_CHECK) {
2348 Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r);
2349 }
2350 scheduleServiceForegroundTransitionTimeoutLocked(r);
2351 } else {
2352 if (DEBUG_BACKGROUND_CHECK) {
2353 Slog.i(TAG, "Service already foreground; no new timeout: " + r);
2354 }
2355 r.fgRequired = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002356 }
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002357 }
2358 int flags = 0;
2359 if (si.deliveryCount > 1) {
2360 flags |= Service.START_FLAG_RETRY;
2361 }
2362 if (si.doneExecutingCount > 0) {
2363 flags |= Service.START_FLAG_REDELIVERY;
2364 }
2365 args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
2366 }
2367
2368 ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
2369 slice.setInlineCountLimit(4);
2370 Exception caughtException = null;
2371 try {
2372 r.app.thread.scheduleServiceArgs(r, slice);
2373 } catch (TransactionTooLargeException e) {
2374 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
2375 + " args, first: " + args.get(0).args);
2376 Slog.w(TAG, "Failed delivering service starts", e);
2377 caughtException = e;
2378 } catch (RemoteException e) {
2379 // Remote process gone... we'll let the normal cleanup take care of this.
2380 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
2381 Slog.w(TAG, "Failed delivering service starts", e);
2382 caughtException = e;
2383 } catch (Exception e) {
2384 Slog.w(TAG, "Unexpected exception", e);
2385 caughtException = e;
2386 }
2387
2388 if (caughtException != null) {
2389 // Keep nesting count correct
2390 final boolean inDestroying = mDestroyingServices.contains(r);
2391 for (int i = 0; i < args.size(); i++) {
2392 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2393 }
2394 if (caughtException instanceof TransactionTooLargeException) {
2395 throw (TransactionTooLargeException)caughtException;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002396 }
2397 }
2398 }
2399
Dianne Hackbornad51be92016-08-16 16:27:36 -07002400 private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn,
2401 boolean hasConn) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002402 // Are we still explicitly being asked to run?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002403 if (r.startRequested) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002404 return true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002405 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002406
Dianne Hackborncb015632017-06-14 17:30:15 -07002407 // Is someone still bound to us keeping us running?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002408 if (!knowConn) {
2409 hasConn = r.hasAutoCreateConnections();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002410 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002411 if (hasConn) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002412 return true;
2413 }
2414
2415 return false;
2416 }
2417
2418 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
2419 boolean hasConn) {
2420 //Slog.i(TAG, "Bring down service:");
2421 //r.dump(" ");
2422
Dianne Hackbornad51be92016-08-16 16:27:36 -07002423 if (isServiceNeededLocked(r, knowConn, hasConn)) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002424 return;
2425 }
2426
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002427 // Are we in the process of launching?
2428 if (mPendingServices.contains(r)) {
2429 return;
2430 }
2431
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002432 bringDownServiceLocked(r);
2433 }
2434
2435 private final void bringDownServiceLocked(ServiceRecord r) {
2436 //Slog.i(TAG, "Bring down service:");
2437 //r.dump(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002438
Dianne Hackborn390517b2013-05-30 15:03:32 -07002439 // Report to all of the connections that the service is no longer
2440 // available.
2441 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2442 ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
2443 for (int i=0; i<c.size(); i++) {
2444 ConnectionRecord cr = c.get(i);
2445 // There is still a connection to the service that is
2446 // being brought down. Mark it as dead.
2447 cr.serviceDead = true;
2448 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07002449 cr.conn.connected(r.name, null, true);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002450 } catch (Exception e) {
2451 Slog.w(TAG, "Failure disconnecting service " + r.name +
2452 " to connection " + c.get(i).conn.asBinder() +
2453 " (in " + c.get(i).binding.client.processName + ")", e);
2454 }
2455 }
2456 }
2457
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002458 // Tell the service that it has been unbound.
Dianne Hackborn390517b2013-05-30 15:03:32 -07002459 if (r.app != null && r.app.thread != null) {
2460 for (int i=r.bindings.size()-1; i>=0; i--) {
2461 IntentBindRecord ibr = r.bindings.valueAt(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002462 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002463 + ": hasBound=" + ibr.hasBound);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002464 if (ibr.hasBound) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002465 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002466 bumpServiceExecutingLocked(r, false, "bring down unbind");
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002467 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002468 ibr.hasBound = false;
Dianne Hackborn85e35642017-01-12 15:10:57 -08002469 ibr.requested = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002470 r.app.thread.scheduleUnbindService(r,
2471 ibr.intent.getIntent());
2472 } catch (Exception e) {
2473 Slog.w(TAG, "Exception when unbinding service "
2474 + r.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002475 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002476 }
2477 }
2478 }
2479 }
2480
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002481 // Check to see if the service had been started as foreground, but being
2482 // brought down before actually showing a notification. That is not allowed.
2483 if (r.fgRequired) {
2484 Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
2485 + r);
2486 r.fgRequired = false;
2487 r.fgWaiting = false;
2488 mAm.mHandler.removeMessages(
2489 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
2490 if (r.app != null) {
2491 Message msg = mAm.mHandler.obtainMessage(
2492 ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
2493 msg.obj = r.app;
2494 mAm.mHandler.sendMessage(msg);
2495 }
2496 }
2497
2498 if (DEBUG_SERVICE) {
2499 RuntimeException here = new RuntimeException();
2500 here.fillInStackTrace();
2501 Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here);
2502 }
Craig Mautner66c4a822015-01-16 12:48:16 -08002503 r.destroyTime = SystemClock.uptimeMillis();
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002504 if (LOG_SERVICE_START_STOP) {
2505 EventLogTags.writeAmDestroyService(
2506 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
2507 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002508
Dianne Hackbornad51be92016-08-16 16:27:36 -07002509 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002510 ServiceRecord found = smap.mServicesByName.remove(r.name);
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002511
2512 // Note when this method is called by bringUpServiceLocked(), the service is not found
2513 // in mServicesByName and found will be null.
2514 if (found != null && found != r) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002515 // This is not actually the service we think is running... this should not happen,
2516 // but if it does, fail hard.
2517 smap.mServicesByName.put(r.name, found);
2518 throw new IllegalStateException("Bringing down " + r + " but actually running "
2519 + found);
2520 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002521 smap.mServicesByIntent.remove(r.intent);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002522 r.totalRestartCount = 0;
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002523 unscheduleServiceRestartLocked(r, 0, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002524
2525 // Also make sure it is not on the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002526 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002527 if (mPendingServices.get(i) == r) {
2528 mPendingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002529 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002530 }
2531 }
2532
Christopher Tate08992ac2017-03-21 11:37:06 -07002533 cancelForegroundNotificationLocked(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002534 if (r.isForeground) {
2535 decActiveForegroundAppLocked(smap, r);
2536 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002537 r.isForeground = false;
2538 r.foregroundId = 0;
2539 r.foregroundNoti = null;
2540
2541 // Clear start entries.
2542 r.clearDeliveredStartsLocked();
2543 r.pendingStarts.clear();
2544
2545 if (r.app != null) {
2546 synchronized (r.stats.getBatteryStats()) {
2547 r.stats.stopLaunchedLocked();
2548 }
2549 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002550 if (r.whitelistManager) {
2551 updateWhitelistManagerLocked(r.app);
2552 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002553 if (r.app.thread != null) {
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002554 updateServiceForegroundLocked(r.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002555 try {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002556 bumpServiceExecutingLocked(r, false, "destroy");
2557 mDestroyingServices.add(r);
Dianne Hackborn455625e2015-01-21 09:55:13 -08002558 r.destroying = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002559 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002560 r.app.thread.scheduleStopService(r);
2561 } catch (Exception e) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002562 Slog.w(TAG, "Exception when destroying service "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002563 + r.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002564 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002565 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002566 } else {
2567 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002568 TAG_SERVICE, "Removed service that has no process: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002569 }
2570 } else {
2571 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002572 TAG_SERVICE, "Removed service that is not running: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002573 }
2574
2575 if (r.bindings.size() > 0) {
2576 r.bindings.clear();
2577 }
2578
2579 if (r.restarter instanceof ServiceRestarter) {
2580 ((ServiceRestarter)r.restarter).setService(null);
2581 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002582
Dianne Hackbornd2932242013-08-05 18:18:42 -07002583 int memFactor = mAm.mProcessStats.getMemFactorLocked();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002584 long now = SystemClock.uptimeMillis();
2585 if (r.tracker != null) {
2586 r.tracker.setStarted(false, memFactor, now);
2587 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002588 if (r.executeNesting == 0) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07002589 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002590 r.tracker = null;
2591 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002592 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002593
Dianne Hackbornad51be92016-08-16 16:27:36 -07002594 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002595 }
2596
2597 void removeConnectionLocked(
2598 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
2599 IBinder binder = c.conn.asBinder();
2600 AppBindRecord b = c.binding;
2601 ServiceRecord s = b.service;
2602 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
2603 if (clist != null) {
2604 clist.remove(c);
2605 if (clist.size() == 0) {
2606 s.connections.remove(binder);
2607 }
2608 }
2609 b.connections.remove(c);
2610 if (c.activity != null && c.activity != skipAct) {
2611 if (c.activity.connections != null) {
2612 c.activity.connections.remove(c);
2613 }
2614 }
2615 if (b.client != skipApp) {
2616 b.client.connections.remove(c);
2617 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
2618 b.client.updateHasAboveClientLocked();
2619 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002620 // If this connection requested whitelist management, see if we should
2621 // now clear that state.
2622 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
2623 s.updateWhitelistManager();
2624 if (!s.whitelistManager && s.app != null) {
2625 updateWhitelistManagerLocked(s.app);
2626 }
2627 }
Dianne Hackborndb926082013-10-31 16:32:44 -07002628 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07002629 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07002630 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002631 }
2632 clist = mServiceConnections.get(binder);
2633 if (clist != null) {
2634 clist.remove(c);
2635 if (clist.size() == 0) {
2636 mServiceConnections.remove(binder);
2637 }
2638 }
2639
Dianne Hackbornab2df062015-01-07 13:43:13 -08002640 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid, s.name);
2641
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002642 if (b.connections.size() == 0) {
2643 b.intent.apps.remove(b.client);
2644 }
2645
2646 if (!c.serviceDead) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002647 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002648 + ": shouldUnbind=" + b.intent.hasBound);
2649 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
2650 && b.intent.hasBound) {
2651 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002652 bumpServiceExecutingLocked(s, false, "unbind");
Dianne Hackborndb926082013-10-31 16:32:44 -07002653 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
Dianne Hackbornf097d422017-12-15 16:32:19 -08002654 && s.app.setProcState <= ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
Dianne Hackborndb926082013-10-31 16:32:44 -07002655 // If this service's process is not already in the cached list,
2656 // then update it in the LRU list here because this may be causing
2657 // it to go down there and we want it to start out near the top.
2658 mAm.updateLruProcessLocked(s.app, false, null);
2659 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002660 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002661 b.intent.hasBound = false;
2662 // Assume the client doesn't want to know about a rebind;
2663 // we will deal with that later if it asks for one.
2664 b.intent.doRebind = false;
2665 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
2666 } catch (Exception e) {
2667 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002668 serviceProcessGoneLocked(s);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002669 }
2670 }
2671
Svet Ganov9c165d72015-12-01 19:52:26 -08002672 // If unbound while waiting to start, remove the pending service
2673 mPendingServices.remove(s);
2674
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002675 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002676 boolean hasAutoCreate = s.hasAutoCreateConnections();
2677 if (!hasAutoCreate) {
2678 if (s.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002679 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002680 SystemClock.uptimeMillis());
2681 }
2682 }
2683 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002684 }
2685 }
2686 }
2687
2688 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002689 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002690 if (r != null) {
Dianne Hackborn455625e2015-01-21 09:55:13 -08002691 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002692 // This is a call from a service start... take care of
2693 // book-keeping.
2694 r.callStart = true;
2695 switch (res) {
2696 case Service.START_STICKY_COMPATIBILITY:
2697 case Service.START_STICKY: {
2698 // We are done with the associated start arguments.
2699 r.findDeliveredStart(startId, true);
2700 // Don't stop if killed.
2701 r.stopIfKilled = false;
2702 break;
2703 }
2704 case Service.START_NOT_STICKY: {
2705 // We are done with the associated start arguments.
2706 r.findDeliveredStart(startId, true);
2707 if (r.getLastStartId() == startId) {
2708 // There is no more work, and this service
2709 // doesn't want to hang around if killed.
2710 r.stopIfKilled = true;
2711 }
2712 break;
2713 }
2714 case Service.START_REDELIVER_INTENT: {
2715 // We'll keep this item until they explicitly
2716 // call stop for it, but keep track of the fact
2717 // that it was delivered.
2718 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
2719 if (si != null) {
2720 si.deliveryCount = 0;
2721 si.doneExecutingCount++;
2722 // Don't stop if killed.
2723 r.stopIfKilled = true;
2724 }
2725 break;
2726 }
2727 case Service.START_TASK_REMOVED_COMPLETE: {
2728 // Special processing for onTaskRemoved(). Don't
2729 // impact normal onStartCommand() processing.
2730 r.findDeliveredStart(startId, true);
2731 break;
2732 }
2733 default:
2734 throw new IllegalArgumentException(
2735 "Unknown service start result: " + res);
2736 }
2737 if (res == Service.START_STICKY_COMPATIBILITY) {
2738 r.callStart = false;
2739 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08002740 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
2741 // This is the final call from destroying the service... we should
2742 // actually be getting rid of the service at this point. Do some
2743 // validation of its state, and ensure it will be fully removed.
2744 if (!inDestroying) {
2745 // Not sure what else to do with this... if it is not actually in the
2746 // destroying list, we don't need to make sure to remove it from it.
Amith Yamasanid0418222016-05-10 15:49:51 -07002747 // If the app is null, then it was probably removed because the process died,
2748 // otherwise wtf
2749 if (r.app != null) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07002750 Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
Amith Yamasanid0418222016-05-10 15:49:51 -07002751 + r + ", app=" + r.app);
2752 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08002753 } else if (r.executeNesting != 1) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07002754 Slog.w(TAG, "Service done with onDestroy, but executeNesting="
Dianne Hackborn455625e2015-01-21 09:55:13 -08002755 + r.executeNesting + ": " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002756 // Fake it to keep from ANR due to orphaned entry.
Dianne Hackborn455625e2015-01-21 09:55:13 -08002757 r.executeNesting = 1;
2758 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002759 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002760 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn164371f2013-10-01 19:10:13 -07002761 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002762 Binder.restoreCallingIdentity(origId);
2763 } else {
2764 Slog.w(TAG, "Done executing unknown service from pid "
2765 + Binder.getCallingPid());
2766 }
2767 }
2768
Dianne Hackborn878deb32013-10-14 16:55:09 -07002769 private void serviceProcessGoneLocked(ServiceRecord r) {
2770 if (r.tracker != null) {
2771 int memFactor = mAm.mProcessStats.getMemFactorLocked();
2772 long now = SystemClock.uptimeMillis();
2773 r.tracker.setExecuting(false, memFactor, now);
2774 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbc72dce2013-11-11 10:43:38 -08002775 r.tracker.setStarted(false, memFactor, now);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002776 }
2777 serviceDoneExecutingLocked(r, true, true);
2778 }
2779
Dianne Hackborn164371f2013-10-01 19:10:13 -07002780 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
2781 boolean finishing) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002782 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002783 + ": nesting=" + r.executeNesting
Dianne Hackborn164371f2013-10-01 19:10:13 -07002784 + ", inDestroying=" + inDestroying + ", app=" + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002785 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
2786 "<<< DONE EXECUTING " + r.shortName);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002787 r.executeNesting--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002788 if (r.executeNesting <= 0) {
2789 if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002790 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002791 "Nesting at 0 of " + r.shortName);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002792 r.app.execServicesFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002793 r.app.executingServices.remove(r);
2794 if (r.app.executingServices.size() == 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002795 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002796 "No more executingServices of " + r.shortName);
2797 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002798 } else if (r.executeFg) {
2799 // Need to re-evaluate whether the app still needs to be in the foreground.
2800 for (int i=r.app.executingServices.size()-1; i>=0; i--) {
2801 if (r.app.executingServices.valueAt(i).executeFg) {
2802 r.app.execServicesFg = true;
2803 break;
2804 }
2805 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002806 }
Dianne Hackborn164371f2013-10-01 19:10:13 -07002807 if (inDestroying) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002808 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn164371f2013-10-01 19:10:13 -07002809 "doneExecuting remove destroying " + r);
2810 mDestroyingServices.remove(r);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002811 r.bindings.clear();
2812 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002813 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002814 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002815 r.executeFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002816 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002817 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002818 SystemClock.uptimeMillis());
Dianne Hackborn164371f2013-10-01 19:10:13 -07002819 if (finishing) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07002820 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002821 r.tracker = null;
2822 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002823 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002824 if (finishing) {
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08002825 if (r.app != null && !r.app.persistent) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002826 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002827 if (r.whitelistManager) {
2828 updateWhitelistManagerLocked(r.app);
2829 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002830 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002831 r.app = null;
2832 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002833 }
2834 }
2835
Dianne Hackbornff072722014-09-24 10:56:28 -07002836 boolean attachApplicationLocked(ProcessRecord proc, String processName)
2837 throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002838 boolean didSomething = false;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002839 // Collect any services that are waiting for this process to come up.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002840 if (mPendingServices.size() > 0) {
2841 ServiceRecord sr = null;
2842 try {
2843 for (int i=0; i<mPendingServices.size(); i++) {
2844 sr = mPendingServices.get(i);
2845 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
2846 || !processName.equals(sr.processName))) {
2847 continue;
2848 }
2849
2850 mPendingServices.remove(i);
2851 i--;
Dianne Hackbornf7097a52014-05-13 09:56:14 -07002852 proc.addPackage(sr.appInfo.packageName, sr.appInfo.versionCode,
2853 mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002854 realStartServiceLocked(sr, proc, sr.createdFromFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002855 didSomething = true;
Dianne Hackbornad51be92016-08-16 16:27:36 -07002856 if (!isServiceNeededLocked(sr, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002857 // We were waiting for this service to start, but it is actually no
2858 // longer needed. This could happen because bringDownServiceIfNeeded
2859 // won't bring down a service that is pending... so now the pending
2860 // is done, so let's drop it.
2861 bringDownServiceLocked(sr);
2862 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002863 }
Dianne Hackbornff072722014-09-24 10:56:28 -07002864 } catch (RemoteException e) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002865 Slog.w(TAG, "Exception in new application when starting service "
2866 + sr.shortName, e);
2867 throw e;
2868 }
2869 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002870 // Also, if there are any services that are waiting to restart and
2871 // would run in this process, now is a good time to start them. It would
2872 // be weird to bring up the process but arbitrarily not let the services
2873 // run at this point just because their restart time hasn't come up.
2874 if (mRestartingServices.size() > 0) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002875 ServiceRecord sr;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002876 for (int i=0; i<mRestartingServices.size(); i++) {
2877 sr = mRestartingServices.get(i);
2878 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
2879 || !processName.equals(sr.processName))) {
2880 continue;
2881 }
2882 mAm.mHandler.removeCallbacks(sr.restarter);
2883 mAm.mHandler.post(sr.restarter);
2884 }
2885 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002886 return didSomething;
2887 }
2888
2889 void processStartTimedOutLocked(ProcessRecord proc) {
2890 for (int i=0; i<mPendingServices.size(); i++) {
2891 ServiceRecord sr = mPendingServices.get(i);
2892 if ((proc.uid == sr.appInfo.uid
2893 && proc.processName.equals(sr.processName))
2894 || sr.isolatedProc == proc) {
2895 Slog.w(TAG, "Forcing bringing down service: " + sr);
2896 sr.isolatedProc = null;
2897 mPendingServices.remove(i);
2898 i--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002899 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002900 }
2901 }
2902 }
2903
Wale Ogunwale540e1232015-05-01 15:35:39 -07002904 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002905 boolean evenPersistent, boolean doit, boolean killProcess,
2906 ArrayMap<ComponentName, ServiceRecord> services) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002907 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002908 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002909 ServiceRecord service = services.valueAt(i);
Wale Ogunwale540e1232015-05-01 15:35:39 -07002910 final boolean sameComponent = packageName == null
2911 || (service.packageName.equals(packageName)
2912 && (filterByClasses == null
2913 || filterByClasses.contains(service.name.getClassName())));
2914 if (sameComponent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002915 && (service.app == null || evenPersistent || !service.app.persistent)) {
2916 if (!doit) {
2917 return true;
2918 }
2919 didSomething = true;
2920 Slog.i(TAG, " Force stopping service " + service);
2921 if (service.app != null) {
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002922 service.app.removed = killProcess;
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08002923 if (!service.app.persistent) {
2924 service.app.services.remove(service);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002925 if (service.whitelistManager) {
2926 updateWhitelistManagerLocked(service.app);
2927 }
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08002928 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002929 }
2930 service.app = null;
2931 service.isolatedProc = null;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002932 if (mTmpCollectionResults == null) {
2933 mTmpCollectionResults = new ArrayList<>();
2934 }
2935 mTmpCollectionResults.add(service);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002936 }
2937 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002938 return didSomething;
2939 }
2940
Wale Ogunwale540e1232015-05-01 15:35:39 -07002941 boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002942 int userId, boolean evenPersistent, boolean killProcess, boolean doit) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002943 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002944
2945 if (mTmpCollectionResults != null) {
2946 mTmpCollectionResults.clear();
2947 }
2948
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002949 if (userId == UserHandle.USER_ALL) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07002950 for (int i = mServiceMap.size() - 1; i >= 0; i--) {
2951 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002952 evenPersistent, doit, killProcess, mServiceMap.valueAt(i).mServicesByName);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002953 if (!doit && didSomething) {
2954 return true;
2955 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07002956 if (doit && filterByClasses == null) {
2957 forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId);
2958 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002959 }
2960 } else {
Amith Yamasani540b6592013-10-01 13:02:52 -07002961 ServiceMap smap = mServiceMap.get(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002962 if (smap != null) {
2963 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByName;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002964 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002965 evenPersistent, doit, killProcess, items);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002966 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07002967 if (doit && filterByClasses == null) {
2968 forceStopPackageLocked(packageName, userId);
2969 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002970 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002971
Wale Ogunwale540e1232015-05-01 15:35:39 -07002972 if (mTmpCollectionResults != null) {
2973 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
2974 bringDownServiceLocked(mTmpCollectionResults.get(i));
2975 }
2976 mTmpCollectionResults.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002977 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07002978
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002979 return didSomething;
2980 }
2981
Dianne Hackbornbe68d492017-05-03 18:04:05 -07002982 void forceStopPackageLocked(String packageName, int userId) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002983 ServiceMap smap = mServiceMap.get(userId);
2984 if (smap != null && smap.mActiveForegroundApps.size() > 0) {
Dianne Hackbornaf597682017-05-01 10:54:07 -07002985 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002986 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
2987 if (aa.mPackageName.equals(packageName)) {
2988 smap.mActiveForegroundApps.removeAt(i);
2989 smap.mActiveForegroundAppsChanged = true;
2990 }
2991 }
2992 if (smap.mActiveForegroundAppsChanged) {
2993 requestUpdateActiveForegroundAppsLocked(smap, 0);
2994 }
2995 }
2996 }
2997
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002998 void cleanUpRemovedTaskLocked(TaskRecord tr, ComponentName component, Intent baseIntent) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07002999 ArrayList<ServiceRecord> services = new ArrayList<>();
Dianne Hackbornad51be92016-08-16 16:27:36 -07003000 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(tr.userId);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003001 for (int i = alls.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003002 ServiceRecord sr = alls.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003003 if (sr.packageName.equals(component.getPackageName())) {
3004 services.add(sr);
3005 }
3006 }
3007
3008 // Take care of any running services associated with the app.
Wale Ogunwale540e1232015-05-01 15:35:39 -07003009 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003010 ServiceRecord sr = services.get(i);
3011 if (sr.startRequested) {
3012 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
3013 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
3014 stopServiceLocked(sr);
3015 } else {
3016 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Todd Kennedy51b3aac2017-03-30 17:50:42 -07003017 sr.makeNextStartId(), baseIntent, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003018 if (sr.app != null && sr.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003019 // We always run in the foreground, since this is called as
3020 // part of the "remove task" UI operation.
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003021 try {
3022 sendServiceArgsLocked(sr, true, false);
3023 } catch (TransactionTooLargeException e) {
3024 // Ignore, keep going.
3025 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003026 }
3027 }
3028 }
3029 }
3030 }
3031
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003032 final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003033 // Report disconnected services.
3034 if (false) {
3035 // XXX we are letting the client link to the service for
3036 // death notifications.
3037 if (app.services.size() > 0) {
3038 Iterator<ServiceRecord> it = app.services.iterator();
3039 while (it.hasNext()) {
3040 ServiceRecord r = it.next();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003041 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3042 ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
3043 for (int i=0; i<cl.size(); i++) {
3044 ConnectionRecord c = cl.get(i);
3045 if (c.binding.client != app) {
3046 try {
3047 //c.conn.connected(r.className, null);
3048 } catch (Exception e) {
3049 // todo: this should be asynchronous!
3050 Slog.w(TAG, "Exception thrown disconnected servce "
3051 + r.shortName
3052 + " from app " + app.processName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003053 }
3054 }
3055 }
3056 }
3057 }
3058 }
3059 }
3060
louis_chang40e259c2015-03-26 13:31:14 +08003061 // Clean up any connections this application has to other services.
3062 for (int i = app.connections.size() - 1; i >= 0; i--) {
3063 ConnectionRecord r = app.connections.valueAt(i);
3064 removeConnectionLocked(r, app, null);
3065 }
3066 updateServiceConnectionActivitiesLocked(app);
3067 app.connections.clear();
3068
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003069 app.whitelistManager = false;
3070
louis_chang40e259c2015-03-26 13:31:14 +08003071 // Clear app state from services.
3072 for (int i = app.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003073 ServiceRecord sr = app.services.valueAt(i);
3074 synchronized (sr.stats.getBatteryStats()) {
3075 sr.stats.stopLaunchedLocked();
3076 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003077 if (sr.app != app && sr.app != null && !sr.app.persistent) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003078 sr.app.services.remove(sr);
3079 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003080 sr.app = null;
3081 sr.isolatedProc = null;
3082 sr.executeNesting = 0;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003083 sr.forceClearTracker();
3084 if (mDestroyingServices.remove(sr)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003085 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003086 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003087
Dianne Hackbornc8230512013-07-13 21:32:12 -07003088 final int numClients = sr.bindings.size();
3089 for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
3090 IntentBindRecord b = sr.bindings.valueAt(bindingi);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003091 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
Dianne Hackbornc8230512013-07-13 21:32:12 -07003092 + ": shouldUnbind=" + b.hasBound);
3093 b.binder = null;
3094 b.requested = b.received = b.hasBound = false;
Dianne Hackborn465fa392014-09-14 14:21:18 -07003095 // If this binding is coming from a cached process and is asking to keep
3096 // the service created, then we'll kill the cached process as well -- we
3097 // don't want to be thrashing around restarting processes that are only
3098 // there to be cached.
3099 for (int appi=b.apps.size()-1; appi>=0; appi--) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003100 final ProcessRecord proc = b.apps.keyAt(appi);
3101 // If the process is already gone, skip it.
3102 if (proc.killedByAm || proc.thread == null) {
3103 continue;
3104 }
3105 // Only do this for processes that have an auto-create binding;
3106 // otherwise the binding can be left, because it won't cause the
3107 // service to restart.
3108 final AppBindRecord abind = b.apps.valueAt(appi);
3109 boolean hasCreate = false;
3110 for (int conni=abind.connections.size()-1; conni>=0; conni--) {
3111 ConnectionRecord conn = abind.connections.valueAt(conni);
Dianne Hackborn0fe3c252014-09-19 15:09:39 -07003112 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
3113 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003114 hasCreate = true;
3115 break;
3116 }
3117 }
3118 if (!hasCreate) {
3119 continue;
3120 }
Dianne Hackborncd97c962014-09-25 18:34:02 -07003121 // XXX turned off for now until we have more time to get a better policy.
3122 if (false && proc != null && !proc.persistent && proc.thread != null
Dianne Hackborn465fa392014-09-14 14:21:18 -07003123 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
3124 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
3125 proc.kill("bound to service " + sr.name.flattenToShortString()
3126 + " in dying proc " + (app != null ? app.processName : "??"), true);
3127 }
3128 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003129 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003130 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003131
Dianne Hackbornad51be92016-08-16 16:27:36 -07003132 ServiceMap smap = getServiceMapLocked(app.userId);
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003133
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003134 // Now do remaining service cleanup.
3135 for (int i=app.services.size()-1; i>=0; i--) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003136 ServiceRecord sr = app.services.valueAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003137
3138 // Unless the process is persistent, this process record is going away,
3139 // so make sure the service is cleaned out of it.
3140 if (!app.persistent) {
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003141 app.services.removeAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003142 }
3143
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003144 // Sanity check: if the service listed for the app is not one
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003145 // we actually are maintaining, just let it drop.
Dianne Hackborn40c87252014-03-19 16:55:40 -07003146 final ServiceRecord curRec = smap.mServicesByName.get(sr.name);
3147 if (curRec != sr) {
3148 if (curRec != null) {
3149 Slog.wtf(TAG, "Service " + sr + " in process " + app
3150 + " not same as in map: " + curRec);
3151 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003152 continue;
3153 }
3154
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003155 // Any services running in the application may need to be placed
3156 // back in the pending list.
Amith Yamasanib0c8a882017-08-28 09:36:42 -07003157 if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
3158 && (sr.serviceInfo.applicationInfo.flags
3159 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003160 Slog.w(TAG, "Service crashed " + sr.crashCount
3161 + " times, stopping: " + sr);
3162 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
3163 sr.userId, sr.crashCount, sr.shortName, app.pid);
3164 bringDownServiceLocked(sr);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003165 } else if (!allowRestart
Fyodor Kupolov1b3edac2017-09-19 15:48:06 -07003166 || !mAm.mUserController.isUserRunning(sr.userId, 0)) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003167 bringDownServiceLocked(sr);
3168 } else {
3169 boolean canceled = scheduleServiceRestartLocked(sr, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003170
Dianne Hackbornc8230512013-07-13 21:32:12 -07003171 // Should the service remain running? Note that in the
3172 // extreme case of so many attempts to deliver a command
3173 // that it failed we also will stop it here.
3174 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
3175 if (sr.pendingStarts.size() == 0) {
3176 sr.startRequested = false;
3177 if (sr.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003178 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackbornc8230512013-07-13 21:32:12 -07003179 SystemClock.uptimeMillis());
3180 }
3181 if (!sr.hasAutoCreateConnections()) {
3182 // Whoops, no reason to restart!
3183 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003184 }
3185 }
3186 }
3187 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003188 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003189
Dianne Hackbornc8230512013-07-13 21:32:12 -07003190 if (!allowRestart) {
3191 app.services.clear();
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003192
3193 // Make sure there are no more restarting services for this process.
3194 for (int i=mRestartingServices.size()-1; i>=0; i--) {
3195 ServiceRecord r = mRestartingServices.get(i);
3196 if (r.processName.equals(app.processName) &&
3197 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3198 mRestartingServices.remove(i);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08003199 clearRestartingIfNeededLocked(r);
3200 }
3201 }
3202 for (int i=mPendingServices.size()-1; i>=0; i--) {
3203 ServiceRecord r = mPendingServices.get(i);
3204 if (r.processName.equals(app.processName) &&
3205 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3206 mPendingServices.remove(i);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003207 }
3208 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003209 }
3210
3211 // Make sure we have no more records on the stopping list.
Dianne Hackborn164371f2013-10-01 19:10:13 -07003212 int i = mDestroyingServices.size();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003213 while (i > 0) {
3214 i--;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003215 ServiceRecord sr = mDestroyingServices.get(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003216 if (sr.app == app) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003217 sr.forceClearTracker();
3218 mDestroyingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003219 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003220 }
3221 }
3222
3223 app.executingServices.clear();
3224 }
3225
3226 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
3227 ActivityManager.RunningServiceInfo info =
3228 new ActivityManager.RunningServiceInfo();
3229 info.service = r.name;
3230 if (r.app != null) {
3231 info.pid = r.app.pid;
3232 }
3233 info.uid = r.appInfo.uid;
3234 info.process = r.processName;
3235 info.foreground = r.isForeground;
Yi Jin6b514142017-10-30 14:54:12 -07003236 info.activeSince = r.createRealTime;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003237 info.started = r.startRequested;
3238 info.clientCount = r.connections.size();
3239 info.crashCount = r.crashCount;
3240 info.lastActivityTime = r.lastActivity;
3241 if (r.isForeground) {
3242 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
3243 }
3244 if (r.startRequested) {
3245 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
3246 }
3247 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
3248 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
3249 }
3250 if (r.app != null && r.app.persistent) {
3251 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
3252 }
3253
Dianne Hackborn390517b2013-05-30 15:03:32 -07003254 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3255 ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003256 for (int i=0; i<connl.size(); i++) {
3257 ConnectionRecord conn = connl.get(i);
3258 if (conn.clientLabel != 0) {
3259 info.clientPackage = conn.binding.client.info.packageName;
3260 info.clientLabel = conn.clientLabel;
3261 return info;
3262 }
3263 }
3264 }
3265 return info;
3266 }
3267
Bryce Lee290e5782017-02-01 16:41:20 -08003268 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags,
Shunta Sato55af6c52016-10-19 15:58:52 +09003269 int callingUid, boolean allowed, boolean canInteractAcrossUsers) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003270 ArrayList<ActivityManager.RunningServiceInfo> res
3271 = new ArrayList<ActivityManager.RunningServiceInfo>();
3272
Dianne Hackborn0c380492012-08-20 17:23:30 -07003273 final long ident = Binder.clearCallingIdentity();
3274 try {
Shunta Sato55af6c52016-10-19 15:58:52 +09003275 if (canInteractAcrossUsers) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003276 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003277 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003278 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003279 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3280 ServiceRecord sr = alls.valueAt(i);
3281 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07003282 }
3283 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003284
Dianne Hackborn0c380492012-08-20 17:23:30 -07003285 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3286 ServiceRecord r = mRestartingServices.get(i);
3287 ActivityManager.RunningServiceInfo info =
3288 makeRunningServiceInfoLocked(r);
3289 info.restarting = r.nextRestartTime;
3290 res.add(info);
3291 }
3292 } else {
Bryce Lee290e5782017-02-01 16:41:20 -08003293 int userId = UserHandle.getUserId(callingUid);
Dianne Hackbornad51be92016-08-16 16:27:36 -07003294 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003295 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3296 ServiceRecord sr = alls.valueAt(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003297
3298 if (allowed || (sr.app != null && sr.app.uid == callingUid)) {
3299 res.add(makeRunningServiceInfoLocked(sr));
3300 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07003301 }
3302
3303 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3304 ServiceRecord r = mRestartingServices.get(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003305 if (r.userId == userId
3306 && (allowed || (r.app != null && r.app.uid == callingUid))) {
Dianne Hackborn0c380492012-08-20 17:23:30 -07003307 ActivityManager.RunningServiceInfo info =
3308 makeRunningServiceInfoLocked(r);
3309 info.restarting = r.nextRestartTime;
3310 res.add(info);
3311 }
3312 }
3313 }
3314 } finally {
3315 Binder.restoreCallingIdentity(ident);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003316 }
3317
3318 return res;
3319 }
3320
3321 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003322 int userId = UserHandle.getUserId(Binder.getCallingUid());
Dianne Hackbornad51be92016-08-16 16:27:36 -07003323 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003324 if (r != null) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003325 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3326 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003327 for (int i=0; i<conn.size(); i++) {
3328 if (conn.get(i).clientIntent != null) {
3329 return conn.get(i).clientIntent;
3330 }
3331 }
3332 }
3333 }
3334 return null;
3335 }
3336
3337 void serviceTimeout(ProcessRecord proc) {
3338 String anrMessage = null;
3339
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003340 synchronized(mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003341 if (proc.executingServices.size() == 0 || proc.thread == null) {
3342 return;
3343 }
Dianne Hackbornab2df062015-01-07 13:43:13 -08003344 final long now = SystemClock.uptimeMillis();
3345 final long maxTime = now -
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003346 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003347 ServiceRecord timeout = null;
3348 long nextTime = 0;
Dianne Hackbornc8230512013-07-13 21:32:12 -07003349 for (int i=proc.executingServices.size()-1; i>=0; i--) {
3350 ServiceRecord sr = proc.executingServices.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003351 if (sr.executingStart < maxTime) {
3352 timeout = sr;
3353 break;
3354 }
3355 if (sr.executingStart > nextTime) {
3356 nextTime = sr.executingStart;
3357 }
3358 }
3359 if (timeout != null && mAm.mLruProcesses.contains(proc)) {
3360 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08003361 StringWriter sw = new StringWriter();
3362 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
3363 pw.println(timeout);
3364 timeout.dump(pw, " ");
3365 pw.close();
3366 mLastAnrDump = sw.toString();
3367 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
3368 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
3369 anrMessage = "executing service " + timeout.shortName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003370 } else {
3371 Message msg = mAm.mHandler.obtainMessage(
3372 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3373 msg.obj = proc;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003374 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
Dianne Hackborn2be00932013-09-22 16:46:00 -07003375 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003376 }
3377 }
3378
3379 if (anrMessage != null) {
Adrian Roos20d7df32016-01-12 18:59:43 +01003380 mAm.mAppErrors.appNotResponding(proc, null, null, false, anrMessage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003381 }
3382 }
3383
Christopher Tate08992ac2017-03-21 11:37:06 -07003384 void serviceForegroundTimeout(ServiceRecord r) {
3385 ProcessRecord app;
3386 synchronized (mAm) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003387 if (!r.fgRequired || r.destroying) {
Christopher Tate08992ac2017-03-21 11:37:06 -07003388 return;
3389 }
3390
3391 if (DEBUG_BACKGROUND_CHECK) {
3392 Slog.i(TAG, "Service foreground-required timeout for " + r);
3393 }
3394 app = r.app;
3395 r.fgWaiting = false;
3396 stopServiceLocked(r);
3397 }
3398
3399 if (app != null) {
3400 mAm.mAppErrors.appNotResponding(app, null, null, false,
3401 "Context.startForegroundService() did not then call Service.startForeground()");
3402 }
3403 }
3404
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003405 void serviceForegroundCrash(ProcessRecord app) {
3406 mAm.crashApplication(app.uid, app.pid, app.info.packageName, app.userId,
3407 "Context.startForegroundService() did not then call Service.startForeground()");
3408 }
3409
Dianne Hackborn2be00932013-09-22 16:46:00 -07003410 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
3411 if (proc.executingServices.size() == 0 || proc.thread == null) {
3412 return;
3413 }
Dianne Hackborn2be00932013-09-22 16:46:00 -07003414 Message msg = mAm.mHandler.obtainMessage(
3415 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3416 msg.obj = proc;
Christopher Tate08992ac2017-03-21 11:37:06 -07003417 mAm.mHandler.sendMessageDelayed(msg,
3418 proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
3419 }
3420
3421 void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
3422 if (r.app.executingServices.size() == 0 || r.app.thread == null) {
3423 return;
3424 }
3425 Message msg = mAm.mHandler.obtainMessage(
3426 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG);
3427 msg.obj = r;
3428 r.fgWaiting = true;
3429 mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT);
Dianne Hackborn2be00932013-09-22 16:46:00 -07003430 }
3431
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003432 final class ServiceDumper {
3433 private final FileDescriptor fd;
3434 private final PrintWriter pw;
3435 private final String[] args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003436 private final boolean dumpAll;
3437 private final String dumpPackage;
3438 private final ItemMatcher matcher;
3439 private final ArrayList<ServiceRecord> services = new ArrayList<>();
3440
3441 private final long nowReal = SystemClock.elapsedRealtime();
3442
3443 private boolean needSep = false;
3444 private boolean printedAnything = false;
3445 private boolean printed = false;
3446
3447 /**
3448 * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
3449 * must be called with the lock held).
3450 */
3451 ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
3452 int opti, boolean dumpAll, String dumpPackage) {
3453 this.fd = fd;
3454 this.pw = pw;
3455 this.args = args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003456 this.dumpAll = dumpAll;
3457 this.dumpPackage = dumpPackage;
3458 matcher = new ItemMatcher();
3459 matcher.build(args, opti);
3460
3461 final int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003462 for (int user : users) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003463 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003464 if (smap.mServicesByName.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003465 for (int si=0; si<smap.mServicesByName.size(); si++) {
3466 ServiceRecord r = smap.mServicesByName.valueAt(si);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003467 if (!matcher.match(r, r.name)) {
3468 continue;
3469 }
3470 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3471 continue;
3472 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003473 services.add(r);
3474 }
3475 }
3476 }
3477 }
3478
3479 private void dumpHeaderLocked() {
3480 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
3481 if (mLastAnrDump != null) {
3482 pw.println(" Last ANR service:");
3483 pw.print(mLastAnrDump);
3484 pw.println();
3485 }
3486 }
3487
3488 void dumpLocked() {
3489 dumpHeaderLocked();
3490
3491 try {
3492 int[] users = mAm.mUserController.getUsers();
3493 for (int user : users) {
3494 // Find the first service for this user.
3495 int serviceIdx = 0;
3496 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3497 serviceIdx++;
3498 }
3499 printed = false;
3500 if (serviceIdx < services.size()) {
3501 needSep = false;
3502 while (serviceIdx < services.size()) {
3503 ServiceRecord r = services.get(serviceIdx);
3504 serviceIdx++;
3505 if (r.userId != user) {
3506 break;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003507 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003508 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003509 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003510 needSep |= printed;
3511 }
3512
3513 dumpUserRemainsLocked(user);
3514 }
3515 } catch (Exception e) {
3516 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3517 }
3518
3519 dumpRemainsLocked();
3520 }
3521
3522 void dumpWithClient() {
3523 synchronized(mAm) {
3524 dumpHeaderLocked();
3525 }
3526
3527 try {
3528 int[] users = mAm.mUserController.getUsers();
3529 for (int user : users) {
3530 // Find the first service for this user.
3531 int serviceIdx = 0;
3532 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3533 serviceIdx++;
3534 }
3535 printed = false;
3536 if (serviceIdx < services.size()) {
3537 needSep = false;
3538 while (serviceIdx < services.size()) {
3539 ServiceRecord r = services.get(serviceIdx);
3540 serviceIdx++;
3541 if (r.userId != user) {
3542 break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003543 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003544 synchronized(mAm) {
3545 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003546 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003547 dumpServiceClient(r);
3548 }
3549 needSep |= printed;
3550 }
3551
3552 synchronized(mAm) {
3553 dumpUserRemainsLocked(user);
3554 }
3555 }
3556 } catch (Exception e) {
3557 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3558 }
3559
3560 synchronized(mAm) {
3561 dumpRemainsLocked();
3562 }
3563 }
3564
3565 private void dumpUserHeaderLocked(int user) {
3566 if (!printed) {
3567 if (printedAnything) {
3568 pw.println();
3569 }
3570 pw.println(" User " + user + " active services:");
3571 printed = true;
3572 }
3573 printedAnything = true;
3574 if (needSep) {
3575 pw.println();
3576 }
3577 }
3578
3579 private void dumpServiceLocalLocked(ServiceRecord r) {
3580 dumpUserHeaderLocked(r.userId);
3581 pw.print(" * ");
3582 pw.println(r);
3583 if (dumpAll) {
3584 r.dump(pw, " ");
3585 needSep = true;
3586 } else {
3587 pw.print(" app=");
3588 pw.println(r.app);
3589 pw.print(" created=");
Yi Jin6b514142017-10-30 14:54:12 -07003590 TimeUtils.formatDuration(r.createRealTime, nowReal, pw);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003591 pw.print(" started=");
3592 pw.print(r.startRequested);
3593 pw.print(" connections=");
3594 pw.println(r.connections.size());
3595 if (r.connections.size() > 0) {
3596 pw.println(" Connections:");
3597 for (int conni=0; conni<r.connections.size(); conni++) {
3598 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
3599 for (int i = 0; i < clist.size(); i++) {
3600 ConnectionRecord conn = clist.get(i);
3601 pw.print(" ");
3602 pw.print(conn.binding.intent.intent.getIntent()
3603 .toShortString(false, false, false, false));
3604 pw.print(" -> ");
3605 ProcessRecord proc = conn.binding.client;
3606 pw.println(proc != null ? proc.toShortString() : "null");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003607 }
3608 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003609 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003610 }
3611 }
3612
3613 private void dumpServiceClient(ServiceRecord r) {
3614 final ProcessRecord proc = r.app;
3615 if (proc == null) {
3616 return;
3617 }
3618 final IApplicationThread thread = proc.thread;
3619 if (thread == null) {
3620 return;
3621 }
3622 pw.println(" Client:");
3623 pw.flush();
3624 try {
3625 TransferPipe tp = new TransferPipe();
3626 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003627 thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003628 tp.setBufferPrefix(" ");
3629 // Short timeout, since blocking here can
3630 // deadlock with the application.
3631 tp.go(fd, 2000);
3632 } finally {
3633 tp.kill();
3634 }
3635 } catch (IOException e) {
3636 pw.println(" Failure while dumping the service: " + e);
3637 } catch (RemoteException e) {
3638 pw.println(" Got a RemoteException while dumping the service");
3639 }
3640 needSep = true;
3641 }
3642
3643 private void dumpUserRemainsLocked(int user) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003644 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003645 printed = false;
3646 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
3647 ServiceRecord r = smap.mDelayedStartList.get(si);
3648 if (!matcher.match(r, r.name)) {
3649 continue;
3650 }
3651 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3652 continue;
3653 }
3654 if (!printed) {
3655 if (printedAnything) {
3656 pw.println();
3657 }
3658 pw.println(" User " + user + " delayed start services:");
3659 printed = true;
3660 }
3661 printedAnything = true;
3662 pw.print(" * Delayed start "); pw.println(r);
3663 }
3664 printed = false;
3665 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
3666 ServiceRecord r = smap.mStartingBackground.get(si);
3667 if (!matcher.match(r, r.name)) {
3668 continue;
3669 }
3670 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3671 continue;
3672 }
3673 if (!printed) {
3674 if (printedAnything) {
3675 pw.println();
3676 }
3677 pw.println(" User " + user + " starting in background:");
3678 printed = true;
3679 }
3680 printedAnything = true;
3681 pw.print(" * Starting bg "); pw.println(r);
3682 }
3683 }
3684
3685 private void dumpRemainsLocked() {
3686 if (mPendingServices.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003687 printed = false;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003688 for (int i=0; i<mPendingServices.size(); i++) {
3689 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003690 if (!matcher.match(r, r.name)) {
3691 continue;
3692 }
3693 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3694 continue;
3695 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003696 printedAnything = true;
3697 if (!printed) {
3698 if (needSep) pw.println();
3699 needSep = true;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003700 pw.println(" Pending services:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003701 printed = true;
3702 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003703 pw.print(" * Pending "); pw.println(r);
3704 r.dump(pw, " ");
3705 }
3706 needSep = true;
3707 }
3708
3709 if (mRestartingServices.size() > 0) {
3710 printed = false;
3711 for (int i=0; i<mRestartingServices.size(); i++) {
3712 ServiceRecord r = mRestartingServices.get(i);
3713 if (!matcher.match(r, r.name)) {
3714 continue;
3715 }
3716 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3717 continue;
3718 }
3719 printedAnything = true;
3720 if (!printed) {
3721 if (needSep) pw.println();
3722 needSep = true;
3723 pw.println(" Restarting services:");
3724 printed = true;
3725 }
3726 pw.print(" * Restarting "); pw.println(r);
3727 r.dump(pw, " ");
3728 }
3729 needSep = true;
3730 }
3731
3732 if (mDestroyingServices.size() > 0) {
3733 printed = false;
3734 for (int i=0; i< mDestroyingServices.size(); i++) {
3735 ServiceRecord r = mDestroyingServices.get(i);
3736 if (!matcher.match(r, r.name)) {
3737 continue;
3738 }
3739 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3740 continue;
3741 }
3742 printedAnything = true;
3743 if (!printed) {
3744 if (needSep) pw.println();
3745 needSep = true;
3746 pw.println(" Destroying services:");
3747 printed = true;
3748 }
3749 pw.print(" * Destroy "); pw.println(r);
3750 r.dump(pw, " ");
3751 }
3752 needSep = true;
3753 }
3754
3755 if (dumpAll) {
3756 printed = false;
3757 for (int ic=0; ic<mServiceConnections.size(); ic++) {
3758 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
3759 for (int i=0; i<r.size(); i++) {
3760 ConnectionRecord cr = r.get(i);
3761 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
3762 continue;
3763 }
3764 if (dumpPackage != null && (cr.binding.client == null
3765 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
3766 continue;
3767 }
3768 printedAnything = true;
3769 if (!printed) {
3770 if (needSep) pw.println();
3771 needSep = true;
3772 pw.println(" Connection bindings to services:");
3773 printed = true;
3774 }
3775 pw.print(" * "); pw.println(cr);
3776 cr.dump(pw, " ");
3777 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003778 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003779 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003780
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003781 if (matcher.all) {
3782 final long nowElapsed = SystemClock.elapsedRealtime();
3783 final int[] users = mAm.mUserController.getUsers();
3784 for (int user : users) {
3785 boolean printedUser = false;
3786 ServiceMap smap = mServiceMap.get(user);
3787 if (smap == null) {
3788 continue;
3789 }
3790 for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) {
3791 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
3792 if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) {
3793 continue;
3794 }
3795 if (!printedUser) {
3796 printedUser = true;
3797 printedAnything = true;
3798 if (needSep) pw.println();
3799 needSep = true;
3800 pw.print("Active foreground apps - user ");
3801 pw.print(user);
3802 pw.println(":");
3803 }
3804 pw.print(" #");
3805 pw.print(i);
3806 pw.print(": ");
3807 pw.println(aa.mPackageName);
3808 if (aa.mLabel != null) {
3809 pw.print(" mLabel=");
3810 pw.println(aa.mLabel);
3811 }
3812 pw.print(" mNumActive=");
3813 pw.print(aa.mNumActive);
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003814 pw.print(" mAppOnTop=");
3815 pw.print(aa.mAppOnTop);
3816 pw.print(" mShownWhileTop=");
3817 pw.print(aa.mShownWhileTop);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003818 pw.print(" mShownWhileScreenOn=");
3819 pw.println(aa.mShownWhileScreenOn);
3820 pw.print(" mStartTime=");
3821 TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw);
3822 pw.print(" mStartVisibleTime=");
3823 TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw);
3824 pw.println();
3825 if (aa.mEndTime != 0) {
3826 pw.print(" mEndTime=");
3827 TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw);
3828 pw.println();
3829 }
3830 }
Dianne Hackborncb015632017-06-14 17:30:15 -07003831 if (smap.hasMessagesOrCallbacks()) {
3832 if (needSep) {
3833 pw.println();
3834 }
3835 printedAnything = true;
3836 needSep = true;
3837 pw.print(" Handler - user ");
3838 pw.print(user);
3839 pw.println(":");
3840 smap.dumpMine(new PrintWriterPrinter(pw), " ");
3841 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003842 }
3843 }
3844
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003845 if (!printedAnything) {
3846 pw.println(" (nothing)");
3847 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003848 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003849 }
3850
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003851 ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
3852 int opti, boolean dumpAll, String dumpPackage) {
3853 return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
3854 }
3855
Yi Jin6b514142017-10-30 14:54:12 -07003856 protected void writeToProto(ProtoOutputStream proto) {
3857 synchronized (mAm) {
3858 int[] users = mAm.mUserController.getUsers();
3859 for (int user : users) {
3860 ServiceMap smap = mServiceMap.get(user);
3861 if (smap == null) {
3862 continue;
3863 }
3864 long token = proto.start(ActiveServicesProto.SERVICES_BY_USERS);
3865 proto.write(ActiveServicesProto.ServicesByUser.USER_ID, user);
3866 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
3867 for (int i=0; i<alls.size(); i++) {
3868 alls.valueAt(i).writeToProto(proto,
3869 ActiveServicesProto.ServicesByUser.SERVICE_RECORDS);
3870 }
3871 proto.end(token);
3872 }
3873 }
3874 }
3875
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003876 /**
3877 * There are three ways to call this:
3878 * - no service specified: dump all the services
3879 * - a flattened component name that matched an existing service was specified as the
3880 * first arg: dump that one service
3881 * - the first arg isn't the flattened component name of an existing service:
3882 * dump all services whose component contains the first arg as a substring
3883 */
3884 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
3885 int opti, boolean dumpAll) {
3886 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
3887
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003888 synchronized (mAm) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003889 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003890 if ("all".equals(name)) {
3891 for (int user : users) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -07003892 ServiceMap smap = mServiceMap.get(user);
3893 if (smap == null) {
3894 continue;
3895 }
3896 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003897 for (int i=0; i<alls.size(); i++) {
3898 ServiceRecord r1 = alls.valueAt(i);
Amith Yamasani258848d2012-08-10 17:06:33 -07003899 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003900 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003901 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003902 } else {
3903 ComponentName componentName = name != null
3904 ? ComponentName.unflattenFromString(name) : null;
3905 int objectId = 0;
3906 if (componentName == null) {
3907 // Not a '/' separated full component name; maybe an object ID?
3908 try {
3909 objectId = Integer.parseInt(name, 16);
3910 name = null;
3911 componentName = null;
3912 } catch (RuntimeException e) {
3913 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003914 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003915
Dianne Hackborn1676c852012-09-10 14:52:30 -07003916 for (int user : users) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -07003917 ServiceMap smap = mServiceMap.get(user);
3918 if (smap == null) {
3919 continue;
3920 }
3921 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003922 for (int i=0; i<alls.size(); i++) {
3923 ServiceRecord r1 = alls.valueAt(i);
Amith Yamasani258848d2012-08-10 17:06:33 -07003924 if (componentName != null) {
3925 if (r1.name.equals(componentName)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003926 services.add(r1);
3927 }
Amith Yamasani258848d2012-08-10 17:06:33 -07003928 } else if (name != null) {
3929 if (r1.name.flattenToString().contains(name)) {
3930 services.add(r1);
3931 }
3932 } else if (System.identityHashCode(r1) == objectId) {
3933 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003934 }
3935 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003936 }
3937 }
3938 }
3939
3940 if (services.size() <= 0) {
3941 return false;
3942 }
3943
3944 boolean needSep = false;
3945 for (int i=0; i<services.size(); i++) {
3946 if (needSep) {
3947 pw.println();
3948 }
3949 needSep = true;
3950 dumpService("", fd, pw, services.get(i), args, dumpAll);
3951 }
3952 return true;
3953 }
3954
3955 /**
3956 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
3957 * there is a thread associated with the service.
3958 */
3959 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
3960 final ServiceRecord r, String[] args, boolean dumpAll) {
3961 String innerPrefix = prefix + " ";
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003962 synchronized (mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003963 pw.print(prefix); pw.print("SERVICE ");
3964 pw.print(r.shortName); pw.print(" ");
3965 pw.print(Integer.toHexString(System.identityHashCode(r)));
3966 pw.print(" pid=");
3967 if (r.app != null) pw.println(r.app.pid);
3968 else pw.println("(not running)");
3969 if (dumpAll) {
3970 r.dump(pw, innerPrefix);
3971 }
3972 }
3973 if (r.app != null && r.app.thread != null) {
3974 pw.print(prefix); pw.println(" Client:");
3975 pw.flush();
3976 try {
3977 TransferPipe tp = new TransferPipe();
3978 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003979 r.app.thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003980 tp.setBufferPrefix(prefix + " ");
3981 tp.go(fd);
3982 } finally {
3983 tp.kill();
3984 }
3985 } catch (IOException e) {
3986 pw.println(prefix + " Failure while dumping the service: " + e);
3987 } catch (RemoteException e) {
3988 pw.println(prefix + " Got a RemoteException while dumping the service");
3989 }
3990 }
3991 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003992}