blob: f7acf7e83200a92003f2beb2d731b43861ad4d67 [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 -080020
Hui Yue361a232018-10-04 15:05:21 -070021import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK;
22import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOREGROUND_SERVICE;
23import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
24import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
25import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE;
26import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE_EXECUTING;
27import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
28import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE;
29import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE_EXECUTING;
30import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
31import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070032
Hui Yue361a232018-10-04 15:05:21 -070033import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070034import android.app.ActivityManagerInternal;
Dianne Hackborn455625e2015-01-21 09:55:13 -080035import android.app.ActivityThread;
Hui Yue361a232018-10-04 15:05:21 -070036import android.app.AppGlobals;
Svet Ganov99b60432015-06-27 13:15:22 -070037import android.app.AppOpsManager;
Hui Yue361a232018-10-04 15:05:21 -070038import android.app.IApplicationThread;
39import android.app.IServiceConnection;
40import android.app.Notification;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070041import android.app.NotificationManager;
Hui Yue361a232018-10-04 15:05:21 -070042import android.app.PendingIntent;
43import android.app.Service;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070044import android.app.ServiceStartArgs;
Hui Yue361a232018-10-04 15:05:21 -070045import android.content.ComponentName;
Makoto Onuki0b575a32018-04-16 14:33:59 -070046import android.content.ComponentName.WithComponentName;
Hui Yue361a232018-10-04 15:05:21 -070047import android.content.Context;
Svet Ganov9c165d72015-12-01 19:52:26 -080048import android.content.IIntentSender;
Hui Yue361a232018-10-04 15:05:21 -070049import android.content.Intent;
Svet Ganov9c165d72015-12-01 19:52:26 -080050import android.content.IntentSender;
Hui Yue361a232018-10-04 15:05:21 -070051import android.content.pm.ApplicationInfo;
52import android.content.pm.PackageManager;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070053import android.content.pm.ParceledListSlice;
Hui Yue361a232018-10-04 15:05:21 -070054import android.content.pm.ResolveInfo;
55import android.content.pm.ServiceInfo;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070056import android.net.Uri;
Hui Yue361a232018-10-04 15:05:21 -070057import android.os.Binder;
Christoph Studer365e4c32014-09-18 20:35:36 +020058import android.os.Build;
Svet Ganov9c165d72015-12-01 19:52:26 -080059import android.os.Bundle;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -070060import android.os.DeadObjectException;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070061import android.os.Handler;
Hui Yue361a232018-10-04 15:05:21 -070062import android.os.IBinder;
Dianne Hackborn13c590d2013-10-07 14:32:00 -070063import android.os.Looper;
Hui Yue361a232018-10-04 15:05:21 -070064import android.os.Message;
65import android.os.Process;
Svet Ganov9c165d72015-12-01 19:52:26 -080066import android.os.RemoteCallback;
Hui Yue361a232018-10-04 15:05:21 -070067import android.os.RemoteException;
68import android.os.SystemClock;
Dianne Hackborn23037412013-11-04 18:11:29 -080069import android.os.SystemProperties;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -070070import android.os.TransactionTooLargeException;
Hui Yue361a232018-10-04 15:05:21 -070071import android.os.UserHandle;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070072import android.provider.Settings;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070073import android.util.ArrayMap;
Dianne Hackborn465fa392014-09-14 14:21:18 -070074import android.util.ArraySet;
Hui Yue361a232018-10-04 15:05:21 -070075import android.util.EventLog;
76import android.util.PrintWriterPrinter;
77import android.util.Slog;
78import android.util.SparseArray;
79import android.util.StatsLog;
80import android.util.TimeUtils;
81import android.util.proto.ProtoOutputStream;
82import android.webkit.WebViewZygote;
Wale Ogunwaled57969f2014-11-15 19:37:29 -080083
Dianne Hackborn83b40f62017-04-26 13:59:47 -070084import com.android.internal.R;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070085import com.android.internal.app.procstats.ServiceState;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070086import com.android.internal.messages.nano.SystemMessageProto;
87import com.android.internal.notification.SystemNotificationChannels;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070088import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborncbfd23e2013-06-11 14:26:53 -070089import com.android.internal.os.TransferPipe;
Makoto Onuki0b575a32018-04-16 14:33:59 -070090import com.android.internal.util.DumpUtils;
Dianne Hackborncff1bbf2015-01-20 13:43:32 -080091import com.android.internal.util.FastPrintWriter;
Christopher Tatec7933ac2018-03-12 17:57:09 -070092import com.android.server.AppStateTracker;
93import com.android.server.LocalServices;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -070094import com.android.server.SystemService;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070095import com.android.server.am.ActivityManagerService.ItemMatcher;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -070096import com.android.server.uri.NeededUriGrants;
Wale Ogunwale59507092018-10-29 09:00:30 -070097import com.android.server.wm.ActivityServiceConnectionsHolder;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070098
Hui Yue361a232018-10-04 15:05:21 -070099import java.io.FileDescriptor;
100import java.io.IOException;
101import java.io.PrintWriter;
102import java.io.StringWriter;
103import java.util.ArrayList;
104import java.util.Comparator;
105import java.util.Iterator;
106import java.util.List;
107import java.util.Set;
108import java.util.function.Predicate;
109
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -0700110public final class ActiveServices {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800111 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM;
112 private static final String TAG_MU = TAG + POSTFIX_MU;
113 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
114 private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING;
115
116 private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE;
117 private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE;
118
119 private static final boolean LOG_SERVICE_START_STOP = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700120
Dianne Hackborn070d1422018-05-02 13:48:30 -0700121 private static final boolean SHOW_DUNGEON_NOTIFICATION = false;
122
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700123 // How long we wait for a service to finish executing.
124 static final int SERVICE_TIMEOUT = 20*1000;
125
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700126 // How long we wait for a service to finish executing.
127 static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
128
Christopher Tate08992ac2017-03-21 11:37:06 -0700129 // How long the startForegroundService() grace period is to get around to
130 // calling startForeground() before we ANR + stop it.
Christopher Tate5e5c3452018-05-25 13:12:12 -0700131 static final int SERVICE_START_FOREGROUND_TIMEOUT = 10*1000;
Christopher Tate08992ac2017-03-21 11:37:06 -0700132
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700133 final ActivityManagerService mAm;
134
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700135 // Maximum number of services that we allow to start in the background
136 // at the same time.
137 final int mMaxStartingBackground;
138
Wale Ogunwale540e1232015-05-01 15:35:39 -0700139 final SparseArray<ServiceMap> mServiceMap = new SparseArray<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700140
141 /**
142 * All currently bound service connections. Keys are the IBinder of
143 * the client's IServiceConnection.
144 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700145 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700146
147 /**
148 * List of services that we have been asked to start,
149 * but haven't yet been able to. It is used to hold start requests
150 * while waiting for their corresponding application thread to get
151 * going.
152 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700153 final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700154
155 /**
156 * List of services that are scheduled to restart following a crash.
157 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700158 final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700159
160 /**
Dianne Hackborn164371f2013-10-01 19:10:13 -0700161 * List of services that are in the process of being destroyed.
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700162 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700163 final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>();
164
165 /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */
166 private ArrayList<ServiceRecord> mTmpCollectionResults = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700167
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700168 /**
169 * For keeping ActiveForegroundApps retaining state while the screen is off.
170 */
171 boolean mScreenOn = true;
172
Dianne Hackborncff1bbf2015-01-20 13:43:32 -0800173 /** Amount of time to allow a last ANR message to exist before freeing the memory. */
174 static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
175
176 String mLastAnrDump;
177
178 final Runnable mLastAnrDumpClearer = new Runnable() {
179 @Override public void run() {
180 synchronized (mAm) {
181 mLastAnrDump = null;
182 }
183 }
184 };
185
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700186 /**
Christopher Tatec7933ac2018-03-12 17:57:09 -0700187 * Watch for apps being put into forced app standby, so we can step their fg
188 * services down.
189 */
190 class ForcedStandbyListener extends AppStateTracker.Listener {
191 @Override
192 public void stopForegroundServicesForUidPackage(final int uid, final String packageName) {
193 synchronized (mAm) {
194 final ServiceMap smap = getServiceMapLocked(UserHandle.getUserId(uid));
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800195 final int N = smap.mServicesByInstanceName.size();
Christopher Tatec7933ac2018-03-12 17:57:09 -0700196 final ArrayList<ServiceRecord> toStop = new ArrayList<>(N);
197 for (int i = 0; i < N; i++) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800198 final ServiceRecord r = smap.mServicesByInstanceName.valueAt(i);
Christopher Tatec7933ac2018-03-12 17:57:09 -0700199 if (uid == r.serviceInfo.applicationInfo.uid
200 || packageName.equals(r.serviceInfo.packageName)) {
201 if (r.isForeground) {
202 toStop.add(r);
203 }
204 }
205 }
206
207 // Now stop them all
208 final int numToStop = toStop.size();
209 if (numToStop > 0 && DEBUG_FOREGROUND_SERVICE) {
210 Slog.i(TAG, "Package " + packageName + "/" + uid
211 + " entering FAS with foreground services");
212 }
213 for (int i = 0; i < numToStop; i++) {
214 final ServiceRecord r = toStop.get(i);
215 if (DEBUG_FOREGROUND_SERVICE) {
216 Slog.i(TAG, " Stopping fg for service " + r);
217 }
218 setServiceForegroundInnerLocked(r, 0, null, 0);
219 }
220 }
221 }
222 }
223
224 /**
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700225 * Information about an app that is currently running one or more foreground services.
Dan Sandler2f36ab82017-05-25 00:15:49 -0400226 * (This maps directly to the running apps we show in the notification.)
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700227 */
228 static final class ActiveForegroundApp {
229 String mPackageName;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700230 int mUid;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700231 CharSequence mLabel;
232 boolean mShownWhileScreenOn;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700233 boolean mAppOnTop;
234 boolean mShownWhileTop;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700235 long mStartTime;
236 long mStartVisibleTime;
237 long mEndTime;
238 int mNumActive;
Dianne Hackborncb015632017-06-14 17:30:15 -0700239
240 // Temp output of foregroundAppShownEnoughLocked
241 long mHideTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700242 }
243
244 /**
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700245 * Information about services for a single user.
246 */
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700247 final class ServiceMap extends Handler {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700248 final int mUserId;
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800249 final ArrayMap<ComponentName, ServiceRecord> mServicesByInstanceName = new ArrayMap<>();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700250 final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700251
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700252 final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700253 /* XXX eventually I'd like to have this based on processes instead of services.
254 * That is, if we try to start two services in a row both running in the same
255 * process, this should be one entry in mStartingBackground for that one process
256 * that remains until all services in it are done.
257 final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
258 = new ArrayMap<ProcessRecord, DelayingProcess>();
259 final ArrayList<DelayingProcess> mStartingProcessList
260 = new ArrayList<DelayingProcess>();
261 */
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700262
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700263 final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700264
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700265 final ArrayMap<String, ActiveForegroundApp> mActiveForegroundApps = new ArrayMap<>();
266 boolean mActiveForegroundAppsChanged;
267
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700268 static final int MSG_BG_START_TIMEOUT = 1;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700269 static final int MSG_UPDATE_FOREGROUND_APPS = 2;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700270
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700271 ServiceMap(Looper looper, int userId) {
272 super(looper);
Dianne Hackborn6285a322013-09-18 12:09:47 -0700273 mUserId = userId;
274 }
275
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700276 @Override
277 public void handleMessage(Message msg) {
278 switch (msg.what) {
279 case MSG_BG_START_TIMEOUT: {
280 synchronized (mAm) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700281 rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700282 }
283 } break;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700284 case MSG_UPDATE_FOREGROUND_APPS: {
285 updateForegroundApps(this);
286 } break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700287 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700288 }
289
Dianne Hackbornad51be92016-08-16 16:27:36 -0700290 void ensureNotStartingBackgroundLocked(ServiceRecord r) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700291 if (mStartingBackground.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800292 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
293 "No longer background starting: " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -0700294 rescheduleDelayedStartsLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700295 }
Dianne Hackborn2e46bb52013-09-13 17:01:26 -0700296 if (mDelayedStartList.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800297 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700298 }
299 }
300
Dianne Hackbornad51be92016-08-16 16:27:36 -0700301 void rescheduleDelayedStartsLocked() {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700302 removeMessages(MSG_BG_START_TIMEOUT);
303 final long now = SystemClock.uptimeMillis();
304 for (int i=0, N=mStartingBackground.size(); i<N; i++) {
305 ServiceRecord r = mStartingBackground.get(i);
306 if (r.startingBgTimeout <= now) {
307 Slog.i(TAG, "Waited long enough for: " + r);
308 mStartingBackground.remove(i);
309 N--;
Junu Kimfcb87362014-02-19 16:25:21 +0900310 i--;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700311 }
312 }
313 while (mDelayedStartList.size() > 0
314 && mStartingBackground.size() < mMaxStartingBackground) {
315 ServiceRecord r = mDelayedStartList.remove(0);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800316 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
317 "REM FR DELAY LIST (exec next): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700318 if (r.pendingStarts.size() <= 0) {
319 Slog.w(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
320 + " delayedStop=" + r.delayedStop);
321 }
322 if (DEBUG_DELAYED_SERVICE) {
323 if (mDelayedStartList.size() > 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800324 Slog.v(TAG_SERVICE, "Remaining delayed list:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700325 for (int i=0; i<mDelayedStartList.size(); i++) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800326 Slog.v(TAG_SERVICE, " #" + i + ": " + mDelayedStartList.get(i));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700327 }
328 }
329 }
330 r.delayed = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700331 try {
332 startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false, true);
333 } catch (TransactionTooLargeException e) {
334 // Ignore, nobody upstack cares.
335 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700336 }
337 if (mStartingBackground.size() > 0) {
338 ServiceRecord next = mStartingBackground.get(0);
339 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800340 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700341 + ", can delay others up to " + when);
342 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
343 sendMessageAtTime(msg, when);
344 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700345 if (mStartingBackground.size() < mMaxStartingBackground) {
346 mAm.backgroundServicesFinishedLocked(mUserId);
347 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700348 }
349 }
350
351 public ActiveServices(ActivityManagerService service) {
352 mAm = service;
Dianne Hackborn23037412013-11-04 18:11:29 -0800353 int maxBg = 0;
354 try {
355 maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
356 } catch(RuntimeException e) {
357 }
Dianne Hackborn20d94742014-05-29 18:35:45 -0700358 mMaxStartingBackground = maxBg > 0
359 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700360 }
361
Christopher Tatec7933ac2018-03-12 17:57:09 -0700362 void systemServicesReady() {
363 AppStateTracker ast = LocalServices.getService(AppStateTracker.class);
364 ast.addListener(new ForcedStandbyListener());
365 }
366
Dianne Hackbornad51be92016-08-16 16:27:36 -0700367 ServiceRecord getServiceByNameLocked(ComponentName name, int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700368 // TODO: Deal with global services
369 if (DEBUG_MU)
Dianne Hackbornad51be92016-08-16 16:27:36 -0700370 Slog.v(TAG_MU, "getServiceByNameLocked(" + name + "), callingUser = " + callingUser);
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800371 return getServiceMapLocked(callingUser).mServicesByInstanceName.get(name);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700372 }
373
Dianne Hackbornad51be92016-08-16 16:27:36 -0700374 boolean hasBackgroundServicesLocked(int callingUser) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700375 ServiceMap smap = mServiceMap.get(callingUser);
376 return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
377 }
378
Dianne Hackbornad51be92016-08-16 16:27:36 -0700379 private ServiceMap getServiceMapLocked(int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700380 ServiceMap smap = mServiceMap.get(callingUser);
381 if (smap == null) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700382 smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700383 mServiceMap.put(callingUser, smap);
384 }
385 return smap;
386 }
387
Dianne Hackbornad51be92016-08-16 16:27:36 -0700388 ArrayMap<ComponentName, ServiceRecord> getServicesLocked(int callingUser) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800389 return getServiceMapLocked(callingUser).mServicesByInstanceName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700390 }
391
Christopher Tatec7933ac2018-03-12 17:57:09 -0700392 private boolean appRestrictedAnyInBackground(final int uid, final String packageName) {
393 final int mode = mAm.mAppOpsService.checkOperation(
394 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, uid, packageName);
395 return (mode != AppOpsManager.MODE_ALLOWED);
396 }
397
Svet Ganov99b60432015-06-27 13:15:22 -0700398 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
Christopher Tate242ba3e92017-04-14 15:07:06 -0700399 int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700400 throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800401 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700402 + " type=" + resolvedType + " args=" + service.getExtras());
403
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700404 final boolean callerFg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700405 if (caller != null) {
406 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
407 if (callerApp == null) {
408 throw new SecurityException(
409 "Unable to find app for caller " + caller
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700410 + " (pid=" + callingPid
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700411 + ") when starting service " + service);
412 }
Dianne Hackborna49ad092016-03-03 13:39:10 -0800413 callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700414 } else {
415 callerFg = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700416 }
417
418 ServiceLookupResult res =
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800419 retrieveServiceLocked(service, null, resolvedType, callingPackage,
Svet Ganovd223db32017-12-22 09:43:48 -0800420 callingPid, callingUid, userId, true, callerFg, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700421 if (res == null) {
422 return null;
423 }
424 if (res.record == null) {
425 return new ComponentName("!", res.permission != null
426 ? res.permission : "private to package");
427 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700428
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700429 ServiceRecord r = res.record;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700430
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700431 if (!mAm.mUserController.exists(r.userId)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700432 Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700433 return null;
434 }
435
Christopher Tate85048282018-03-30 14:08:59 -0700436 // If we're starting indirectly (e.g. from PendingIntent), figure out whether
Christopher Tate45f06c792018-04-25 10:47:23 -0700437 // we're launching into an app in a background state. This keys off of the same
438 // idleness state tracking as e.g. O+ background service start policy.
439 final boolean bgLaunch = !mAm.isUidActiveLocked(r.appInfo.uid);
Christopher Tate85048282018-03-30 14:08:59 -0700440
441 // If the app has strict background restrictions, we treat any bg service
442 // start analogously to the legacy-app forced-restrictions case, regardless
443 // of its target SDK version.
Christopher Tatec7933ac2018-03-12 17:57:09 -0700444 boolean forcedStandby = false;
Christopher Tate85048282018-03-30 14:08:59 -0700445 if (bgLaunch && appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
Christopher Tatec7933ac2018-03-12 17:57:09 -0700446 if (DEBUG_FOREGROUND_SERVICE) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800447 Slog.d(TAG, "Forcing bg-only service start only for " + r.shortInstanceName
Christopher Tate85048282018-03-30 14:08:59 -0700448 + " : bgLaunch=" + bgLaunch + " callerFg=" + callerFg);
Christopher Tatec7933ac2018-03-12 17:57:09 -0700449 }
450 forcedStandby = true;
451 }
452
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700453 // If this is a direct-to-foreground start, make sure it is allowed as per the app op.
454 boolean forceSilentAbort = false;
455 if (fgRequired) {
456 final int mode = mAm.mAppOpsService.checkOperation(
457 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
458 switch (mode) {
459 case AppOpsManager.MODE_ALLOWED:
460 case AppOpsManager.MODE_DEFAULT:
461 // All okay.
462 break;
463 case AppOpsManager.MODE_IGNORED:
464 // Not allowed, fall back to normal start service, failing siliently
465 // if background check restricts that.
466 Slog.w(TAG, "startForegroundService not allowed due to app op: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800467 + service + " to " + r.shortInstanceName
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700468 + " from pid=" + callingPid + " uid=" + callingUid
469 + " pkg=" + callingPackage);
470 fgRequired = false;
471 forceSilentAbort = true;
472 break;
473 default:
474 return new ComponentName("!!", "foreground not allowed as per app op");
475 }
476 }
477
Christopher Tate08992ac2017-03-21 11:37:06 -0700478 // If this isn't a direct-to-foreground start, check our ability to kick off an
479 // arbitrary service
Christopher Tatec7933ac2018-03-12 17:57:09 -0700480 if (forcedStandby || (!r.startRequested && !fgRequired)) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700481 // Before going further -- if this app is not allowed to start services in the
482 // background, then at this point we aren't going to let it period.
483 final int allowed = mAm.getAppStartModeLocked(r.appInfo.uid, r.packageName,
Christopher Tatec7933ac2018-03-12 17:57:09 -0700484 r.appInfo.targetSdkVersion, callingPid, false, false, forcedStandby);
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700485 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
486 Slog.w(TAG, "Background start not allowed: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800487 + service + " to " + r.shortInstanceName
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700488 + " from pid=" + callingPid + " uid=" + callingUid
Christopher Tatee84ffd92018-05-16 12:59:43 -0700489 + " pkg=" + callingPackage + " startFg?=" + fgRequired);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700490 if (allowed == ActivityManager.APP_START_MODE_DELAYED || forceSilentAbort) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700491 // In this case we are silently disabling the app, to disrupt as
492 // little as possible existing apps.
493 return null;
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700494 }
Christopher Tatee84ffd92018-05-16 12:59:43 -0700495 if (forcedStandby) {
496 // This is an O+ app, but we might be here because the user has placed
497 // it under strict background restrictions. Don't punish the app if it's
498 // trying to do the right thing but we're denying it for that reason.
499 if (fgRequired) {
500 if (DEBUG_BACKGROUND_CHECK) {
501 Slog.v(TAG, "Silently dropping foreground service launch due to FAS");
502 }
503 return null;
504 }
505 }
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700506 // This app knows it is in the new model where this operation is not
507 // allowed, so tell it what has happened.
508 UidRecord uidRec = mAm.mActiveUids.get(r.appInfo.uid);
509 return new ComponentName("?", "app is in background uid " + uidRec);
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700510 }
511 }
512
Christopher Tate0a826902018-05-25 15:15:44 -0700513 // At this point we've applied allowed-to-start policy based on whether this was
514 // an ordinary startService() or a startForegroundService(). Now, only require that
515 // the app follow through on the startForegroundService() -> startForeground()
516 // contract if it actually targets O+.
517 if (r.appInfo.targetSdkVersion < Build.VERSION_CODES.O && fgRequired) {
518 if (DEBUG_BACKGROUND_CHECK || DEBUG_FOREGROUND_SERVICE) {
519 Slog.i(TAG, "startForegroundService() but host targets "
520 + r.appInfo.targetSdkVersion + " - not requiring startForeground()");
521 }
522 fgRequired = false;
523 }
524
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700525 NeededUriGrants neededGrants = mAm.mUgmInternal.checkGrantUriPermissionFromIntent(
Nicolas Prevotc6cf95c2014-05-29 11:30:36 +0100526 callingUid, r.packageName, service, service.getFlags(), null, r.userId);
Svet Ganov9c165d72015-12-01 19:52:26 -0800527
528 // If permissions need a review before any of the app components can run,
529 // we do not start the service and launch a review activity if the calling app
530 // is in the foreground passing it a pending intent to start the service when
531 // review is completed.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700532
533 // XXX This is not dealing with fgRequired!
534 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage,
535 callingUid, service, callerFg, userId)) {
536 return null;
Svet Ganov9c165d72015-12-01 19:52:26 -0800537 }
538
Dianne Hackbornd6f5b622013-11-11 17:25:37 -0800539 if (unscheduleServiceRestartLocked(r, callingUid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800540 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700541 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700542 r.lastActivity = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700543 r.startRequested = true;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700544 r.delayedStop = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700545 r.fgRequired = fgRequired;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700546 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -0700547 service, neededGrants, callingUid));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700548
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700549 if (fgRequired) {
550 // We are now effectively running a foreground service.
Dianne Hackborn2aec55a2018-06-26 10:35:35 -0700551 ServiceState stracker = r.getTracker();
552 if (stracker != null) {
553 stracker.setForeground(true, mAm.mProcessStats.getMemFactorLocked(),
554 r.lastActivity);
555 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700556 mAm.mAppOpsService.startOperation(AppOpsManager.getToken(mAm.mAppOpsService),
557 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, true);
558 }
559
Dianne Hackbornad51be92016-08-16 16:27:36 -0700560 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700561 boolean addToStarting = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700562 if (!callerFg && !fgRequired && r.app == null
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700563 && mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700564 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700565 if (proc == null || proc.getCurProcState() > ActivityManager.PROCESS_STATE_RECEIVER) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700566 // If this is not coming from a foreground caller, then we may want
567 // to delay the start if there are already other background services
568 // that are starting. This is to avoid process start spam when lots
569 // of applications are all handling things like connectivity broadcasts.
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700570 // We only do this for cached processes, because otherwise an application
571 // can have assumptions about calling startService() for a service to run
572 // in its own process, and for that process to not be killed before the
573 // service is started. This is especially the case for receivers, which
574 // may start a service in onReceive() to do some additional work and have
575 // initialized some global state as part of that.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800576 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
577 + r + " in " + proc);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700578 if (r.delayed) {
579 // This service is already scheduled for a delayed start; just leave
580 // it still waiting.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800581 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700582 return r.name;
583 }
584 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
585 // Something else is starting, delay!
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800586 Slog.i(TAG_SERVICE, "Delaying start of: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700587 smap.mDelayedStartList.add(r);
588 r.delayed = true;
589 return r.name;
590 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800591 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700592 addToStarting = true;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700593 } else if (proc.getCurProcState() >= ActivityManager.PROCESS_STATE_SERVICE) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700594 // We slightly loosen when we will enqueue this new service as a background
595 // starting service we are waiting for, to also include processes that are
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700596 // currently running other services or receivers.
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700597 addToStarting = true;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800598 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
599 "Not delaying, but counting as bg: " + r);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800600 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn8e692572013-09-10 19:06:15 -0700601 StringBuilder sb = new StringBuilder(128);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700602 sb.append("Not potential delay (state=").append(proc.getCurProcState())
Dianne Hackborn8e692572013-09-10 19:06:15 -0700603 .append(' ').append(proc.adjType);
604 String reason = proc.makeAdjReason();
605 if (reason != null) {
606 sb.append(' ');
607 sb.append(reason);
608 }
609 sb.append("): ");
610 sb.append(r.toString());
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800611 Slog.v(TAG_SERVICE, sb.toString());
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700612 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800613 } else if (DEBUG_DELAYED_STARTS) {
Christopher Tate08992ac2017-03-21 11:37:06 -0700614 if (callerFg || fgRequired) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800615 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
Christopher Tate08992ac2017-03-21 11:37:06 -0700616 + callingUid + " pid=" + callingPid + " fgRequired=" + fgRequired + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700617 } else if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800618 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700619 } else {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800620 Slog.v(TAG_SERVICE,
621 "Not potential delay (user " + r.userId + " not started): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700622 }
623 }
624
Christopher Tate42a386b2016-11-07 12:21:21 -0800625 ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
Christopher Tate42a386b2016-11-07 12:21:21 -0800626 return cmp;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700627 }
628
Svet Ganov9c165d72015-12-01 19:52:26 -0800629 private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
630 String callingPackage, int callingUid, Intent service, boolean callerFg,
631 final int userId) {
632 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
633 r.packageName, r.userId)) {
634
635 // Show a permission review UI only for starting from a foreground app
636 if (!callerFg) {
637 Slog.w(TAG, "u" + r.userId + " Starting a service in package"
638 + r.packageName + " requires a permissions review");
639 return false;
640 }
641
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700642 IIntentSender target = mAm.mPendingIntentController.getIntentSender(
Svet Ganov9c165d72015-12-01 19:52:26 -0800643 ActivityManager.INTENT_SENDER_SERVICE, callingPackage,
644 callingUid, userId, null, null, 0, new Intent[]{service},
645 new String[]{service.resolveType(mAm.mContext.getContentResolver())},
646 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
647 | PendingIntent.FLAG_IMMUTABLE, null);
648
649 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
650 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
651 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
652 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
653 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
654
655 if (DEBUG_PERMISSIONS_REVIEW) {
656 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
657 + r.packageName);
658 }
659
660 mAm.mHandler.post(new Runnable() {
661 @Override
662 public void run() {
663 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
664 }
665 });
666
667 return false;
668 }
669
670 return true;
671 }
672
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700673 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
674 boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
Joe Onorato4eb64fd2016-03-21 15:30:09 -0700675 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700676 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700677 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700678 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700679 r.callStart = false;
Chenjie Yu75b3c492018-10-06 21:45:19 -0700680 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid, r.name.getPackageName(),
681 r.name.getClassName(), StatsLog.SERVICE_STATE_CHANGED__STATE__START);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700682 synchronized (r.stats.getBatteryStats()) {
683 r.stats.startRunningLocked();
684 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800685 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700686 if (error != null) {
687 return new ComponentName("!!", error);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700688 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700689
690 if (r.startRequested && addToStarting) {
691 boolean first = smap.mStartingBackground.size() == 0;
692 smap.mStartingBackground.add(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700693 r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700694 if (DEBUG_DELAYED_SERVICE) {
695 RuntimeException here = new RuntimeException("here");
696 here.fillInStackTrace();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800697 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800698 } else if (DEBUG_DELAYED_STARTS) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800699 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700700 }
701 if (first) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700702 smap.rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700703 }
Christopher Tate08992ac2017-03-21 11:37:06 -0700704 } else if (callerFg || r.fgRequired) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700705 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700706 }
707
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700708 return r.name;
709 }
710
711 private void stopServiceLocked(ServiceRecord service) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700712 if (service.delayed) {
713 // If service isn't actually running, but is is being held in the
714 // delayed list, then we need to keep it started but note that it
715 // should be stopped once no longer delayed.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800716 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700717 service.delayedStop = true;
718 return;
719 }
Chenjie Yu75b3c492018-10-06 21:45:19 -0700720 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, service.appInfo.uid,
721 service.name.getPackageName(), service.name.getClassName(),
722 StatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700723 synchronized (service.stats.getBatteryStats()) {
724 service.stats.stopRunningLocked();
725 }
726 service.startRequested = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700727 if (service.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700728 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700729 SystemClock.uptimeMillis());
730 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700731 service.callStart = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700732 bringDownServiceIfNeededLocked(service, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700733 }
734
735 int stopServiceLocked(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700736 String resolvedType, int userId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800737 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700738 + " type=" + resolvedType);
739
740 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
741 if (caller != null && callerApp == null) {
742 throw new SecurityException(
743 "Unable to find app for caller " + caller
744 + " (pid=" + Binder.getCallingPid()
745 + ") when stopping service " + service);
746 }
747
748 // If this service is active, make sure it is stopped.
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800749 ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, null,
Svet Ganovd223db32017-12-22 09:43:48 -0800750 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700751 if (r != null) {
752 if (r.record != null) {
753 final long origId = Binder.clearCallingIdentity();
754 try {
755 stopServiceLocked(r.record);
756 } finally {
757 Binder.restoreCallingIdentity(origId);
758 }
759 return 1;
760 }
761 return -1;
762 }
763
764 return 0;
765 }
766
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700767 void stopInBackgroundLocked(int uid) {
768 // Stop all services associated with this uid due to it going to the background
769 // stopped state.
770 ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
771 ArrayList<ServiceRecord> stopping = null;
772 if (services != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800773 for (int i = services.mServicesByInstanceName.size() - 1; i >= 0; i--) {
774 ServiceRecord service = services.mServicesByInstanceName.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700775 if (service.appInfo.uid == uid && service.startRequested) {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800776 if (mAm.getAppStartModeLocked(service.appInfo.uid, service.packageName,
Christopher Tatec7933ac2018-03-12 17:57:09 -0700777 service.appInfo.targetSdkVersion, -1, false, false, false)
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800778 != ActivityManager.APP_START_MODE_NORMAL) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700779 if (stopping == null) {
780 stopping = new ArrayList<>();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700781 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800782 String compName = service.shortInstanceName;
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700783 EventLogTags.writeAmStopIdleService(service.appInfo.uid, compName);
784 StringBuilder sb = new StringBuilder(64);
785 sb.append("Stopping service due to app idle: ");
786 UserHandle.formatUid(sb, service.appInfo.uid);
787 sb.append(" ");
Yi Jin6b514142017-10-30 14:54:12 -0700788 TimeUtils.formatDuration(service.createRealTime
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700789 - SystemClock.elapsedRealtime(), sb);
790 sb.append(" ");
791 sb.append(compName);
792 Slog.w(TAG, sb.toString());
793 stopping.add(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700794 }
795 }
796 }
797 if (stopping != null) {
798 for (int i=stopping.size()-1; i>=0; i--) {
799 ServiceRecord service = stopping.get(i);
800 service.delayed = false;
Dianne Hackbornad51be92016-08-16 16:27:36 -0700801 services.ensureNotStartingBackgroundLocked(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700802 stopServiceLocked(service);
803 }
804 }
805 }
806 }
807
Svet Ganov99b60432015-06-27 13:15:22 -0700808 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800809 ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, callingPackage,
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -0700810 Binder.getCallingPid(), Binder.getCallingUid(),
Svet Ganovd223db32017-12-22 09:43:48 -0800811 UserHandle.getCallingUserId(), false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700812
813 IBinder ret = null;
814 if (r != null) {
815 // r.record is null if findServiceLocked() failed the caller permission check
816 if (r.record == null) {
817 throw new SecurityException(
Christopher Desjardins5862c5f2015-05-19 11:25:40 +0000818 "Permission Denial: Accessing service"
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700819 + " from pid=" + Binder.getCallingPid()
820 + ", uid=" + Binder.getCallingUid()
821 + " requires " + r.permission);
822 }
823 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
824 if (ib != null) {
825 ret = ib.binder;
826 }
827 }
828
829 return ret;
830 }
831
832 boolean stopServiceTokenLocked(ComponentName className, IBinder token,
833 int startId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800834 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700835 + " " + token + " startId=" + startId);
Dianne Hackborn41203752012-08-31 14:05:51 -0700836 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700837 if (r != null) {
838 if (startId >= 0) {
839 // Asked to only stop if done with all work. Note that
840 // to avoid leaks, we will take this as dropping all
841 // start items up to and including this one.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -0700842 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700843 if (si != null) {
844 while (r.deliveredStarts.size() > 0) {
845 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
846 cur.removeUriPermissionsLocked();
847 if (cur == si) {
848 break;
849 }
850 }
851 }
852
853 if (r.getLastStartId() != startId) {
854 return false;
855 }
856
857 if (r.deliveredStarts.size() > 0) {
858 Slog.w(TAG, "stopServiceToken startId " + startId
859 + " is last, but have " + r.deliveredStarts.size()
860 + " remaining args");
861 }
862 }
863
Chenjie Yu75b3c492018-10-06 21:45:19 -0700864 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid, r.name.getPackageName(),
865 r.name.getClassName(), StatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700866 synchronized (r.stats.getBatteryStats()) {
867 r.stats.stopRunningLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700868 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700869 r.startRequested = false;
870 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700871 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700872 SystemClock.uptimeMillis());
873 }
874 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700875 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700876 bringDownServiceIfNeededLocked(r, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700877 Binder.restoreCallingIdentity(origId);
878 return true;
879 }
880 return false;
881 }
882
Sudheer Shankac9d94072017-02-22 22:13:55 +0000883 public void setServiceForegroundLocked(ComponentName className, IBinder token,
Dianne Hackborn67324c92016-04-18 13:55:25 -0700884 int id, Notification notification, int flags) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700885 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700886 final long origId = Binder.clearCallingIdentity();
887 try {
Dianne Hackborn41203752012-08-31 14:05:51 -0700888 ServiceRecord r = findServiceLocked(className, token, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700889 if (r != null) {
Sudheer Shankac9d94072017-02-22 22:13:55 +0000890 setServiceForegroundInnerLocked(r, id, notification, flags);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700891 }
892 } finally {
893 Binder.restoreCallingIdentity(origId);
894 }
895 }
896
Dianne Hackborncb015632017-06-14 17:30:15 -0700897 boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) {
898 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid="
899 + aa.mUid);
900 boolean canRemove = false;
901 aa.mHideTime = Long.MAX_VALUE;
902 if (aa.mShownWhileTop) {
903 // If the app was ever at the top of the screen while the foreground
904 // service was running, then we can always just immediately remove it.
905 canRemove = true;
906 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown while on top");
907 } else if (mScreenOn || aa.mShownWhileScreenOn) {
908 final long minTime = aa.mStartVisibleTime
909 + (aa.mStartTime != aa.mStartVisibleTime
910 ? mAm.mConstants.FGSERVICE_SCREEN_ON_AFTER_TIME
911 : mAm.mConstants.FGSERVICE_MIN_SHOWN_TIME);
912 if (nowElapsed >= minTime) {
913 // If shown while the screen is on, and it has been shown for
914 // at least the minimum show time, then we can now remove it.
915 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown long enough with screen on");
916 canRemove = true;
917 } else {
918 // This is when we will be okay to stop telling the user.
919 long reportTime = nowElapsed + mAm.mConstants.FGSERVICE_MIN_REPORT_TIME;
920 aa.mHideTime = reportTime > minTime ? reportTime : minTime;
921 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
922 + " with screen on");
923 }
924 } else {
925 final long minTime = aa.mEndTime
926 + mAm.mConstants.FGSERVICE_SCREEN_ON_BEFORE_TIME;
927 if (nowElapsed >= minTime) {
928 // If the foreground service has only run while the screen is
929 // off, but it has been gone now for long enough that we won't
930 // care to tell the user about it when the screen comes back on,
931 // then we can remove it now.
932 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - gone long enough with screen off");
933 canRemove = true;
934 } else {
935 // This is when we won't care about this old fg service.
936 aa.mHideTime = minTime;
937 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
938 + " with screen off");
939 }
940 }
941 return canRemove;
942 }
943
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700944 void updateForegroundApps(ServiceMap smap) {
945 // This is called from the handler without the lock held.
946 ArrayList<ActiveForegroundApp> active = null;
947 synchronized (mAm) {
948 final long now = SystemClock.elapsedRealtime();
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700949 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700950 if (smap != null) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700951 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Updating foreground apps for user "
952 + smap.mUserId);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700953 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
954 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -0700955 if (aa.mEndTime != 0) {
956 boolean canRemove = foregroundAppShownEnoughLocked(aa, now);
957 if (canRemove) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700958 // This was up for longer than the timeout, so just remove immediately.
959 smap.mActiveForegroundApps.removeAt(i);
960 smap.mActiveForegroundAppsChanged = true;
961 continue;
962 }
Dianne Hackborncb015632017-06-14 17:30:15 -0700963 if (aa.mHideTime < nextUpdateTime) {
964 nextUpdateTime = aa.mHideTime;
965 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700966 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700967 if (!aa.mAppOnTop) {
968 if (active == null) {
969 active = new ArrayList<>();
970 }
Dianne Hackborncb015632017-06-14 17:30:15 -0700971 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
972 + aa.mPackageName + ", uid=" + aa.mUid);
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700973 active.add(aa);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700974 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700975 }
976 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
977 if (nextUpdateTime < Long.MAX_VALUE) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700978 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Next update time in: "
979 + (nextUpdateTime-now));
980 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700981 smap.sendMessageAtTime(msg, nextUpdateTime
982 + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700983 }
984 }
985 if (!smap.mActiveForegroundAppsChanged) {
986 return;
987 }
988 smap.mActiveForegroundAppsChanged = false;
989 }
990
Dianne Hackborn070d1422018-05-02 13:48:30 -0700991 if (!SHOW_DUNGEON_NOTIFICATION) {
992 return;
993 }
994
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700995 final NotificationManager nm = (NotificationManager) mAm.mContext.getSystemService(
996 Context.NOTIFICATION_SERVICE);
997 final Context context = mAm.mContext;
998
999 if (active != null) {
1000 for (int i = 0; i < active.size(); i++) {
1001 ActiveForegroundApp aa = active.get(i);
1002 if (aa.mLabel == null) {
1003 PackageManager pm = context.getPackageManager();
1004 try {
1005 ApplicationInfo ai = pm.getApplicationInfoAsUser(aa.mPackageName,
1006 PackageManager.MATCH_KNOWN_PACKAGES, smap.mUserId);
1007 aa.mLabel = ai.loadLabel(pm);
1008 } catch (PackageManager.NameNotFoundException e) {
1009 aa.mLabel = aa.mPackageName;
1010 }
1011 }
1012 }
1013
1014 Intent intent;
1015 String title;
1016 String msg;
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001017 String[] pkgs;
Dan Sandler886e0162017-06-06 14:23:43 -04001018 final long nowElapsed = SystemClock.elapsedRealtime();
1019 long oldestStartTime = nowElapsed;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001020 if (active.size() == 1) {
1021 intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
1022 intent.setData(Uri.fromParts("package", active.get(0).mPackageName, null));
1023 title = context.getString(
1024 R.string.foreground_service_app_in_background, active.get(0).mLabel);
1025 msg = context.getString(R.string.foreground_service_tap_for_details);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001026 pkgs = new String[] { active.get(0).mPackageName };
Dan Sandler2f36ab82017-05-25 00:15:49 -04001027 oldestStartTime = active.get(0).mStartTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001028 } else {
1029 intent = new Intent(Settings.ACTION_FOREGROUND_SERVICES_SETTINGS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001030 pkgs = new String[active.size()];
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001031 for (int i = 0; i < active.size(); i++) {
1032 pkgs[i] = active.get(i).mPackageName;
Dan Sandler2f36ab82017-05-25 00:15:49 -04001033 oldestStartTime = Math.min(oldestStartTime, active.get(i).mStartTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001034 }
1035 intent.putExtra("packages", pkgs);
1036 title = context.getString(
1037 R.string.foreground_service_apps_in_background, active.size());
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001038 msg = active.get(0).mLabel.toString();
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001039 for (int i = 1; i < active.size(); i++) {
1040 msg = context.getString(R.string.foreground_service_multiple_separator,
1041 msg, active.get(i).mLabel);
1042 }
1043 }
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001044 Bundle notificationBundle = new Bundle();
1045 notificationBundle.putStringArray(Notification.EXTRA_FOREGROUND_APPS, pkgs);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001046 Notification.Builder n =
1047 new Notification.Builder(context,
1048 SystemNotificationChannels.FOREGROUND_SERVICE)
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001049 .addExtras(notificationBundle)
Dan Sandler2f36ab82017-05-25 00:15:49 -04001050 .setSmallIcon(R.drawable.stat_sys_vitals)
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001051 .setOngoing(true)
Dan Sandler886e0162017-06-06 14:23:43 -04001052 .setShowWhen(oldestStartTime < nowElapsed)
1053 .setWhen(System.currentTimeMillis() - (nowElapsed - oldestStartTime))
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001054 .setColor(context.getColor(
1055 com.android.internal.R.color.system_notification_accent_color))
1056 .setContentTitle(title)
1057 .setContentText(msg)
1058 .setContentIntent(
1059 PendingIntent.getActivityAsUser(context, 0, intent,
1060 PendingIntent.FLAG_UPDATE_CURRENT,
1061 null, new UserHandle(smap.mUserId)));
1062 nm.notifyAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1063 n.build(), new UserHandle(smap.mUserId));
1064 } else {
1065 nm.cancelAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1066 new UserHandle(smap.mUserId));
1067 }
1068 }
1069
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001070 private void requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001071 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001072 if (timeElapsed != 0) {
1073 smap.sendMessageAtTime(msg,
1074 timeElapsed + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001075 } else {
1076 smap.mActiveForegroundAppsChanged = true;
1077 smap.sendMessage(msg);
1078 }
1079 }
1080
1081 private void decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r) {
1082 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1083 if (active != null) {
1084 active.mNumActive--;
1085 if (active.mNumActive <= 0) {
1086 active.mEndTime = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001087 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Ended running of service");
1088 if (foregroundAppShownEnoughLocked(active, active.mEndTime)) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001089 // Have been active for long enough that we will remove it immediately.
1090 smap.mActiveForegroundApps.remove(r.packageName);
1091 smap.mActiveForegroundAppsChanged = true;
1092 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001093 } else if (active.mHideTime < Long.MAX_VALUE){
1094 requestUpdateActiveForegroundAppsLocked(smap, active.mHideTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001095 }
1096 }
1097 }
1098 }
1099
1100 void updateScreenStateLocked(boolean screenOn) {
1101 if (mScreenOn != screenOn) {
1102 mScreenOn = screenOn;
1103
1104 // If screen is turning on, then we now reset the start time of any foreground
1105 // services that were started while the screen was off.
1106 if (screenOn) {
1107 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001108 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Screen turned on");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001109 for (int i = mServiceMap.size()-1; i >= 0; i--) {
1110 ServiceMap smap = mServiceMap.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -07001111 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001112 boolean changed = false;
1113 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1114 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
Dianne Hackborncb015632017-06-14 17:30:15 -07001115 if (active.mEndTime == 0) {
1116 if (!active.mShownWhileScreenOn) {
1117 active.mShownWhileScreenOn = true;
1118 active.mStartVisibleTime = nowElapsed;
1119 }
1120 } else {
1121 if (!active.mShownWhileScreenOn
1122 && active.mStartVisibleTime == active.mStartTime) {
1123 // If this was never shown while the screen was on, then we will
1124 // count the time it started being visible as now, to tell the user
1125 // about it now that they have a screen to look at.
1126 active.mEndTime = active.mStartVisibleTime = nowElapsed;
1127 }
1128 if (foregroundAppShownEnoughLocked(active, nowElapsed)) {
1129 // Have been active for long enough that we will remove it
1130 // immediately.
1131 smap.mActiveForegroundApps.remove(active.mPackageName);
1132 smap.mActiveForegroundAppsChanged = true;
1133 changed = true;
1134 } else {
1135 if (active.mHideTime < nextUpdateTime) {
1136 nextUpdateTime = active.mHideTime;
1137 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001138 }
1139 }
1140 }
1141 if (changed) {
Dianne Hackborncb015632017-06-14 17:30:15 -07001142 // Need to immediately update.
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001143 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001144 } else if (nextUpdateTime < Long.MAX_VALUE) {
1145 requestUpdateActiveForegroundAppsLocked(smap, nextUpdateTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001146 }
1147 }
1148 }
1149 }
1150 }
1151
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001152 void foregroundServiceProcStateChangedLocked(UidRecord uidRec) {
1153 ServiceMap smap = mServiceMap.get(UserHandle.getUserId(uidRec.uid));
1154 if (smap != null) {
1155 boolean changed = false;
1156 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1157 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
1158 if (active.mUid == uidRec.uid) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07001159 if (uidRec.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001160 if (!active.mAppOnTop) {
1161 active.mAppOnTop = true;
1162 changed = true;
1163 }
1164 active.mShownWhileTop = true;
1165 } else if (active.mAppOnTop) {
1166 active.mAppOnTop = false;
1167 changed = true;
1168 }
1169 }
1170 }
1171 if (changed) {
1172 requestUpdateActiveForegroundAppsLocked(smap, 0);
1173 }
1174 }
1175 }
1176
Christopher Tatec7933ac2018-03-12 17:57:09 -07001177 /**
1178 * @param id Notification ID. Zero === exit foreground state for the given service.
1179 */
1180 private void setServiceForegroundInnerLocked(final ServiceRecord r, int id,
Christopher Tate42a386b2016-11-07 12:21:21 -08001181 Notification notification, int flags) {
1182 if (id != 0) {
1183 if (notification == null) {
1184 throw new IllegalArgumentException("null notification");
1185 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001186 // Instant apps need permission to create foreground services.
1187 if (r.appInfo.isInstantApp()) {
1188 final int mode = mAm.mAppOpsService.checkOperation(
1189 AppOpsManager.OP_INSTANT_APP_START_FOREGROUND,
1190 r.appInfo.uid,
1191 r.appInfo.packageName);
1192 switch (mode) {
1193 case AppOpsManager.MODE_ALLOWED:
1194 break;
1195 case AppOpsManager.MODE_IGNORED:
1196 Slog.w(TAG, "Instant app " + r.appInfo.packageName
1197 + " does not have permission to create foreground services"
1198 + ", ignoring.");
Sudheer Shankac9d94072017-02-22 22:13:55 +00001199 return;
Chad Brubaker97b383f2017-02-02 15:04:35 -08001200 case AppOpsManager.MODE_ERRORED:
1201 throw new SecurityException("Instant app " + r.appInfo.packageName
1202 + " does not have permission to create foreground services");
1203 default:
Dianne Hackborndd027b32018-01-19 17:44:46 -08001204 mAm.enforcePermission(
1205 android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
1206 r.app.pid, r.appInfo.uid, "startForeground");
Chad Brubaker97b383f2017-02-02 15:04:35 -08001207 }
Hui Yu1ea85522018-12-06 16:59:18 -08001208 } else {
1209 if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
1210 mAm.enforcePermission(
1211 android.Manifest.permission.FOREGROUND_SERVICE,
1212 r.app.pid, r.appInfo.uid, "startForeground");
1213 }
1214 if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.Q) {
1215 if (r.serviceInfo.getForegroundServiceType()
1216 == ServiceInfo.FOREGROUND_SERVICE_TYPE_UNSPECIFIED) {
1217 // STOPSHIP(b/120611119): replace log message with SecurityException.
1218 Slog.w(TAG, "missing foregroundServiceType attribute in "
1219 + "service element of manifest file");
1220 }
1221 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001222 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001223 boolean alreadyStartedOp = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001224 boolean stopProcStatsOp = false;
Christopher Tate08992ac2017-03-21 11:37:06 -07001225 if (r.fgRequired) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001226 if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001227 Slog.i(TAG, "Service called startForeground() as required: " + r);
1228 }
1229 r.fgRequired = false;
1230 r.fgWaiting = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001231 alreadyStartedOp = stopProcStatsOp = true;
Christopher Tate08992ac2017-03-21 11:37:06 -07001232 mAm.mHandler.removeMessages(
1233 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
1234 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001235
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001236 try {
1237 boolean ignoreForeground = false;
1238 final int mode = mAm.mAppOpsService.checkOperation(
1239 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
1240 switch (mode) {
1241 case AppOpsManager.MODE_ALLOWED:
1242 case AppOpsManager.MODE_DEFAULT:
1243 // All okay.
1244 break;
1245 case AppOpsManager.MODE_IGNORED:
1246 // Whoops, silently ignore this.
1247 Slog.w(TAG, "Service.startForeground() not allowed due to app op: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001248 + r.shortInstanceName);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001249 ignoreForeground = true;
1250 break;
1251 default:
1252 throw new SecurityException("Foreground not allowed as per app op");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001253 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001254
1255 if (!ignoreForeground &&
1256 appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001257 Slog.w(TAG,
1258 "Service.startForeground() not allowed due to bg restriction: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001259 + r.shortInstanceName);
Christopher Tate45f06c792018-04-25 10:47:23 -07001260 // Back off of any foreground expectations around this service, since we've
1261 // just turned down its fg request.
1262 updateServiceForegroundLocked(r.app, false);
1263 ignoreForeground = true;
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001264 }
1265
1266 // Apps under strict background restrictions simply don't get to have foreground
1267 // services, so now that we've enforced the startForegroundService() contract
1268 // we only do the machinery of making the service foreground when the app
1269 // is not restricted.
1270 if (!ignoreForeground) {
1271 if (r.foregroundId != id) {
1272 cancelForegroundNotificationLocked(r);
1273 r.foregroundId = id;
Christopher Tatec7933ac2018-03-12 17:57:09 -07001274 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001275 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
1276 r.foregroundNoti = notification;
1277 if (!r.isForeground) {
1278 final ServiceMap smap = getServiceMapLocked(r.userId);
1279 if (smap != null) {
1280 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1281 if (active == null) {
1282 active = new ActiveForegroundApp();
1283 active.mPackageName = r.packageName;
1284 active.mUid = r.appInfo.uid;
1285 active.mShownWhileScreenOn = mScreenOn;
1286 if (r.app != null) {
1287 active.mAppOnTop = active.mShownWhileTop =
Wale Ogunwalebff2df42018-10-18 17:09:19 -07001288 r.app.uidRecord.getCurProcState()
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001289 <= ActivityManager.PROCESS_STATE_TOP;
1290 }
1291 active.mStartTime = active.mStartVisibleTime
1292 = SystemClock.elapsedRealtime();
1293 smap.mActiveForegroundApps.put(r.packageName, active);
1294 requestUpdateActiveForegroundAppsLocked(smap, 0);
1295 }
1296 active.mNumActive++;
1297 }
1298 r.isForeground = true;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001299 if (!stopProcStatsOp) {
1300 ServiceState stracker = r.getTracker();
1301 if (stracker != null) {
1302 stracker.setForeground(true,
1303 mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
1304 }
1305 } else {
1306 stopProcStatsOp = false;
1307 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001308 mAm.mAppOpsService.startOperation(
1309 AppOpsManager.getToken(mAm.mAppOpsService),
1310 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName,
1311 true);
1312 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001313 r.appInfo.uid, r.shortInstanceName,
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001314 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER);
Hui Yue361a232018-10-04 15:05:21 -07001315 mAm.updateForegroundServiceUsageStats(r.name, r.userId, true);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001316 }
1317 r.postNotification();
1318 if (r.app != null) {
1319 updateServiceForegroundLocked(r.app, true);
1320 }
1321 getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
1322 mAm.notifyPackageUse(r.serviceInfo.packageName,
1323 PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
1324 } else {
1325 if (DEBUG_FOREGROUND_SERVICE) {
1326 Slog.d(TAG, "Suppressing startForeground() for FAS " + r);
1327 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001328 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001329 } finally {
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001330 if (stopProcStatsOp) {
1331 // We got through to this point with it actively being started foreground,
1332 // and never decided we wanted to keep it like that, so drop it.
1333 ServiceState stracker = r.getTracker();
1334 if (stracker != null) {
1335 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1336 r.lastActivity);
1337 }
1338 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001339 if (alreadyStartedOp) {
1340 // If we had previously done a start op for direct foreground start,
1341 // we have cleared the flag so can now drop it.
1342 mAm.mAppOpsService.finishOperation(
1343 AppOpsManager.getToken(mAm.mAppOpsService),
1344 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001345 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001346 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001347 } else {
1348 if (r.isForeground) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001349 final ServiceMap smap = getServiceMapLocked(r.userId);
1350 if (smap != null) {
1351 decActiveForegroundAppLocked(smap, r);
1352 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001353 r.isForeground = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001354 ServiceState stracker = r.getTracker();
1355 if (stracker != null) {
1356 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1357 r.lastActivity);
1358 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001359 mAm.mAppOpsService.finishOperation(
1360 AppOpsManager.getToken(mAm.mAppOpsService),
1361 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001362 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001363 r.appInfo.uid, r.shortInstanceName,
Chenjie Yuccfe6452018-01-30 11:33:21 -08001364 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Hui Yue361a232018-10-04 15:05:21 -07001365 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
Christopher Tate42a386b2016-11-07 12:21:21 -08001366 if (r.app != null) {
1367 mAm.updateLruProcessLocked(r.app, false, null);
1368 updateServiceForegroundLocked(r.app, true);
1369 }
1370 }
1371 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001372 cancelForegroundNotificationLocked(r);
Christopher Tate42a386b2016-11-07 12:21:21 -08001373 r.foregroundId = 0;
1374 r.foregroundNoti = null;
1375 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1376 r.stripForegroundServiceFlagFromNotification();
1377 if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
1378 r.foregroundId = 0;
1379 r.foregroundNoti = null;
1380 }
1381 }
1382 }
1383 }
1384
Christopher Tate08992ac2017-03-21 11:37:06 -07001385 private void cancelForegroundNotificationLocked(ServiceRecord r) {
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001386 if (r.foregroundId != 0) {
1387 // First check to see if this app has any other active foreground services
1388 // with the same notification ID. If so, we shouldn't actually cancel it,
1389 // because that would wipe away the notification that still needs to be shown
1390 // due the other service.
Dianne Hackbornad51be92016-08-16 16:27:36 -07001391 ServiceMap sm = getServiceMapLocked(r.userId);
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001392 if (sm != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001393 for (int i = sm.mServicesByInstanceName.size() - 1; i >= 0; i--) {
1394 ServiceRecord other = sm.mServicesByInstanceName.valueAt(i);
Dianne Hackborn569a4582016-08-04 14:00:22 -07001395 if (other != r && other.foregroundId == r.foregroundId
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001396 && other.packageName.equals(r.packageName)) {
1397 // Found one! Abort the cancel.
1398 return;
1399 }
1400 }
1401 }
1402 r.cancelNotification();
1403 }
1404 }
1405
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001406 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
1407 boolean anyForeground = false;
Dianne Hackbornc8230512013-07-13 21:32:12 -07001408 for (int i=proc.services.size()-1; i>=0; i--) {
1409 ServiceRecord sr = proc.services.valueAt(i);
Christopher Tatee23fa2b2017-04-20 14:48:13 -07001410 if (sr.isForeground || sr.fgRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001411 anyForeground = true;
1412 break;
1413 }
1414 }
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08001415 mAm.updateProcessForegroundLocked(proc, anyForeground, oomAdj);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001416 }
1417
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001418 private void updateWhitelistManagerLocked(ProcessRecord proc) {
1419 proc.whitelistManager = false;
1420 for (int i=proc.services.size()-1; i>=0; i--) {
1421 ServiceRecord sr = proc.services.valueAt(i);
1422 if (sr.whitelistManager) {
1423 proc.whitelistManager = true;
1424 break;
1425 }
1426 }
1427 }
1428
Dianne Hackborn465fa392014-09-14 14:21:18 -07001429 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
1430 ArraySet<ProcessRecord> updatedProcesses = null;
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001431 for (int i = 0; i < clientProc.connections.size(); i++) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001432 final ConnectionRecord conn = clientProc.connections.valueAt(i);
1433 final ProcessRecord proc = conn.binding.service.app;
1434 if (proc == null || proc == clientProc) {
1435 continue;
1436 } else if (updatedProcesses == null) {
1437 updatedProcesses = new ArraySet<>();
1438 } else if (updatedProcesses.contains(proc)) {
1439 continue;
1440 }
1441 updatedProcesses.add(proc);
1442 updateServiceClientActivitiesLocked(proc, null, false);
1443 }
1444 }
1445
Dianne Hackborndb926082013-10-31 16:32:44 -07001446 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
Dianne Hackborn465fa392014-09-14 14:21:18 -07001447 ConnectionRecord modCr, boolean updateLru) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001448 if (modCr != null && modCr.binding.client != null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001449 if (!modCr.binding.client.hasActivities()) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001450 // This connection is from a client without activities, so adding
1451 // and removing is not interesting.
1452 return false;
1453 }
1454 }
1455
1456 boolean anyClientActivities = false;
1457 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
1458 ServiceRecord sr = proc.services.valueAt(i);
1459 for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) {
1460 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni);
1461 for (int cri=clist.size()-1; cri>=0; cri--) {
1462 ConnectionRecord cr = clist.get(cri);
1463 if (cr.binding.client == null || cr.binding.client == proc) {
1464 // Binding to ourself is not interesting.
1465 continue;
1466 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001467 if (cr.binding.client.hasActivities()) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001468 anyClientActivities = true;
1469 break;
1470 }
1471 }
1472 }
1473 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001474 if (anyClientActivities != proc.hasClientActivities()) {
1475 proc.setHasClientActivities(anyClientActivities);
Dianne Hackborn465fa392014-09-14 14:21:18 -07001476 if (updateLru) {
1477 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
1478 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001479 return true;
1480 }
1481 return false;
1482 }
1483
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001484 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
Svet Ganov9c165d72015-12-01 19:52:26 -08001485 String resolvedType, final IServiceConnection connection, int flags,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001486 String instanceName, String callingPackage, final int userId)
1487 throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001488 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001489 + " type=" + resolvedType + " conn=" + connection.asBinder()
1490 + " flags=0x" + Integer.toHexString(flags));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001491 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
1492 if (callerApp == null) {
1493 throw new SecurityException(
1494 "Unable to find app for caller " + caller
1495 + " (pid=" + Binder.getCallingPid()
1496 + ") when binding service " + service);
1497 }
1498
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001499 ActivityServiceConnectionsHolder<ConnectionRecord> activity = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001500 if (token != null) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001501 activity = mAm.mAtmInternal.getServiceConnectionsHolder(token);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001502 if (activity == null) {
1503 Slog.w(TAG, "Binding with unknown activity: " + token);
1504 return 0;
1505 }
1506 }
1507
1508 int clientLabel = 0;
1509 PendingIntent clientIntent = null;
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001510 final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001511
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001512 if (isCallerSystem) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001513 // Hacky kind of thing -- allow system stuff to tell us
1514 // what they are, so we can report this elsewhere for
1515 // others to know why certain services are running.
Jeff Sharkeyf0ec2e02016-03-21 12:37:54 -06001516 service.setDefusable(true);
1517 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001518 if (clientIntent != null) {
1519 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
1520 if (clientLabel != 0) {
1521 // There are no useful extras in the intent, trash them.
1522 // System code calling with this stuff just needs to know
1523 // this will happen.
1524 service = service.cloneFilter();
1525 }
1526 }
1527 }
1528
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001529 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1530 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
1531 "BIND_TREAT_LIKE_ACTIVITY");
1532 }
1533
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001534 if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
1535 throw new SecurityException(
1536 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1537 + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
1538 }
1539
Svet Ganovd223db32017-12-22 09:43:48 -08001540 if ((flags & Context.BIND_ALLOW_INSTANT) != 0 && !isCallerSystem) {
1541 throw new SecurityException(
1542 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1543 + ") set BIND_ALLOW_INSTANT when binding service " + service);
1544 }
1545
Dianne Hackborna49ad092016-03-03 13:39:10 -08001546 final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Robert Sesekb9a86662015-12-09 16:22:45 -05001547 final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
Svet Ganovd223db32017-12-22 09:43:48 -08001548 final boolean allowInstant = (flags & Context.BIND_ALLOW_INSTANT) != 0;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001549
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001550 ServiceLookupResult res =
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001551 retrieveServiceLocked(service, instanceName, resolvedType, callingPackage,
1552 Binder.getCallingPid(), Binder.getCallingUid(), userId, true,
1553 callerFg, isBindExternal, allowInstant);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001554 if (res == null) {
1555 return 0;
1556 }
1557 if (res.record == null) {
1558 return -1;
1559 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001560 ServiceRecord s = res.record;
1561
Svet Ganov9c165d72015-12-01 19:52:26 -08001562 boolean permissionsReviewRequired = false;
1563
1564 // If permissions need a review before any of the app components can run,
1565 // we schedule binding to the service but do not start its process, then
1566 // we launch a review activity to which is passed a callback to invoke
1567 // when done to start the bound service's process to completing the binding.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001568 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
1569 s.packageName, s.userId)) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001570
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001571 permissionsReviewRequired = true;
Svet Ganov9c165d72015-12-01 19:52:26 -08001572
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001573 // Show a permission review UI only for binding from a foreground app
1574 if (!callerFg) {
1575 Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
1576 + s.packageName + " requires a permissions review");
1577 return 0;
1578 }
Svet Ganov9c165d72015-12-01 19:52:26 -08001579
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001580 final ServiceRecord serviceRecord = s;
1581 final Intent serviceIntent = service;
Svet Ganov9c165d72015-12-01 19:52:26 -08001582
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001583 RemoteCallback callback = new RemoteCallback(
1584 new RemoteCallback.OnResultListener() {
1585 @Override
1586 public void onResult(Bundle result) {
1587 synchronized(mAm) {
1588 final long identity = Binder.clearCallingIdentity();
1589 try {
1590 if (!mPendingServices.contains(serviceRecord)) {
1591 return;
Svet Ganov9c165d72015-12-01 19:52:26 -08001592 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001593 // If there is still a pending record, then the service
1594 // binding request is still valid, so hook them up. We
1595 // proceed only if the caller cleared the review requirement
1596 // otherwise we unbind because the user didn't approve.
1597 if (!mAm.getPackageManagerInternalLocked()
1598 .isPermissionsReviewRequired(
1599 serviceRecord.packageName,
1600 serviceRecord.userId)) {
1601 try {
1602 bringUpServiceLocked(serviceRecord,
1603 serviceIntent.getFlags(),
1604 callerFg, false, false);
1605 } catch (RemoteException e) {
1606 /* ignore - local call */
1607 }
1608 } else {
1609 unbindServiceLocked(connection);
1610 }
1611 } finally {
1612 Binder.restoreCallingIdentity(identity);
Svet Ganov9c165d72015-12-01 19:52:26 -08001613 }
1614 }
Svet Ganov9c165d72015-12-01 19:52:26 -08001615 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001616 });
Svet Ganov9c165d72015-12-01 19:52:26 -08001617
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001618 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
1619 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1620 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1621 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
1622 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
1623
1624 if (DEBUG_PERMISSIONS_REVIEW) {
1625 Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
1626 + s.packageName);
Svet Ganov9c165d72015-12-01 19:52:26 -08001627 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001628
1629 mAm.mHandler.post(new Runnable() {
1630 @Override
1631 public void run() {
1632 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
1633 }
1634 });
Svet Ganov9c165d72015-12-01 19:52:26 -08001635 }
1636
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001637 final long origId = Binder.clearCallingIdentity();
1638
1639 try {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001640 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001641 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001642 + s);
1643 }
1644
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001645 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1646 s.lastActivity = SystemClock.uptimeMillis();
1647 if (!s.hasAutoCreateConnections()) {
1648 // This is the first binding, let the tracker know.
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001649 ServiceState stracker = s.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001650 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001651 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001652 s.lastActivity);
1653 }
1654 }
1655 }
1656
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001657 mAm.startAssociationLocked(callerApp.uid, callerApp.processName,
1658 callerApp.getCurProcState(), s.appInfo.uid, s.appInfo.longVersionCode,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001659 s.instanceName, s.processName);
Jesse Evans02af3ea2017-05-03 09:57:16 -07001660 // Once the apps have become associated, if one of them is caller is ephemeral
1661 // the target app should now be able to see the calling app
1662 mAm.grantEphemeralAccessLocked(callerApp.userId, service,
Hai Zhangbb23d532018-08-27 16:00:35 -07001663 UserHandle.getAppId(s.appInfo.uid), UserHandle.getAppId(callerApp.uid));
Dianne Hackbornab2df062015-01-07 13:43:13 -08001664
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001665 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
1666 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001667 connection, flags, clientLabel, clientIntent,
1668 callerApp.uid, callerApp.processName);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001669
1670 IBinder binder = connection.asBinder();
1671 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
1672 if (clist == null) {
1673 clist = new ArrayList<ConnectionRecord>();
1674 s.connections.put(binder, clist);
1675 }
1676 clist.add(c);
1677 b.connections.add(c);
1678 if (activity != null) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001679 activity.addConnection(c);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001680 }
1681 b.client.connections.add(c);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001682 c.startAssociationIfNeeded();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001683 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
1684 b.client.hasAboveClient = true;
1685 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001686 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
1687 s.whitelistManager = true;
1688 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001689 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001690 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07001691 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001692 clist = mServiceConnections.get(binder);
1693 if (clist == null) {
1694 clist = new ArrayList<ConnectionRecord>();
1695 mServiceConnections.put(binder, clist);
1696 }
1697 clist.add(c);
1698
1699 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1700 s.lastActivity = SystemClock.uptimeMillis();
Svet Ganov9c165d72015-12-01 19:52:26 -08001701 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
1702 permissionsReviewRequired) != null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001703 return 0;
1704 }
1705 }
1706
1707 if (s.app != null) {
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001708 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1709 s.app.treatLikeActivity = true;
1710 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001711 if (s.whitelistManager) {
1712 s.app.whitelistManager = true;
1713 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001714 // This could have made the service more important.
Dianne Hackborna631d562018-11-20 15:58:15 -08001715 mAm.updateLruProcessLocked(s.app,
1716 (callerApp.hasActivitiesOrRecentTasks() && s.app.hasClientActivities())
1717 || (callerApp.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP
1718 && (flags & Context.BIND_TREAT_LIKE_ACTIVITY) != 0),
1719 b.client);
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001720 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001721 }
1722
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001723 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001724 + ": received=" + b.intent.received
1725 + " apps=" + b.intent.apps.size()
1726 + " doRebind=" + b.intent.doRebind);
1727
1728 if (s.app != null && b.intent.received) {
1729 // Service is already running, so we can immediately
1730 // publish the connection.
1731 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001732 c.conn.connected(s.name, b.intent.binder, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001733 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001734 Slog.w(TAG, "Failure sending service " + s.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001735 + " to connection " + c.conn.asBinder()
1736 + " (in " + c.binding.client.processName + ")", e);
1737 }
1738
1739 // If this is the first app connected back to this binding,
1740 // and the service had previously asked to be told when
1741 // rebound, then do so.
1742 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001743 requestServiceBindingLocked(s, b.intent, callerFg, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001744 }
1745 } else if (!b.intent.requested) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001746 requestServiceBindingLocked(s, b.intent, callerFg, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001747 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001748
Dianne Hackbornad51be92016-08-16 16:27:36 -07001749 getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001750
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001751 } finally {
1752 Binder.restoreCallingIdentity(origId);
1753 }
1754
1755 return 1;
1756 }
1757
1758 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
1759 final long origId = Binder.clearCallingIdentity();
1760 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001761 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001762 + " " + intent + ": " + service);
1763 if (r != null) {
1764 Intent.FilterComparison filter
1765 = new Intent.FilterComparison(intent);
1766 IntentBindRecord b = r.bindings.get(filter);
1767 if (b != null && !b.received) {
1768 b.binder = service;
1769 b.requested = true;
1770 b.received = true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07001771 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1772 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
1773 for (int i=0; i<clist.size(); i++) {
1774 ConnectionRecord c = clist.get(i);
1775 if (!filter.equals(c.binding.intent.intent)) {
1776 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001777 TAG_SERVICE, "Not publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001778 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001779 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001780 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001781 TAG_SERVICE, "Published intent: " + intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001782 continue;
1783 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001784 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001785 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001786 c.conn.connected(r.name, service, false);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001787 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001788 Slog.w(TAG, "Failure sending service " + r.shortInstanceName
1789 + " to connection " + c.conn.asBinder()
1790 + " (in " + c.binding.client.processName + ")", e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001791 }
1792 }
1793 }
1794 }
1795
Dianne Hackborn164371f2013-10-01 19:10:13 -07001796 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001797 }
1798 } finally {
1799 Binder.restoreCallingIdentity(origId);
1800 }
1801 }
1802
Dianne Hackborna631d562018-11-20 15:58:15 -08001803 void updateServiceGroupLocked(IServiceConnection connection, int group, int importance) {
1804 final IBinder binder = connection.asBinder();
1805 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "updateServiceGroup: conn=" + binder);
1806 final ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1807 if (clist == null) {
1808 throw new IllegalArgumentException("Could not find connection for "
1809 + connection.asBinder());
1810 }
1811 for (int i = clist.size() - 1; i >= 0; i--) {
1812 final ConnectionRecord crec = clist.get(i);
1813 final ServiceRecord srec = crec.binding.service;
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08001814 if (srec != null && (srec.serviceInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) != 0) {
1815 if (srec.app != null) {
1816 if (group > 0) {
1817 srec.app.connectionService = srec;
1818 srec.app.connectionGroup = group;
1819 srec.app.connectionImportance = importance;
1820 } else {
1821 srec.app.connectionService = null;
1822 srec.app.connectionGroup = 0;
1823 srec.app.connectionImportance = 0;
1824 }
Dianne Hackborna631d562018-11-20 15:58:15 -08001825 } else {
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08001826 if (group > 0) {
1827 srec.pendingConnectionGroup = group;
1828 srec.pendingConnectionImportance = importance;
1829 } else {
1830 srec.pendingConnectionGroup = 0;
1831 srec.pendingConnectionImportance = 0;
1832 }
Dianne Hackborna631d562018-11-20 15:58:15 -08001833 }
1834 }
1835 }
1836 }
1837
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001838 boolean unbindServiceLocked(IServiceConnection connection) {
1839 IBinder binder = connection.asBinder();
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001840 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001841 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1842 if (clist == null) {
1843 Slog.w(TAG, "Unbind failed: could not find connection for "
1844 + connection.asBinder());
1845 return false;
1846 }
1847
1848 final long origId = Binder.clearCallingIdentity();
1849 try {
1850 while (clist.size() > 0) {
1851 ConnectionRecord r = clist.get(0);
1852 removeConnectionLocked(r, null, null);
Dianne Hackborn25e1eca2014-09-23 10:13:13 -07001853 if (clist.size() > 0 && clist.get(0) == r) {
1854 // In case it didn't get removed above, do it now.
1855 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
1856 clist.remove(0);
1857 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001858
1859 if (r.binding.service.app != null) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001860 if (r.binding.service.app.whitelistManager) {
Felipe Lemea7778b02016-06-28 10:38:59 -07001861 updateWhitelistManagerLocked(r.binding.service.app);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001862 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001863 // This could have made the service less important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001864 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1865 r.binding.service.app.treatLikeActivity = true;
1866 mAm.updateLruProcessLocked(r.binding.service.app,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001867 r.binding.service.app.hasClientActivities()
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001868 || r.binding.service.app.treatLikeActivity, null);
1869 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001870 mAm.updateOomAdjLocked(r.binding.service.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001871 }
1872 }
Amith Yamasanib2926b12017-05-11 11:13:52 -07001873
1874 mAm.updateOomAdjLocked();
1875
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001876 } finally {
1877 Binder.restoreCallingIdentity(origId);
1878 }
1879
1880 return true;
1881 }
1882
1883 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
1884 final long origId = Binder.clearCallingIdentity();
1885 try {
1886 if (r != null) {
1887 Intent.FilterComparison filter
1888 = new Intent.FilterComparison(intent);
1889 IntentBindRecord b = r.bindings.get(filter);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001890 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001891 + " at " + b + ": apps="
1892 + (b != null ? b.apps.size() : 0));
1893
Dianne Hackborn164371f2013-10-01 19:10:13 -07001894 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001895 if (b != null) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001896 if (b.apps.size() > 0 && !inDestroying) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001897 // Applications have already bound since the last
1898 // unbind, so just rebind right here.
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001899 boolean inFg = false;
1900 for (int i=b.apps.size()-1; i>=0; i--) {
1901 ProcessRecord client = b.apps.valueAt(i).client;
1902 if (client != null && client.setSchedGroup
Dianne Hackborna49ad092016-03-03 13:39:10 -08001903 != ProcessList.SCHED_GROUP_BACKGROUND) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001904 inFg = true;
1905 break;
1906 }
1907 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001908 try {
1909 requestServiceBindingLocked(r, b, inFg, true);
1910 } catch (TransactionTooLargeException e) {
1911 // Don't pass this back to ActivityThread, it's unrelated.
1912 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001913 } else {
1914 // Note to tell the service the next time there is
1915 // a new client.
1916 b.doRebind = true;
1917 }
1918 }
1919
Dianne Hackborn164371f2013-10-01 19:10:13 -07001920 serviceDoneExecutingLocked(r, inDestroying, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001921 }
1922 } finally {
1923 Binder.restoreCallingIdentity(origId);
1924 }
1925 }
1926
1927 private final ServiceRecord findServiceLocked(ComponentName name,
Dianne Hackborn41203752012-08-31 14:05:51 -07001928 IBinder token, int userId) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07001929 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001930 return r == token ? r : null;
1931 }
1932
1933 private final class ServiceLookupResult {
1934 final ServiceRecord record;
1935 final String permission;
1936
1937 ServiceLookupResult(ServiceRecord _record, String _permission) {
1938 record = _record;
1939 permission = _permission;
1940 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001941 }
1942
1943 private class ServiceRestarter implements Runnable {
1944 private ServiceRecord mService;
1945
1946 void setService(ServiceRecord service) {
1947 mService = service;
1948 }
1949
1950 public void run() {
1951 synchronized(mAm) {
1952 performServiceRestartLocked(mService);
1953 }
1954 }
1955 }
1956
1957 private ServiceLookupResult retrieveServiceLocked(Intent service,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001958 String instanceName, String resolvedType, String callingPackage,
1959 int callingPid, int callingUid, int userId,
Svet Ganovd223db32017-12-22 09:43:48 -08001960 boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
1961 boolean allowInstant) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001962 ServiceRecord r = null;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001963 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001964 + " type=" + resolvedType + " callingUid=" + callingUid);
1965
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001966 userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001967 ActivityManagerInternal.ALLOW_NON_FULL_IN_PROFILE, "service", null);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001968
Dianne Hackbornad51be92016-08-16 16:27:36 -07001969 ServiceMap smap = getServiceMapLocked(userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001970 final ComponentName comp;
1971 if (instanceName == null) {
1972 comp = service.getComponent();
1973 } else {
1974 final ComponentName realComp = service.getComponent();
1975 if (realComp == null) {
1976 throw new IllegalArgumentException("Can't use custom instance name '" + instanceName
1977 + "' without expicit component in Intent");
1978 }
1979 comp = new ComponentName(realComp.getPackageName(),
1980 realComp.getClassName() + ":" + instanceName);
1981 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001982 if (comp != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001983 r = smap.mServicesByInstanceName.get(comp);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001984 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001985 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001986 if (r == null && !isBindExternal && instanceName == null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001987 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001988 r = smap.mServicesByIntent.get(filter);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001989 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001990 }
Robert Sesekb9a86662015-12-09 16:22:45 -05001991 if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
1992 && !callingPackage.equals(r.packageName)) {
1993 // If an external service is running within its own package, other packages
1994 // should not bind to that instance.
1995 r = null;
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001996 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Whoops, can't use existing external service");
Robert Sesekb9a86662015-12-09 16:22:45 -05001997 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001998 if (r == null) {
1999 try {
Svet Ganovd223db32017-12-22 09:43:48 -08002000 int flags = ActivityManagerService.STOCK_PM_FLAGS
2001 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
2002 if (allowInstant) {
2003 flags |= PackageManager.MATCH_INSTANT;
2004 }
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002005 // TODO: come back and remove this assumption to triage all services
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002006 ResolveInfo rInfo = mAm.getPackageManagerInternalLocked().resolveService(service,
Svet Ganovd223db32017-12-22 09:43:48 -08002007 resolvedType, flags, userId, callingUid);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002008 ServiceInfo sInfo = rInfo != null ? rInfo.serviceInfo : null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002009 if (sInfo == null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002010 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002011 ": not found");
2012 return null;
2013 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002014 if (instanceName != null
2015 && (sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
2016 throw new IllegalArgumentException("Can't use instance name '" + instanceName
2017 + "' with non-isolated service '" + sInfo.name + "'");
2018 }
2019 ComponentName className = new ComponentName(
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002020 sInfo.applicationInfo.packageName, sInfo.name);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002021 ComponentName name = comp != null ? comp : className;
Robert Sesekb9a86662015-12-09 16:22:45 -05002022 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
2023 if (isBindExternal) {
2024 if (!sInfo.exported) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002025 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
2026 + className + " is not exported");
Robert Sesekb9a86662015-12-09 16:22:45 -05002027 }
2028 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002029 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
2030 + className + " is not an isolatedProcess");
Robert Sesekb9a86662015-12-09 16:22:45 -05002031 }
2032 // Run the service under the calling package's application.
2033 ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
2034 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
2035 if (aInfo == null) {
2036 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
2037 "could not resolve client package " + callingPackage);
2038 }
2039 sInfo = new ServiceInfo(sInfo);
2040 sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
2041 sInfo.applicationInfo.packageName = aInfo.packageName;
2042 sInfo.applicationInfo.uid = aInfo.uid;
2043 name = new ComponentName(aInfo.packageName, name.getClassName());
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002044 className = new ComponentName(aInfo.packageName,
2045 instanceName == null ? className.getClassName()
2046 : (className.getClassName() + ":" + instanceName));
Robert Sesekb9a86662015-12-09 16:22:45 -05002047 service.setComponent(name);
2048 } else {
2049 throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
2050 name);
2051 }
2052 } else if (isBindExternal) {
2053 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
2054 " is not an externalService");
2055 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002056 if (userId > 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07002057 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
Amith Yamasani4b9d79c2014-05-21 19:14:21 -07002058 sInfo.name, sInfo.flags)
2059 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002060 userId = 0;
Dianne Hackbornad51be92016-08-16 16:27:36 -07002061 smap = getServiceMapLocked(0);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002062 }
2063 sInfo = new ServiceInfo(sInfo);
2064 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
2065 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002066 r = smap.mServicesByInstanceName.get(name);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002067 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE,
2068 "Retrieved via pm by intent: " + r);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002069 if (r == null && createIfNeeded) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002070 final Intent.FilterComparison filter
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002071 = new Intent.FilterComparison(service.cloneFilter());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002072 final ServiceRestarter res = new ServiceRestarter();
2073 final BatteryStatsImpl.Uid.Pkg.Serv ss;
2074 final BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002075 synchronized (stats) {
2076 ss = stats.getServiceStatsLocked(
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002077 sInfo.applicationInfo.uid, name.getPackageName(),
2078 name.getClassName());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002079 }
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08002080 r = new ServiceRecord(mAm, ss, className, name, filter, sInfo,
2081 callingFromFg, res);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002082 res.setService(r);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002083 smap.mServicesByInstanceName.put(name, r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002084 smap.mServicesByIntent.put(filter, r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002085
2086 // Make sure this component isn't in the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002087 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002088 final ServiceRecord pr = mPendingServices.get(i);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002089 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002090 && pr.instanceName.equals(name)) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002091 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002092 mPendingServices.remove(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002093 }
2094 }
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002095 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002096 }
2097 } catch (RemoteException ex) {
2098 // pm is in same process, this will never happen.
2099 }
2100 }
2101 if (r != null) {
2102 if (mAm.checkComponentPermission(r.permission,
Bryce Lee290e5782017-02-01 16:41:20 -08002103 callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002104 if (!r.exported) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002105 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002106 + " from pid=" + callingPid
2107 + ", uid=" + callingUid
2108 + " that is not exported from uid " + r.appInfo.uid);
2109 return new ServiceLookupResult(null, "not exported from uid "
2110 + r.appInfo.uid);
2111 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002112 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002113 + " from pid=" + callingPid
2114 + ", uid=" + callingUid
2115 + " requires " + r.permission);
2116 return new ServiceLookupResult(null, r.permission);
Svet Ganov99b60432015-06-27 13:15:22 -07002117 } else if (r.permission != null && callingPackage != null) {
2118 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
2119 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation(
2120 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002121 Slog.w(TAG, "Appop Denial: Accessing service " + r.shortInstanceName
Svet Ganov99b60432015-06-27 13:15:22 -07002122 + " from pid=" + callingPid
2123 + ", uid=" + callingUid
2124 + " requires appop " + AppOpsManager.opToName(opCode));
2125 return null;
2126 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002127 }
Svet Ganov99b60432015-06-27 13:15:22 -07002128
Ben Gruverf5323fe2013-07-31 15:09:51 -07002129 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
2130 resolvedType, r.appInfo)) {
Ben Gruverb6223792013-07-29 16:35:40 -07002131 return null;
2132 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002133 return new ServiceLookupResult(r, null);
2134 }
2135 return null;
2136 }
2137
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002138 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002139 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002140 + why + " of " + r + " in app " + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002141 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002142 + why + " of " + r.shortInstanceName);
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002143
2144 // For b/34123235: Services within the system server won't start until SystemServer
2145 // does Looper.loop(), so we shouldn't try to start/bind to them too early in the boot
2146 // process. However, since there's a little point of showing the ANR dialog in that case,
2147 // let's suppress the timeout until PHASE_THIRD_PARTY_APPS_CAN_START.
2148 //
2149 // (Note there are multiple services start at PHASE_THIRD_PARTY_APPS_CAN_START too,
2150 // which technically could also trigger this timeout if there's a system server
2151 // that takes a long time to handle PHASE_THIRD_PARTY_APPS_CAN_START, but that shouldn't
2152 // happen.)
2153 boolean timeoutNeeded = true;
2154 if ((mAm.mBootPhase < SystemService.PHASE_THIRD_PARTY_APPS_CAN_START)
2155 && (r.app != null) && (r.app.pid == android.os.Process.myPid())) {
2156
2157 Slog.w(TAG, "Too early to start/bind service in system_server: Phase=" + mAm.mBootPhase
2158 + " " + r.getComponentName());
2159 timeoutNeeded = false;
2160 }
2161
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002162 long now = SystemClock.uptimeMillis();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002163 if (r.executeNesting == 0) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002164 r.executeFg = fg;
Joe Onorato4eb64fd2016-03-21 15:30:09 -07002165 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002166 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002167 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002168 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002169 if (r.app != null) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002170 r.app.executingServices.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002171 r.app.execServicesFg |= fg;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002172 if (timeoutNeeded && r.app.executingServices.size() == 1) {
Dianne Hackborn2be00932013-09-22 16:46:00 -07002173 scheduleServiceTimeoutLocked(r.app);
2174 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002175 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002176 } else if (r.app != null && fg && !r.app.execServicesFg) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002177 r.app.execServicesFg = true;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002178 if (timeoutNeeded) {
2179 scheduleServiceTimeoutLocked(r.app);
2180 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002181 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002182 r.executeFg |= fg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002183 r.executeNesting++;
2184 r.executingStart = now;
2185 }
2186
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002187 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
2188 boolean execInFg, boolean rebind) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002189 if (r.app == null || r.app.thread == null) {
2190 // If service is not currently running, can't yet bind.
2191 return false;
2192 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08002193 if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
2194 + " rebind=" + rebind);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002195 if ((!i.requested || rebind) && i.apps.size() > 0) {
2196 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002197 bumpServiceExecutingLocked(r, execInFg, "bind");
Dianne Hackborna413dc02013-07-12 12:02:55 -07002198 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
2199 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002200 r.app.getReportedProcState());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002201 if (!rebind) {
2202 i.requested = true;
2203 }
2204 i.hasBound = true;
2205 i.doRebind = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002206 } catch (TransactionTooLargeException e) {
2207 // Keep the executeNesting count accurate.
2208 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
2209 final boolean inDestroying = mDestroyingServices.contains(r);
2210 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2211 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002212 } catch (RemoteException e) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002213 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002214 // Keep the executeNesting count accurate.
2215 final boolean inDestroying = mDestroyingServices.contains(r);
2216 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002217 return false;
2218 }
2219 }
2220 return true;
2221 }
2222
Dianne Hackbornad51be92016-08-16 16:27:36 -07002223 private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002224 boolean canceled = false;
2225
Wale Ogunwalef6733932018-06-27 05:14:34 -07002226 if (mAm.mAtmInternal.isShuttingDown()) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002227 Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortInstanceName
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07002228 + " - system is shutting down");
2229 return false;
2230 }
2231
Dianne Hackbornad51be92016-08-16 16:27:36 -07002232 ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002233 if (smap.mServicesByInstanceName.get(r.instanceName) != r) {
2234 ServiceRecord cur = smap.mServicesByInstanceName.get(r.instanceName);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002235 Slog.wtf(TAG, "Attempting to schedule restart of " + r
2236 + " when found in map: " + cur);
2237 return false;
2238 }
2239
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002240 final long now = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002241
2242 if ((r.serviceInfo.applicationInfo.flags
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002243 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002244 long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION;
2245 long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002246
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002247 // Any delivered but not yet finished starts should be put back
2248 // on the pending list.
2249 final int N = r.deliveredStarts.size();
2250 if (N > 0) {
2251 for (int i=N-1; i>=0; i--) {
2252 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
2253 si.removeUriPermissionsLocked();
2254 if (si.intent == null) {
2255 // We'll generate this again if needed.
2256 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
2257 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
2258 r.pendingStarts.add(0, si);
2259 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
2260 dur *= 2;
2261 if (minDuration < dur) minDuration = dur;
2262 if (resetTime < dur) resetTime = dur;
2263 } else {
2264 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002265 + r.shortInstanceName);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002266 canceled = true;
2267 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002268 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002269 r.deliveredStarts.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002270 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002271
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002272 r.totalRestartCount++;
2273 if (r.restartDelay == 0) {
2274 r.restartCount++;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002275 r.restartDelay = minDuration;
Amith Yamasanib0c8a882017-08-28 09:36:42 -07002276 } else if (r.crashCount > 1) {
2277 r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
2278 * (r.crashCount - 1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002279 } else {
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002280 // If it has been a "reasonably long time" since the service
2281 // was started, then reset our restart duration back to
2282 // the beginning, so we don't infinitely increase the duration
2283 // on a service that just occasionally gets killed (which is
2284 // a normal case, due to process being killed to reclaim memory).
2285 if (now > (r.restartTime+resetTime)) {
2286 r.restartCount = 1;
2287 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002288 } else {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002289 r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
Dianne Hackborn7b492722013-11-01 09:58:45 -07002290 if (r.restartDelay < minDuration) {
2291 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002292 }
2293 }
2294 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002295
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002296 r.nextRestartTime = now + r.restartDelay;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002297
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002298 // Make sure that we don't end up restarting a bunch of services
2299 // all at the same time.
2300 boolean repeat;
2301 do {
2302 repeat = false;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002303 final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002304 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2305 ServiceRecord r2 = mRestartingServices.get(i);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002306 if (r2 != r && r.nextRestartTime >= (r2.nextRestartTime-restartTimeBetween)
2307 && r.nextRestartTime < (r2.nextRestartTime+restartTimeBetween)) {
2308 r.nextRestartTime = r2.nextRestartTime + restartTimeBetween;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002309 r.restartDelay = r.nextRestartTime - now;
2310 repeat = true;
2311 break;
2312 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002313 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002314 } while (repeat);
2315
2316 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07002317 // Persistent processes are immediately restarted, so there is no
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002318 // reason to hold of on restarting their services.
2319 r.totalRestartCount++;
2320 r.restartCount = 0;
2321 r.restartDelay = 0;
2322 r.nextRestartTime = now;
2323 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002324
2325 if (!mRestartingServices.contains(r)) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002326 r.createdFromFg = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002327 mRestartingServices.add(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002328 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002329 }
2330
Christopher Tate08992ac2017-03-21 11:37:06 -07002331 cancelForegroundNotificationLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002332
2333 mAm.mHandler.removeCallbacks(r.restarter);
2334 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
2335 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
2336 Slog.w(TAG, "Scheduling restart of crashed service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002337 + r.shortInstanceName + " in " + r.restartDelay + "ms");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002338 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002339 r.userId, r.shortInstanceName, r.restartDelay);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002340
2341 return canceled;
2342 }
2343
2344 final void performServiceRestartLocked(ServiceRecord r) {
2345 if (!mRestartingServices.contains(r)) {
2346 return;
2347 }
Dianne Hackbornad51be92016-08-16 16:27:36 -07002348 if (!isServiceNeededLocked(r, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002349 // Paranoia: is this service actually needed? In theory a service that is not
2350 // needed should never remain on the restart list. In practice... well, there
2351 // have been bugs where this happens, and bad things happen because the process
2352 // ends up just being cached, so quickly killed, then restarted again and again.
2353 // Let's not let that happen.
2354 Slog.wtf(TAG, "Restarting service that is not needed: " + r);
2355 return;
2356 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002357 try {
Svet Ganov9c165d72015-12-01 19:52:26 -08002358 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002359 } catch (TransactionTooLargeException e) {
2360 // Ignore, it's been logged and nothing upstack cares.
2361 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002362 }
2363
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002364 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
2365 boolean force) {
2366 if (!force && r.restartDelay == 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002367 return false;
2368 }
Dianne Hackborn7b492722013-11-01 09:58:45 -07002369 // Remove from the restarting list; if the service is currently on the
2370 // restarting list, or the call is coming from another app, then this
2371 // service has become of much more interest so we reset the restart interval.
2372 boolean removed = mRestartingServices.remove(r);
2373 if (removed || callingUid != r.appInfo.uid) {
2374 r.resetRestartCounter();
2375 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002376 if (removed) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002377 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002378 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002379 mAm.mHandler.removeCallbacks(r.restarter);
2380 return true;
2381 }
2382
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002383 private void clearRestartingIfNeededLocked(ServiceRecord r) {
2384 if (r.restartTracker != null) {
2385 // If this is the last restarting record with this tracker, then clear
2386 // the tracker's restarting state.
2387 boolean stillTracking = false;
2388 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2389 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
2390 stillTracking = true;
2391 break;
2392 }
2393 }
2394 if (!stillTracking) {
2395 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
2396 SystemClock.uptimeMillis());
2397 r.restartTracker = null;
2398 }
2399 }
2400 }
2401
Svet Ganov9c165d72015-12-01 19:52:26 -08002402 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
2403 boolean whileRestarting, boolean permissionsReviewRequired)
2404 throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002405 //Slog.i(TAG, "Bring up service:");
2406 //r.dump(" ");
2407
2408 if (r.app != null && r.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002409 sendServiceArgsLocked(r, execInFg, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002410 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002411 }
2412
Sudheer Shanka03d0f812017-04-20 16:57:50 -07002413 if (!whileRestarting && mRestartingServices.contains(r)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002414 // If waiting for a restart, then do nothing.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002415 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002416 }
2417
Christopher Tate08992ac2017-03-21 11:37:06 -07002418 if (DEBUG_SERVICE) {
2419 Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
2420 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002421
2422 // We are now bringing the service up, so no longer in the
2423 // restarting state.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002424 if (mRestartingServices.remove(r)) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002425 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002426 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002427
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002428 // Make sure this service is no longer considered delayed, we are starting it now.
2429 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002430 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002431 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002432 r.delayed = false;
2433 }
2434
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002435 // Make sure that the user who owns this service is started. If not,
2436 // we don't want to allow it to run.
Fyodor Kupolov610acda2015-10-19 18:44:07 -07002437 if (!mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002438 String msg = "Unable to launch app "
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002439 + r.appInfo.packageName + "/"
2440 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002441 + r.intent.getIntent() + ": user " + r.userId + " is stopped";
2442 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002443 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002444 return msg;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002445 }
2446
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002447 // Service is now being launched, its package can't be stopped.
2448 try {
2449 AppGlobals.getPackageManager().setPackageStoppedState(
2450 r.packageName, false, r.userId);
2451 } catch (RemoteException e) {
2452 } catch (IllegalArgumentException e) {
2453 Slog.w(TAG, "Failed trying to unstop package "
2454 + r.packageName + ": " + e);
2455 }
2456
2457 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
2458 final String procName = r.processName;
Robert Sesekc5f86642016-11-04 10:20:38 -04002459 String hostingType = "service";
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002460 ProcessRecord app;
2461
2462 if (!isolated) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07002463 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
2464 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
2465 + " app=" + app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002466 if (app != null && app.thread != null) {
2467 try {
Patrick Baumannc2def582018-04-04 12:14:15 -07002468 app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode, mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002469 realStartServiceLocked(r, app, execInFg);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002470 return null;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002471 } catch (TransactionTooLargeException e) {
2472 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002473 } catch (RemoteException e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002474 Slog.w(TAG, "Exception when starting service " + r.shortInstanceName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002475 }
2476
2477 // If a dead object exception was thrown -- fall through to
2478 // restart the application.
2479 }
2480 } else {
2481 // If this service runs in an isolated process, then each time
2482 // we call startProcessLocked() we will get a new isolated
2483 // process, starting another process if we are currently waiting
2484 // for a previous process to come up. To deal with this, we store
2485 // in the service any current isolated process it is running in or
2486 // waiting to have come up.
2487 app = r.isolatedProc;
Robert Sesekc5f86642016-11-04 10:20:38 -04002488 if (WebViewZygote.isMultiprocessEnabled()
2489 && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
2490 hostingType = "webview_service";
2491 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002492 }
2493
2494 // Not running -- get it started, and enqueue this service record
2495 // to be executed when the app comes up.
Svet Ganov9c165d72015-12-01 19:52:26 -08002496 if (app == null && !permissionsReviewRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002497 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002498 hostingType, r.instanceName, false, isolated, false)) == null) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002499 String msg = "Unable to launch app "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002500 + r.appInfo.packageName + "/"
2501 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002502 + r.intent.getIntent() + ": process is bad";
2503 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002504 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002505 return msg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002506 }
2507 if (isolated) {
2508 r.isolatedProc = app;
2509 }
2510 }
2511
Christopher Tate1536cc22017-09-18 16:43:30 -07002512 if (r.fgRequired) {
2513 if (DEBUG_FOREGROUND_SERVICE) {
2514 Slog.v(TAG, "Whitelisting " + UserHandle.formatUid(r.appInfo.uid)
2515 + " for fg-service launch");
2516 }
2517 mAm.tempWhitelistUidLocked(r.appInfo.uid,
2518 SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch");
2519 }
2520
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002521 if (!mPendingServices.contains(r)) {
2522 mPendingServices.add(r);
2523 }
2524
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002525 if (r.delayedStop) {
2526 // Oh and hey we've already been asked to stop!
2527 r.delayedStop = false;
2528 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002529 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2530 "Applying delayed stop (in bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002531 stopServiceLocked(r);
2532 }
2533 }
2534
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002535 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002536 }
2537
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002538 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
2539 throws TransactionTooLargeException {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002540 for (int i=r.bindings.size()-1; i>=0; i--) {
2541 IntentBindRecord ibr = r.bindings.valueAt(i);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002542 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002543 break;
2544 }
2545 }
2546 }
2547
2548 private final void realStartServiceLocked(ServiceRecord r,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002549 ProcessRecord app, boolean execInFg) throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002550 if (app.thread == null) {
2551 throw new RemoteException();
2552 }
2553 if (DEBUG_MU)
2554 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
2555 + ", ProcessRecord.uid = " + app.uid);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002556 r.setProcess(app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002557 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
2558
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002559 final boolean newService = app.services.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002560 bumpServiceExecutingLocked(r, execInFg, "create");
Dianne Hackborndb926082013-10-31 16:32:44 -07002561 mAm.updateLruProcessLocked(app, false, null);
Makoto Onuki0f421292017-04-28 15:03:33 -07002562 updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
2563 mAm.updateOomAdjLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002564
2565 boolean created = false;
2566 try {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002567 if (LOG_SERVICE_START_STOP) {
Dianne Hackbornab2df062015-01-07 13:43:13 -08002568 String nameTerm;
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002569 int lastPeriod = r.shortInstanceName.lastIndexOf('.');
2570 nameTerm = lastPeriod >= 0 ? r.shortInstanceName.substring(lastPeriod)
2571 : r.shortInstanceName;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002572 EventLogTags.writeAmCreateService(
2573 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
2574 }
Chenjie Yu75b3c492018-10-06 21:45:19 -07002575 StatsLog.write(StatsLog.SERVICE_LAUNCH_REPORTED, r.appInfo.uid, r.name.getPackageName(),
2576 r.name.getClassName());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002577 synchronized (r.stats.getBatteryStats()) {
2578 r.stats.startLaunchedLocked();
2579 }
Brian Carlstromca82e612016-04-19 23:16:08 -07002580 mAm.notifyPackageUse(r.serviceInfo.packageName,
2581 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
Dianne Hackborna413dc02013-07-12 12:02:55 -07002582 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002583 app.thread.scheduleCreateService(r, r.serviceInfo,
Wale Ogunwale53783742018-09-16 10:21:51 -07002584 mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002585 app.getReportedProcState());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002586 r.postNotification();
2587 created = true;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -07002588 } catch (DeadObjectException e) {
2589 Slog.w(TAG, "Application dead when creating service " + r);
2590 mAm.appDiedLocked(app);
Wale Ogunwalebfac4682015-04-08 14:33:21 -07002591 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002592 } finally {
2593 if (!created) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002594 // Keep the executeNesting count accurate.
2595 final boolean inDestroying = mDestroyingServices.contains(r);
2596 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2597
2598 // Cleanup.
2599 if (newService) {
2600 app.services.remove(r);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002601 r.setProcess(null);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002602 }
2603
2604 // Retry.
2605 if (!inDestroying) {
2606 scheduleServiceRestartLocked(r, false);
2607 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002608 }
2609 }
2610
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002611 if (r.whitelistManager) {
2612 app.whitelistManager = true;
2613 }
2614
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002615 requestServiceBindingsLocked(r, execInFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002616
Dianne Hackborn465fa392014-09-14 14:21:18 -07002617 updateServiceClientActivitiesLocked(app, null, true);
2618
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002619 // If the service is in the started state, and there are no
2620 // pending arguments, then fake up one so its onStartCommand() will
2621 // be called.
2622 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
2623 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002624 null, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002625 }
2626
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002627 sendServiceArgsLocked(r, execInFg, true);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002628
2629 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002630 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002631 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002632 r.delayed = false;
2633 }
2634
2635 if (r.delayedStop) {
2636 // Oh and hey we've already been asked to stop!
2637 r.delayedStop = false;
2638 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002639 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2640 "Applying delayed stop (from start): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002641 stopServiceLocked(r);
2642 }
2643 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002644 }
2645
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002646 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002647 boolean oomAdjusted) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002648 final int N = r.pendingStarts.size();
2649 if (N == 0) {
2650 return;
2651 }
2652
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002653 ArrayList<ServiceStartArgs> args = new ArrayList<>();
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002654
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002655 while (r.pendingStarts.size() > 0) {
2656 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
2657 if (DEBUG_SERVICE) {
2658 Slog.v(TAG_SERVICE, "Sending arguments to: "
2659 + r + " " + r.intent + " args=" + si.intent);
2660 }
2661 if (si.intent == null && N > 1) {
2662 // If somehow we got a dummy null intent in the middle,
2663 // then skip it. DO NOT skip a null intent when it is
2664 // the only one in the list -- this is to support the
2665 // onStartCommand(null) case.
2666 continue;
2667 }
2668 si.deliveredTime = SystemClock.uptimeMillis();
2669 r.deliveredStarts.add(si);
2670 si.deliveryCount++;
2671 if (si.neededGrants != null) {
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07002672 mAm.mUgmInternal.grantUriPermissionUncheckedFromIntent(si.neededGrants,
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002673 si.getUriPermissionsLocked());
2674 }
Hai Zhangbb23d532018-08-27 16:00:35 -07002675 mAm.grantEphemeralAccessLocked(r.userId, si.intent, UserHandle.getAppId(r.appInfo.uid),
2676 UserHandle.getAppId(si.callingId));
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002677 bumpServiceExecutingLocked(r, execInFg, "start");
2678 if (!oomAdjusted) {
2679 oomAdjusted = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002680 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002681 }
2682 if (r.fgRequired && !r.fgWaiting) {
2683 if (!r.isForeground) {
2684 if (DEBUG_BACKGROUND_CHECK) {
2685 Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r);
2686 }
2687 scheduleServiceForegroundTransitionTimeoutLocked(r);
2688 } else {
2689 if (DEBUG_BACKGROUND_CHECK) {
2690 Slog.i(TAG, "Service already foreground; no new timeout: " + r);
2691 }
2692 r.fgRequired = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002693 }
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002694 }
2695 int flags = 0;
2696 if (si.deliveryCount > 1) {
2697 flags |= Service.START_FLAG_RETRY;
2698 }
2699 if (si.doneExecutingCount > 0) {
2700 flags |= Service.START_FLAG_REDELIVERY;
2701 }
2702 args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
2703 }
2704
2705 ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
2706 slice.setInlineCountLimit(4);
2707 Exception caughtException = null;
2708 try {
2709 r.app.thread.scheduleServiceArgs(r, slice);
2710 } catch (TransactionTooLargeException e) {
2711 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
2712 + " args, first: " + args.get(0).args);
2713 Slog.w(TAG, "Failed delivering service starts", e);
2714 caughtException = e;
2715 } catch (RemoteException e) {
2716 // Remote process gone... we'll let the normal cleanup take care of this.
2717 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
2718 Slog.w(TAG, "Failed delivering service starts", e);
2719 caughtException = e;
2720 } catch (Exception e) {
2721 Slog.w(TAG, "Unexpected exception", e);
2722 caughtException = e;
2723 }
2724
2725 if (caughtException != null) {
2726 // Keep nesting count correct
2727 final boolean inDestroying = mDestroyingServices.contains(r);
2728 for (int i = 0; i < args.size(); i++) {
2729 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2730 }
2731 if (caughtException instanceof TransactionTooLargeException) {
2732 throw (TransactionTooLargeException)caughtException;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002733 }
2734 }
2735 }
2736
Dianne Hackbornad51be92016-08-16 16:27:36 -07002737 private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn,
2738 boolean hasConn) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002739 // Are we still explicitly being asked to run?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002740 if (r.startRequested) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002741 return true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002742 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002743
Dianne Hackborncb015632017-06-14 17:30:15 -07002744 // Is someone still bound to us keeping us running?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002745 if (!knowConn) {
2746 hasConn = r.hasAutoCreateConnections();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002747 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002748 if (hasConn) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002749 return true;
2750 }
2751
2752 return false;
2753 }
2754
2755 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
2756 boolean hasConn) {
2757 //Slog.i(TAG, "Bring down service:");
2758 //r.dump(" ");
2759
Dianne Hackbornad51be92016-08-16 16:27:36 -07002760 if (isServiceNeededLocked(r, knowConn, hasConn)) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002761 return;
2762 }
2763
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002764 // Are we in the process of launching?
2765 if (mPendingServices.contains(r)) {
2766 return;
2767 }
2768
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002769 bringDownServiceLocked(r);
2770 }
2771
2772 private final void bringDownServiceLocked(ServiceRecord r) {
2773 //Slog.i(TAG, "Bring down service:");
2774 //r.dump(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002775
Dianne Hackborn390517b2013-05-30 15:03:32 -07002776 // Report to all of the connections that the service is no longer
2777 // available.
2778 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2779 ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
2780 for (int i=0; i<c.size(); i++) {
2781 ConnectionRecord cr = c.get(i);
2782 // There is still a connection to the service that is
2783 // being brought down. Mark it as dead.
2784 cr.serviceDead = true;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002785 cr.stopAssociation();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002786 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07002787 cr.conn.connected(r.name, null, true);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002788 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002789 Slog.w(TAG, "Failure disconnecting service " + r.shortInstanceName
2790 + " to connection " + c.get(i).conn.asBinder()
2791 + " (in " + c.get(i).binding.client.processName + ")", e);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002792 }
2793 }
2794 }
2795
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002796 // Tell the service that it has been unbound.
Dianne Hackborn390517b2013-05-30 15:03:32 -07002797 if (r.app != null && r.app.thread != null) {
2798 for (int i=r.bindings.size()-1; i>=0; i--) {
2799 IntentBindRecord ibr = r.bindings.valueAt(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002800 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002801 + ": hasBound=" + ibr.hasBound);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002802 if (ibr.hasBound) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002803 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002804 bumpServiceExecutingLocked(r, false, "bring down unbind");
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002805 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002806 ibr.hasBound = false;
Dianne Hackborn85e35642017-01-12 15:10:57 -08002807 ibr.requested = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002808 r.app.thread.scheduleUnbindService(r,
2809 ibr.intent.getIntent());
2810 } catch (Exception e) {
2811 Slog.w(TAG, "Exception when unbinding service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002812 + r.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002813 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002814 }
2815 }
2816 }
2817 }
2818
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002819 // Check to see if the service had been started as foreground, but being
2820 // brought down before actually showing a notification. That is not allowed.
2821 if (r.fgRequired) {
2822 Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
2823 + r);
2824 r.fgRequired = false;
2825 r.fgWaiting = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002826 ServiceState stracker = r.getTracker();
2827 if (stracker != null) {
2828 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
2829 r.lastActivity);
2830 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07002831 mAm.mAppOpsService.finishOperation(AppOpsManager.getToken(mAm.mAppOpsService),
2832 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002833 mAm.mHandler.removeMessages(
2834 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
2835 if (r.app != null) {
2836 Message msg = mAm.mHandler.obtainMessage(
2837 ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
2838 msg.obj = r.app;
Kodlee Yin7e951262018-04-05 12:59:56 -07002839 msg.getData().putCharSequence(
2840 ActivityManagerService.SERVICE_RECORD_KEY, r.toString());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002841 mAm.mHandler.sendMessage(msg);
2842 }
2843 }
2844
2845 if (DEBUG_SERVICE) {
2846 RuntimeException here = new RuntimeException();
2847 here.fillInStackTrace();
2848 Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here);
2849 }
Craig Mautner66c4a822015-01-16 12:48:16 -08002850 r.destroyTime = SystemClock.uptimeMillis();
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002851 if (LOG_SERVICE_START_STOP) {
2852 EventLogTags.writeAmDestroyService(
2853 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
2854 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002855
Dianne Hackbornad51be92016-08-16 16:27:36 -07002856 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002857 ServiceRecord found = smap.mServicesByInstanceName.remove(r.instanceName);
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002858
2859 // Note when this method is called by bringUpServiceLocked(), the service is not found
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002860 // in mServicesByInstanceName and found will be null.
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002861 if (found != null && found != r) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002862 // This is not actually the service we think is running... this should not happen,
2863 // but if it does, fail hard.
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002864 smap.mServicesByInstanceName.put(r.instanceName, found);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002865 throw new IllegalStateException("Bringing down " + r + " but actually running "
2866 + found);
2867 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002868 smap.mServicesByIntent.remove(r.intent);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002869 r.totalRestartCount = 0;
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002870 unscheduleServiceRestartLocked(r, 0, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002871
2872 // Also make sure it is not on the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002873 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002874 if (mPendingServices.get(i) == r) {
2875 mPendingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002876 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002877 }
2878 }
2879
Christopher Tate08992ac2017-03-21 11:37:06 -07002880 cancelForegroundNotificationLocked(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002881 if (r.isForeground) {
2882 decActiveForegroundAppLocked(smap, r);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002883 ServiceState stracker = r.getTracker();
2884 if (stracker != null) {
2885 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
2886 r.lastActivity);
2887 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07002888 mAm.mAppOpsService.finishOperation(
2889 AppOpsManager.getToken(mAm.mAppOpsService),
2890 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002891 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED, r.appInfo.uid,
2892 r.shortInstanceName, StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Hui Yue361a232018-10-04 15:05:21 -07002893 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002894 }
Chenjie Yuccfe6452018-01-30 11:33:21 -08002895
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002896 r.isForeground = false;
2897 r.foregroundId = 0;
2898 r.foregroundNoti = null;
2899
2900 // Clear start entries.
2901 r.clearDeliveredStartsLocked();
2902 r.pendingStarts.clear();
2903
2904 if (r.app != null) {
2905 synchronized (r.stats.getBatteryStats()) {
2906 r.stats.stopLaunchedLocked();
2907 }
2908 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002909 if (r.whitelistManager) {
2910 updateWhitelistManagerLocked(r.app);
2911 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002912 if (r.app.thread != null) {
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002913 updateServiceForegroundLocked(r.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002914 try {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002915 bumpServiceExecutingLocked(r, false, "destroy");
2916 mDestroyingServices.add(r);
Dianne Hackborn455625e2015-01-21 09:55:13 -08002917 r.destroying = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002918 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002919 r.app.thread.scheduleStopService(r);
2920 } catch (Exception e) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002921 Slog.w(TAG, "Exception when destroying service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002922 + r.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002923 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002924 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002925 } else {
2926 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002927 TAG_SERVICE, "Removed service that has no process: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002928 }
2929 } else {
2930 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002931 TAG_SERVICE, "Removed service that is not running: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002932 }
2933
2934 if (r.bindings.size() > 0) {
2935 r.bindings.clear();
2936 }
2937
2938 if (r.restarter instanceof ServiceRestarter) {
2939 ((ServiceRestarter)r.restarter).setService(null);
2940 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002941
Dianne Hackbornd2932242013-08-05 18:18:42 -07002942 int memFactor = mAm.mProcessStats.getMemFactorLocked();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002943 long now = SystemClock.uptimeMillis();
2944 if (r.tracker != null) {
2945 r.tracker.setStarted(false, memFactor, now);
2946 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002947 if (r.executeNesting == 0) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07002948 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002949 r.tracker = null;
2950 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002951 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002952
Dianne Hackbornad51be92016-08-16 16:27:36 -07002953 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002954 }
2955
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07002956 void removeConnectionLocked(ConnectionRecord c, ProcessRecord skipApp,
2957 ActivityServiceConnectionsHolder skipAct) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002958 IBinder binder = c.conn.asBinder();
2959 AppBindRecord b = c.binding;
2960 ServiceRecord s = b.service;
2961 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
2962 if (clist != null) {
2963 clist.remove(c);
2964 if (clist.size() == 0) {
2965 s.connections.remove(binder);
2966 }
2967 }
2968 b.connections.remove(c);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002969 c.stopAssociation();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002970 if (c.activity != null && c.activity != skipAct) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07002971 c.activity.removeConnection(c);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002972 }
2973 if (b.client != skipApp) {
2974 b.client.connections.remove(c);
2975 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
2976 b.client.updateHasAboveClientLocked();
2977 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002978 // If this connection requested whitelist management, see if we should
2979 // now clear that state.
2980 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
2981 s.updateWhitelistManager();
2982 if (!s.whitelistManager && s.app != null) {
2983 updateWhitelistManagerLocked(s.app);
2984 }
2985 }
Dianne Hackborndb926082013-10-31 16:32:44 -07002986 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07002987 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07002988 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002989 }
2990 clist = mServiceConnections.get(binder);
2991 if (clist != null) {
2992 clist.remove(c);
2993 if (clist.size() == 0) {
2994 mServiceConnections.remove(binder);
2995 }
2996 }
2997
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002998 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002999 s.appInfo.longVersionCode, s.instanceName, s.processName);
Dianne Hackbornab2df062015-01-07 13:43:13 -08003000
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003001 if (b.connections.size() == 0) {
3002 b.intent.apps.remove(b.client);
3003 }
3004
3005 if (!c.serviceDead) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003006 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003007 + ": shouldUnbind=" + b.intent.hasBound);
3008 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
3009 && b.intent.hasBound) {
3010 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003011 bumpServiceExecutingLocked(s, false, "unbind");
Dianne Hackborndb926082013-10-31 16:32:44 -07003012 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
Dianne Hackbornf097d422017-12-15 16:32:19 -08003013 && s.app.setProcState <= ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
Dianne Hackborndb926082013-10-31 16:32:44 -07003014 // If this service's process is not already in the cached list,
3015 // then update it in the LRU list here because this may be causing
3016 // it to go down there and we want it to start out near the top.
3017 mAm.updateLruProcessLocked(s.app, false, null);
3018 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07003019 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003020 b.intent.hasBound = false;
3021 // Assume the client doesn't want to know about a rebind;
3022 // we will deal with that later if it asks for one.
3023 b.intent.doRebind = false;
3024 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
3025 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003026 Slog.w(TAG, "Exception when unbinding service " + s.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07003027 serviceProcessGoneLocked(s);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003028 }
3029 }
3030
Svet Ganov9c165d72015-12-01 19:52:26 -08003031 // If unbound while waiting to start, remove the pending service
3032 mPendingServices.remove(s);
3033
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003034 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003035 boolean hasAutoCreate = s.hasAutoCreateConnections();
3036 if (!hasAutoCreate) {
3037 if (s.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003038 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003039 SystemClock.uptimeMillis());
3040 }
3041 }
3042 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003043 }
3044 }
3045 }
3046
3047 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003048 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003049 if (r != null) {
Dianne Hackborn455625e2015-01-21 09:55:13 -08003050 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003051 // This is a call from a service start... take care of
3052 // book-keeping.
3053 r.callStart = true;
3054 switch (res) {
3055 case Service.START_STICKY_COMPATIBILITY:
3056 case Service.START_STICKY: {
3057 // We are done with the associated start arguments.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003058 r.findDeliveredStart(startId, false, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003059 // Don't stop if killed.
3060 r.stopIfKilled = false;
3061 break;
3062 }
3063 case Service.START_NOT_STICKY: {
3064 // We are done with the associated start arguments.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003065 r.findDeliveredStart(startId, false, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003066 if (r.getLastStartId() == startId) {
3067 // There is no more work, and this service
3068 // doesn't want to hang around if killed.
3069 r.stopIfKilled = true;
3070 }
3071 break;
3072 }
3073 case Service.START_REDELIVER_INTENT: {
3074 // We'll keep this item until they explicitly
3075 // call stop for it, but keep track of the fact
3076 // that it was delivered.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003077 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003078 if (si != null) {
3079 si.deliveryCount = 0;
3080 si.doneExecutingCount++;
3081 // Don't stop if killed.
3082 r.stopIfKilled = true;
3083 }
3084 break;
3085 }
3086 case Service.START_TASK_REMOVED_COMPLETE: {
3087 // Special processing for onTaskRemoved(). Don't
3088 // impact normal onStartCommand() processing.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003089 r.findDeliveredStart(startId, true, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003090 break;
3091 }
3092 default:
3093 throw new IllegalArgumentException(
3094 "Unknown service start result: " + res);
3095 }
3096 if (res == Service.START_STICKY_COMPATIBILITY) {
3097 r.callStart = false;
3098 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08003099 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
3100 // This is the final call from destroying the service... we should
3101 // actually be getting rid of the service at this point. Do some
3102 // validation of its state, and ensure it will be fully removed.
3103 if (!inDestroying) {
3104 // Not sure what else to do with this... if it is not actually in the
3105 // destroying list, we don't need to make sure to remove it from it.
Amith Yamasanid0418222016-05-10 15:49:51 -07003106 // If the app is null, then it was probably removed because the process died,
3107 // otherwise wtf
3108 if (r.app != null) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07003109 Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
Amith Yamasanid0418222016-05-10 15:49:51 -07003110 + r + ", app=" + r.app);
3111 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08003112 } else if (r.executeNesting != 1) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07003113 Slog.w(TAG, "Service done with onDestroy, but executeNesting="
Dianne Hackborn455625e2015-01-21 09:55:13 -08003114 + r.executeNesting + ": " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003115 // Fake it to keep from ANR due to orphaned entry.
Dianne Hackborn455625e2015-01-21 09:55:13 -08003116 r.executeNesting = 1;
3117 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003118 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003119 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn164371f2013-10-01 19:10:13 -07003120 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003121 Binder.restoreCallingIdentity(origId);
3122 } else {
3123 Slog.w(TAG, "Done executing unknown service from pid "
3124 + Binder.getCallingPid());
3125 }
3126 }
3127
Dianne Hackborn878deb32013-10-14 16:55:09 -07003128 private void serviceProcessGoneLocked(ServiceRecord r) {
3129 if (r.tracker != null) {
3130 int memFactor = mAm.mProcessStats.getMemFactorLocked();
3131 long now = SystemClock.uptimeMillis();
3132 r.tracker.setExecuting(false, memFactor, now);
3133 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbc72dce2013-11-11 10:43:38 -08003134 r.tracker.setStarted(false, memFactor, now);
Dianne Hackborn878deb32013-10-14 16:55:09 -07003135 }
3136 serviceDoneExecutingLocked(r, true, true);
3137 }
3138
Dianne Hackborn164371f2013-10-01 19:10:13 -07003139 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
3140 boolean finishing) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003141 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003142 + ": nesting=" + r.executeNesting
Dianne Hackborn164371f2013-10-01 19:10:13 -07003143 + ", inDestroying=" + inDestroying + ", app=" + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003144 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003145 "<<< DONE EXECUTING " + r.shortInstanceName);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003146 r.executeNesting--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003147 if (r.executeNesting <= 0) {
3148 if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003149 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003150 "Nesting at 0 of " + r.shortInstanceName);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003151 r.app.execServicesFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003152 r.app.executingServices.remove(r);
3153 if (r.app.executingServices.size() == 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003154 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003155 "No more executingServices of " + r.shortInstanceName);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003156 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003157 } else if (r.executeFg) {
3158 // Need to re-evaluate whether the app still needs to be in the foreground.
3159 for (int i=r.app.executingServices.size()-1; i>=0; i--) {
3160 if (r.app.executingServices.valueAt(i).executeFg) {
3161 r.app.execServicesFg = true;
3162 break;
3163 }
3164 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003165 }
Dianne Hackborn164371f2013-10-01 19:10:13 -07003166 if (inDestroying) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003167 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn164371f2013-10-01 19:10:13 -07003168 "doneExecuting remove destroying " + r);
3169 mDestroyingServices.remove(r);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003170 r.bindings.clear();
3171 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07003172 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003173 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003174 r.executeFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003175 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003176 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003177 SystemClock.uptimeMillis());
Dianne Hackborn164371f2013-10-01 19:10:13 -07003178 if (finishing) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07003179 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003180 r.tracker = null;
3181 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003182 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003183 if (finishing) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003184 if (r.app != null && !r.app.isPersistent()) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003185 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003186 if (r.whitelistManager) {
3187 updateWhitelistManagerLocked(r.app);
3188 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003189 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003190 r.setProcess(null);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003191 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003192 }
3193 }
3194
Dianne Hackbornff072722014-09-24 10:56:28 -07003195 boolean attachApplicationLocked(ProcessRecord proc, String processName)
3196 throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003197 boolean didSomething = false;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003198 // Collect any services that are waiting for this process to come up.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003199 if (mPendingServices.size() > 0) {
3200 ServiceRecord sr = null;
3201 try {
3202 for (int i=0; i<mPendingServices.size(); i++) {
3203 sr = mPendingServices.get(i);
3204 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3205 || !processName.equals(sr.processName))) {
3206 continue;
3207 }
3208
3209 mPendingServices.remove(i);
3210 i--;
Patrick Baumannc2def582018-04-04 12:14:15 -07003211 proc.addPackage(sr.appInfo.packageName, sr.appInfo.longVersionCode,
Dianne Hackbornf7097a52014-05-13 09:56:14 -07003212 mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003213 realStartServiceLocked(sr, proc, sr.createdFromFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003214 didSomething = true;
Dianne Hackbornad51be92016-08-16 16:27:36 -07003215 if (!isServiceNeededLocked(sr, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003216 // We were waiting for this service to start, but it is actually no
3217 // longer needed. This could happen because bringDownServiceIfNeeded
3218 // won't bring down a service that is pending... so now the pending
3219 // is done, so let's drop it.
3220 bringDownServiceLocked(sr);
3221 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003222 }
Dianne Hackbornff072722014-09-24 10:56:28 -07003223 } catch (RemoteException e) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003224 Slog.w(TAG, "Exception in new application when starting service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003225 + sr.shortInstanceName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003226 throw e;
3227 }
3228 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003229 // Also, if there are any services that are waiting to restart and
3230 // would run in this process, now is a good time to start them. It would
3231 // be weird to bring up the process but arbitrarily not let the services
3232 // run at this point just because their restart time hasn't come up.
3233 if (mRestartingServices.size() > 0) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003234 ServiceRecord sr;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003235 for (int i=0; i<mRestartingServices.size(); i++) {
3236 sr = mRestartingServices.get(i);
3237 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3238 || !processName.equals(sr.processName))) {
3239 continue;
3240 }
3241 mAm.mHandler.removeCallbacks(sr.restarter);
3242 mAm.mHandler.post(sr.restarter);
3243 }
3244 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003245 return didSomething;
3246 }
3247
3248 void processStartTimedOutLocked(ProcessRecord proc) {
3249 for (int i=0; i<mPendingServices.size(); i++) {
3250 ServiceRecord sr = mPendingServices.get(i);
3251 if ((proc.uid == sr.appInfo.uid
3252 && proc.processName.equals(sr.processName))
3253 || sr.isolatedProc == proc) {
3254 Slog.w(TAG, "Forcing bringing down service: " + sr);
3255 sr.isolatedProc = null;
3256 mPendingServices.remove(i);
3257 i--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003258 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003259 }
3260 }
3261 }
3262
Wale Ogunwale540e1232015-05-01 15:35:39 -07003263 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003264 boolean evenPersistent, boolean doit, boolean killProcess,
3265 ArrayMap<ComponentName, ServiceRecord> services) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003266 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003267 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003268 ServiceRecord service = services.valueAt(i);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003269 final boolean sameComponent = packageName == null
3270 || (service.packageName.equals(packageName)
3271 && (filterByClasses == null
3272 || filterByClasses.contains(service.name.getClassName())));
3273 if (sameComponent
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003274 && (service.app == null || evenPersistent || !service.app.isPersistent())) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003275 if (!doit) {
3276 return true;
3277 }
3278 didSomething = true;
3279 Slog.i(TAG, " Force stopping service " + service);
3280 if (service.app != null) {
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003281 service.app.removed = killProcess;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003282 if (!service.app.isPersistent()) {
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08003283 service.app.services.remove(service);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003284 if (service.whitelistManager) {
3285 updateWhitelistManagerLocked(service.app);
3286 }
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08003287 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003288 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003289 service.setProcess(null);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003290 service.isolatedProc = null;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003291 if (mTmpCollectionResults == null) {
3292 mTmpCollectionResults = new ArrayList<>();
3293 }
3294 mTmpCollectionResults.add(service);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003295 }
3296 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003297 return didSomething;
3298 }
3299
Wale Ogunwale540e1232015-05-01 15:35:39 -07003300 boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003301 int userId, boolean evenPersistent, boolean killProcess, boolean doit) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003302 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003303
3304 if (mTmpCollectionResults != null) {
3305 mTmpCollectionResults.clear();
3306 }
3307
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003308 if (userId == UserHandle.USER_ALL) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003309 for (int i = mServiceMap.size() - 1; i >= 0; i--) {
3310 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003311 evenPersistent, doit, killProcess,
3312 mServiceMap.valueAt(i).mServicesByInstanceName);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003313 if (!doit && didSomething) {
3314 return true;
3315 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003316 if (doit && filterByClasses == null) {
3317 forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId);
3318 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003319 }
3320 } else {
Amith Yamasani540b6592013-10-01 13:02:52 -07003321 ServiceMap smap = mServiceMap.get(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003322 if (smap != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003323 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByInstanceName;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003324 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003325 evenPersistent, doit, killProcess, items);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003326 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003327 if (doit && filterByClasses == null) {
3328 forceStopPackageLocked(packageName, userId);
3329 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003330 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003331
Wale Ogunwale540e1232015-05-01 15:35:39 -07003332 if (mTmpCollectionResults != null) {
3333 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
3334 bringDownServiceLocked(mTmpCollectionResults.get(i));
3335 }
3336 mTmpCollectionResults.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003337 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003338
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003339 return didSomething;
3340 }
3341
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003342 void forceStopPackageLocked(String packageName, int userId) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003343 ServiceMap smap = mServiceMap.get(userId);
3344 if (smap != null && smap.mActiveForegroundApps.size() > 0) {
Dianne Hackbornaf597682017-05-01 10:54:07 -07003345 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003346 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
3347 if (aa.mPackageName.equals(packageName)) {
3348 smap.mActiveForegroundApps.removeAt(i);
3349 smap.mActiveForegroundAppsChanged = true;
3350 }
3351 }
3352 if (smap.mActiveForegroundAppsChanged) {
3353 requestUpdateActiveForegroundAppsLocked(smap, 0);
3354 }
3355 }
3356 }
3357
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003358 void cleanUpServices(int userId, ComponentName component, Intent baseIntent) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003359 ArrayList<ServiceRecord> services = new ArrayList<>();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003360 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003361 for (int i = alls.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003362 ServiceRecord sr = alls.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003363 if (sr.packageName.equals(component.getPackageName())) {
3364 services.add(sr);
3365 }
3366 }
3367
3368 // Take care of any running services associated with the app.
Wale Ogunwale540e1232015-05-01 15:35:39 -07003369 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003370 ServiceRecord sr = services.get(i);
3371 if (sr.startRequested) {
3372 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003373 Slog.i(TAG, "Stopping service " + sr.shortInstanceName + ": remove task");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003374 stopServiceLocked(sr);
3375 } else {
3376 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003377 sr.getLastStartId(), baseIntent, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003378 if (sr.app != null && sr.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003379 // We always run in the foreground, since this is called as
3380 // part of the "remove task" UI operation.
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003381 try {
3382 sendServiceArgsLocked(sr, true, false);
3383 } catch (TransactionTooLargeException e) {
3384 // Ignore, keep going.
3385 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003386 }
3387 }
3388 }
3389 }
3390 }
3391
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003392 final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003393 // Report disconnected services.
3394 if (false) {
3395 // XXX we are letting the client link to the service for
3396 // death notifications.
3397 if (app.services.size() > 0) {
3398 Iterator<ServiceRecord> it = app.services.iterator();
3399 while (it.hasNext()) {
3400 ServiceRecord r = it.next();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003401 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3402 ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
3403 for (int i=0; i<cl.size(); i++) {
3404 ConnectionRecord c = cl.get(i);
3405 if (c.binding.client != app) {
3406 try {
3407 //c.conn.connected(r.className, null);
3408 } catch (Exception e) {
3409 // todo: this should be asynchronous!
3410 Slog.w(TAG, "Exception thrown disconnected servce "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003411 + r.shortInstanceName
Dianne Hackborn390517b2013-05-30 15:03:32 -07003412 + " from app " + app.processName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003413 }
3414 }
3415 }
3416 }
3417 }
3418 }
3419 }
3420
louis_chang40e259c2015-03-26 13:31:14 +08003421 // Clean up any connections this application has to other services.
3422 for (int i = app.connections.size() - 1; i >= 0; i--) {
3423 ConnectionRecord r = app.connections.valueAt(i);
3424 removeConnectionLocked(r, app, null);
3425 }
3426 updateServiceConnectionActivitiesLocked(app);
3427 app.connections.clear();
3428
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003429 app.whitelistManager = false;
3430
louis_chang40e259c2015-03-26 13:31:14 +08003431 // Clear app state from services.
3432 for (int i = app.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003433 ServiceRecord sr = app.services.valueAt(i);
3434 synchronized (sr.stats.getBatteryStats()) {
3435 sr.stats.stopLaunchedLocked();
3436 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003437 if (sr.app != app && sr.app != null && !sr.app.isPersistent()) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003438 sr.app.services.remove(sr);
3439 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003440 sr.setProcess(null);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003441 sr.isolatedProc = null;
3442 sr.executeNesting = 0;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003443 sr.forceClearTracker();
3444 if (mDestroyingServices.remove(sr)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003445 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003446 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003447
Dianne Hackbornc8230512013-07-13 21:32:12 -07003448 final int numClients = sr.bindings.size();
3449 for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
3450 IntentBindRecord b = sr.bindings.valueAt(bindingi);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003451 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
Dianne Hackbornc8230512013-07-13 21:32:12 -07003452 + ": shouldUnbind=" + b.hasBound);
3453 b.binder = null;
3454 b.requested = b.received = b.hasBound = false;
Dianne Hackborn465fa392014-09-14 14:21:18 -07003455 // If this binding is coming from a cached process and is asking to keep
3456 // the service created, then we'll kill the cached process as well -- we
3457 // don't want to be thrashing around restarting processes that are only
3458 // there to be cached.
3459 for (int appi=b.apps.size()-1; appi>=0; appi--) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003460 final ProcessRecord proc = b.apps.keyAt(appi);
3461 // If the process is already gone, skip it.
3462 if (proc.killedByAm || proc.thread == null) {
3463 continue;
3464 }
3465 // Only do this for processes that have an auto-create binding;
3466 // otherwise the binding can be left, because it won't cause the
3467 // service to restart.
3468 final AppBindRecord abind = b.apps.valueAt(appi);
3469 boolean hasCreate = false;
3470 for (int conni=abind.connections.size()-1; conni>=0; conni--) {
3471 ConnectionRecord conn = abind.connections.valueAt(conni);
Dianne Hackborn0fe3c252014-09-19 15:09:39 -07003472 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
3473 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003474 hasCreate = true;
3475 break;
3476 }
3477 }
3478 if (!hasCreate) {
3479 continue;
3480 }
Dianne Hackborncd97c962014-09-25 18:34:02 -07003481 // XXX turned off for now until we have more time to get a better policy.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003482 if (false && proc != null && !proc.isPersistent() && proc.thread != null
Dianne Hackborn465fa392014-09-14 14:21:18 -07003483 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
3484 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003485 proc.kill("bound to service " + sr.shortInstanceName
Dianne Hackborn465fa392014-09-14 14:21:18 -07003486 + " in dying proc " + (app != null ? app.processName : "??"), true);
3487 }
3488 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003489 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003490 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003491
Dianne Hackbornad51be92016-08-16 16:27:36 -07003492 ServiceMap smap = getServiceMapLocked(app.userId);
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003493
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003494 // Now do remaining service cleanup.
3495 for (int i=app.services.size()-1; i>=0; i--) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003496 ServiceRecord sr = app.services.valueAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003497
3498 // Unless the process is persistent, this process record is going away,
3499 // so make sure the service is cleaned out of it.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003500 if (!app.isPersistent()) {
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003501 app.services.removeAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003502 }
3503
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003504 // Sanity check: if the service listed for the app is not one
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003505 // we actually are maintaining, just let it drop.
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003506 final ServiceRecord curRec = smap.mServicesByInstanceName.get(sr.instanceName);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003507 if (curRec != sr) {
3508 if (curRec != null) {
3509 Slog.wtf(TAG, "Service " + sr + " in process " + app
3510 + " not same as in map: " + curRec);
3511 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003512 continue;
3513 }
3514
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003515 // Any services running in the application may need to be placed
3516 // back in the pending list.
Amith Yamasanib0c8a882017-08-28 09:36:42 -07003517 if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
3518 && (sr.serviceInfo.applicationInfo.flags
3519 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003520 Slog.w(TAG, "Service crashed " + sr.crashCount
3521 + " times, stopping: " + sr);
3522 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003523 sr.userId, sr.crashCount, sr.shortInstanceName, app.pid);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003524 bringDownServiceLocked(sr);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003525 } else if (!allowRestart
Fyodor Kupolov1b3edac2017-09-19 15:48:06 -07003526 || !mAm.mUserController.isUserRunning(sr.userId, 0)) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003527 bringDownServiceLocked(sr);
3528 } else {
3529 boolean canceled = scheduleServiceRestartLocked(sr, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003530
Dianne Hackbornc8230512013-07-13 21:32:12 -07003531 // Should the service remain running? Note that in the
3532 // extreme case of so many attempts to deliver a command
3533 // that it failed we also will stop it here.
3534 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
3535 if (sr.pendingStarts.size() == 0) {
3536 sr.startRequested = false;
3537 if (sr.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003538 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackbornc8230512013-07-13 21:32:12 -07003539 SystemClock.uptimeMillis());
3540 }
3541 if (!sr.hasAutoCreateConnections()) {
3542 // Whoops, no reason to restart!
3543 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003544 }
3545 }
3546 }
3547 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003548 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003549
Dianne Hackbornc8230512013-07-13 21:32:12 -07003550 if (!allowRestart) {
3551 app.services.clear();
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003552
3553 // Make sure there are no more restarting services for this process.
3554 for (int i=mRestartingServices.size()-1; i>=0; i--) {
3555 ServiceRecord r = mRestartingServices.get(i);
3556 if (r.processName.equals(app.processName) &&
3557 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3558 mRestartingServices.remove(i);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08003559 clearRestartingIfNeededLocked(r);
3560 }
3561 }
3562 for (int i=mPendingServices.size()-1; i>=0; i--) {
3563 ServiceRecord r = mPendingServices.get(i);
3564 if (r.processName.equals(app.processName) &&
3565 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3566 mPendingServices.remove(i);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003567 }
3568 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003569 }
3570
3571 // Make sure we have no more records on the stopping list.
Dianne Hackborn164371f2013-10-01 19:10:13 -07003572 int i = mDestroyingServices.size();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003573 while (i > 0) {
3574 i--;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003575 ServiceRecord sr = mDestroyingServices.get(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003576 if (sr.app == app) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003577 sr.forceClearTracker();
3578 mDestroyingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003579 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003580 }
3581 }
3582
3583 app.executingServices.clear();
3584 }
3585
3586 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
3587 ActivityManager.RunningServiceInfo info =
3588 new ActivityManager.RunningServiceInfo();
3589 info.service = r.name;
3590 if (r.app != null) {
3591 info.pid = r.app.pid;
3592 }
3593 info.uid = r.appInfo.uid;
3594 info.process = r.processName;
3595 info.foreground = r.isForeground;
Yi Jin6b514142017-10-30 14:54:12 -07003596 info.activeSince = r.createRealTime;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003597 info.started = r.startRequested;
3598 info.clientCount = r.connections.size();
3599 info.crashCount = r.crashCount;
3600 info.lastActivityTime = r.lastActivity;
3601 if (r.isForeground) {
3602 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
3603 }
3604 if (r.startRequested) {
3605 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
3606 }
3607 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
3608 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
3609 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003610 if (r.app != null && r.app.isPersistent()) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003611 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
3612 }
3613
Dianne Hackborn390517b2013-05-30 15:03:32 -07003614 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3615 ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003616 for (int i=0; i<connl.size(); i++) {
3617 ConnectionRecord conn = connl.get(i);
3618 if (conn.clientLabel != 0) {
3619 info.clientPackage = conn.binding.client.info.packageName;
3620 info.clientLabel = conn.clientLabel;
3621 return info;
3622 }
3623 }
3624 }
3625 return info;
3626 }
3627
Bryce Lee290e5782017-02-01 16:41:20 -08003628 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags,
Shunta Sato55af6c52016-10-19 15:58:52 +09003629 int callingUid, boolean allowed, boolean canInteractAcrossUsers) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003630 ArrayList<ActivityManager.RunningServiceInfo> res
3631 = new ArrayList<ActivityManager.RunningServiceInfo>();
3632
Dianne Hackborn0c380492012-08-20 17:23:30 -07003633 final long ident = Binder.clearCallingIdentity();
3634 try {
Shunta Sato55af6c52016-10-19 15:58:52 +09003635 if (canInteractAcrossUsers) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003636 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003637 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003638 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003639 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3640 ServiceRecord sr = alls.valueAt(i);
3641 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07003642 }
3643 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003644
Dianne Hackborn0c380492012-08-20 17:23:30 -07003645 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3646 ServiceRecord r = mRestartingServices.get(i);
3647 ActivityManager.RunningServiceInfo info =
3648 makeRunningServiceInfoLocked(r);
3649 info.restarting = r.nextRestartTime;
3650 res.add(info);
3651 }
3652 } else {
Bryce Lee290e5782017-02-01 16:41:20 -08003653 int userId = UserHandle.getUserId(callingUid);
Dianne Hackbornad51be92016-08-16 16:27:36 -07003654 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003655 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3656 ServiceRecord sr = alls.valueAt(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003657
3658 if (allowed || (sr.app != null && sr.app.uid == callingUid)) {
3659 res.add(makeRunningServiceInfoLocked(sr));
3660 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07003661 }
3662
3663 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3664 ServiceRecord r = mRestartingServices.get(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003665 if (r.userId == userId
3666 && (allowed || (r.app != null && r.app.uid == callingUid))) {
Dianne Hackborn0c380492012-08-20 17:23:30 -07003667 ActivityManager.RunningServiceInfo info =
3668 makeRunningServiceInfoLocked(r);
3669 info.restarting = r.nextRestartTime;
3670 res.add(info);
3671 }
3672 }
3673 }
3674 } finally {
3675 Binder.restoreCallingIdentity(ident);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003676 }
3677
3678 return res;
3679 }
3680
3681 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003682 int userId = UserHandle.getUserId(Binder.getCallingUid());
Dianne Hackbornad51be92016-08-16 16:27:36 -07003683 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003684 if (r != null) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003685 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3686 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003687 for (int i=0; i<conn.size(); i++) {
3688 if (conn.get(i).clientIntent != null) {
3689 return conn.get(i).clientIntent;
3690 }
3691 }
3692 }
3693 }
3694 return null;
3695 }
3696
3697 void serviceTimeout(ProcessRecord proc) {
3698 String anrMessage = null;
3699
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003700 synchronized(mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003701 if (proc.executingServices.size() == 0 || proc.thread == null) {
3702 return;
3703 }
Dianne Hackbornab2df062015-01-07 13:43:13 -08003704 final long now = SystemClock.uptimeMillis();
3705 final long maxTime = now -
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003706 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003707 ServiceRecord timeout = null;
3708 long nextTime = 0;
Dianne Hackbornc8230512013-07-13 21:32:12 -07003709 for (int i=proc.executingServices.size()-1; i>=0; i--) {
3710 ServiceRecord sr = proc.executingServices.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003711 if (sr.executingStart < maxTime) {
3712 timeout = sr;
3713 break;
3714 }
3715 if (sr.executingStart > nextTime) {
3716 nextTime = sr.executingStart;
3717 }
3718 }
Amith Yamasani98a00922018-08-21 12:50:30 -04003719 if (timeout != null && mAm.mProcessList.mLruProcesses.contains(proc)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003720 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08003721 StringWriter sw = new StringWriter();
3722 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
3723 pw.println(timeout);
3724 timeout.dump(pw, " ");
3725 pw.close();
3726 mLastAnrDump = sw.toString();
3727 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
3728 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003729 anrMessage = "executing service " + timeout.shortInstanceName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003730 } else {
3731 Message msg = mAm.mHandler.obtainMessage(
3732 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3733 msg.obj = proc;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003734 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
Dianne Hackborn2be00932013-09-22 16:46:00 -07003735 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003736 }
3737 }
3738
3739 if (anrMessage != null) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07003740 proc.appNotResponding(null, null, null, null, false, anrMessage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003741 }
3742 }
3743
Christopher Tate08992ac2017-03-21 11:37:06 -07003744 void serviceForegroundTimeout(ServiceRecord r) {
3745 ProcessRecord app;
3746 synchronized (mAm) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003747 if (!r.fgRequired || r.destroying) {
Christopher Tate08992ac2017-03-21 11:37:06 -07003748 return;
3749 }
3750
Christopher Tate54f51b02018-02-16 11:07:12 -08003751 app = r.app;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07003752 if (app != null && app.isDebugging()) {
Christopher Tate54f51b02018-02-16 11:07:12 -08003753 // The app's being debugged; let it ride
3754 return;
3755 }
3756
Christopher Tate08992ac2017-03-21 11:37:06 -07003757 if (DEBUG_BACKGROUND_CHECK) {
3758 Slog.i(TAG, "Service foreground-required timeout for " + r);
3759 }
Christopher Tate08992ac2017-03-21 11:37:06 -07003760 r.fgWaiting = false;
3761 stopServiceLocked(r);
3762 }
3763
3764 if (app != null) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07003765 app.appNotResponding(null, null, null, null, false,
Kodlee Yin7e951262018-04-05 12:59:56 -07003766 "Context.startForegroundService() did not then call Service.startForeground(): "
3767 + r);
Christopher Tate08992ac2017-03-21 11:37:06 -07003768 }
3769 }
3770
Fyodor Kupolovcc269d92018-05-14 14:20:29 -07003771 public void updateServiceApplicationInfoLocked(ApplicationInfo applicationInfo) {
3772 final int userId = UserHandle.getUserId(applicationInfo.uid);
3773 ServiceMap serviceMap = mServiceMap.get(userId);
3774 if (serviceMap != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003775 ArrayMap<ComponentName, ServiceRecord> servicesByName
3776 = serviceMap.mServicesByInstanceName;
Fyodor Kupolovcc269d92018-05-14 14:20:29 -07003777 for (int j = servicesByName.size() - 1; j >= 0; j--) {
3778 ServiceRecord serviceRecord = servicesByName.valueAt(j);
3779 if (applicationInfo.packageName.equals(serviceRecord.appInfo.packageName)) {
3780 serviceRecord.appInfo = applicationInfo;
3781 serviceRecord.serviceInfo.applicationInfo = applicationInfo;
3782 }
3783 }
3784 }
3785 }
3786
Kodlee Yin7e951262018-04-05 12:59:56 -07003787 void serviceForegroundCrash(ProcessRecord app, CharSequence serviceRecord) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003788 mAm.crashApplication(app.uid, app.pid, app.info.packageName, app.userId,
Kodlee Yin7e951262018-04-05 12:59:56 -07003789 "Context.startForegroundService() did not then call Service.startForeground(): "
3790 + serviceRecord);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003791 }
3792
Dianne Hackborn2be00932013-09-22 16:46:00 -07003793 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
3794 if (proc.executingServices.size() == 0 || proc.thread == null) {
3795 return;
3796 }
Dianne Hackborn2be00932013-09-22 16:46:00 -07003797 Message msg = mAm.mHandler.obtainMessage(
3798 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3799 msg.obj = proc;
Christopher Tate08992ac2017-03-21 11:37:06 -07003800 mAm.mHandler.sendMessageDelayed(msg,
3801 proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
3802 }
3803
3804 void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
3805 if (r.app.executingServices.size() == 0 || r.app.thread == null) {
3806 return;
3807 }
3808 Message msg = mAm.mHandler.obtainMessage(
3809 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG);
3810 msg.obj = r;
3811 r.fgWaiting = true;
3812 mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT);
Dianne Hackborn2be00932013-09-22 16:46:00 -07003813 }
3814
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003815 final class ServiceDumper {
3816 private final FileDescriptor fd;
3817 private final PrintWriter pw;
3818 private final String[] args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003819 private final boolean dumpAll;
3820 private final String dumpPackage;
3821 private final ItemMatcher matcher;
3822 private final ArrayList<ServiceRecord> services = new ArrayList<>();
3823
3824 private final long nowReal = SystemClock.elapsedRealtime();
3825
3826 private boolean needSep = false;
3827 private boolean printedAnything = false;
3828 private boolean printed = false;
3829
3830 /**
3831 * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
3832 * must be called with the lock held).
3833 */
3834 ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
3835 int opti, boolean dumpAll, String dumpPackage) {
3836 this.fd = fd;
3837 this.pw = pw;
3838 this.args = args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003839 this.dumpAll = dumpAll;
3840 this.dumpPackage = dumpPackage;
3841 matcher = new ItemMatcher();
3842 matcher.build(args, opti);
3843
3844 final int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003845 for (int user : users) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003846 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003847 if (smap.mServicesByInstanceName.size() > 0) {
3848 for (int si=0; si<smap.mServicesByInstanceName.size(); si++) {
3849 ServiceRecord r = smap.mServicesByInstanceName.valueAt(si);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003850 if (!matcher.match(r, r.name)) {
3851 continue;
3852 }
3853 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3854 continue;
3855 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003856 services.add(r);
3857 }
3858 }
3859 }
3860 }
3861
3862 private void dumpHeaderLocked() {
3863 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
3864 if (mLastAnrDump != null) {
3865 pw.println(" Last ANR service:");
3866 pw.print(mLastAnrDump);
3867 pw.println();
3868 }
3869 }
3870
3871 void dumpLocked() {
3872 dumpHeaderLocked();
3873
3874 try {
3875 int[] users = mAm.mUserController.getUsers();
3876 for (int user : users) {
3877 // Find the first service for this user.
3878 int serviceIdx = 0;
3879 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3880 serviceIdx++;
3881 }
3882 printed = false;
3883 if (serviceIdx < services.size()) {
3884 needSep = false;
3885 while (serviceIdx < services.size()) {
3886 ServiceRecord r = services.get(serviceIdx);
3887 serviceIdx++;
3888 if (r.userId != user) {
3889 break;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003890 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003891 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003892 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003893 needSep |= printed;
3894 }
3895
3896 dumpUserRemainsLocked(user);
3897 }
3898 } catch (Exception e) {
3899 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3900 }
3901
3902 dumpRemainsLocked();
3903 }
3904
3905 void dumpWithClient() {
3906 synchronized(mAm) {
3907 dumpHeaderLocked();
3908 }
3909
3910 try {
3911 int[] users = mAm.mUserController.getUsers();
3912 for (int user : users) {
3913 // Find the first service for this user.
3914 int serviceIdx = 0;
3915 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3916 serviceIdx++;
3917 }
3918 printed = false;
3919 if (serviceIdx < services.size()) {
3920 needSep = false;
3921 while (serviceIdx < services.size()) {
3922 ServiceRecord r = services.get(serviceIdx);
3923 serviceIdx++;
3924 if (r.userId != user) {
3925 break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003926 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003927 synchronized(mAm) {
3928 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003929 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003930 dumpServiceClient(r);
3931 }
3932 needSep |= printed;
3933 }
3934
3935 synchronized(mAm) {
3936 dumpUserRemainsLocked(user);
3937 }
3938 }
3939 } catch (Exception e) {
3940 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3941 }
3942
3943 synchronized(mAm) {
3944 dumpRemainsLocked();
3945 }
3946 }
3947
3948 private void dumpUserHeaderLocked(int user) {
3949 if (!printed) {
3950 if (printedAnything) {
3951 pw.println();
3952 }
3953 pw.println(" User " + user + " active services:");
3954 printed = true;
3955 }
3956 printedAnything = true;
3957 if (needSep) {
3958 pw.println();
3959 }
3960 }
3961
3962 private void dumpServiceLocalLocked(ServiceRecord r) {
3963 dumpUserHeaderLocked(r.userId);
3964 pw.print(" * ");
3965 pw.println(r);
3966 if (dumpAll) {
3967 r.dump(pw, " ");
3968 needSep = true;
3969 } else {
3970 pw.print(" app=");
3971 pw.println(r.app);
3972 pw.print(" created=");
Yi Jin6b514142017-10-30 14:54:12 -07003973 TimeUtils.formatDuration(r.createRealTime, nowReal, pw);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003974 pw.print(" started=");
3975 pw.print(r.startRequested);
3976 pw.print(" connections=");
3977 pw.println(r.connections.size());
3978 if (r.connections.size() > 0) {
3979 pw.println(" Connections:");
3980 for (int conni=0; conni<r.connections.size(); conni++) {
3981 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
3982 for (int i = 0; i < clist.size(); i++) {
3983 ConnectionRecord conn = clist.get(i);
3984 pw.print(" ");
3985 pw.print(conn.binding.intent.intent.getIntent()
3986 .toShortString(false, false, false, false));
3987 pw.print(" -> ");
3988 ProcessRecord proc = conn.binding.client;
3989 pw.println(proc != null ? proc.toShortString() : "null");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003990 }
3991 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003992 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003993 }
3994 }
3995
3996 private void dumpServiceClient(ServiceRecord r) {
3997 final ProcessRecord proc = r.app;
3998 if (proc == null) {
3999 return;
4000 }
4001 final IApplicationThread thread = proc.thread;
4002 if (thread == null) {
4003 return;
4004 }
4005 pw.println(" Client:");
4006 pw.flush();
4007 try {
4008 TransferPipe tp = new TransferPipe();
4009 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004010 thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004011 tp.setBufferPrefix(" ");
4012 // Short timeout, since blocking here can
4013 // deadlock with the application.
4014 tp.go(fd, 2000);
4015 } finally {
4016 tp.kill();
4017 }
4018 } catch (IOException e) {
4019 pw.println(" Failure while dumping the service: " + e);
4020 } catch (RemoteException e) {
4021 pw.println(" Got a RemoteException while dumping the service");
4022 }
4023 needSep = true;
4024 }
4025
4026 private void dumpUserRemainsLocked(int user) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07004027 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004028 printed = false;
4029 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
4030 ServiceRecord r = smap.mDelayedStartList.get(si);
4031 if (!matcher.match(r, r.name)) {
4032 continue;
4033 }
4034 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4035 continue;
4036 }
4037 if (!printed) {
4038 if (printedAnything) {
4039 pw.println();
4040 }
4041 pw.println(" User " + user + " delayed start services:");
4042 printed = true;
4043 }
4044 printedAnything = true;
4045 pw.print(" * Delayed start "); pw.println(r);
4046 }
4047 printed = false;
4048 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
4049 ServiceRecord r = smap.mStartingBackground.get(si);
4050 if (!matcher.match(r, r.name)) {
4051 continue;
4052 }
4053 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4054 continue;
4055 }
4056 if (!printed) {
4057 if (printedAnything) {
4058 pw.println();
4059 }
4060 pw.println(" User " + user + " starting in background:");
4061 printed = true;
4062 }
4063 printedAnything = true;
4064 pw.print(" * Starting bg "); pw.println(r);
4065 }
4066 }
4067
4068 private void dumpRemainsLocked() {
4069 if (mPendingServices.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004070 printed = false;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004071 for (int i=0; i<mPendingServices.size(); i++) {
4072 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004073 if (!matcher.match(r, r.name)) {
4074 continue;
4075 }
4076 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4077 continue;
4078 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004079 printedAnything = true;
4080 if (!printed) {
4081 if (needSep) pw.println();
4082 needSep = true;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004083 pw.println(" Pending services:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004084 printed = true;
4085 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004086 pw.print(" * Pending "); pw.println(r);
4087 r.dump(pw, " ");
4088 }
4089 needSep = true;
4090 }
4091
4092 if (mRestartingServices.size() > 0) {
4093 printed = false;
4094 for (int i=0; i<mRestartingServices.size(); i++) {
4095 ServiceRecord r = mRestartingServices.get(i);
4096 if (!matcher.match(r, r.name)) {
4097 continue;
4098 }
4099 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4100 continue;
4101 }
4102 printedAnything = true;
4103 if (!printed) {
4104 if (needSep) pw.println();
4105 needSep = true;
4106 pw.println(" Restarting services:");
4107 printed = true;
4108 }
4109 pw.print(" * Restarting "); pw.println(r);
4110 r.dump(pw, " ");
4111 }
4112 needSep = true;
4113 }
4114
4115 if (mDestroyingServices.size() > 0) {
4116 printed = false;
4117 for (int i=0; i< mDestroyingServices.size(); i++) {
4118 ServiceRecord r = mDestroyingServices.get(i);
4119 if (!matcher.match(r, r.name)) {
4120 continue;
4121 }
4122 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4123 continue;
4124 }
4125 printedAnything = true;
4126 if (!printed) {
4127 if (needSep) pw.println();
4128 needSep = true;
4129 pw.println(" Destroying services:");
4130 printed = true;
4131 }
4132 pw.print(" * Destroy "); pw.println(r);
4133 r.dump(pw, " ");
4134 }
4135 needSep = true;
4136 }
4137
4138 if (dumpAll) {
4139 printed = false;
4140 for (int ic=0; ic<mServiceConnections.size(); ic++) {
4141 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
4142 for (int i=0; i<r.size(); i++) {
4143 ConnectionRecord cr = r.get(i);
4144 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
4145 continue;
4146 }
4147 if (dumpPackage != null && (cr.binding.client == null
4148 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
4149 continue;
4150 }
4151 printedAnything = true;
4152 if (!printed) {
4153 if (needSep) pw.println();
4154 needSep = true;
4155 pw.println(" Connection bindings to services:");
4156 printed = true;
4157 }
4158 pw.print(" * "); pw.println(cr);
4159 cr.dump(pw, " ");
4160 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004161 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004162 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004163
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004164 if (matcher.all) {
4165 final long nowElapsed = SystemClock.elapsedRealtime();
4166 final int[] users = mAm.mUserController.getUsers();
4167 for (int user : users) {
4168 boolean printedUser = false;
4169 ServiceMap smap = mServiceMap.get(user);
4170 if (smap == null) {
4171 continue;
4172 }
4173 for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) {
4174 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
4175 if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) {
4176 continue;
4177 }
4178 if (!printedUser) {
4179 printedUser = true;
4180 printedAnything = true;
4181 if (needSep) pw.println();
4182 needSep = true;
4183 pw.print("Active foreground apps - user ");
4184 pw.print(user);
4185 pw.println(":");
4186 }
4187 pw.print(" #");
4188 pw.print(i);
4189 pw.print(": ");
4190 pw.println(aa.mPackageName);
4191 if (aa.mLabel != null) {
4192 pw.print(" mLabel=");
4193 pw.println(aa.mLabel);
4194 }
4195 pw.print(" mNumActive=");
4196 pw.print(aa.mNumActive);
Dianne Hackbornbe68d492017-05-03 18:04:05 -07004197 pw.print(" mAppOnTop=");
4198 pw.print(aa.mAppOnTop);
4199 pw.print(" mShownWhileTop=");
4200 pw.print(aa.mShownWhileTop);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004201 pw.print(" mShownWhileScreenOn=");
4202 pw.println(aa.mShownWhileScreenOn);
4203 pw.print(" mStartTime=");
4204 TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw);
4205 pw.print(" mStartVisibleTime=");
4206 TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw);
4207 pw.println();
4208 if (aa.mEndTime != 0) {
4209 pw.print(" mEndTime=");
4210 TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw);
4211 pw.println();
4212 }
4213 }
Dianne Hackborncb015632017-06-14 17:30:15 -07004214 if (smap.hasMessagesOrCallbacks()) {
4215 if (needSep) {
4216 pw.println();
4217 }
4218 printedAnything = true;
4219 needSep = true;
4220 pw.print(" Handler - user ");
4221 pw.print(user);
4222 pw.println(":");
4223 smap.dumpMine(new PrintWriterPrinter(pw), " ");
4224 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004225 }
4226 }
4227
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004228 if (!printedAnything) {
4229 pw.println(" (nothing)");
4230 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07004231 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004232 }
4233
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004234 ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4235 int opti, boolean dumpAll, String dumpPackage) {
4236 return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
4237 }
4238
Yi Jin2b30f322018-02-20 15:41:47 -08004239 protected void writeToProto(ProtoOutputStream proto, long fieldId) {
Yi Jin6b514142017-10-30 14:54:12 -07004240 synchronized (mAm) {
Yi Jin2b30f322018-02-20 15:41:47 -08004241 final long outterToken = proto.start(fieldId);
Yi Jin6b514142017-10-30 14:54:12 -07004242 int[] users = mAm.mUserController.getUsers();
4243 for (int user : users) {
4244 ServiceMap smap = mServiceMap.get(user);
4245 if (smap == null) {
4246 continue;
4247 }
4248 long token = proto.start(ActiveServicesProto.SERVICES_BY_USERS);
4249 proto.write(ActiveServicesProto.ServicesByUser.USER_ID, user);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004250 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
Yi Jin6b514142017-10-30 14:54:12 -07004251 for (int i=0; i<alls.size(); i++) {
4252 alls.valueAt(i).writeToProto(proto,
4253 ActiveServicesProto.ServicesByUser.SERVICE_RECORDS);
4254 }
4255 proto.end(token);
4256 }
Yi Jin2b30f322018-02-20 15:41:47 -08004257 proto.end(outterToken);
Yi Jin6b514142017-10-30 14:54:12 -07004258 }
4259 }
4260
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004261 /**
4262 * There are three ways to call this:
4263 * - no service specified: dump all the services
4264 * - a flattened component name that matched an existing service was specified as the
4265 * first arg: dump that one service
4266 * - the first arg isn't the flattened component name of an existing service:
4267 * dump all services whose component contains the first arg as a substring
4268 */
Makoto Onuki0b575a32018-04-16 14:33:59 -07004269 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, final String name,
4270 String[] args, int opti, boolean dumpAll) {
4271 final ArrayList<ServiceRecord> services = new ArrayList<>();
4272
4273 final Predicate<ServiceRecord> filter = DumpUtils.filterRecord(name);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004274
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004275 synchronized (mAm) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07004276 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004277
Makoto Onuki0b575a32018-04-16 14:33:59 -07004278 for (int user : users) {
4279 ServiceMap smap = mServiceMap.get(user);
4280 if (smap == null) {
4281 continue;
4282 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004283 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
Makoto Onuki0b575a32018-04-16 14:33:59 -07004284 for (int i=0; i<alls.size(); i++) {
4285 ServiceRecord r1 = alls.valueAt(i);
4286
4287 if (filter.test(r1)) {
4288 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004289 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004290 }
4291 }
4292 }
4293
4294 if (services.size() <= 0) {
4295 return false;
4296 }
4297
Makoto Onuki0b575a32018-04-16 14:33:59 -07004298 // Sort by component name.
4299 services.sort(Comparator.comparing(WithComponentName::getComponentName));
4300
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004301 boolean needSep = false;
4302 for (int i=0; i<services.size(); i++) {
4303 if (needSep) {
4304 pw.println();
4305 }
4306 needSep = true;
4307 dumpService("", fd, pw, services.get(i), args, dumpAll);
4308 }
4309 return true;
4310 }
4311
4312 /**
4313 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
4314 * there is a thread associated with the service.
4315 */
4316 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
4317 final ServiceRecord r, String[] args, boolean dumpAll) {
4318 String innerPrefix = prefix + " ";
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004319 synchronized (mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004320 pw.print(prefix); pw.print("SERVICE ");
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004321 pw.print(r.shortInstanceName); pw.print(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004322 pw.print(Integer.toHexString(System.identityHashCode(r)));
4323 pw.print(" pid=");
4324 if (r.app != null) pw.println(r.app.pid);
4325 else pw.println("(not running)");
4326 if (dumpAll) {
4327 r.dump(pw, innerPrefix);
4328 }
4329 }
4330 if (r.app != null && r.app.thread != null) {
4331 pw.print(prefix); pw.println(" Client:");
4332 pw.flush();
4333 try {
4334 TransferPipe tp = new TransferPipe();
4335 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004336 r.app.thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004337 tp.setBufferPrefix(prefix + " ");
4338 tp.go(fd);
4339 } finally {
4340 tp.kill();
4341 }
4342 } catch (IOException e) {
4343 pw.println(prefix + " Failure while dumping the service: " + e);
4344 } catch (RemoteException e) {
4345 pw.println(prefix + " Got a RemoteException while dumping the service");
4346 }
4347 }
4348 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004349}