blob: 230f69dd43a0866b70ab9e5a0f67c5a062068d30 [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;
Chenjie Yuccfe6452018-01-30 11:33:21 -080087import android.util.StatsLog;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070088import android.util.SparseArray;
89import android.util.TimeUtils;
Yi Jin6b514142017-10-30 14:54:12 -070090import android.util.proto.ProtoOutputStream;
Robert Sesekc5f86642016-11-04 10:20:38 -040091import android.webkit.WebViewZygote;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070092
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -070093public final class ActiveServices {
Wale Ogunwaled57969f2014-11-15 19:37:29 -080094 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM;
95 private static final String TAG_MU = TAG + POSTFIX_MU;
96 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
97 private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING;
98
99 private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE;
100 private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE;
101
102 private static final boolean LOG_SERVICE_START_STOP = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700103
104 // How long we wait for a service to finish executing.
105 static final int SERVICE_TIMEOUT = 20*1000;
106
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700107 // How long we wait for a service to finish executing.
108 static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
109
Christopher Tate08992ac2017-03-21 11:37:06 -0700110 // How long the startForegroundService() grace period is to get around to
111 // calling startForeground() before we ANR + stop it.
112 static final int SERVICE_START_FOREGROUND_TIMEOUT = 5*1000;
113
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700114 final ActivityManagerService mAm;
115
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700116 // Maximum number of services that we allow to start in the background
117 // at the same time.
118 final int mMaxStartingBackground;
119
Wale Ogunwale540e1232015-05-01 15:35:39 -0700120 final SparseArray<ServiceMap> mServiceMap = new SparseArray<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700121
122 /**
123 * All currently bound service connections. Keys are the IBinder of
124 * the client's IServiceConnection.
125 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700126 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700127
128 /**
129 * List of services that we have been asked to start,
130 * but haven't yet been able to. It is used to hold start requests
131 * while waiting for their corresponding application thread to get
132 * going.
133 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700134 final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700135
136 /**
137 * List of services that are scheduled to restart following a crash.
138 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700139 final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700140
141 /**
Dianne Hackborn164371f2013-10-01 19:10:13 -0700142 * List of services that are in the process of being destroyed.
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700143 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700144 final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>();
145
146 /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */
147 private ArrayList<ServiceRecord> mTmpCollectionResults = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700148
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700149 /**
150 * For keeping ActiveForegroundApps retaining state while the screen is off.
151 */
152 boolean mScreenOn = true;
153
Dianne Hackborncff1bbf2015-01-20 13:43:32 -0800154 /** Amount of time to allow a last ANR message to exist before freeing the memory. */
155 static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
156
157 String mLastAnrDump;
158
159 final Runnable mLastAnrDumpClearer = new Runnable() {
160 @Override public void run() {
161 synchronized (mAm) {
162 mLastAnrDump = null;
163 }
164 }
165 };
166
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700167 /**
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700168 * Information about an app that is currently running one or more foreground services.
Dan Sandler2f36ab82017-05-25 00:15:49 -0400169 * (This maps directly to the running apps we show in the notification.)
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700170 */
171 static final class ActiveForegroundApp {
172 String mPackageName;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700173 int mUid;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700174 CharSequence mLabel;
175 boolean mShownWhileScreenOn;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700176 boolean mAppOnTop;
177 boolean mShownWhileTop;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700178 long mStartTime;
179 long mStartVisibleTime;
180 long mEndTime;
181 int mNumActive;
Dianne Hackborncb015632017-06-14 17:30:15 -0700182
183 // Temp output of foregroundAppShownEnoughLocked
184 long mHideTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700185 }
186
187 /**
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700188 * Information about services for a single user.
189 */
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700190 final class ServiceMap extends Handler {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700191 final int mUserId;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700192 final ArrayMap<ComponentName, ServiceRecord> mServicesByName = new ArrayMap<>();
193 final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700194
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700195 final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700196 /* XXX eventually I'd like to have this based on processes instead of services.
197 * That is, if we try to start two services in a row both running in the same
198 * process, this should be one entry in mStartingBackground for that one process
199 * that remains until all services in it are done.
200 final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
201 = new ArrayMap<ProcessRecord, DelayingProcess>();
202 final ArrayList<DelayingProcess> mStartingProcessList
203 = new ArrayList<DelayingProcess>();
204 */
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700205
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700206 final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700207
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700208 final ArrayMap<String, ActiveForegroundApp> mActiveForegroundApps = new ArrayMap<>();
209 boolean mActiveForegroundAppsChanged;
210
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700211 static final int MSG_BG_START_TIMEOUT = 1;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700212 static final int MSG_UPDATE_FOREGROUND_APPS = 2;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700213
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700214 ServiceMap(Looper looper, int userId) {
215 super(looper);
Dianne Hackborn6285a322013-09-18 12:09:47 -0700216 mUserId = userId;
217 }
218
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700219 @Override
220 public void handleMessage(Message msg) {
221 switch (msg.what) {
222 case MSG_BG_START_TIMEOUT: {
223 synchronized (mAm) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700224 rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700225 }
226 } break;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700227 case MSG_UPDATE_FOREGROUND_APPS: {
228 updateForegroundApps(this);
229 } break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700230 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700231 }
232
Dianne Hackbornad51be92016-08-16 16:27:36 -0700233 void ensureNotStartingBackgroundLocked(ServiceRecord r) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700234 if (mStartingBackground.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800235 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
236 "No longer background starting: " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -0700237 rescheduleDelayedStartsLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700238 }
Dianne Hackborn2e46bb52013-09-13 17:01:26 -0700239 if (mDelayedStartList.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800240 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700241 }
242 }
243
Dianne Hackbornad51be92016-08-16 16:27:36 -0700244 void rescheduleDelayedStartsLocked() {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700245 removeMessages(MSG_BG_START_TIMEOUT);
246 final long now = SystemClock.uptimeMillis();
247 for (int i=0, N=mStartingBackground.size(); i<N; i++) {
248 ServiceRecord r = mStartingBackground.get(i);
249 if (r.startingBgTimeout <= now) {
250 Slog.i(TAG, "Waited long enough for: " + r);
251 mStartingBackground.remove(i);
252 N--;
Junu Kimfcb87362014-02-19 16:25:21 +0900253 i--;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700254 }
255 }
256 while (mDelayedStartList.size() > 0
257 && mStartingBackground.size() < mMaxStartingBackground) {
258 ServiceRecord r = mDelayedStartList.remove(0);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800259 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
260 "REM FR DELAY LIST (exec next): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700261 if (r.pendingStarts.size() <= 0) {
262 Slog.w(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
263 + " delayedStop=" + r.delayedStop);
264 }
265 if (DEBUG_DELAYED_SERVICE) {
266 if (mDelayedStartList.size() > 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800267 Slog.v(TAG_SERVICE, "Remaining delayed list:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700268 for (int i=0; i<mDelayedStartList.size(); i++) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800269 Slog.v(TAG_SERVICE, " #" + i + ": " + mDelayedStartList.get(i));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700270 }
271 }
272 }
273 r.delayed = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700274 try {
275 startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false, true);
276 } catch (TransactionTooLargeException e) {
277 // Ignore, nobody upstack cares.
278 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700279 }
280 if (mStartingBackground.size() > 0) {
281 ServiceRecord next = mStartingBackground.get(0);
282 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800283 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700284 + ", can delay others up to " + when);
285 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
286 sendMessageAtTime(msg, when);
287 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700288 if (mStartingBackground.size() < mMaxStartingBackground) {
289 mAm.backgroundServicesFinishedLocked(mUserId);
290 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700291 }
292 }
293
294 public ActiveServices(ActivityManagerService service) {
295 mAm = service;
Dianne Hackborn23037412013-11-04 18:11:29 -0800296 int maxBg = 0;
297 try {
298 maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
299 } catch(RuntimeException e) {
300 }
Dianne Hackborn20d94742014-05-29 18:35:45 -0700301 mMaxStartingBackground = maxBg > 0
302 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700303 }
304
Dianne Hackbornad51be92016-08-16 16:27:36 -0700305 ServiceRecord getServiceByNameLocked(ComponentName name, int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700306 // TODO: Deal with global services
307 if (DEBUG_MU)
Dianne Hackbornad51be92016-08-16 16:27:36 -0700308 Slog.v(TAG_MU, "getServiceByNameLocked(" + name + "), callingUser = " + callingUser);
309 return getServiceMapLocked(callingUser).mServicesByName.get(name);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700310 }
311
Dianne Hackbornad51be92016-08-16 16:27:36 -0700312 boolean hasBackgroundServicesLocked(int callingUser) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700313 ServiceMap smap = mServiceMap.get(callingUser);
314 return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
315 }
316
Dianne Hackbornad51be92016-08-16 16:27:36 -0700317 private ServiceMap getServiceMapLocked(int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700318 ServiceMap smap = mServiceMap.get(callingUser);
319 if (smap == null) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700320 smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700321 mServiceMap.put(callingUser, smap);
322 }
323 return smap;
324 }
325
Dianne Hackbornad51be92016-08-16 16:27:36 -0700326 ArrayMap<ComponentName, ServiceRecord> getServicesLocked(int callingUser) {
327 return getServiceMapLocked(callingUser).mServicesByName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700328 }
329
Svet Ganov99b60432015-06-27 13:15:22 -0700330 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
Christopher Tate242ba3e92017-04-14 15:07:06 -0700331 int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700332 throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800333 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700334 + " type=" + resolvedType + " args=" + service.getExtras());
335
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700336 final boolean callerFg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700337 if (caller != null) {
338 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
339 if (callerApp == null) {
340 throw new SecurityException(
341 "Unable to find app for caller " + caller
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700342 + " (pid=" + callingPid
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700343 + ") when starting service " + service);
344 }
Dianne Hackborna49ad092016-03-03 13:39:10 -0800345 callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700346 } else {
347 callerFg = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700348 }
349
350 ServiceLookupResult res =
Svet Ganov99b60432015-06-27 13:15:22 -0700351 retrieveServiceLocked(service, resolvedType, callingPackage,
Svet Ganovd223db32017-12-22 09:43:48 -0800352 callingPid, callingUid, userId, true, callerFg, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700353 if (res == null) {
354 return null;
355 }
356 if (res.record == null) {
357 return new ComponentName("!", res.permission != null
358 ? res.permission : "private to package");
359 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700360
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700361 ServiceRecord r = res.record;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700362
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700363 if (!mAm.mUserController.exists(r.userId)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700364 Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700365 return null;
366 }
367
Christopher Tate08992ac2017-03-21 11:37:06 -0700368 // If this isn't a direct-to-foreground start, check our ability to kick off an
369 // arbitrary service
370 if (!r.startRequested && !fgRequired) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700371 // Before going further -- if this app is not allowed to start services in the
372 // background, then at this point we aren't going to let it period.
373 final int allowed = mAm.getAppStartModeLocked(r.appInfo.uid, r.packageName,
374 r.appInfo.targetSdkVersion, callingPid, false, false);
375 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
376 Slog.w(TAG, "Background start not allowed: service "
377 + service + " to " + r.name.flattenToShortString()
378 + " from pid=" + callingPid + " uid=" + callingUid
379 + " pkg=" + callingPackage);
380 if (allowed == ActivityManager.APP_START_MODE_DELAYED) {
381 // In this case we are silently disabling the app, to disrupt as
382 // little as possible existing apps.
383 return null;
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700384 }
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700385 // This app knows it is in the new model where this operation is not
386 // allowed, so tell it what has happened.
387 UidRecord uidRec = mAm.mActiveUids.get(r.appInfo.uid);
388 return new ComponentName("?", "app is in background uid " + uidRec);
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700389 }
390 }
391
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700392 NeededUriGrants neededGrants = mAm.checkGrantUriPermissionFromIntentLocked(
Nicolas Prevotc6cf95c2014-05-29 11:30:36 +0100393 callingUid, r.packageName, service, service.getFlags(), null, r.userId);
Svet Ganov9c165d72015-12-01 19:52:26 -0800394
395 // If permissions need a review before any of the app components can run,
396 // we do not start the service and launch a review activity if the calling app
397 // is in the foreground passing it a pending intent to start the service when
398 // review is completed.
Svet Ganov77df6f32016-08-17 11:46:34 -0700399 if (mAm.mPermissionReviewRequired) {
Svet Ganov9c165d72015-12-01 19:52:26 -0800400 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage,
401 callingUid, service, callerFg, userId)) {
402 return null;
403 }
404 }
405
Dianne Hackbornd6f5b622013-11-11 17:25:37 -0800406 if (unscheduleServiceRestartLocked(r, callingUid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800407 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700408 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700409 r.lastActivity = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700410 r.startRequested = true;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700411 r.delayedStop = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700412 r.fgRequired = fgRequired;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700413 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -0700414 service, neededGrants, callingUid));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700415
Dianne Hackbornad51be92016-08-16 16:27:36 -0700416 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700417 boolean addToStarting = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700418 if (!callerFg && !fgRequired && r.app == null
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700419 && mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700420 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700421 if (proc == null || proc.curProcState > ActivityManager.PROCESS_STATE_RECEIVER) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700422 // If this is not coming from a foreground caller, then we may want
423 // to delay the start if there are already other background services
424 // that are starting. This is to avoid process start spam when lots
425 // of applications are all handling things like connectivity broadcasts.
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700426 // We only do this for cached processes, because otherwise an application
427 // can have assumptions about calling startService() for a service to run
428 // in its own process, and for that process to not be killed before the
429 // service is started. This is especially the case for receivers, which
430 // may start a service in onReceive() to do some additional work and have
431 // initialized some global state as part of that.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800432 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
433 + r + " in " + proc);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700434 if (r.delayed) {
435 // This service is already scheduled for a delayed start; just leave
436 // it still waiting.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800437 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700438 return r.name;
439 }
440 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
441 // Something else is starting, delay!
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800442 Slog.i(TAG_SERVICE, "Delaying start of: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700443 smap.mDelayedStartList.add(r);
444 r.delayed = true;
445 return r.name;
446 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800447 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700448 addToStarting = true;
449 } else if (proc.curProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
450 // We slightly loosen when we will enqueue this new service as a background
451 // starting service we are waiting for, to also include processes that are
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700452 // currently running other services or receivers.
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700453 addToStarting = true;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800454 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
455 "Not delaying, but counting as bg: " + r);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800456 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn8e692572013-09-10 19:06:15 -0700457 StringBuilder sb = new StringBuilder(128);
458 sb.append("Not potential delay (state=").append(proc.curProcState)
459 .append(' ').append(proc.adjType);
460 String reason = proc.makeAdjReason();
461 if (reason != null) {
462 sb.append(' ');
463 sb.append(reason);
464 }
465 sb.append("): ");
466 sb.append(r.toString());
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800467 Slog.v(TAG_SERVICE, sb.toString());
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700468 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800469 } else if (DEBUG_DELAYED_STARTS) {
Christopher Tate08992ac2017-03-21 11:37:06 -0700470 if (callerFg || fgRequired) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800471 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
Christopher Tate08992ac2017-03-21 11:37:06 -0700472 + callingUid + " pid=" + callingPid + " fgRequired=" + fgRequired + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700473 } else if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800474 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700475 } else {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800476 Slog.v(TAG_SERVICE,
477 "Not potential delay (user " + r.userId + " not started): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700478 }
479 }
480
Christopher Tate42a386b2016-11-07 12:21:21 -0800481 ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
Christopher Tate42a386b2016-11-07 12:21:21 -0800482 return cmp;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700483 }
484
Svet Ganov9c165d72015-12-01 19:52:26 -0800485 private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
486 String callingPackage, int callingUid, Intent service, boolean callerFg,
487 final int userId) {
488 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
489 r.packageName, r.userId)) {
490
491 // Show a permission review UI only for starting from a foreground app
492 if (!callerFg) {
493 Slog.w(TAG, "u" + r.userId + " Starting a service in package"
494 + r.packageName + " requires a permissions review");
495 return false;
496 }
497
498 IIntentSender target = mAm.getIntentSenderLocked(
499 ActivityManager.INTENT_SENDER_SERVICE, callingPackage,
500 callingUid, userId, null, null, 0, new Intent[]{service},
501 new String[]{service.resolveType(mAm.mContext.getContentResolver())},
502 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
503 | PendingIntent.FLAG_IMMUTABLE, null);
504
505 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
506 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
507 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
508 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
509 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
510
511 if (DEBUG_PERMISSIONS_REVIEW) {
512 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
513 + r.packageName);
514 }
515
516 mAm.mHandler.post(new Runnable() {
517 @Override
518 public void run() {
519 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
520 }
521 });
522
523 return false;
524 }
525
526 return true;
527 }
528
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700529 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
530 boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
Joe Onorato4eb64fd2016-03-21 15:30:09 -0700531 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700532 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700533 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700534 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700535 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700536 synchronized (r.stats.getBatteryStats()) {
537 r.stats.startRunningLocked();
538 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800539 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700540 if (error != null) {
541 return new ComponentName("!!", error);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700542 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700543
544 if (r.startRequested && addToStarting) {
545 boolean first = smap.mStartingBackground.size() == 0;
546 smap.mStartingBackground.add(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700547 r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700548 if (DEBUG_DELAYED_SERVICE) {
549 RuntimeException here = new RuntimeException("here");
550 here.fillInStackTrace();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800551 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800552 } else if (DEBUG_DELAYED_STARTS) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800553 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700554 }
555 if (first) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700556 smap.rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700557 }
Christopher Tate08992ac2017-03-21 11:37:06 -0700558 } else if (callerFg || r.fgRequired) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700559 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700560 }
561
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700562 return r.name;
563 }
564
565 private void stopServiceLocked(ServiceRecord service) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700566 if (service.delayed) {
567 // If service isn't actually running, but is is being held in the
568 // delayed list, then we need to keep it started but note that it
569 // should be stopped once no longer delayed.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800570 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700571 service.delayedStop = true;
572 return;
573 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700574 synchronized (service.stats.getBatteryStats()) {
575 service.stats.stopRunningLocked();
576 }
577 service.startRequested = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700578 if (service.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700579 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700580 SystemClock.uptimeMillis());
581 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700582 service.callStart = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700583 bringDownServiceIfNeededLocked(service, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700584 }
585
586 int stopServiceLocked(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700587 String resolvedType, int userId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800588 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700589 + " type=" + resolvedType);
590
591 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
592 if (caller != null && callerApp == null) {
593 throw new SecurityException(
594 "Unable to find app for caller " + caller
595 + " (pid=" + Binder.getCallingPid()
596 + ") when stopping service " + service);
597 }
598
599 // If this service is active, make sure it is stopped.
Svet Ganov99b60432015-06-27 13:15:22 -0700600 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, null,
Svet Ganovd223db32017-12-22 09:43:48 -0800601 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700602 if (r != null) {
603 if (r.record != null) {
604 final long origId = Binder.clearCallingIdentity();
605 try {
606 stopServiceLocked(r.record);
607 } finally {
608 Binder.restoreCallingIdentity(origId);
609 }
610 return 1;
611 }
612 return -1;
613 }
614
615 return 0;
616 }
617
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700618 void stopInBackgroundLocked(int uid) {
619 // Stop all services associated with this uid due to it going to the background
620 // stopped state.
621 ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
622 ArrayList<ServiceRecord> stopping = null;
623 if (services != null) {
624 for (int i=services.mServicesByName.size()-1; i>=0; i--) {
625 ServiceRecord service = services.mServicesByName.valueAt(i);
626 if (service.appInfo.uid == uid && service.startRequested) {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800627 if (mAm.getAppStartModeLocked(service.appInfo.uid, service.packageName,
628 service.appInfo.targetSdkVersion, -1, false, false)
629 != ActivityManager.APP_START_MODE_NORMAL) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700630 if (stopping == null) {
631 stopping = new ArrayList<>();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700632 }
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700633 String compName = service.name.flattenToShortString();
634 EventLogTags.writeAmStopIdleService(service.appInfo.uid, compName);
635 StringBuilder sb = new StringBuilder(64);
636 sb.append("Stopping service due to app idle: ");
637 UserHandle.formatUid(sb, service.appInfo.uid);
638 sb.append(" ");
Yi Jin6b514142017-10-30 14:54:12 -0700639 TimeUtils.formatDuration(service.createRealTime
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700640 - SystemClock.elapsedRealtime(), sb);
641 sb.append(" ");
642 sb.append(compName);
643 Slog.w(TAG, sb.toString());
644 stopping.add(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700645 }
646 }
647 }
648 if (stopping != null) {
649 for (int i=stopping.size()-1; i>=0; i--) {
650 ServiceRecord service = stopping.get(i);
651 service.delayed = false;
Dianne Hackbornad51be92016-08-16 16:27:36 -0700652 services.ensureNotStartingBackgroundLocked(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700653 stopServiceLocked(service);
654 }
655 }
656 }
657 }
658
Svet Ganov99b60432015-06-27 13:15:22 -0700659 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
660 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, callingPackage,
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -0700661 Binder.getCallingPid(), Binder.getCallingUid(),
Svet Ganovd223db32017-12-22 09:43:48 -0800662 UserHandle.getCallingUserId(), false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700663
664 IBinder ret = null;
665 if (r != null) {
666 // r.record is null if findServiceLocked() failed the caller permission check
667 if (r.record == null) {
668 throw new SecurityException(
Christopher Desjardins5862c5f2015-05-19 11:25:40 +0000669 "Permission Denial: Accessing service"
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700670 + " from pid=" + Binder.getCallingPid()
671 + ", uid=" + Binder.getCallingUid()
672 + " requires " + r.permission);
673 }
674 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
675 if (ib != null) {
676 ret = ib.binder;
677 }
678 }
679
680 return ret;
681 }
682
683 boolean stopServiceTokenLocked(ComponentName className, IBinder token,
684 int startId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800685 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700686 + " " + token + " startId=" + startId);
Dianne Hackborn41203752012-08-31 14:05:51 -0700687 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700688 if (r != null) {
689 if (startId >= 0) {
690 // Asked to only stop if done with all work. Note that
691 // to avoid leaks, we will take this as dropping all
692 // start items up to and including this one.
693 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
694 if (si != null) {
695 while (r.deliveredStarts.size() > 0) {
696 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
697 cur.removeUriPermissionsLocked();
698 if (cur == si) {
699 break;
700 }
701 }
702 }
703
704 if (r.getLastStartId() != startId) {
705 return false;
706 }
707
708 if (r.deliveredStarts.size() > 0) {
709 Slog.w(TAG, "stopServiceToken startId " + startId
710 + " is last, but have " + r.deliveredStarts.size()
711 + " remaining args");
712 }
713 }
714
715 synchronized (r.stats.getBatteryStats()) {
716 r.stats.stopRunningLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700717 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700718 r.startRequested = false;
719 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700720 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700721 SystemClock.uptimeMillis());
722 }
723 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700724 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700725 bringDownServiceIfNeededLocked(r, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700726 Binder.restoreCallingIdentity(origId);
727 return true;
728 }
729 return false;
730 }
731
Sudheer Shankac9d94072017-02-22 22:13:55 +0000732 public void setServiceForegroundLocked(ComponentName className, IBinder token,
Dianne Hackborn67324c92016-04-18 13:55:25 -0700733 int id, Notification notification, int flags) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700734 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700735 final long origId = Binder.clearCallingIdentity();
736 try {
Dianne Hackborn41203752012-08-31 14:05:51 -0700737 ServiceRecord r = findServiceLocked(className, token, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700738 if (r != null) {
Sudheer Shankac9d94072017-02-22 22:13:55 +0000739 setServiceForegroundInnerLocked(r, id, notification, flags);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700740 }
741 } finally {
742 Binder.restoreCallingIdentity(origId);
743 }
744 }
745
Dianne Hackborncb015632017-06-14 17:30:15 -0700746 boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) {
747 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid="
748 + aa.mUid);
749 boolean canRemove = false;
750 aa.mHideTime = Long.MAX_VALUE;
751 if (aa.mShownWhileTop) {
752 // If the app was ever at the top of the screen while the foreground
753 // service was running, then we can always just immediately remove it.
754 canRemove = true;
755 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown while on top");
756 } else if (mScreenOn || aa.mShownWhileScreenOn) {
757 final long minTime = aa.mStartVisibleTime
758 + (aa.mStartTime != aa.mStartVisibleTime
759 ? mAm.mConstants.FGSERVICE_SCREEN_ON_AFTER_TIME
760 : mAm.mConstants.FGSERVICE_MIN_SHOWN_TIME);
761 if (nowElapsed >= minTime) {
762 // If shown while the screen is on, and it has been shown for
763 // at least the minimum show time, then we can now remove it.
764 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown long enough with screen on");
765 canRemove = true;
766 } else {
767 // This is when we will be okay to stop telling the user.
768 long reportTime = nowElapsed + mAm.mConstants.FGSERVICE_MIN_REPORT_TIME;
769 aa.mHideTime = reportTime > minTime ? reportTime : minTime;
770 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
771 + " with screen on");
772 }
773 } else {
774 final long minTime = aa.mEndTime
775 + mAm.mConstants.FGSERVICE_SCREEN_ON_BEFORE_TIME;
776 if (nowElapsed >= minTime) {
777 // If the foreground service has only run while the screen is
778 // off, but it has been gone now for long enough that we won't
779 // care to tell the user about it when the screen comes back on,
780 // then we can remove it now.
781 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - gone long enough with screen off");
782 canRemove = true;
783 } else {
784 // This is when we won't care about this old fg service.
785 aa.mHideTime = minTime;
786 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
787 + " with screen off");
788 }
789 }
790 return canRemove;
791 }
792
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700793 void updateForegroundApps(ServiceMap smap) {
794 // This is called from the handler without the lock held.
795 ArrayList<ActiveForegroundApp> active = null;
796 synchronized (mAm) {
797 final long now = SystemClock.elapsedRealtime();
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700798 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700799 if (smap != null) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700800 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Updating foreground apps for user "
801 + smap.mUserId);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700802 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
803 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -0700804 if (aa.mEndTime != 0) {
805 boolean canRemove = foregroundAppShownEnoughLocked(aa, now);
806 if (canRemove) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700807 // This was up for longer than the timeout, so just remove immediately.
808 smap.mActiveForegroundApps.removeAt(i);
809 smap.mActiveForegroundAppsChanged = true;
810 continue;
811 }
Dianne Hackborncb015632017-06-14 17:30:15 -0700812 if (aa.mHideTime < nextUpdateTime) {
813 nextUpdateTime = aa.mHideTime;
814 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700815 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700816 if (!aa.mAppOnTop) {
817 if (active == null) {
818 active = new ArrayList<>();
819 }
Dianne Hackborncb015632017-06-14 17:30:15 -0700820 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
821 + aa.mPackageName + ", uid=" + aa.mUid);
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700822 active.add(aa);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700823 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700824 }
825 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
826 if (nextUpdateTime < Long.MAX_VALUE) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700827 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Next update time in: "
828 + (nextUpdateTime-now));
829 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700830 smap.sendMessageAtTime(msg, nextUpdateTime
831 + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700832 }
833 }
834 if (!smap.mActiveForegroundAppsChanged) {
835 return;
836 }
837 smap.mActiveForegroundAppsChanged = false;
838 }
839
840 final NotificationManager nm = (NotificationManager) mAm.mContext.getSystemService(
841 Context.NOTIFICATION_SERVICE);
842 final Context context = mAm.mContext;
843
844 if (active != null) {
845 for (int i = 0; i < active.size(); i++) {
846 ActiveForegroundApp aa = active.get(i);
847 if (aa.mLabel == null) {
848 PackageManager pm = context.getPackageManager();
849 try {
850 ApplicationInfo ai = pm.getApplicationInfoAsUser(aa.mPackageName,
851 PackageManager.MATCH_KNOWN_PACKAGES, smap.mUserId);
852 aa.mLabel = ai.loadLabel(pm);
853 } catch (PackageManager.NameNotFoundException e) {
854 aa.mLabel = aa.mPackageName;
855 }
856 }
857 }
858
859 Intent intent;
860 String title;
861 String msg;
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700862 String[] pkgs;
Dan Sandler886e0162017-06-06 14:23:43 -0400863 final long nowElapsed = SystemClock.elapsedRealtime();
864 long oldestStartTime = nowElapsed;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700865 if (active.size() == 1) {
866 intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
867 intent.setData(Uri.fromParts("package", active.get(0).mPackageName, null));
868 title = context.getString(
869 R.string.foreground_service_app_in_background, active.get(0).mLabel);
870 msg = context.getString(R.string.foreground_service_tap_for_details);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700871 pkgs = new String[] { active.get(0).mPackageName };
Dan Sandler2f36ab82017-05-25 00:15:49 -0400872 oldestStartTime = active.get(0).mStartTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700873 } else {
874 intent = new Intent(Settings.ACTION_FOREGROUND_SERVICES_SETTINGS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700875 pkgs = new String[active.size()];
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700876 for (int i = 0; i < active.size(); i++) {
877 pkgs[i] = active.get(i).mPackageName;
Dan Sandler2f36ab82017-05-25 00:15:49 -0400878 oldestStartTime = Math.min(oldestStartTime, active.get(i).mStartTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700879 }
880 intent.putExtra("packages", pkgs);
881 title = context.getString(
882 R.string.foreground_service_apps_in_background, active.size());
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700883 msg = active.get(0).mLabel.toString();
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700884 for (int i = 1; i < active.size(); i++) {
885 msg = context.getString(R.string.foreground_service_multiple_separator,
886 msg, active.get(i).mLabel);
887 }
888 }
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700889 Bundle notificationBundle = new Bundle();
890 notificationBundle.putStringArray(Notification.EXTRA_FOREGROUND_APPS, pkgs);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700891 Notification.Builder n =
892 new Notification.Builder(context,
893 SystemNotificationChannels.FOREGROUND_SERVICE)
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700894 .addExtras(notificationBundle)
Dan Sandler2f36ab82017-05-25 00:15:49 -0400895 .setSmallIcon(R.drawable.stat_sys_vitals)
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700896 .setOngoing(true)
Dan Sandler886e0162017-06-06 14:23:43 -0400897 .setShowWhen(oldestStartTime < nowElapsed)
898 .setWhen(System.currentTimeMillis() - (nowElapsed - oldestStartTime))
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700899 .setColor(context.getColor(
900 com.android.internal.R.color.system_notification_accent_color))
901 .setContentTitle(title)
902 .setContentText(msg)
903 .setContentIntent(
904 PendingIntent.getActivityAsUser(context, 0, intent,
905 PendingIntent.FLAG_UPDATE_CURRENT,
906 null, new UserHandle(smap.mUserId)));
907 nm.notifyAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
908 n.build(), new UserHandle(smap.mUserId));
909 } else {
910 nm.cancelAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
911 new UserHandle(smap.mUserId));
912 }
913 }
914
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700915 private void requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700916 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700917 if (timeElapsed != 0) {
918 smap.sendMessageAtTime(msg,
919 timeElapsed + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700920 } else {
921 smap.mActiveForegroundAppsChanged = true;
922 smap.sendMessage(msg);
923 }
924 }
925
926 private void decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r) {
927 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
928 if (active != null) {
929 active.mNumActive--;
930 if (active.mNumActive <= 0) {
931 active.mEndTime = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -0700932 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Ended running of service");
933 if (foregroundAppShownEnoughLocked(active, active.mEndTime)) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700934 // Have been active for long enough that we will remove it immediately.
935 smap.mActiveForegroundApps.remove(r.packageName);
936 smap.mActiveForegroundAppsChanged = true;
937 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -0700938 } else if (active.mHideTime < Long.MAX_VALUE){
939 requestUpdateActiveForegroundAppsLocked(smap, active.mHideTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700940 }
941 }
942 }
943 }
944
945 void updateScreenStateLocked(boolean screenOn) {
946 if (mScreenOn != screenOn) {
947 mScreenOn = screenOn;
948
949 // If screen is turning on, then we now reset the start time of any foreground
950 // services that were started while the screen was off.
951 if (screenOn) {
952 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -0700953 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Screen turned on");
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700954 for (int i = mServiceMap.size()-1; i >= 0; i--) {
955 ServiceMap smap = mServiceMap.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -0700956 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700957 boolean changed = false;
958 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
959 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
Dianne Hackborncb015632017-06-14 17:30:15 -0700960 if (active.mEndTime == 0) {
961 if (!active.mShownWhileScreenOn) {
962 active.mShownWhileScreenOn = true;
963 active.mStartVisibleTime = nowElapsed;
964 }
965 } else {
966 if (!active.mShownWhileScreenOn
967 && active.mStartVisibleTime == active.mStartTime) {
968 // If this was never shown while the screen was on, then we will
969 // count the time it started being visible as now, to tell the user
970 // about it now that they have a screen to look at.
971 active.mEndTime = active.mStartVisibleTime = nowElapsed;
972 }
973 if (foregroundAppShownEnoughLocked(active, nowElapsed)) {
974 // Have been active for long enough that we will remove it
975 // immediately.
976 smap.mActiveForegroundApps.remove(active.mPackageName);
977 smap.mActiveForegroundAppsChanged = true;
978 changed = true;
979 } else {
980 if (active.mHideTime < nextUpdateTime) {
981 nextUpdateTime = active.mHideTime;
982 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700983 }
984 }
985 }
986 if (changed) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700987 // Need to immediately update.
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700988 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -0700989 } else if (nextUpdateTime < Long.MAX_VALUE) {
990 requestUpdateActiveForegroundAppsLocked(smap, nextUpdateTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700991 }
992 }
993 }
994 }
995 }
996
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700997 void foregroundServiceProcStateChangedLocked(UidRecord uidRec) {
998 ServiceMap smap = mServiceMap.get(UserHandle.getUserId(uidRec.uid));
999 if (smap != null) {
1000 boolean changed = false;
1001 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1002 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
1003 if (active.mUid == uidRec.uid) {
1004 if (uidRec.curProcState <= ActivityManager.PROCESS_STATE_TOP) {
1005 if (!active.mAppOnTop) {
1006 active.mAppOnTop = true;
1007 changed = true;
1008 }
1009 active.mShownWhileTop = true;
1010 } else if (active.mAppOnTop) {
1011 active.mAppOnTop = false;
1012 changed = true;
1013 }
1014 }
1015 }
1016 if (changed) {
1017 requestUpdateActiveForegroundAppsLocked(smap, 0);
1018 }
1019 }
1020 }
1021
Sudheer Shankac9d94072017-02-22 22:13:55 +00001022 private void setServiceForegroundInnerLocked(ServiceRecord r, int id,
Christopher Tate42a386b2016-11-07 12:21:21 -08001023 Notification notification, int flags) {
1024 if (id != 0) {
1025 if (notification == null) {
1026 throw new IllegalArgumentException("null notification");
1027 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001028 // Instant apps need permission to create foreground services.
1029 if (r.appInfo.isInstantApp()) {
1030 final int mode = mAm.mAppOpsService.checkOperation(
1031 AppOpsManager.OP_INSTANT_APP_START_FOREGROUND,
1032 r.appInfo.uid,
1033 r.appInfo.packageName);
1034 switch (mode) {
1035 case AppOpsManager.MODE_ALLOWED:
1036 break;
1037 case AppOpsManager.MODE_IGNORED:
1038 Slog.w(TAG, "Instant app " + r.appInfo.packageName
1039 + " does not have permission to create foreground services"
1040 + ", ignoring.");
Sudheer Shankac9d94072017-02-22 22:13:55 +00001041 return;
Chad Brubaker97b383f2017-02-02 15:04:35 -08001042 case AppOpsManager.MODE_ERRORED:
1043 throw new SecurityException("Instant app " + r.appInfo.packageName
1044 + " does not have permission to create foreground services");
1045 default:
Dianne Hackborna9da85f2018-01-19 17:44:46 -08001046 mAm.enforcePermission(
1047 android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
1048 r.app.pid, r.appInfo.uid, "startForeground");
Chad Brubaker97b383f2017-02-02 15:04:35 -08001049 }
Dianne Hackborna9da85f2018-01-19 17:44:46 -08001050 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
1051 mAm.enforcePermission(
1052 android.Manifest.permission.FOREGROUND_SERVICE,
1053 r.app.pid, r.appInfo.uid, "startForeground");
Chad Brubaker97b383f2017-02-02 15:04:35 -08001054 }
Christopher Tate08992ac2017-03-21 11:37:06 -07001055 if (r.fgRequired) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001056 if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001057 Slog.i(TAG, "Service called startForeground() as required: " + r);
1058 }
1059 r.fgRequired = false;
1060 r.fgWaiting = false;
1061 mAm.mHandler.removeMessages(
1062 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
1063 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001064 if (r.foregroundId != id) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001065 cancelForegroundNotificationLocked(r);
Christopher Tate42a386b2016-11-07 12:21:21 -08001066 r.foregroundId = id;
1067 }
1068 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
1069 r.foregroundNoti = notification;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001070 if (!r.isForeground) {
1071 final ServiceMap smap = getServiceMapLocked(r.userId);
1072 if (smap != null) {
1073 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1074 if (active == null) {
1075 active = new ActiveForegroundApp();
1076 active.mPackageName = r.packageName;
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001077 active.mUid = r.appInfo.uid;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001078 active.mShownWhileScreenOn = mScreenOn;
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001079 if (r.app != null) {
1080 active.mAppOnTop = active.mShownWhileTop =
1081 r.app.uidRecord.curProcState
1082 <= ActivityManager.PROCESS_STATE_TOP;
1083 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001084 active.mStartTime = active.mStartVisibleTime
1085 = SystemClock.elapsedRealtime();
1086 smap.mActiveForegroundApps.put(r.packageName, active);
1087 requestUpdateActiveForegroundAppsLocked(smap, 0);
1088 }
1089 active.mNumActive++;
1090 }
1091 r.isForeground = true;
Chenjie Yuccfe6452018-01-30 11:33:21 -08001092 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED, r.userId, r.shortName,
1093 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001094 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001095 r.postNotification();
1096 if (r.app != null) {
1097 updateServiceForegroundLocked(r.app, true);
1098 }
1099 getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
1100 mAm.notifyPackageUse(r.serviceInfo.packageName,
1101 PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
1102 } else {
1103 if (r.isForeground) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001104 final ServiceMap smap = getServiceMapLocked(r.userId);
1105 if (smap != null) {
1106 decActiveForegroundAppLocked(smap, r);
1107 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001108 r.isForeground = false;
Chenjie Yuccfe6452018-01-30 11:33:21 -08001109 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED, r.userId, r.shortName,
1110 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Christopher Tate42a386b2016-11-07 12:21:21 -08001111 if (r.app != null) {
1112 mAm.updateLruProcessLocked(r.app, false, null);
1113 updateServiceForegroundLocked(r.app, true);
1114 }
1115 }
1116 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001117 cancelForegroundNotificationLocked(r);
Christopher Tate42a386b2016-11-07 12:21:21 -08001118 r.foregroundId = 0;
1119 r.foregroundNoti = null;
1120 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1121 r.stripForegroundServiceFlagFromNotification();
1122 if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
1123 r.foregroundId = 0;
1124 r.foregroundNoti = null;
1125 }
1126 }
1127 }
1128 }
1129
Christopher Tate08992ac2017-03-21 11:37:06 -07001130 private void cancelForegroundNotificationLocked(ServiceRecord r) {
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001131 if (r.foregroundId != 0) {
1132 // First check to see if this app has any other active foreground services
1133 // with the same notification ID. If so, we shouldn't actually cancel it,
1134 // because that would wipe away the notification that still needs to be shown
1135 // due the other service.
Dianne Hackbornad51be92016-08-16 16:27:36 -07001136 ServiceMap sm = getServiceMapLocked(r.userId);
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001137 if (sm != null) {
1138 for (int i = sm.mServicesByName.size()-1; i >= 0; i--) {
1139 ServiceRecord other = sm.mServicesByName.valueAt(i);
Dianne Hackborn569a4582016-08-04 14:00:22 -07001140 if (other != r && other.foregroundId == r.foregroundId
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001141 && other.packageName.equals(r.packageName)) {
1142 // Found one! Abort the cancel.
1143 return;
1144 }
1145 }
1146 }
1147 r.cancelNotification();
1148 }
1149 }
1150
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001151 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
1152 boolean anyForeground = false;
Dianne Hackbornc8230512013-07-13 21:32:12 -07001153 for (int i=proc.services.size()-1; i>=0; i--) {
1154 ServiceRecord sr = proc.services.valueAt(i);
Christopher Tatee23fa2b2017-04-20 14:48:13 -07001155 if (sr.isForeground || sr.fgRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001156 anyForeground = true;
1157 break;
1158 }
1159 }
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08001160 mAm.updateProcessForegroundLocked(proc, anyForeground, oomAdj);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001161 }
1162
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001163 private void updateWhitelistManagerLocked(ProcessRecord proc) {
1164 proc.whitelistManager = false;
1165 for (int i=proc.services.size()-1; i>=0; i--) {
1166 ServiceRecord sr = proc.services.valueAt(i);
1167 if (sr.whitelistManager) {
1168 proc.whitelistManager = true;
1169 break;
1170 }
1171 }
1172 }
1173
Dianne Hackborn465fa392014-09-14 14:21:18 -07001174 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
1175 ArraySet<ProcessRecord> updatedProcesses = null;
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001176 for (int i = 0; i < clientProc.connections.size(); i++) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001177 final ConnectionRecord conn = clientProc.connections.valueAt(i);
1178 final ProcessRecord proc = conn.binding.service.app;
1179 if (proc == null || proc == clientProc) {
1180 continue;
1181 } else if (updatedProcesses == null) {
1182 updatedProcesses = new ArraySet<>();
1183 } else if (updatedProcesses.contains(proc)) {
1184 continue;
1185 }
1186 updatedProcesses.add(proc);
1187 updateServiceClientActivitiesLocked(proc, null, false);
1188 }
1189 }
1190
Dianne Hackborndb926082013-10-31 16:32:44 -07001191 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
Dianne Hackborn465fa392014-09-14 14:21:18 -07001192 ConnectionRecord modCr, boolean updateLru) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001193 if (modCr != null && modCr.binding.client != null) {
1194 if (modCr.binding.client.activities.size() <= 0) {
1195 // This connection is from a client without activities, so adding
1196 // and removing is not interesting.
1197 return false;
1198 }
1199 }
1200
1201 boolean anyClientActivities = false;
1202 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
1203 ServiceRecord sr = proc.services.valueAt(i);
1204 for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) {
1205 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni);
1206 for (int cri=clist.size()-1; cri>=0; cri--) {
1207 ConnectionRecord cr = clist.get(cri);
1208 if (cr.binding.client == null || cr.binding.client == proc) {
1209 // Binding to ourself is not interesting.
1210 continue;
1211 }
1212 if (cr.binding.client.activities.size() > 0) {
1213 anyClientActivities = true;
1214 break;
1215 }
1216 }
1217 }
1218 }
1219 if (anyClientActivities != proc.hasClientActivities) {
1220 proc.hasClientActivities = anyClientActivities;
Dianne Hackborn465fa392014-09-14 14:21:18 -07001221 if (updateLru) {
1222 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
1223 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001224 return true;
1225 }
1226 return false;
1227 }
1228
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001229 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
Svet Ganov9c165d72015-12-01 19:52:26 -08001230 String resolvedType, final IServiceConnection connection, int flags,
1231 String callingPackage, final int userId) throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001232 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001233 + " type=" + resolvedType + " conn=" + connection.asBinder()
1234 + " flags=0x" + Integer.toHexString(flags));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001235 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
1236 if (callerApp == null) {
1237 throw new SecurityException(
1238 "Unable to find app for caller " + caller
1239 + " (pid=" + Binder.getCallingPid()
1240 + ") when binding service " + service);
1241 }
1242
1243 ActivityRecord activity = null;
1244 if (token != null) {
Craig Mautnerd2328952013-03-05 12:46:26 -08001245 activity = ActivityRecord.isInStackLocked(token);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001246 if (activity == null) {
1247 Slog.w(TAG, "Binding with unknown activity: " + token);
1248 return 0;
1249 }
1250 }
1251
1252 int clientLabel = 0;
1253 PendingIntent clientIntent = null;
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001254 final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001255
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001256 if (isCallerSystem) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001257 // Hacky kind of thing -- allow system stuff to tell us
1258 // what they are, so we can report this elsewhere for
1259 // others to know why certain services are running.
Jeff Sharkeyf0ec2e02016-03-21 12:37:54 -06001260 service.setDefusable(true);
1261 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001262 if (clientIntent != null) {
1263 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
1264 if (clientLabel != 0) {
1265 // There are no useful extras in the intent, trash them.
1266 // System code calling with this stuff just needs to know
1267 // this will happen.
1268 service = service.cloneFilter();
1269 }
1270 }
1271 }
1272
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001273 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1274 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
1275 "BIND_TREAT_LIKE_ACTIVITY");
1276 }
1277
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001278 if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
1279 throw new SecurityException(
1280 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1281 + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
1282 }
1283
Svet Ganovd223db32017-12-22 09:43:48 -08001284 if ((flags & Context.BIND_ALLOW_INSTANT) != 0 && !isCallerSystem) {
1285 throw new SecurityException(
1286 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1287 + ") set BIND_ALLOW_INSTANT when binding service " + service);
1288 }
1289
Dianne Hackborna49ad092016-03-03 13:39:10 -08001290 final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Robert Sesekb9a86662015-12-09 16:22:45 -05001291 final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
Svet Ganovd223db32017-12-22 09:43:48 -08001292 final boolean allowInstant = (flags & Context.BIND_ALLOW_INSTANT) != 0;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001293
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001294 ServiceLookupResult res =
Robert Sesekb9a86662015-12-09 16:22:45 -05001295 retrieveServiceLocked(service, resolvedType, callingPackage, Binder.getCallingPid(),
Svet Ganovd223db32017-12-22 09:43:48 -08001296 Binder.getCallingUid(), userId, true, callerFg, isBindExternal, allowInstant);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001297 if (res == null) {
1298 return 0;
1299 }
1300 if (res.record == null) {
1301 return -1;
1302 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001303 ServiceRecord s = res.record;
1304
Svet Ganov9c165d72015-12-01 19:52:26 -08001305 boolean permissionsReviewRequired = false;
1306
1307 // If permissions need a review before any of the app components can run,
1308 // we schedule binding to the service but do not start its process, then
1309 // we launch a review activity to which is passed a callback to invoke
1310 // when done to start the bound service's process to completing the binding.
Svet Ganov77df6f32016-08-17 11:46:34 -07001311 if (mAm.mPermissionReviewRequired) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001312 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
1313 s.packageName, s.userId)) {
1314
1315 permissionsReviewRequired = true;
1316
1317 // Show a permission review UI only for binding from a foreground app
1318 if (!callerFg) {
1319 Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
1320 + s.packageName + " requires a permissions review");
1321 return 0;
1322 }
1323
1324 final ServiceRecord serviceRecord = s;
1325 final Intent serviceIntent = service;
1326
1327 RemoteCallback callback = new RemoteCallback(
1328 new RemoteCallback.OnResultListener() {
1329 @Override
1330 public void onResult(Bundle result) {
1331 synchronized(mAm) {
1332 final long identity = Binder.clearCallingIdentity();
1333 try {
1334 if (!mPendingServices.contains(serviceRecord)) {
1335 return;
1336 }
1337 // If there is still a pending record, then the service
1338 // binding request is still valid, so hook them up. We
1339 // proceed only if the caller cleared the review requirement
1340 // otherwise we unbind because the user didn't approve.
1341 if (!mAm.getPackageManagerInternalLocked()
1342 .isPermissionsReviewRequired(
1343 serviceRecord.packageName,
1344 serviceRecord.userId)) {
1345 try {
1346 bringUpServiceLocked(serviceRecord,
1347 serviceIntent.getFlags(),
1348 callerFg, false, false);
1349 } catch (RemoteException e) {
1350 /* ignore - local call */
1351 }
1352 } else {
1353 unbindServiceLocked(connection);
1354 }
1355 } finally {
1356 Binder.restoreCallingIdentity(identity);
1357 }
1358 }
1359 }
1360 });
1361
1362 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
1363 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1364 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1365 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
1366 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
1367
1368 if (DEBUG_PERMISSIONS_REVIEW) {
1369 Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
1370 + s.packageName);
1371 }
1372
1373 mAm.mHandler.post(new Runnable() {
1374 @Override
1375 public void run() {
1376 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
1377 }
1378 });
1379 }
1380 }
1381
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001382 final long origId = Binder.clearCallingIdentity();
1383
1384 try {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001385 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001386 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001387 + s);
1388 }
1389
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001390 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1391 s.lastActivity = SystemClock.uptimeMillis();
1392 if (!s.hasAutoCreateConnections()) {
1393 // This is the first binding, let the tracker know.
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001394 ServiceState stracker = s.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001395 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001396 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001397 s.lastActivity);
1398 }
1399 }
1400 }
1401
Joe Onorato05c9ecc2016-03-30 15:13:46 -07001402 mAm.startAssociationLocked(callerApp.uid, callerApp.processName, callerApp.curProcState,
Dianne Hackbornab2df062015-01-07 13:43:13 -08001403 s.appInfo.uid, s.name, s.processName);
Jesse Evans02af3ea2017-05-03 09:57:16 -07001404 // Once the apps have become associated, if one of them is caller is ephemeral
1405 // the target app should now be able to see the calling app
1406 mAm.grantEphemeralAccessLocked(callerApp.userId, service,
1407 s.appInfo.uid, UserHandle.getAppId(callerApp.uid));
Dianne Hackbornab2df062015-01-07 13:43:13 -08001408
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001409 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
1410 ConnectionRecord c = new ConnectionRecord(b, activity,
1411 connection, flags, clientLabel, clientIntent);
1412
1413 IBinder binder = connection.asBinder();
1414 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
1415 if (clist == null) {
1416 clist = new ArrayList<ConnectionRecord>();
1417 s.connections.put(binder, clist);
1418 }
1419 clist.add(c);
1420 b.connections.add(c);
1421 if (activity != null) {
1422 if (activity.connections == null) {
1423 activity.connections = new HashSet<ConnectionRecord>();
1424 }
1425 activity.connections.add(c);
1426 }
1427 b.client.connections.add(c);
1428 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
1429 b.client.hasAboveClient = true;
1430 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001431 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
1432 s.whitelistManager = true;
1433 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001434 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001435 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07001436 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001437 clist = mServiceConnections.get(binder);
1438 if (clist == null) {
1439 clist = new ArrayList<ConnectionRecord>();
1440 mServiceConnections.put(binder, clist);
1441 }
1442 clist.add(c);
1443
1444 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1445 s.lastActivity = SystemClock.uptimeMillis();
Svet Ganov9c165d72015-12-01 19:52:26 -08001446 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
1447 permissionsReviewRequired) != null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001448 return 0;
1449 }
1450 }
1451
1452 if (s.app != null) {
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001453 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1454 s.app.treatLikeActivity = true;
1455 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001456 if (s.whitelistManager) {
1457 s.app.whitelistManager = true;
1458 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001459 // This could have made the service more important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001460 mAm.updateLruProcessLocked(s.app, s.app.hasClientActivities
1461 || s.app.treatLikeActivity, b.client);
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001462 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001463 }
1464
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001465 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001466 + ": received=" + b.intent.received
1467 + " apps=" + b.intent.apps.size()
1468 + " doRebind=" + b.intent.doRebind);
1469
1470 if (s.app != null && b.intent.received) {
1471 // Service is already running, so we can immediately
1472 // publish the connection.
1473 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001474 c.conn.connected(s.name, b.intent.binder, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001475 } catch (Exception e) {
1476 Slog.w(TAG, "Failure sending service " + s.shortName
1477 + " to connection " + c.conn.asBinder()
1478 + " (in " + c.binding.client.processName + ")", e);
1479 }
1480
1481 // If this is the first app connected back to this binding,
1482 // and the service had previously asked to be told when
1483 // rebound, then do so.
1484 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001485 requestServiceBindingLocked(s, b.intent, callerFg, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001486 }
1487 } else if (!b.intent.requested) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001488 requestServiceBindingLocked(s, b.intent, callerFg, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001489 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001490
Dianne Hackbornad51be92016-08-16 16:27:36 -07001491 getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001492
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001493 } finally {
1494 Binder.restoreCallingIdentity(origId);
1495 }
1496
1497 return 1;
1498 }
1499
1500 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
1501 final long origId = Binder.clearCallingIdentity();
1502 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001503 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001504 + " " + intent + ": " + service);
1505 if (r != null) {
1506 Intent.FilterComparison filter
1507 = new Intent.FilterComparison(intent);
1508 IntentBindRecord b = r.bindings.get(filter);
1509 if (b != null && !b.received) {
1510 b.binder = service;
1511 b.requested = true;
1512 b.received = true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07001513 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1514 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
1515 for (int i=0; i<clist.size(); i++) {
1516 ConnectionRecord c = clist.get(i);
1517 if (!filter.equals(c.binding.intent.intent)) {
1518 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001519 TAG_SERVICE, "Not publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001520 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001521 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001522 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001523 TAG_SERVICE, "Published intent: " + intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001524 continue;
1525 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001526 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001527 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001528 c.conn.connected(r.name, service, false);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001529 } catch (Exception e) {
1530 Slog.w(TAG, "Failure sending service " + r.name +
1531 " to connection " + c.conn.asBinder() +
1532 " (in " + c.binding.client.processName + ")", e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001533 }
1534 }
1535 }
1536 }
1537
Dianne Hackborn164371f2013-10-01 19:10:13 -07001538 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001539 }
1540 } finally {
1541 Binder.restoreCallingIdentity(origId);
1542 }
1543 }
1544
1545 boolean unbindServiceLocked(IServiceConnection connection) {
1546 IBinder binder = connection.asBinder();
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001547 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001548 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1549 if (clist == null) {
1550 Slog.w(TAG, "Unbind failed: could not find connection for "
1551 + connection.asBinder());
1552 return false;
1553 }
1554
1555 final long origId = Binder.clearCallingIdentity();
1556 try {
1557 while (clist.size() > 0) {
1558 ConnectionRecord r = clist.get(0);
1559 removeConnectionLocked(r, null, null);
Dianne Hackborn25e1eca2014-09-23 10:13:13 -07001560 if (clist.size() > 0 && clist.get(0) == r) {
1561 // In case it didn't get removed above, do it now.
1562 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
1563 clist.remove(0);
1564 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001565
1566 if (r.binding.service.app != null) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001567 if (r.binding.service.app.whitelistManager) {
Felipe Lemea7778b02016-06-28 10:38:59 -07001568 updateWhitelistManagerLocked(r.binding.service.app);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001569 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001570 // This could have made the service less important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001571 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1572 r.binding.service.app.treatLikeActivity = true;
1573 mAm.updateLruProcessLocked(r.binding.service.app,
1574 r.binding.service.app.hasClientActivities
1575 || r.binding.service.app.treatLikeActivity, null);
1576 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001577 mAm.updateOomAdjLocked(r.binding.service.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001578 }
1579 }
Amith Yamasanib2926b12017-05-11 11:13:52 -07001580
1581 mAm.updateOomAdjLocked();
1582
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001583 } finally {
1584 Binder.restoreCallingIdentity(origId);
1585 }
1586
1587 return true;
1588 }
1589
1590 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
1591 final long origId = Binder.clearCallingIdentity();
1592 try {
1593 if (r != null) {
1594 Intent.FilterComparison filter
1595 = new Intent.FilterComparison(intent);
1596 IntentBindRecord b = r.bindings.get(filter);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001597 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001598 + " at " + b + ": apps="
1599 + (b != null ? b.apps.size() : 0));
1600
Dianne Hackborn164371f2013-10-01 19:10:13 -07001601 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001602 if (b != null) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001603 if (b.apps.size() > 0 && !inDestroying) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001604 // Applications have already bound since the last
1605 // unbind, so just rebind right here.
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001606 boolean inFg = false;
1607 for (int i=b.apps.size()-1; i>=0; i--) {
1608 ProcessRecord client = b.apps.valueAt(i).client;
1609 if (client != null && client.setSchedGroup
Dianne Hackborna49ad092016-03-03 13:39:10 -08001610 != ProcessList.SCHED_GROUP_BACKGROUND) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001611 inFg = true;
1612 break;
1613 }
1614 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001615 try {
1616 requestServiceBindingLocked(r, b, inFg, true);
1617 } catch (TransactionTooLargeException e) {
1618 // Don't pass this back to ActivityThread, it's unrelated.
1619 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001620 } else {
1621 // Note to tell the service the next time there is
1622 // a new client.
1623 b.doRebind = true;
1624 }
1625 }
1626
Dianne Hackborn164371f2013-10-01 19:10:13 -07001627 serviceDoneExecutingLocked(r, inDestroying, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001628 }
1629 } finally {
1630 Binder.restoreCallingIdentity(origId);
1631 }
1632 }
1633
1634 private final ServiceRecord findServiceLocked(ComponentName name,
Dianne Hackborn41203752012-08-31 14:05:51 -07001635 IBinder token, int userId) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07001636 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001637 return r == token ? r : null;
1638 }
1639
1640 private final class ServiceLookupResult {
1641 final ServiceRecord record;
1642 final String permission;
1643
1644 ServiceLookupResult(ServiceRecord _record, String _permission) {
1645 record = _record;
1646 permission = _permission;
1647 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001648 }
1649
1650 private class ServiceRestarter implements Runnable {
1651 private ServiceRecord mService;
1652
1653 void setService(ServiceRecord service) {
1654 mService = service;
1655 }
1656
1657 public void run() {
1658 synchronized(mAm) {
1659 performServiceRestartLocked(mService);
1660 }
1661 }
1662 }
1663
1664 private ServiceLookupResult retrieveServiceLocked(Intent service,
Svet Ganov99b60432015-06-27 13:15:22 -07001665 String resolvedType, String callingPackage, int callingPid, int callingUid, int userId,
Svet Ganovd223db32017-12-22 09:43:48 -08001666 boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
1667 boolean allowInstant) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001668 ServiceRecord r = null;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001669 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001670 + " type=" + resolvedType + " callingUid=" + callingUid);
1671
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001672 userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
1673 ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE, "service", null);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001674
Dianne Hackbornad51be92016-08-16 16:27:36 -07001675 ServiceMap smap = getServiceMapLocked(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001676 final ComponentName comp = service.getComponent();
1677 if (comp != null) {
1678 r = smap.mServicesByName.get(comp);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001679 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001680 }
Robert Sesekb9a86662015-12-09 16:22:45 -05001681 if (r == null && !isBindExternal) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001682 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001683 r = smap.mServicesByIntent.get(filter);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001684 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001685 }
Robert Sesekb9a86662015-12-09 16:22:45 -05001686 if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
1687 && !callingPackage.equals(r.packageName)) {
1688 // If an external service is running within its own package, other packages
1689 // should not bind to that instance.
1690 r = null;
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001691 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Whoops, can't use existing external service");
Robert Sesekb9a86662015-12-09 16:22:45 -05001692 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001693 if (r == null) {
1694 try {
Svet Ganovd223db32017-12-22 09:43:48 -08001695 int flags = ActivityManagerService.STOCK_PM_FLAGS
1696 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
1697 if (allowInstant) {
1698 flags |= PackageManager.MATCH_INSTANT;
1699 }
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001700 // TODO: come back and remove this assumption to triage all services
Todd Kennedy51b3aac2017-03-30 17:50:42 -07001701 ResolveInfo rInfo = mAm.getPackageManagerInternalLocked().resolveService(service,
Svet Ganovd223db32017-12-22 09:43:48 -08001702 resolvedType, flags, userId, callingUid);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001703 ServiceInfo sInfo =
1704 rInfo != null ? rInfo.serviceInfo : null;
1705 if (sInfo == null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001706 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001707 ": not found");
1708 return null;
1709 }
1710 ComponentName name = new ComponentName(
1711 sInfo.applicationInfo.packageName, sInfo.name);
Robert Sesekb9a86662015-12-09 16:22:45 -05001712 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
1713 if (isBindExternal) {
1714 if (!sInfo.exported) {
1715 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1716 " is not exported");
1717 }
1718 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
1719 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1720 " is not an isolatedProcess");
1721 }
1722 // Run the service under the calling package's application.
1723 ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
1724 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
1725 if (aInfo == null) {
1726 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
1727 "could not resolve client package " + callingPackage);
1728 }
1729 sInfo = new ServiceInfo(sInfo);
1730 sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
1731 sInfo.applicationInfo.packageName = aInfo.packageName;
1732 sInfo.applicationInfo.uid = aInfo.uid;
1733 name = new ComponentName(aInfo.packageName, name.getClassName());
1734 service.setComponent(name);
1735 } else {
1736 throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
1737 name);
1738 }
1739 } else if (isBindExternal) {
1740 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1741 " is not an externalService");
1742 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001743 if (userId > 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001744 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
Amith Yamasani4b9d79c2014-05-21 19:14:21 -07001745 sInfo.name, sInfo.flags)
1746 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001747 userId = 0;
Dianne Hackbornad51be92016-08-16 16:27:36 -07001748 smap = getServiceMapLocked(0);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001749 }
1750 sInfo = new ServiceInfo(sInfo);
1751 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
1752 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001753 r = smap.mServicesByName.get(name);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001754 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE,
1755 "Retrieved via pm by intent: " + r);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001756 if (r == null && createIfNeeded) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001757 final Intent.FilterComparison filter
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001758 = new Intent.FilterComparison(service.cloneFilter());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001759 final ServiceRestarter res = new ServiceRestarter();
1760 final BatteryStatsImpl.Uid.Pkg.Serv ss;
1761 final BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001762 synchronized (stats) {
1763 ss = stats.getServiceStatsLocked(
1764 sInfo.applicationInfo.uid, sInfo.packageName,
1765 sInfo.name);
1766 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001767 r = new ServiceRecord(mAm, ss, name, filter, sInfo, callingFromFg, res);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001768 res.setService(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001769 smap.mServicesByName.put(name, r);
1770 smap.mServicesByIntent.put(filter, r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001771
1772 // Make sure this component isn't in the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001773 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001774 final ServiceRecord pr = mPendingServices.get(i);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001775 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
1776 && pr.name.equals(name)) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001777 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001778 mPendingServices.remove(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001779 }
1780 }
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001781 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001782 }
1783 } catch (RemoteException ex) {
1784 // pm is in same process, this will never happen.
1785 }
1786 }
1787 if (r != null) {
1788 if (mAm.checkComponentPermission(r.permission,
Bryce Lee290e5782017-02-01 16:41:20 -08001789 callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001790 if (!r.exported) {
1791 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1792 + " from pid=" + callingPid
1793 + ", uid=" + callingUid
1794 + " that is not exported from uid " + r.appInfo.uid);
1795 return new ServiceLookupResult(null, "not exported from uid "
1796 + r.appInfo.uid);
1797 }
1798 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1799 + " from pid=" + callingPid
1800 + ", uid=" + callingUid
1801 + " requires " + r.permission);
1802 return new ServiceLookupResult(null, r.permission);
Svet Ganov99b60432015-06-27 13:15:22 -07001803 } else if (r.permission != null && callingPackage != null) {
1804 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
1805 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation(
1806 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
1807 Slog.w(TAG, "Appop Denial: Accessing service " + r.name
1808 + " from pid=" + callingPid
1809 + ", uid=" + callingUid
1810 + " requires appop " + AppOpsManager.opToName(opCode));
1811 return null;
1812 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001813 }
Svet Ganov99b60432015-06-27 13:15:22 -07001814
Ben Gruverf5323fe2013-07-31 15:09:51 -07001815 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
1816 resolvedType, r.appInfo)) {
Ben Gruverb6223792013-07-29 16:35:40 -07001817 return null;
1818 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001819 return new ServiceLookupResult(r, null);
1820 }
1821 return null;
1822 }
1823
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001824 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001825 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001826 + why + " of " + r + " in app " + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001827 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001828 + why + " of " + r.shortName);
1829 long now = SystemClock.uptimeMillis();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001830 if (r.executeNesting == 0) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001831 r.executeFg = fg;
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001832 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001833 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001834 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001835 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001836 if (r.app != null) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001837 r.app.executingServices.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001838 r.app.execServicesFg |= fg;
Dianne Hackborn2be00932013-09-22 16:46:00 -07001839 if (r.app.executingServices.size() == 1) {
1840 scheduleServiceTimeoutLocked(r.app);
1841 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001842 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001843 } else if (r.app != null && fg && !r.app.execServicesFg) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001844 r.app.execServicesFg = true;
Dianne Hackborn2be00932013-09-22 16:46:00 -07001845 scheduleServiceTimeoutLocked(r.app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001846 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001847 r.executeFg |= fg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001848 r.executeNesting++;
1849 r.executingStart = now;
1850 }
1851
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001852 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
1853 boolean execInFg, boolean rebind) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001854 if (r.app == null || r.app.thread == null) {
1855 // If service is not currently running, can't yet bind.
1856 return false;
1857 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08001858 if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
1859 + " rebind=" + rebind);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001860 if ((!i.requested || rebind) && i.apps.size() > 0) {
1861 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001862 bumpServiceExecutingLocked(r, execInFg, "bind");
Dianne Hackborna413dc02013-07-12 12:02:55 -07001863 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
1864 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
1865 r.app.repProcState);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001866 if (!rebind) {
1867 i.requested = true;
1868 }
1869 i.hasBound = true;
1870 i.doRebind = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001871 } catch (TransactionTooLargeException e) {
1872 // Keep the executeNesting count accurate.
1873 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
1874 final boolean inDestroying = mDestroyingServices.contains(r);
1875 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
1876 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001877 } catch (RemoteException e) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001878 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001879 // Keep the executeNesting count accurate.
1880 final boolean inDestroying = mDestroyingServices.contains(r);
1881 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001882 return false;
1883 }
1884 }
1885 return true;
1886 }
1887
Dianne Hackbornad51be92016-08-16 16:27:36 -07001888 private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001889 boolean canceled = false;
1890
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07001891 if (mAm.isShuttingDownLocked()) {
1892 Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortName
1893 + " - system is shutting down");
1894 return false;
1895 }
1896
Dianne Hackbornad51be92016-08-16 16:27:36 -07001897 ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001898 if (smap.mServicesByName.get(r.name) != r) {
1899 ServiceRecord cur = smap.mServicesByName.get(r.name);
1900 Slog.wtf(TAG, "Attempting to schedule restart of " + r
1901 + " when found in map: " + cur);
1902 return false;
1903 }
1904
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001905 final long now = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001906
1907 if ((r.serviceInfo.applicationInfo.flags
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001908 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001909 long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION;
1910 long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001911
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001912 // Any delivered but not yet finished starts should be put back
1913 // on the pending list.
1914 final int N = r.deliveredStarts.size();
1915 if (N > 0) {
1916 for (int i=N-1; i>=0; i--) {
1917 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
1918 si.removeUriPermissionsLocked();
1919 if (si.intent == null) {
1920 // We'll generate this again if needed.
1921 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
1922 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
1923 r.pendingStarts.add(0, si);
1924 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
1925 dur *= 2;
1926 if (minDuration < dur) minDuration = dur;
1927 if (resetTime < dur) resetTime = dur;
1928 } else {
1929 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
1930 + r.name);
1931 canceled = true;
1932 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001933 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001934 r.deliveredStarts.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001935 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001936
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001937 r.totalRestartCount++;
1938 if (r.restartDelay == 0) {
1939 r.restartCount++;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001940 r.restartDelay = minDuration;
Amith Yamasanib0c8a882017-08-28 09:36:42 -07001941 } else if (r.crashCount > 1) {
1942 r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
1943 * (r.crashCount - 1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001944 } else {
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001945 // If it has been a "reasonably long time" since the service
1946 // was started, then reset our restart duration back to
1947 // the beginning, so we don't infinitely increase the duration
1948 // on a service that just occasionally gets killed (which is
1949 // a normal case, due to process being killed to reclaim memory).
1950 if (now > (r.restartTime+resetTime)) {
1951 r.restartCount = 1;
1952 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001953 } else {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001954 r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
Dianne Hackborn7b492722013-11-01 09:58:45 -07001955 if (r.restartDelay < minDuration) {
1956 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001957 }
1958 }
1959 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001960
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001961 r.nextRestartTime = now + r.restartDelay;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001962
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001963 // Make sure that we don't end up restarting a bunch of services
1964 // all at the same time.
1965 boolean repeat;
1966 do {
1967 repeat = false;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001968 final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001969 for (int i=mRestartingServices.size()-1; i>=0; i--) {
1970 ServiceRecord r2 = mRestartingServices.get(i);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001971 if (r2 != r && r.nextRestartTime >= (r2.nextRestartTime-restartTimeBetween)
1972 && r.nextRestartTime < (r2.nextRestartTime+restartTimeBetween)) {
1973 r.nextRestartTime = r2.nextRestartTime + restartTimeBetween;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001974 r.restartDelay = r.nextRestartTime - now;
1975 repeat = true;
1976 break;
1977 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001978 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001979 } while (repeat);
1980
1981 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07001982 // Persistent processes are immediately restarted, so there is no
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001983 // reason to hold of on restarting their services.
1984 r.totalRestartCount++;
1985 r.restartCount = 0;
1986 r.restartDelay = 0;
1987 r.nextRestartTime = now;
1988 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001989
1990 if (!mRestartingServices.contains(r)) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001991 r.createdFromFg = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001992 mRestartingServices.add(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08001993 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001994 }
1995
Christopher Tate08992ac2017-03-21 11:37:06 -07001996 cancelForegroundNotificationLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001997
1998 mAm.mHandler.removeCallbacks(r.restarter);
1999 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
2000 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
2001 Slog.w(TAG, "Scheduling restart of crashed service "
2002 + r.shortName + " in " + r.restartDelay + "ms");
2003 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002004 r.userId, r.shortName, r.restartDelay);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002005
2006 return canceled;
2007 }
2008
2009 final void performServiceRestartLocked(ServiceRecord r) {
2010 if (!mRestartingServices.contains(r)) {
2011 return;
2012 }
Dianne Hackbornad51be92016-08-16 16:27:36 -07002013 if (!isServiceNeededLocked(r, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002014 // Paranoia: is this service actually needed? In theory a service that is not
2015 // needed should never remain on the restart list. In practice... well, there
2016 // have been bugs where this happens, and bad things happen because the process
2017 // ends up just being cached, so quickly killed, then restarted again and again.
2018 // Let's not let that happen.
2019 Slog.wtf(TAG, "Restarting service that is not needed: " + r);
2020 return;
2021 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002022 try {
Svet Ganov9c165d72015-12-01 19:52:26 -08002023 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002024 } catch (TransactionTooLargeException e) {
2025 // Ignore, it's been logged and nothing upstack cares.
2026 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002027 }
2028
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002029 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
2030 boolean force) {
2031 if (!force && r.restartDelay == 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002032 return false;
2033 }
Dianne Hackborn7b492722013-11-01 09:58:45 -07002034 // Remove from the restarting list; if the service is currently on the
2035 // restarting list, or the call is coming from another app, then this
2036 // service has become of much more interest so we reset the restart interval.
2037 boolean removed = mRestartingServices.remove(r);
2038 if (removed || callingUid != r.appInfo.uid) {
2039 r.resetRestartCounter();
2040 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002041 if (removed) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002042 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002043 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002044 mAm.mHandler.removeCallbacks(r.restarter);
2045 return true;
2046 }
2047
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002048 private void clearRestartingIfNeededLocked(ServiceRecord r) {
2049 if (r.restartTracker != null) {
2050 // If this is the last restarting record with this tracker, then clear
2051 // the tracker's restarting state.
2052 boolean stillTracking = false;
2053 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2054 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
2055 stillTracking = true;
2056 break;
2057 }
2058 }
2059 if (!stillTracking) {
2060 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
2061 SystemClock.uptimeMillis());
2062 r.restartTracker = null;
2063 }
2064 }
2065 }
2066
Svet Ganov9c165d72015-12-01 19:52:26 -08002067 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
2068 boolean whileRestarting, boolean permissionsReviewRequired)
2069 throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002070 //Slog.i(TAG, "Bring up service:");
2071 //r.dump(" ");
2072
2073 if (r.app != null && r.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002074 sendServiceArgsLocked(r, execInFg, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002075 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002076 }
2077
Sudheer Shanka03d0f812017-04-20 16:57:50 -07002078 if (!whileRestarting && mRestartingServices.contains(r)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002079 // If waiting for a restart, then do nothing.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002080 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002081 }
2082
Christopher Tate08992ac2017-03-21 11:37:06 -07002083 if (DEBUG_SERVICE) {
2084 Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
2085 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002086
2087 // We are now bringing the service up, so no longer in the
2088 // restarting state.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002089 if (mRestartingServices.remove(r)) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002090 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002091 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002092
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002093 // Make sure this service is no longer considered delayed, we are starting it now.
2094 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002095 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002096 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002097 r.delayed = false;
2098 }
2099
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002100 // Make sure that the user who owns this service is started. If not,
2101 // we don't want to allow it to run.
Fyodor Kupolov610acda2015-10-19 18:44:07 -07002102 if (!mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002103 String msg = "Unable to launch app "
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002104 + r.appInfo.packageName + "/"
2105 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002106 + r.intent.getIntent() + ": user " + r.userId + " is stopped";
2107 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002108 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002109 return msg;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002110 }
2111
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002112 // Service is now being launched, its package can't be stopped.
2113 try {
2114 AppGlobals.getPackageManager().setPackageStoppedState(
2115 r.packageName, false, r.userId);
2116 } catch (RemoteException e) {
2117 } catch (IllegalArgumentException e) {
2118 Slog.w(TAG, "Failed trying to unstop package "
2119 + r.packageName + ": " + e);
2120 }
2121
2122 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
2123 final String procName = r.processName;
Robert Sesekc5f86642016-11-04 10:20:38 -04002124 String hostingType = "service";
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002125 ProcessRecord app;
2126
2127 if (!isolated) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07002128 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
2129 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
2130 + " app=" + app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002131 if (app != null && app.thread != null) {
2132 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07002133 app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002134 realStartServiceLocked(r, app, execInFg);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002135 return null;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002136 } catch (TransactionTooLargeException e) {
2137 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002138 } catch (RemoteException e) {
2139 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
2140 }
2141
2142 // If a dead object exception was thrown -- fall through to
2143 // restart the application.
2144 }
2145 } else {
2146 // If this service runs in an isolated process, then each time
2147 // we call startProcessLocked() we will get a new isolated
2148 // process, starting another process if we are currently waiting
2149 // for a previous process to come up. To deal with this, we store
2150 // in the service any current isolated process it is running in or
2151 // waiting to have come up.
2152 app = r.isolatedProc;
Robert Sesekc5f86642016-11-04 10:20:38 -04002153 if (WebViewZygote.isMultiprocessEnabled()
2154 && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
2155 hostingType = "webview_service";
2156 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002157 }
2158
2159 // Not running -- get it started, and enqueue this service record
2160 // to be executed when the app comes up.
Svet Ganov9c165d72015-12-01 19:52:26 -08002161 if (app == null && !permissionsReviewRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002162 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
Robert Sesekc5f86642016-11-04 10:20:38 -04002163 hostingType, r.name, false, isolated, false)) == null) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002164 String msg = "Unable to launch app "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002165 + r.appInfo.packageName + "/"
2166 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002167 + r.intent.getIntent() + ": process is bad";
2168 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002169 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002170 return msg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002171 }
2172 if (isolated) {
2173 r.isolatedProc = app;
2174 }
2175 }
2176
Christopher Tate1536cc22017-09-18 16:43:30 -07002177 if (r.fgRequired) {
2178 if (DEBUG_FOREGROUND_SERVICE) {
2179 Slog.v(TAG, "Whitelisting " + UserHandle.formatUid(r.appInfo.uid)
2180 + " for fg-service launch");
2181 }
2182 mAm.tempWhitelistUidLocked(r.appInfo.uid,
2183 SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch");
2184 }
2185
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002186 if (!mPendingServices.contains(r)) {
2187 mPendingServices.add(r);
2188 }
2189
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002190 if (r.delayedStop) {
2191 // Oh and hey we've already been asked to stop!
2192 r.delayedStop = false;
2193 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002194 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2195 "Applying delayed stop (in bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002196 stopServiceLocked(r);
2197 }
2198 }
2199
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002200 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002201 }
2202
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002203 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
2204 throws TransactionTooLargeException {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002205 for (int i=r.bindings.size()-1; i>=0; i--) {
2206 IntentBindRecord ibr = r.bindings.valueAt(i);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002207 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002208 break;
2209 }
2210 }
2211 }
2212
2213 private final void realStartServiceLocked(ServiceRecord r,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002214 ProcessRecord app, boolean execInFg) throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002215 if (app.thread == null) {
2216 throw new RemoteException();
2217 }
2218 if (DEBUG_MU)
2219 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
2220 + ", ProcessRecord.uid = " + app.uid);
2221 r.app = app;
2222 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
2223
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002224 final boolean newService = app.services.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002225 bumpServiceExecutingLocked(r, execInFg, "create");
Dianne Hackborndb926082013-10-31 16:32:44 -07002226 mAm.updateLruProcessLocked(app, false, null);
Makoto Onuki0f421292017-04-28 15:03:33 -07002227 updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
2228 mAm.updateOomAdjLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002229
2230 boolean created = false;
2231 try {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002232 if (LOG_SERVICE_START_STOP) {
Dianne Hackbornab2df062015-01-07 13:43:13 -08002233 String nameTerm;
2234 int lastPeriod = r.shortName.lastIndexOf('.');
2235 nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002236 EventLogTags.writeAmCreateService(
2237 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
2238 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002239 synchronized (r.stats.getBatteryStats()) {
2240 r.stats.startLaunchedLocked();
2241 }
Brian Carlstromca82e612016-04-19 23:16:08 -07002242 mAm.notifyPackageUse(r.serviceInfo.packageName,
2243 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
Dianne Hackborna413dc02013-07-12 12:02:55 -07002244 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002245 app.thread.scheduleCreateService(r, r.serviceInfo,
Dianne Hackborna413dc02013-07-12 12:02:55 -07002246 mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
2247 app.repProcState);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002248 r.postNotification();
2249 created = true;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -07002250 } catch (DeadObjectException e) {
2251 Slog.w(TAG, "Application dead when creating service " + r);
2252 mAm.appDiedLocked(app);
Wale Ogunwalebfac4682015-04-08 14:33:21 -07002253 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002254 } finally {
2255 if (!created) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002256 // Keep the executeNesting count accurate.
2257 final boolean inDestroying = mDestroyingServices.contains(r);
2258 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2259
2260 // Cleanup.
2261 if (newService) {
2262 app.services.remove(r);
2263 r.app = null;
2264 }
2265
2266 // Retry.
2267 if (!inDestroying) {
2268 scheduleServiceRestartLocked(r, false);
2269 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002270 }
2271 }
2272
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002273 if (r.whitelistManager) {
2274 app.whitelistManager = true;
2275 }
2276
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002277 requestServiceBindingsLocked(r, execInFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002278
Dianne Hackborn465fa392014-09-14 14:21:18 -07002279 updateServiceClientActivitiesLocked(app, null, true);
2280
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002281 // If the service is in the started state, and there are no
2282 // pending arguments, then fake up one so its onStartCommand() will
2283 // be called.
2284 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
2285 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002286 null, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002287 }
2288
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002289 sendServiceArgsLocked(r, execInFg, true);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002290
2291 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002292 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002293 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002294 r.delayed = false;
2295 }
2296
2297 if (r.delayedStop) {
2298 // Oh and hey we've already been asked to stop!
2299 r.delayedStop = false;
2300 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002301 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2302 "Applying delayed stop (from start): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002303 stopServiceLocked(r);
2304 }
2305 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002306 }
2307
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002308 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002309 boolean oomAdjusted) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002310 final int N = r.pendingStarts.size();
2311 if (N == 0) {
2312 return;
2313 }
2314
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002315 ArrayList<ServiceStartArgs> args = new ArrayList<>();
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002316
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002317 while (r.pendingStarts.size() > 0) {
2318 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
2319 if (DEBUG_SERVICE) {
2320 Slog.v(TAG_SERVICE, "Sending arguments to: "
2321 + r + " " + r.intent + " args=" + si.intent);
2322 }
2323 if (si.intent == null && N > 1) {
2324 // If somehow we got a dummy null intent in the middle,
2325 // then skip it. DO NOT skip a null intent when it is
2326 // the only one in the list -- this is to support the
2327 // onStartCommand(null) case.
2328 continue;
2329 }
2330 si.deliveredTime = SystemClock.uptimeMillis();
2331 r.deliveredStarts.add(si);
2332 si.deliveryCount++;
2333 if (si.neededGrants != null) {
2334 mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
2335 si.getUriPermissionsLocked());
2336 }
2337 mAm.grantEphemeralAccessLocked(r.userId, si.intent,
2338 r.appInfo.uid, UserHandle.getAppId(si.callingId));
2339 bumpServiceExecutingLocked(r, execInFg, "start");
2340 if (!oomAdjusted) {
2341 oomAdjusted = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002342 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002343 }
2344 if (r.fgRequired && !r.fgWaiting) {
2345 if (!r.isForeground) {
2346 if (DEBUG_BACKGROUND_CHECK) {
2347 Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r);
2348 }
2349 scheduleServiceForegroundTransitionTimeoutLocked(r);
2350 } else {
2351 if (DEBUG_BACKGROUND_CHECK) {
2352 Slog.i(TAG, "Service already foreground; no new timeout: " + r);
2353 }
2354 r.fgRequired = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002355 }
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002356 }
2357 int flags = 0;
2358 if (si.deliveryCount > 1) {
2359 flags |= Service.START_FLAG_RETRY;
2360 }
2361 if (si.doneExecutingCount > 0) {
2362 flags |= Service.START_FLAG_REDELIVERY;
2363 }
2364 args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
2365 }
2366
2367 ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
2368 slice.setInlineCountLimit(4);
2369 Exception caughtException = null;
2370 try {
2371 r.app.thread.scheduleServiceArgs(r, slice);
2372 } catch (TransactionTooLargeException e) {
2373 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
2374 + " args, first: " + args.get(0).args);
2375 Slog.w(TAG, "Failed delivering service starts", e);
2376 caughtException = e;
2377 } catch (RemoteException e) {
2378 // Remote process gone... we'll let the normal cleanup take care of this.
2379 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
2380 Slog.w(TAG, "Failed delivering service starts", e);
2381 caughtException = e;
2382 } catch (Exception e) {
2383 Slog.w(TAG, "Unexpected exception", e);
2384 caughtException = e;
2385 }
2386
2387 if (caughtException != null) {
2388 // Keep nesting count correct
2389 final boolean inDestroying = mDestroyingServices.contains(r);
2390 for (int i = 0; i < args.size(); i++) {
2391 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2392 }
2393 if (caughtException instanceof TransactionTooLargeException) {
2394 throw (TransactionTooLargeException)caughtException;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002395 }
2396 }
2397 }
2398
Dianne Hackbornad51be92016-08-16 16:27:36 -07002399 private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn,
2400 boolean hasConn) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002401 // Are we still explicitly being asked to run?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002402 if (r.startRequested) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002403 return true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002404 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002405
Dianne Hackborncb015632017-06-14 17:30:15 -07002406 // Is someone still bound to us keeping us running?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002407 if (!knowConn) {
2408 hasConn = r.hasAutoCreateConnections();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002409 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002410 if (hasConn) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002411 return true;
2412 }
2413
2414 return false;
2415 }
2416
2417 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
2418 boolean hasConn) {
2419 //Slog.i(TAG, "Bring down service:");
2420 //r.dump(" ");
2421
Dianne Hackbornad51be92016-08-16 16:27:36 -07002422 if (isServiceNeededLocked(r, knowConn, hasConn)) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002423 return;
2424 }
2425
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002426 // Are we in the process of launching?
2427 if (mPendingServices.contains(r)) {
2428 return;
2429 }
2430
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002431 bringDownServiceLocked(r);
2432 }
2433
2434 private final void bringDownServiceLocked(ServiceRecord r) {
2435 //Slog.i(TAG, "Bring down service:");
2436 //r.dump(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002437
Dianne Hackborn390517b2013-05-30 15:03:32 -07002438 // Report to all of the connections that the service is no longer
2439 // available.
2440 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2441 ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
2442 for (int i=0; i<c.size(); i++) {
2443 ConnectionRecord cr = c.get(i);
2444 // There is still a connection to the service that is
2445 // being brought down. Mark it as dead.
2446 cr.serviceDead = true;
2447 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07002448 cr.conn.connected(r.name, null, true);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002449 } catch (Exception e) {
2450 Slog.w(TAG, "Failure disconnecting service " + r.name +
2451 " to connection " + c.get(i).conn.asBinder() +
2452 " (in " + c.get(i).binding.client.processName + ")", e);
2453 }
2454 }
2455 }
2456
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002457 // Tell the service that it has been unbound.
Dianne Hackborn390517b2013-05-30 15:03:32 -07002458 if (r.app != null && r.app.thread != null) {
2459 for (int i=r.bindings.size()-1; i>=0; i--) {
2460 IntentBindRecord ibr = r.bindings.valueAt(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002461 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002462 + ": hasBound=" + ibr.hasBound);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002463 if (ibr.hasBound) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002464 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002465 bumpServiceExecutingLocked(r, false, "bring down unbind");
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002466 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002467 ibr.hasBound = false;
Dianne Hackborn85e35642017-01-12 15:10:57 -08002468 ibr.requested = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002469 r.app.thread.scheduleUnbindService(r,
2470 ibr.intent.getIntent());
2471 } catch (Exception e) {
2472 Slog.w(TAG, "Exception when unbinding service "
2473 + r.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002474 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002475 }
2476 }
2477 }
2478 }
2479
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002480 // Check to see if the service had been started as foreground, but being
2481 // brought down before actually showing a notification. That is not allowed.
2482 if (r.fgRequired) {
2483 Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
2484 + r);
2485 r.fgRequired = false;
2486 r.fgWaiting = false;
2487 mAm.mHandler.removeMessages(
2488 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
2489 if (r.app != null) {
2490 Message msg = mAm.mHandler.obtainMessage(
2491 ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
2492 msg.obj = r.app;
2493 mAm.mHandler.sendMessage(msg);
2494 }
2495 }
2496
2497 if (DEBUG_SERVICE) {
2498 RuntimeException here = new RuntimeException();
2499 here.fillInStackTrace();
2500 Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here);
2501 }
Craig Mautner66c4a822015-01-16 12:48:16 -08002502 r.destroyTime = SystemClock.uptimeMillis();
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002503 if (LOG_SERVICE_START_STOP) {
2504 EventLogTags.writeAmDestroyService(
2505 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
2506 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002507
Dianne Hackbornad51be92016-08-16 16:27:36 -07002508 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002509 ServiceRecord found = smap.mServicesByName.remove(r.name);
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002510
2511 // Note when this method is called by bringUpServiceLocked(), the service is not found
2512 // in mServicesByName and found will be null.
2513 if (found != null && found != r) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002514 // This is not actually the service we think is running... this should not happen,
2515 // but if it does, fail hard.
2516 smap.mServicesByName.put(r.name, found);
2517 throw new IllegalStateException("Bringing down " + r + " but actually running "
2518 + found);
2519 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002520 smap.mServicesByIntent.remove(r.intent);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002521 r.totalRestartCount = 0;
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002522 unscheduleServiceRestartLocked(r, 0, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002523
2524 // Also make sure it is not on the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002525 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002526 if (mPendingServices.get(i) == r) {
2527 mPendingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002528 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002529 }
2530 }
2531
Christopher Tate08992ac2017-03-21 11:37:06 -07002532 cancelForegroundNotificationLocked(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002533 if (r.isForeground) {
2534 decActiveForegroundAppLocked(smap, r);
Chenjie Yuccfe6452018-01-30 11:33:21 -08002535 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED, r.userId, r.shortName,
2536 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002537 }
Chenjie Yuccfe6452018-01-30 11:33:21 -08002538
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002539 r.isForeground = false;
2540 r.foregroundId = 0;
2541 r.foregroundNoti = null;
2542
2543 // Clear start entries.
2544 r.clearDeliveredStartsLocked();
2545 r.pendingStarts.clear();
2546
2547 if (r.app != null) {
2548 synchronized (r.stats.getBatteryStats()) {
2549 r.stats.stopLaunchedLocked();
2550 }
2551 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002552 if (r.whitelistManager) {
2553 updateWhitelistManagerLocked(r.app);
2554 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002555 if (r.app.thread != null) {
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002556 updateServiceForegroundLocked(r.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002557 try {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002558 bumpServiceExecutingLocked(r, false, "destroy");
2559 mDestroyingServices.add(r);
Dianne Hackborn455625e2015-01-21 09:55:13 -08002560 r.destroying = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002561 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002562 r.app.thread.scheduleStopService(r);
2563 } catch (Exception e) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002564 Slog.w(TAG, "Exception when destroying service "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002565 + r.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002566 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002567 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002568 } else {
2569 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002570 TAG_SERVICE, "Removed service that has no process: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002571 }
2572 } else {
2573 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002574 TAG_SERVICE, "Removed service that is not running: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002575 }
2576
2577 if (r.bindings.size() > 0) {
2578 r.bindings.clear();
2579 }
2580
2581 if (r.restarter instanceof ServiceRestarter) {
2582 ((ServiceRestarter)r.restarter).setService(null);
2583 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002584
Dianne Hackbornd2932242013-08-05 18:18:42 -07002585 int memFactor = mAm.mProcessStats.getMemFactorLocked();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002586 long now = SystemClock.uptimeMillis();
2587 if (r.tracker != null) {
2588 r.tracker.setStarted(false, memFactor, now);
2589 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002590 if (r.executeNesting == 0) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07002591 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002592 r.tracker = null;
2593 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002594 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002595
Dianne Hackbornad51be92016-08-16 16:27:36 -07002596 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002597 }
2598
2599 void removeConnectionLocked(
2600 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
2601 IBinder binder = c.conn.asBinder();
2602 AppBindRecord b = c.binding;
2603 ServiceRecord s = b.service;
2604 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
2605 if (clist != null) {
2606 clist.remove(c);
2607 if (clist.size() == 0) {
2608 s.connections.remove(binder);
2609 }
2610 }
2611 b.connections.remove(c);
2612 if (c.activity != null && c.activity != skipAct) {
2613 if (c.activity.connections != null) {
2614 c.activity.connections.remove(c);
2615 }
2616 }
2617 if (b.client != skipApp) {
2618 b.client.connections.remove(c);
2619 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
2620 b.client.updateHasAboveClientLocked();
2621 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002622 // If this connection requested whitelist management, see if we should
2623 // now clear that state.
2624 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
2625 s.updateWhitelistManager();
2626 if (!s.whitelistManager && s.app != null) {
2627 updateWhitelistManagerLocked(s.app);
2628 }
2629 }
Dianne Hackborndb926082013-10-31 16:32:44 -07002630 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07002631 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07002632 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002633 }
2634 clist = mServiceConnections.get(binder);
2635 if (clist != null) {
2636 clist.remove(c);
2637 if (clist.size() == 0) {
2638 mServiceConnections.remove(binder);
2639 }
2640 }
2641
Dianne Hackbornab2df062015-01-07 13:43:13 -08002642 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid, s.name);
2643
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002644 if (b.connections.size() == 0) {
2645 b.intent.apps.remove(b.client);
2646 }
2647
2648 if (!c.serviceDead) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002649 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002650 + ": shouldUnbind=" + b.intent.hasBound);
2651 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
2652 && b.intent.hasBound) {
2653 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002654 bumpServiceExecutingLocked(s, false, "unbind");
Dianne Hackborndb926082013-10-31 16:32:44 -07002655 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
Dianne Hackbornf097d422017-12-15 16:32:19 -08002656 && s.app.setProcState <= ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
Dianne Hackborndb926082013-10-31 16:32:44 -07002657 // If this service's process is not already in the cached list,
2658 // then update it in the LRU list here because this may be causing
2659 // it to go down there and we want it to start out near the top.
2660 mAm.updateLruProcessLocked(s.app, false, null);
2661 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002662 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002663 b.intent.hasBound = false;
2664 // Assume the client doesn't want to know about a rebind;
2665 // we will deal with that later if it asks for one.
2666 b.intent.doRebind = false;
2667 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
2668 } catch (Exception e) {
2669 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002670 serviceProcessGoneLocked(s);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002671 }
2672 }
2673
Svet Ganov9c165d72015-12-01 19:52:26 -08002674 // If unbound while waiting to start, remove the pending service
2675 mPendingServices.remove(s);
2676
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002677 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002678 boolean hasAutoCreate = s.hasAutoCreateConnections();
2679 if (!hasAutoCreate) {
2680 if (s.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002681 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002682 SystemClock.uptimeMillis());
2683 }
2684 }
2685 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002686 }
2687 }
2688 }
2689
2690 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002691 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002692 if (r != null) {
Dianne Hackborn455625e2015-01-21 09:55:13 -08002693 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002694 // This is a call from a service start... take care of
2695 // book-keeping.
2696 r.callStart = true;
2697 switch (res) {
2698 case Service.START_STICKY_COMPATIBILITY:
2699 case Service.START_STICKY: {
2700 // We are done with the associated start arguments.
2701 r.findDeliveredStart(startId, true);
2702 // Don't stop if killed.
2703 r.stopIfKilled = false;
2704 break;
2705 }
2706 case Service.START_NOT_STICKY: {
2707 // We are done with the associated start arguments.
2708 r.findDeliveredStart(startId, true);
2709 if (r.getLastStartId() == startId) {
2710 // There is no more work, and this service
2711 // doesn't want to hang around if killed.
2712 r.stopIfKilled = true;
2713 }
2714 break;
2715 }
2716 case Service.START_REDELIVER_INTENT: {
2717 // We'll keep this item until they explicitly
2718 // call stop for it, but keep track of the fact
2719 // that it was delivered.
2720 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
2721 if (si != null) {
2722 si.deliveryCount = 0;
2723 si.doneExecutingCount++;
2724 // Don't stop if killed.
2725 r.stopIfKilled = true;
2726 }
2727 break;
2728 }
2729 case Service.START_TASK_REMOVED_COMPLETE: {
2730 // Special processing for onTaskRemoved(). Don't
2731 // impact normal onStartCommand() processing.
2732 r.findDeliveredStart(startId, true);
2733 break;
2734 }
2735 default:
2736 throw new IllegalArgumentException(
2737 "Unknown service start result: " + res);
2738 }
2739 if (res == Service.START_STICKY_COMPATIBILITY) {
2740 r.callStart = false;
2741 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08002742 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
2743 // This is the final call from destroying the service... we should
2744 // actually be getting rid of the service at this point. Do some
2745 // validation of its state, and ensure it will be fully removed.
2746 if (!inDestroying) {
2747 // Not sure what else to do with this... if it is not actually in the
2748 // destroying list, we don't need to make sure to remove it from it.
Amith Yamasanid0418222016-05-10 15:49:51 -07002749 // If the app is null, then it was probably removed because the process died,
2750 // otherwise wtf
2751 if (r.app != null) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07002752 Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
Amith Yamasanid0418222016-05-10 15:49:51 -07002753 + r + ", app=" + r.app);
2754 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08002755 } else if (r.executeNesting != 1) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07002756 Slog.w(TAG, "Service done with onDestroy, but executeNesting="
Dianne Hackborn455625e2015-01-21 09:55:13 -08002757 + r.executeNesting + ": " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002758 // Fake it to keep from ANR due to orphaned entry.
Dianne Hackborn455625e2015-01-21 09:55:13 -08002759 r.executeNesting = 1;
2760 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002761 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002762 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn164371f2013-10-01 19:10:13 -07002763 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002764 Binder.restoreCallingIdentity(origId);
2765 } else {
2766 Slog.w(TAG, "Done executing unknown service from pid "
2767 + Binder.getCallingPid());
2768 }
2769 }
2770
Dianne Hackborn878deb32013-10-14 16:55:09 -07002771 private void serviceProcessGoneLocked(ServiceRecord r) {
2772 if (r.tracker != null) {
2773 int memFactor = mAm.mProcessStats.getMemFactorLocked();
2774 long now = SystemClock.uptimeMillis();
2775 r.tracker.setExecuting(false, memFactor, now);
2776 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbc72dce2013-11-11 10:43:38 -08002777 r.tracker.setStarted(false, memFactor, now);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002778 }
2779 serviceDoneExecutingLocked(r, true, true);
2780 }
2781
Dianne Hackborn164371f2013-10-01 19:10:13 -07002782 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
2783 boolean finishing) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002784 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002785 + ": nesting=" + r.executeNesting
Dianne Hackborn164371f2013-10-01 19:10:13 -07002786 + ", inDestroying=" + inDestroying + ", app=" + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002787 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
2788 "<<< DONE EXECUTING " + r.shortName);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002789 r.executeNesting--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002790 if (r.executeNesting <= 0) {
2791 if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002792 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002793 "Nesting at 0 of " + r.shortName);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002794 r.app.execServicesFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002795 r.app.executingServices.remove(r);
2796 if (r.app.executingServices.size() == 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002797 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002798 "No more executingServices of " + r.shortName);
2799 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002800 } else if (r.executeFg) {
2801 // Need to re-evaluate whether the app still needs to be in the foreground.
2802 for (int i=r.app.executingServices.size()-1; i>=0; i--) {
2803 if (r.app.executingServices.valueAt(i).executeFg) {
2804 r.app.execServicesFg = true;
2805 break;
2806 }
2807 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002808 }
Dianne Hackborn164371f2013-10-01 19:10:13 -07002809 if (inDestroying) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002810 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn164371f2013-10-01 19:10:13 -07002811 "doneExecuting remove destroying " + r);
2812 mDestroyingServices.remove(r);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002813 r.bindings.clear();
2814 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002815 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002816 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002817 r.executeFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002818 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002819 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002820 SystemClock.uptimeMillis());
Dianne Hackborn164371f2013-10-01 19:10:13 -07002821 if (finishing) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07002822 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002823 r.tracker = null;
2824 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002825 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002826 if (finishing) {
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08002827 if (r.app != null && !r.app.persistent) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002828 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002829 if (r.whitelistManager) {
2830 updateWhitelistManagerLocked(r.app);
2831 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002832 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002833 r.app = null;
2834 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002835 }
2836 }
2837
Dianne Hackbornff072722014-09-24 10:56:28 -07002838 boolean attachApplicationLocked(ProcessRecord proc, String processName)
2839 throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002840 boolean didSomething = false;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002841 // Collect any services that are waiting for this process to come up.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002842 if (mPendingServices.size() > 0) {
2843 ServiceRecord sr = null;
2844 try {
2845 for (int i=0; i<mPendingServices.size(); i++) {
2846 sr = mPendingServices.get(i);
2847 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
2848 || !processName.equals(sr.processName))) {
2849 continue;
2850 }
2851
2852 mPendingServices.remove(i);
2853 i--;
Dianne Hackbornf7097a52014-05-13 09:56:14 -07002854 proc.addPackage(sr.appInfo.packageName, sr.appInfo.versionCode,
2855 mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002856 realStartServiceLocked(sr, proc, sr.createdFromFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002857 didSomething = true;
Dianne Hackbornad51be92016-08-16 16:27:36 -07002858 if (!isServiceNeededLocked(sr, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002859 // We were waiting for this service to start, but it is actually no
2860 // longer needed. This could happen because bringDownServiceIfNeeded
2861 // won't bring down a service that is pending... so now the pending
2862 // is done, so let's drop it.
2863 bringDownServiceLocked(sr);
2864 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002865 }
Dianne Hackbornff072722014-09-24 10:56:28 -07002866 } catch (RemoteException e) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002867 Slog.w(TAG, "Exception in new application when starting service "
2868 + sr.shortName, e);
2869 throw e;
2870 }
2871 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002872 // Also, if there are any services that are waiting to restart and
2873 // would run in this process, now is a good time to start them. It would
2874 // be weird to bring up the process but arbitrarily not let the services
2875 // run at this point just because their restart time hasn't come up.
2876 if (mRestartingServices.size() > 0) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002877 ServiceRecord sr;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002878 for (int i=0; i<mRestartingServices.size(); i++) {
2879 sr = mRestartingServices.get(i);
2880 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
2881 || !processName.equals(sr.processName))) {
2882 continue;
2883 }
2884 mAm.mHandler.removeCallbacks(sr.restarter);
2885 mAm.mHandler.post(sr.restarter);
2886 }
2887 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002888 return didSomething;
2889 }
2890
2891 void processStartTimedOutLocked(ProcessRecord proc) {
2892 for (int i=0; i<mPendingServices.size(); i++) {
2893 ServiceRecord sr = mPendingServices.get(i);
2894 if ((proc.uid == sr.appInfo.uid
2895 && proc.processName.equals(sr.processName))
2896 || sr.isolatedProc == proc) {
2897 Slog.w(TAG, "Forcing bringing down service: " + sr);
2898 sr.isolatedProc = null;
2899 mPendingServices.remove(i);
2900 i--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002901 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002902 }
2903 }
2904 }
2905
Wale Ogunwale540e1232015-05-01 15:35:39 -07002906 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002907 boolean evenPersistent, boolean doit, boolean killProcess,
2908 ArrayMap<ComponentName, ServiceRecord> services) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002909 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002910 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002911 ServiceRecord service = services.valueAt(i);
Wale Ogunwale540e1232015-05-01 15:35:39 -07002912 final boolean sameComponent = packageName == null
2913 || (service.packageName.equals(packageName)
2914 && (filterByClasses == null
2915 || filterByClasses.contains(service.name.getClassName())));
2916 if (sameComponent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002917 && (service.app == null || evenPersistent || !service.app.persistent)) {
2918 if (!doit) {
2919 return true;
2920 }
2921 didSomething = true;
2922 Slog.i(TAG, " Force stopping service " + service);
2923 if (service.app != null) {
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002924 service.app.removed = killProcess;
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08002925 if (!service.app.persistent) {
2926 service.app.services.remove(service);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002927 if (service.whitelistManager) {
2928 updateWhitelistManagerLocked(service.app);
2929 }
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08002930 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002931 }
2932 service.app = null;
2933 service.isolatedProc = null;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002934 if (mTmpCollectionResults == null) {
2935 mTmpCollectionResults = new ArrayList<>();
2936 }
2937 mTmpCollectionResults.add(service);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002938 }
2939 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002940 return didSomething;
2941 }
2942
Wale Ogunwale540e1232015-05-01 15:35:39 -07002943 boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002944 int userId, boolean evenPersistent, boolean killProcess, boolean doit) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002945 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002946
2947 if (mTmpCollectionResults != null) {
2948 mTmpCollectionResults.clear();
2949 }
2950
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002951 if (userId == UserHandle.USER_ALL) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07002952 for (int i = mServiceMap.size() - 1; i >= 0; i--) {
2953 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002954 evenPersistent, doit, killProcess, mServiceMap.valueAt(i).mServicesByName);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002955 if (!doit && didSomething) {
2956 return true;
2957 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07002958 if (doit && filterByClasses == null) {
2959 forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId);
2960 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002961 }
2962 } else {
Amith Yamasani540b6592013-10-01 13:02:52 -07002963 ServiceMap smap = mServiceMap.get(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002964 if (smap != null) {
2965 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByName;
Wale Ogunwale540e1232015-05-01 15:35:39 -07002966 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07002967 evenPersistent, doit, killProcess, items);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002968 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07002969 if (doit && filterByClasses == null) {
2970 forceStopPackageLocked(packageName, userId);
2971 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002972 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002973
Wale Ogunwale540e1232015-05-01 15:35:39 -07002974 if (mTmpCollectionResults != null) {
2975 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
2976 bringDownServiceLocked(mTmpCollectionResults.get(i));
2977 }
2978 mTmpCollectionResults.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002979 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07002980
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002981 return didSomething;
2982 }
2983
Dianne Hackbornbe68d492017-05-03 18:04:05 -07002984 void forceStopPackageLocked(String packageName, int userId) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002985 ServiceMap smap = mServiceMap.get(userId);
2986 if (smap != null && smap.mActiveForegroundApps.size() > 0) {
Dianne Hackbornaf597682017-05-01 10:54:07 -07002987 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002988 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
2989 if (aa.mPackageName.equals(packageName)) {
2990 smap.mActiveForegroundApps.removeAt(i);
2991 smap.mActiveForegroundAppsChanged = true;
2992 }
2993 }
2994 if (smap.mActiveForegroundAppsChanged) {
2995 requestUpdateActiveForegroundAppsLocked(smap, 0);
2996 }
2997 }
2998 }
2999
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003000 void cleanUpRemovedTaskLocked(TaskRecord tr, ComponentName component, Intent baseIntent) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003001 ArrayList<ServiceRecord> services = new ArrayList<>();
Dianne Hackbornad51be92016-08-16 16:27:36 -07003002 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(tr.userId);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003003 for (int i = alls.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003004 ServiceRecord sr = alls.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003005 if (sr.packageName.equals(component.getPackageName())) {
3006 services.add(sr);
3007 }
3008 }
3009
3010 // Take care of any running services associated with the app.
Wale Ogunwale540e1232015-05-01 15:35:39 -07003011 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003012 ServiceRecord sr = services.get(i);
3013 if (sr.startRequested) {
3014 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
3015 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
3016 stopServiceLocked(sr);
3017 } else {
3018 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Todd Kennedy51b3aac2017-03-30 17:50:42 -07003019 sr.makeNextStartId(), baseIntent, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003020 if (sr.app != null && sr.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003021 // We always run in the foreground, since this is called as
3022 // part of the "remove task" UI operation.
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003023 try {
3024 sendServiceArgsLocked(sr, true, false);
3025 } catch (TransactionTooLargeException e) {
3026 // Ignore, keep going.
3027 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003028 }
3029 }
3030 }
3031 }
3032 }
3033
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003034 final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003035 // Report disconnected services.
3036 if (false) {
3037 // XXX we are letting the client link to the service for
3038 // death notifications.
3039 if (app.services.size() > 0) {
3040 Iterator<ServiceRecord> it = app.services.iterator();
3041 while (it.hasNext()) {
3042 ServiceRecord r = it.next();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003043 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3044 ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
3045 for (int i=0; i<cl.size(); i++) {
3046 ConnectionRecord c = cl.get(i);
3047 if (c.binding.client != app) {
3048 try {
3049 //c.conn.connected(r.className, null);
3050 } catch (Exception e) {
3051 // todo: this should be asynchronous!
3052 Slog.w(TAG, "Exception thrown disconnected servce "
3053 + r.shortName
3054 + " from app " + app.processName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003055 }
3056 }
3057 }
3058 }
3059 }
3060 }
3061 }
3062
louis_chang40e259c2015-03-26 13:31:14 +08003063 // Clean up any connections this application has to other services.
3064 for (int i = app.connections.size() - 1; i >= 0; i--) {
3065 ConnectionRecord r = app.connections.valueAt(i);
3066 removeConnectionLocked(r, app, null);
3067 }
3068 updateServiceConnectionActivitiesLocked(app);
3069 app.connections.clear();
3070
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003071 app.whitelistManager = false;
3072
louis_chang40e259c2015-03-26 13:31:14 +08003073 // Clear app state from services.
3074 for (int i = app.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003075 ServiceRecord sr = app.services.valueAt(i);
3076 synchronized (sr.stats.getBatteryStats()) {
3077 sr.stats.stopLaunchedLocked();
3078 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003079 if (sr.app != app && sr.app != null && !sr.app.persistent) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003080 sr.app.services.remove(sr);
3081 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003082 sr.app = null;
3083 sr.isolatedProc = null;
3084 sr.executeNesting = 0;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003085 sr.forceClearTracker();
3086 if (mDestroyingServices.remove(sr)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003087 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003088 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003089
Dianne Hackbornc8230512013-07-13 21:32:12 -07003090 final int numClients = sr.bindings.size();
3091 for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
3092 IntentBindRecord b = sr.bindings.valueAt(bindingi);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003093 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
Dianne Hackbornc8230512013-07-13 21:32:12 -07003094 + ": shouldUnbind=" + b.hasBound);
3095 b.binder = null;
3096 b.requested = b.received = b.hasBound = false;
Dianne Hackborn465fa392014-09-14 14:21:18 -07003097 // If this binding is coming from a cached process and is asking to keep
3098 // the service created, then we'll kill the cached process as well -- we
3099 // don't want to be thrashing around restarting processes that are only
3100 // there to be cached.
3101 for (int appi=b.apps.size()-1; appi>=0; appi--) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003102 final ProcessRecord proc = b.apps.keyAt(appi);
3103 // If the process is already gone, skip it.
3104 if (proc.killedByAm || proc.thread == null) {
3105 continue;
3106 }
3107 // Only do this for processes that have an auto-create binding;
3108 // otherwise the binding can be left, because it won't cause the
3109 // service to restart.
3110 final AppBindRecord abind = b.apps.valueAt(appi);
3111 boolean hasCreate = false;
3112 for (int conni=abind.connections.size()-1; conni>=0; conni--) {
3113 ConnectionRecord conn = abind.connections.valueAt(conni);
Dianne Hackborn0fe3c252014-09-19 15:09:39 -07003114 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
3115 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003116 hasCreate = true;
3117 break;
3118 }
3119 }
3120 if (!hasCreate) {
3121 continue;
3122 }
Dianne Hackborncd97c962014-09-25 18:34:02 -07003123 // XXX turned off for now until we have more time to get a better policy.
3124 if (false && proc != null && !proc.persistent && proc.thread != null
Dianne Hackborn465fa392014-09-14 14:21:18 -07003125 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
3126 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
3127 proc.kill("bound to service " + sr.name.flattenToShortString()
3128 + " in dying proc " + (app != null ? app.processName : "??"), true);
3129 }
3130 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003131 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003132 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003133
Dianne Hackbornad51be92016-08-16 16:27:36 -07003134 ServiceMap smap = getServiceMapLocked(app.userId);
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003135
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003136 // Now do remaining service cleanup.
3137 for (int i=app.services.size()-1; i>=0; i--) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003138 ServiceRecord sr = app.services.valueAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003139
3140 // Unless the process is persistent, this process record is going away,
3141 // so make sure the service is cleaned out of it.
3142 if (!app.persistent) {
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003143 app.services.removeAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003144 }
3145
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003146 // Sanity check: if the service listed for the app is not one
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003147 // we actually are maintaining, just let it drop.
Dianne Hackborn40c87252014-03-19 16:55:40 -07003148 final ServiceRecord curRec = smap.mServicesByName.get(sr.name);
3149 if (curRec != sr) {
3150 if (curRec != null) {
3151 Slog.wtf(TAG, "Service " + sr + " in process " + app
3152 + " not same as in map: " + curRec);
3153 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003154 continue;
3155 }
3156
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003157 // Any services running in the application may need to be placed
3158 // back in the pending list.
Amith Yamasanib0c8a882017-08-28 09:36:42 -07003159 if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
3160 && (sr.serviceInfo.applicationInfo.flags
3161 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003162 Slog.w(TAG, "Service crashed " + sr.crashCount
3163 + " times, stopping: " + sr);
3164 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
3165 sr.userId, sr.crashCount, sr.shortName, app.pid);
3166 bringDownServiceLocked(sr);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003167 } else if (!allowRestart
Fyodor Kupolov1b3edac2017-09-19 15:48:06 -07003168 || !mAm.mUserController.isUserRunning(sr.userId, 0)) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003169 bringDownServiceLocked(sr);
3170 } else {
3171 boolean canceled = scheduleServiceRestartLocked(sr, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003172
Dianne Hackbornc8230512013-07-13 21:32:12 -07003173 // Should the service remain running? Note that in the
3174 // extreme case of so many attempts to deliver a command
3175 // that it failed we also will stop it here.
3176 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
3177 if (sr.pendingStarts.size() == 0) {
3178 sr.startRequested = false;
3179 if (sr.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003180 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackbornc8230512013-07-13 21:32:12 -07003181 SystemClock.uptimeMillis());
3182 }
3183 if (!sr.hasAutoCreateConnections()) {
3184 // Whoops, no reason to restart!
3185 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003186 }
3187 }
3188 }
3189 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003190 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003191
Dianne Hackbornc8230512013-07-13 21:32:12 -07003192 if (!allowRestart) {
3193 app.services.clear();
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003194
3195 // Make sure there are no more restarting services for this process.
3196 for (int i=mRestartingServices.size()-1; i>=0; i--) {
3197 ServiceRecord r = mRestartingServices.get(i);
3198 if (r.processName.equals(app.processName) &&
3199 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3200 mRestartingServices.remove(i);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08003201 clearRestartingIfNeededLocked(r);
3202 }
3203 }
3204 for (int i=mPendingServices.size()-1; i>=0; i--) {
3205 ServiceRecord r = mPendingServices.get(i);
3206 if (r.processName.equals(app.processName) &&
3207 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3208 mPendingServices.remove(i);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003209 }
3210 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003211 }
3212
3213 // Make sure we have no more records on the stopping list.
Dianne Hackborn164371f2013-10-01 19:10:13 -07003214 int i = mDestroyingServices.size();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003215 while (i > 0) {
3216 i--;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003217 ServiceRecord sr = mDestroyingServices.get(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003218 if (sr.app == app) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003219 sr.forceClearTracker();
3220 mDestroyingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003221 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003222 }
3223 }
3224
3225 app.executingServices.clear();
3226 }
3227
3228 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
3229 ActivityManager.RunningServiceInfo info =
3230 new ActivityManager.RunningServiceInfo();
3231 info.service = r.name;
3232 if (r.app != null) {
3233 info.pid = r.app.pid;
3234 }
3235 info.uid = r.appInfo.uid;
3236 info.process = r.processName;
3237 info.foreground = r.isForeground;
Yi Jin6b514142017-10-30 14:54:12 -07003238 info.activeSince = r.createRealTime;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003239 info.started = r.startRequested;
3240 info.clientCount = r.connections.size();
3241 info.crashCount = r.crashCount;
3242 info.lastActivityTime = r.lastActivity;
3243 if (r.isForeground) {
3244 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
3245 }
3246 if (r.startRequested) {
3247 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
3248 }
3249 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
3250 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
3251 }
3252 if (r.app != null && r.app.persistent) {
3253 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
3254 }
3255
Dianne Hackborn390517b2013-05-30 15:03:32 -07003256 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3257 ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003258 for (int i=0; i<connl.size(); i++) {
3259 ConnectionRecord conn = connl.get(i);
3260 if (conn.clientLabel != 0) {
3261 info.clientPackage = conn.binding.client.info.packageName;
3262 info.clientLabel = conn.clientLabel;
3263 return info;
3264 }
3265 }
3266 }
3267 return info;
3268 }
3269
Bryce Lee290e5782017-02-01 16:41:20 -08003270 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags,
Shunta Sato55af6c52016-10-19 15:58:52 +09003271 int callingUid, boolean allowed, boolean canInteractAcrossUsers) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003272 ArrayList<ActivityManager.RunningServiceInfo> res
3273 = new ArrayList<ActivityManager.RunningServiceInfo>();
3274
Dianne Hackborn0c380492012-08-20 17:23:30 -07003275 final long ident = Binder.clearCallingIdentity();
3276 try {
Shunta Sato55af6c52016-10-19 15:58:52 +09003277 if (canInteractAcrossUsers) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003278 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003279 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003280 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003281 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3282 ServiceRecord sr = alls.valueAt(i);
3283 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07003284 }
3285 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003286
Dianne Hackborn0c380492012-08-20 17:23:30 -07003287 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3288 ServiceRecord r = mRestartingServices.get(i);
3289 ActivityManager.RunningServiceInfo info =
3290 makeRunningServiceInfoLocked(r);
3291 info.restarting = r.nextRestartTime;
3292 res.add(info);
3293 }
3294 } else {
Bryce Lee290e5782017-02-01 16:41:20 -08003295 int userId = UserHandle.getUserId(callingUid);
Dianne Hackbornad51be92016-08-16 16:27:36 -07003296 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003297 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3298 ServiceRecord sr = alls.valueAt(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003299
3300 if (allowed || (sr.app != null && sr.app.uid == callingUid)) {
3301 res.add(makeRunningServiceInfoLocked(sr));
3302 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07003303 }
3304
3305 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3306 ServiceRecord r = mRestartingServices.get(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003307 if (r.userId == userId
3308 && (allowed || (r.app != null && r.app.uid == callingUid))) {
Dianne Hackborn0c380492012-08-20 17:23:30 -07003309 ActivityManager.RunningServiceInfo info =
3310 makeRunningServiceInfoLocked(r);
3311 info.restarting = r.nextRestartTime;
3312 res.add(info);
3313 }
3314 }
3315 }
3316 } finally {
3317 Binder.restoreCallingIdentity(ident);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003318 }
3319
3320 return res;
3321 }
3322
3323 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003324 int userId = UserHandle.getUserId(Binder.getCallingUid());
Dianne Hackbornad51be92016-08-16 16:27:36 -07003325 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003326 if (r != null) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003327 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3328 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003329 for (int i=0; i<conn.size(); i++) {
3330 if (conn.get(i).clientIntent != null) {
3331 return conn.get(i).clientIntent;
3332 }
3333 }
3334 }
3335 }
3336 return null;
3337 }
3338
3339 void serviceTimeout(ProcessRecord proc) {
3340 String anrMessage = null;
3341
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003342 synchronized(mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003343 if (proc.executingServices.size() == 0 || proc.thread == null) {
3344 return;
3345 }
Dianne Hackbornab2df062015-01-07 13:43:13 -08003346 final long now = SystemClock.uptimeMillis();
3347 final long maxTime = now -
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003348 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003349 ServiceRecord timeout = null;
3350 long nextTime = 0;
Dianne Hackbornc8230512013-07-13 21:32:12 -07003351 for (int i=proc.executingServices.size()-1; i>=0; i--) {
3352 ServiceRecord sr = proc.executingServices.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003353 if (sr.executingStart < maxTime) {
3354 timeout = sr;
3355 break;
3356 }
3357 if (sr.executingStart > nextTime) {
3358 nextTime = sr.executingStart;
3359 }
3360 }
3361 if (timeout != null && mAm.mLruProcesses.contains(proc)) {
3362 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08003363 StringWriter sw = new StringWriter();
3364 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
3365 pw.println(timeout);
3366 timeout.dump(pw, " ");
3367 pw.close();
3368 mLastAnrDump = sw.toString();
3369 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
3370 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
3371 anrMessage = "executing service " + timeout.shortName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003372 } else {
3373 Message msg = mAm.mHandler.obtainMessage(
3374 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3375 msg.obj = proc;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003376 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
Dianne Hackborn2be00932013-09-22 16:46:00 -07003377 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003378 }
3379 }
3380
3381 if (anrMessage != null) {
Adrian Roos20d7df32016-01-12 18:59:43 +01003382 mAm.mAppErrors.appNotResponding(proc, null, null, false, anrMessage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003383 }
3384 }
3385
Christopher Tate08992ac2017-03-21 11:37:06 -07003386 void serviceForegroundTimeout(ServiceRecord r) {
3387 ProcessRecord app;
3388 synchronized (mAm) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003389 if (!r.fgRequired || r.destroying) {
Christopher Tate08992ac2017-03-21 11:37:06 -07003390 return;
3391 }
3392
3393 if (DEBUG_BACKGROUND_CHECK) {
3394 Slog.i(TAG, "Service foreground-required timeout for " + r);
3395 }
3396 app = r.app;
3397 r.fgWaiting = false;
3398 stopServiceLocked(r);
3399 }
3400
3401 if (app != null) {
3402 mAm.mAppErrors.appNotResponding(app, null, null, false,
3403 "Context.startForegroundService() did not then call Service.startForeground()");
3404 }
3405 }
3406
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003407 void serviceForegroundCrash(ProcessRecord app) {
3408 mAm.crashApplication(app.uid, app.pid, app.info.packageName, app.userId,
3409 "Context.startForegroundService() did not then call Service.startForeground()");
3410 }
3411
Dianne Hackborn2be00932013-09-22 16:46:00 -07003412 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
3413 if (proc.executingServices.size() == 0 || proc.thread == null) {
3414 return;
3415 }
Dianne Hackborn2be00932013-09-22 16:46:00 -07003416 Message msg = mAm.mHandler.obtainMessage(
3417 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3418 msg.obj = proc;
Christopher Tate08992ac2017-03-21 11:37:06 -07003419 mAm.mHandler.sendMessageDelayed(msg,
3420 proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
3421 }
3422
3423 void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
3424 if (r.app.executingServices.size() == 0 || r.app.thread == null) {
3425 return;
3426 }
3427 Message msg = mAm.mHandler.obtainMessage(
3428 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG);
3429 msg.obj = r;
3430 r.fgWaiting = true;
3431 mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT);
Dianne Hackborn2be00932013-09-22 16:46:00 -07003432 }
3433
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003434 final class ServiceDumper {
3435 private final FileDescriptor fd;
3436 private final PrintWriter pw;
3437 private final String[] args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003438 private final boolean dumpAll;
3439 private final String dumpPackage;
3440 private final ItemMatcher matcher;
3441 private final ArrayList<ServiceRecord> services = new ArrayList<>();
3442
3443 private final long nowReal = SystemClock.elapsedRealtime();
3444
3445 private boolean needSep = false;
3446 private boolean printedAnything = false;
3447 private boolean printed = false;
3448
3449 /**
3450 * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
3451 * must be called with the lock held).
3452 */
3453 ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
3454 int opti, boolean dumpAll, String dumpPackage) {
3455 this.fd = fd;
3456 this.pw = pw;
3457 this.args = args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003458 this.dumpAll = dumpAll;
3459 this.dumpPackage = dumpPackage;
3460 matcher = new ItemMatcher();
3461 matcher.build(args, opti);
3462
3463 final int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003464 for (int user : users) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003465 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003466 if (smap.mServicesByName.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003467 for (int si=0; si<smap.mServicesByName.size(); si++) {
3468 ServiceRecord r = smap.mServicesByName.valueAt(si);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003469 if (!matcher.match(r, r.name)) {
3470 continue;
3471 }
3472 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3473 continue;
3474 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003475 services.add(r);
3476 }
3477 }
3478 }
3479 }
3480
3481 private void dumpHeaderLocked() {
3482 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
3483 if (mLastAnrDump != null) {
3484 pw.println(" Last ANR service:");
3485 pw.print(mLastAnrDump);
3486 pw.println();
3487 }
3488 }
3489
3490 void dumpLocked() {
3491 dumpHeaderLocked();
3492
3493 try {
3494 int[] users = mAm.mUserController.getUsers();
3495 for (int user : users) {
3496 // Find the first service for this user.
3497 int serviceIdx = 0;
3498 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3499 serviceIdx++;
3500 }
3501 printed = false;
3502 if (serviceIdx < services.size()) {
3503 needSep = false;
3504 while (serviceIdx < services.size()) {
3505 ServiceRecord r = services.get(serviceIdx);
3506 serviceIdx++;
3507 if (r.userId != user) {
3508 break;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003509 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003510 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003511 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003512 needSep |= printed;
3513 }
3514
3515 dumpUserRemainsLocked(user);
3516 }
3517 } catch (Exception e) {
3518 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3519 }
3520
3521 dumpRemainsLocked();
3522 }
3523
3524 void dumpWithClient() {
3525 synchronized(mAm) {
3526 dumpHeaderLocked();
3527 }
3528
3529 try {
3530 int[] users = mAm.mUserController.getUsers();
3531 for (int user : users) {
3532 // Find the first service for this user.
3533 int serviceIdx = 0;
3534 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3535 serviceIdx++;
3536 }
3537 printed = false;
3538 if (serviceIdx < services.size()) {
3539 needSep = false;
3540 while (serviceIdx < services.size()) {
3541 ServiceRecord r = services.get(serviceIdx);
3542 serviceIdx++;
3543 if (r.userId != user) {
3544 break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003545 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003546 synchronized(mAm) {
3547 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003548 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003549 dumpServiceClient(r);
3550 }
3551 needSep |= printed;
3552 }
3553
3554 synchronized(mAm) {
3555 dumpUserRemainsLocked(user);
3556 }
3557 }
3558 } catch (Exception e) {
3559 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3560 }
3561
3562 synchronized(mAm) {
3563 dumpRemainsLocked();
3564 }
3565 }
3566
3567 private void dumpUserHeaderLocked(int user) {
3568 if (!printed) {
3569 if (printedAnything) {
3570 pw.println();
3571 }
3572 pw.println(" User " + user + " active services:");
3573 printed = true;
3574 }
3575 printedAnything = true;
3576 if (needSep) {
3577 pw.println();
3578 }
3579 }
3580
3581 private void dumpServiceLocalLocked(ServiceRecord r) {
3582 dumpUserHeaderLocked(r.userId);
3583 pw.print(" * ");
3584 pw.println(r);
3585 if (dumpAll) {
3586 r.dump(pw, " ");
3587 needSep = true;
3588 } else {
3589 pw.print(" app=");
3590 pw.println(r.app);
3591 pw.print(" created=");
Yi Jin6b514142017-10-30 14:54:12 -07003592 TimeUtils.formatDuration(r.createRealTime, nowReal, pw);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003593 pw.print(" started=");
3594 pw.print(r.startRequested);
3595 pw.print(" connections=");
3596 pw.println(r.connections.size());
3597 if (r.connections.size() > 0) {
3598 pw.println(" Connections:");
3599 for (int conni=0; conni<r.connections.size(); conni++) {
3600 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
3601 for (int i = 0; i < clist.size(); i++) {
3602 ConnectionRecord conn = clist.get(i);
3603 pw.print(" ");
3604 pw.print(conn.binding.intent.intent.getIntent()
3605 .toShortString(false, false, false, false));
3606 pw.print(" -> ");
3607 ProcessRecord proc = conn.binding.client;
3608 pw.println(proc != null ? proc.toShortString() : "null");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003609 }
3610 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003611 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003612 }
3613 }
3614
3615 private void dumpServiceClient(ServiceRecord r) {
3616 final ProcessRecord proc = r.app;
3617 if (proc == null) {
3618 return;
3619 }
3620 final IApplicationThread thread = proc.thread;
3621 if (thread == null) {
3622 return;
3623 }
3624 pw.println(" Client:");
3625 pw.flush();
3626 try {
3627 TransferPipe tp = new TransferPipe();
3628 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003629 thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003630 tp.setBufferPrefix(" ");
3631 // Short timeout, since blocking here can
3632 // deadlock with the application.
3633 tp.go(fd, 2000);
3634 } finally {
3635 tp.kill();
3636 }
3637 } catch (IOException e) {
3638 pw.println(" Failure while dumping the service: " + e);
3639 } catch (RemoteException e) {
3640 pw.println(" Got a RemoteException while dumping the service");
3641 }
3642 needSep = true;
3643 }
3644
3645 private void dumpUserRemainsLocked(int user) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003646 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003647 printed = false;
3648 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
3649 ServiceRecord r = smap.mDelayedStartList.get(si);
3650 if (!matcher.match(r, r.name)) {
3651 continue;
3652 }
3653 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3654 continue;
3655 }
3656 if (!printed) {
3657 if (printedAnything) {
3658 pw.println();
3659 }
3660 pw.println(" User " + user + " delayed start services:");
3661 printed = true;
3662 }
3663 printedAnything = true;
3664 pw.print(" * Delayed start "); pw.println(r);
3665 }
3666 printed = false;
3667 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
3668 ServiceRecord r = smap.mStartingBackground.get(si);
3669 if (!matcher.match(r, r.name)) {
3670 continue;
3671 }
3672 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3673 continue;
3674 }
3675 if (!printed) {
3676 if (printedAnything) {
3677 pw.println();
3678 }
3679 pw.println(" User " + user + " starting in background:");
3680 printed = true;
3681 }
3682 printedAnything = true;
3683 pw.print(" * Starting bg "); pw.println(r);
3684 }
3685 }
3686
3687 private void dumpRemainsLocked() {
3688 if (mPendingServices.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003689 printed = false;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003690 for (int i=0; i<mPendingServices.size(); i++) {
3691 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003692 if (!matcher.match(r, r.name)) {
3693 continue;
3694 }
3695 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3696 continue;
3697 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003698 printedAnything = true;
3699 if (!printed) {
3700 if (needSep) pw.println();
3701 needSep = true;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003702 pw.println(" Pending services:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003703 printed = true;
3704 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003705 pw.print(" * Pending "); pw.println(r);
3706 r.dump(pw, " ");
3707 }
3708 needSep = true;
3709 }
3710
3711 if (mRestartingServices.size() > 0) {
3712 printed = false;
3713 for (int i=0; i<mRestartingServices.size(); i++) {
3714 ServiceRecord r = mRestartingServices.get(i);
3715 if (!matcher.match(r, r.name)) {
3716 continue;
3717 }
3718 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3719 continue;
3720 }
3721 printedAnything = true;
3722 if (!printed) {
3723 if (needSep) pw.println();
3724 needSep = true;
3725 pw.println(" Restarting services:");
3726 printed = true;
3727 }
3728 pw.print(" * Restarting "); pw.println(r);
3729 r.dump(pw, " ");
3730 }
3731 needSep = true;
3732 }
3733
3734 if (mDestroyingServices.size() > 0) {
3735 printed = false;
3736 for (int i=0; i< mDestroyingServices.size(); i++) {
3737 ServiceRecord r = mDestroyingServices.get(i);
3738 if (!matcher.match(r, r.name)) {
3739 continue;
3740 }
3741 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3742 continue;
3743 }
3744 printedAnything = true;
3745 if (!printed) {
3746 if (needSep) pw.println();
3747 needSep = true;
3748 pw.println(" Destroying services:");
3749 printed = true;
3750 }
3751 pw.print(" * Destroy "); pw.println(r);
3752 r.dump(pw, " ");
3753 }
3754 needSep = true;
3755 }
3756
3757 if (dumpAll) {
3758 printed = false;
3759 for (int ic=0; ic<mServiceConnections.size(); ic++) {
3760 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
3761 for (int i=0; i<r.size(); i++) {
3762 ConnectionRecord cr = r.get(i);
3763 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
3764 continue;
3765 }
3766 if (dumpPackage != null && (cr.binding.client == null
3767 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
3768 continue;
3769 }
3770 printedAnything = true;
3771 if (!printed) {
3772 if (needSep) pw.println();
3773 needSep = true;
3774 pw.println(" Connection bindings to services:");
3775 printed = true;
3776 }
3777 pw.print(" * "); pw.println(cr);
3778 cr.dump(pw, " ");
3779 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003780 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003781 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003782
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003783 if (matcher.all) {
3784 final long nowElapsed = SystemClock.elapsedRealtime();
3785 final int[] users = mAm.mUserController.getUsers();
3786 for (int user : users) {
3787 boolean printedUser = false;
3788 ServiceMap smap = mServiceMap.get(user);
3789 if (smap == null) {
3790 continue;
3791 }
3792 for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) {
3793 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
3794 if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) {
3795 continue;
3796 }
3797 if (!printedUser) {
3798 printedUser = true;
3799 printedAnything = true;
3800 if (needSep) pw.println();
3801 needSep = true;
3802 pw.print("Active foreground apps - user ");
3803 pw.print(user);
3804 pw.println(":");
3805 }
3806 pw.print(" #");
3807 pw.print(i);
3808 pw.print(": ");
3809 pw.println(aa.mPackageName);
3810 if (aa.mLabel != null) {
3811 pw.print(" mLabel=");
3812 pw.println(aa.mLabel);
3813 }
3814 pw.print(" mNumActive=");
3815 pw.print(aa.mNumActive);
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003816 pw.print(" mAppOnTop=");
3817 pw.print(aa.mAppOnTop);
3818 pw.print(" mShownWhileTop=");
3819 pw.print(aa.mShownWhileTop);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003820 pw.print(" mShownWhileScreenOn=");
3821 pw.println(aa.mShownWhileScreenOn);
3822 pw.print(" mStartTime=");
3823 TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw);
3824 pw.print(" mStartVisibleTime=");
3825 TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw);
3826 pw.println();
3827 if (aa.mEndTime != 0) {
3828 pw.print(" mEndTime=");
3829 TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw);
3830 pw.println();
3831 }
3832 }
Dianne Hackborncb015632017-06-14 17:30:15 -07003833 if (smap.hasMessagesOrCallbacks()) {
3834 if (needSep) {
3835 pw.println();
3836 }
3837 printedAnything = true;
3838 needSep = true;
3839 pw.print(" Handler - user ");
3840 pw.print(user);
3841 pw.println(":");
3842 smap.dumpMine(new PrintWriterPrinter(pw), " ");
3843 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003844 }
3845 }
3846
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003847 if (!printedAnything) {
3848 pw.println(" (nothing)");
3849 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07003850 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003851 }
3852
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003853 ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
3854 int opti, boolean dumpAll, String dumpPackage) {
3855 return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
3856 }
3857
Yi Jin6b514142017-10-30 14:54:12 -07003858 protected void writeToProto(ProtoOutputStream proto) {
3859 synchronized (mAm) {
3860 int[] users = mAm.mUserController.getUsers();
3861 for (int user : users) {
3862 ServiceMap smap = mServiceMap.get(user);
3863 if (smap == null) {
3864 continue;
3865 }
3866 long token = proto.start(ActiveServicesProto.SERVICES_BY_USERS);
3867 proto.write(ActiveServicesProto.ServicesByUser.USER_ID, user);
3868 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
3869 for (int i=0; i<alls.size(); i++) {
3870 alls.valueAt(i).writeToProto(proto,
3871 ActiveServicesProto.ServicesByUser.SERVICE_RECORDS);
3872 }
3873 proto.end(token);
3874 }
3875 }
3876 }
3877
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003878 /**
3879 * There are three ways to call this:
3880 * - no service specified: dump all the services
3881 * - a flattened component name that matched an existing service was specified as the
3882 * first arg: dump that one service
3883 * - the first arg isn't the flattened component name of an existing service:
3884 * dump all services whose component contains the first arg as a substring
3885 */
3886 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
3887 int opti, boolean dumpAll) {
3888 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
3889
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003890 synchronized (mAm) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003891 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003892 if ("all".equals(name)) {
3893 for (int user : users) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -07003894 ServiceMap smap = mServiceMap.get(user);
3895 if (smap == null) {
3896 continue;
3897 }
3898 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003899 for (int i=0; i<alls.size(); i++) {
3900 ServiceRecord r1 = alls.valueAt(i);
Amith Yamasani258848d2012-08-10 17:06:33 -07003901 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003902 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003903 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003904 } else {
3905 ComponentName componentName = name != null
3906 ? ComponentName.unflattenFromString(name) : null;
3907 int objectId = 0;
3908 if (componentName == null) {
3909 // Not a '/' separated full component name; maybe an object ID?
3910 try {
3911 objectId = Integer.parseInt(name, 16);
3912 name = null;
3913 componentName = null;
3914 } catch (RuntimeException e) {
3915 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003916 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003917
Dianne Hackborn1676c852012-09-10 14:52:30 -07003918 for (int user : users) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -07003919 ServiceMap smap = mServiceMap.get(user);
3920 if (smap == null) {
3921 continue;
3922 }
3923 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003924 for (int i=0; i<alls.size(); i++) {
3925 ServiceRecord r1 = alls.valueAt(i);
Amith Yamasani258848d2012-08-10 17:06:33 -07003926 if (componentName != null) {
3927 if (r1.name.equals(componentName)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003928 services.add(r1);
3929 }
Amith Yamasani258848d2012-08-10 17:06:33 -07003930 } else if (name != null) {
3931 if (r1.name.flattenToString().contains(name)) {
3932 services.add(r1);
3933 }
3934 } else if (System.identityHashCode(r1) == objectId) {
3935 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003936 }
3937 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003938 }
3939 }
3940 }
3941
3942 if (services.size() <= 0) {
3943 return false;
3944 }
3945
3946 boolean needSep = false;
3947 for (int i=0; i<services.size(); i++) {
3948 if (needSep) {
3949 pw.println();
3950 }
3951 needSep = true;
3952 dumpService("", fd, pw, services.get(i), args, dumpAll);
3953 }
3954 return true;
3955 }
3956
3957 /**
3958 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
3959 * there is a thread associated with the service.
3960 */
3961 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
3962 final ServiceRecord r, String[] args, boolean dumpAll) {
3963 String innerPrefix = prefix + " ";
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003964 synchronized (mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003965 pw.print(prefix); pw.print("SERVICE ");
3966 pw.print(r.shortName); pw.print(" ");
3967 pw.print(Integer.toHexString(System.identityHashCode(r)));
3968 pw.print(" pid=");
3969 if (r.app != null) pw.println(r.app.pid);
3970 else pw.println("(not running)");
3971 if (dumpAll) {
3972 r.dump(pw, innerPrefix);
3973 }
3974 }
3975 if (r.app != null && r.app.thread != null) {
3976 pw.print(prefix); pw.println(" Client:");
3977 pw.flush();
3978 try {
3979 TransferPipe tp = new TransferPipe();
3980 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003981 r.app.thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003982 tp.setBufferPrefix(prefix + " ");
3983 tp.go(fd);
3984 } finally {
3985 tp.kill();
3986 }
3987 } catch (IOException e) {
3988 pw.println(prefix + " Failure while dumping the service: " + e);
3989 } catch (RemoteException e) {
3990 pw.println(prefix + " Got a RemoteException while dumping the service");
3991 }
3992 }
3993 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003994}