blob: 2f1f91e1734ac2a9d961776b898bc5b9f7bd0238 [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;
Hui Yu2d4207f2019-01-22 15:32:20 -080020import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST;
Wale Ogunwaled57969f2014-11-15 19:37:29 -080021
Hui Yue361a232018-10-04 15:05:21 -070022import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK;
23import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOREGROUND_SERVICE;
24import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
25import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
26import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE;
27import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE_EXECUTING;
28import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
29import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE;
30import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE_EXECUTING;
31import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
32import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070033
Hui Yue361a232018-10-04 15:05:21 -070034import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070035import android.app.ActivityManagerInternal;
Dianne Hackborn455625e2015-01-21 09:55:13 -080036import android.app.ActivityThread;
Hui Yue361a232018-10-04 15:05:21 -070037import android.app.AppGlobals;
Svet Ganov99b60432015-06-27 13:15:22 -070038import android.app.AppOpsManager;
Hui Yue361a232018-10-04 15:05:21 -070039import android.app.IApplicationThread;
40import android.app.IServiceConnection;
41import android.app.Notification;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070042import android.app.NotificationManager;
Hui Yue361a232018-10-04 15:05:21 -070043import android.app.PendingIntent;
44import android.app.Service;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070045import android.app.ServiceStartArgs;
Hui Yue361a232018-10-04 15:05:21 -070046import android.content.ComponentName;
Makoto Onuki0b575a32018-04-16 14:33:59 -070047import android.content.ComponentName.WithComponentName;
Hui Yue361a232018-10-04 15:05:21 -070048import android.content.Context;
Svet Ganov9c165d72015-12-01 19:52:26 -080049import android.content.IIntentSender;
Hui Yue361a232018-10-04 15:05:21 -070050import android.content.Intent;
Svet Ganov9c165d72015-12-01 19:52:26 -080051import android.content.IntentSender;
Hui Yue361a232018-10-04 15:05:21 -070052import android.content.pm.ApplicationInfo;
53import android.content.pm.PackageManager;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070054import android.content.pm.ParceledListSlice;
Hui Yue361a232018-10-04 15:05:21 -070055import android.content.pm.ResolveInfo;
56import android.content.pm.ServiceInfo;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070057import android.net.Uri;
Hui Yue361a232018-10-04 15:05:21 -070058import android.os.Binder;
Christoph Studer365e4c32014-09-18 20:35:36 +020059import android.os.Build;
Svet Ganov9c165d72015-12-01 19:52:26 -080060import android.os.Bundle;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -070061import android.os.DeadObjectException;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070062import android.os.Handler;
Hui Yue361a232018-10-04 15:05:21 -070063import android.os.IBinder;
Dianne Hackborn13c590d2013-10-07 14:32:00 -070064import android.os.Looper;
Hui Yue361a232018-10-04 15:05:21 -070065import android.os.Message;
66import android.os.Process;
Svet Ganov9c165d72015-12-01 19:52:26 -080067import android.os.RemoteCallback;
Hui Yue361a232018-10-04 15:05:21 -070068import android.os.RemoteException;
69import android.os.SystemClock;
Dianne Hackborn23037412013-11-04 18:11:29 -080070import android.os.SystemProperties;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -070071import android.os.TransactionTooLargeException;
Hui Yue361a232018-10-04 15:05:21 -070072import android.os.UserHandle;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070073import android.provider.Settings;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070074import android.util.ArrayMap;
Dianne Hackborn465fa392014-09-14 14:21:18 -070075import android.util.ArraySet;
Hui Yue361a232018-10-04 15:05:21 -070076import android.util.EventLog;
77import android.util.PrintWriterPrinter;
78import android.util.Slog;
79import android.util.SparseArray;
80import android.util.StatsLog;
81import android.util.TimeUtils;
82import android.util.proto.ProtoOutputStream;
83import android.webkit.WebViewZygote;
Wale Ogunwaled57969f2014-11-15 19:37:29 -080084
Dianne Hackborn83b40f62017-04-26 13:59:47 -070085import com.android.internal.R;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070086import com.android.internal.app.procstats.ServiceState;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070087import com.android.internal.messages.nano.SystemMessageProto;
88import com.android.internal.notification.SystemNotificationChannels;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070089import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborncbfd23e2013-06-11 14:26:53 -070090import com.android.internal.os.TransferPipe;
Makoto Onuki0b575a32018-04-16 14:33:59 -070091import com.android.internal.util.DumpUtils;
Dianne Hackborncff1bbf2015-01-20 13:43:32 -080092import com.android.internal.util.FastPrintWriter;
Christopher Tatec7933ac2018-03-12 17:57:09 -070093import com.android.server.AppStateTracker;
94import com.android.server.LocalServices;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -070095import com.android.server.SystemService;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070096import com.android.server.am.ActivityManagerService.ItemMatcher;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -070097import com.android.server.uri.NeededUriGrants;
Wale Ogunwale59507092018-10-29 09:00:30 -070098import com.android.server.wm.ActivityServiceConnectionsHolder;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070099
Hui Yue361a232018-10-04 15:05:21 -0700100import java.io.FileDescriptor;
101import java.io.IOException;
102import java.io.PrintWriter;
103import java.io.StringWriter;
104import java.util.ArrayList;
105import java.util.Comparator;
106import java.util.Iterator;
107import java.util.List;
108import java.util.Set;
109import java.util.function.Predicate;
110
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -0700111public final class ActiveServices {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800112 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM;
113 private static final String TAG_MU = TAG + POSTFIX_MU;
114 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
115 private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING;
116
117 private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE;
118 private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE;
119
120 private static final boolean LOG_SERVICE_START_STOP = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700121
Dianne Hackborn070d1422018-05-02 13:48:30 -0700122 private static final boolean SHOW_DUNGEON_NOTIFICATION = false;
123
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700124 // How long we wait for a service to finish executing.
125 static final int SERVICE_TIMEOUT = 20*1000;
126
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700127 // How long we wait for a service to finish executing.
128 static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
129
Christopher Tate08992ac2017-03-21 11:37:06 -0700130 // How long the startForegroundService() grace period is to get around to
131 // calling startForeground() before we ANR + stop it.
Christopher Tate5e5c3452018-05-25 13:12:12 -0700132 static final int SERVICE_START_FOREGROUND_TIMEOUT = 10*1000;
Christopher Tate08992ac2017-03-21 11:37:06 -0700133
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000134 // For how long after a whitelisted service's start its process can start a background activity
135 private static final int SERVICE_BG_ACTIVITY_START_TIMEOUT_MS = 10*1000;
136
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700137 final ActivityManagerService mAm;
138
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700139 // Maximum number of services that we allow to start in the background
140 // at the same time.
141 final int mMaxStartingBackground;
142
Wale Ogunwale540e1232015-05-01 15:35:39 -0700143 final SparseArray<ServiceMap> mServiceMap = new SparseArray<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700144
145 /**
146 * All currently bound service connections. Keys are the IBinder of
147 * the client's IServiceConnection.
148 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700149 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700150
151 /**
152 * List of services that we have been asked to start,
153 * but haven't yet been able to. It is used to hold start requests
154 * while waiting for their corresponding application thread to get
155 * going.
156 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700157 final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700158
159 /**
160 * List of services that are scheduled to restart following a crash.
161 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700162 final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700163
164 /**
Dianne Hackborn164371f2013-10-01 19:10:13 -0700165 * List of services that are in the process of being destroyed.
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700166 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700167 final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>();
168
169 /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */
170 private ArrayList<ServiceRecord> mTmpCollectionResults = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700171
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700172 /**
173 * For keeping ActiveForegroundApps retaining state while the screen is off.
174 */
175 boolean mScreenOn = true;
176
Dianne Hackborncff1bbf2015-01-20 13:43:32 -0800177 /** Amount of time to allow a last ANR message to exist before freeing the memory. */
178 static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
179
180 String mLastAnrDump;
181
182 final Runnable mLastAnrDumpClearer = new Runnable() {
183 @Override public void run() {
184 synchronized (mAm) {
185 mLastAnrDump = null;
186 }
187 }
188 };
189
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700190 /**
Christopher Tatec7933ac2018-03-12 17:57:09 -0700191 * Watch for apps being put into forced app standby, so we can step their fg
192 * services down.
193 */
194 class ForcedStandbyListener extends AppStateTracker.Listener {
195 @Override
196 public void stopForegroundServicesForUidPackage(final int uid, final String packageName) {
197 synchronized (mAm) {
198 final ServiceMap smap = getServiceMapLocked(UserHandle.getUserId(uid));
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800199 final int N = smap.mServicesByInstanceName.size();
Christopher Tatec7933ac2018-03-12 17:57:09 -0700200 final ArrayList<ServiceRecord> toStop = new ArrayList<>(N);
201 for (int i = 0; i < N; i++) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800202 final ServiceRecord r = smap.mServicesByInstanceName.valueAt(i);
Christopher Tatec7933ac2018-03-12 17:57:09 -0700203 if (uid == r.serviceInfo.applicationInfo.uid
204 || packageName.equals(r.serviceInfo.packageName)) {
205 if (r.isForeground) {
206 toStop.add(r);
207 }
208 }
209 }
210
211 // Now stop them all
212 final int numToStop = toStop.size();
213 if (numToStop > 0 && DEBUG_FOREGROUND_SERVICE) {
214 Slog.i(TAG, "Package " + packageName + "/" + uid
215 + " entering FAS with foreground services");
216 }
217 for (int i = 0; i < numToStop; i++) {
218 final ServiceRecord r = toStop.get(i);
219 if (DEBUG_FOREGROUND_SERVICE) {
220 Slog.i(TAG, " Stopping fg for service " + r);
221 }
Hui Yu2d4207f2019-01-22 15:32:20 -0800222 setServiceForegroundInnerLocked(r, 0, null, 0, 0);
Christopher Tatec7933ac2018-03-12 17:57:09 -0700223 }
224 }
225 }
226 }
227
228 /**
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700229 * Information about an app that is currently running one or more foreground services.
Dan Sandler2f36ab82017-05-25 00:15:49 -0400230 * (This maps directly to the running apps we show in the notification.)
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700231 */
232 static final class ActiveForegroundApp {
233 String mPackageName;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700234 int mUid;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700235 CharSequence mLabel;
236 boolean mShownWhileScreenOn;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700237 boolean mAppOnTop;
238 boolean mShownWhileTop;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700239 long mStartTime;
240 long mStartVisibleTime;
241 long mEndTime;
242 int mNumActive;
Dianne Hackborncb015632017-06-14 17:30:15 -0700243
244 // Temp output of foregroundAppShownEnoughLocked
245 long mHideTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700246 }
247
248 /**
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700249 * Information about services for a single user.
250 */
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700251 final class ServiceMap extends Handler {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700252 final int mUserId;
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800253 final ArrayMap<ComponentName, ServiceRecord> mServicesByInstanceName = new ArrayMap<>();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700254 final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700255
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700256 final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700257 /* XXX eventually I'd like to have this based on processes instead of services.
258 * That is, if we try to start two services in a row both running in the same
259 * process, this should be one entry in mStartingBackground for that one process
260 * that remains until all services in it are done.
261 final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
262 = new ArrayMap<ProcessRecord, DelayingProcess>();
263 final ArrayList<DelayingProcess> mStartingProcessList
264 = new ArrayList<DelayingProcess>();
265 */
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700266
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700267 final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700268
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700269 final ArrayMap<String, ActiveForegroundApp> mActiveForegroundApps = new ArrayMap<>();
270 boolean mActiveForegroundAppsChanged;
271
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700272 static final int MSG_BG_START_TIMEOUT = 1;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700273 static final int MSG_UPDATE_FOREGROUND_APPS = 2;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700274
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700275 ServiceMap(Looper looper, int userId) {
276 super(looper);
Dianne Hackborn6285a322013-09-18 12:09:47 -0700277 mUserId = userId;
278 }
279
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700280 @Override
281 public void handleMessage(Message msg) {
282 switch (msg.what) {
283 case MSG_BG_START_TIMEOUT: {
284 synchronized (mAm) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700285 rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700286 }
287 } break;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700288 case MSG_UPDATE_FOREGROUND_APPS: {
289 updateForegroundApps(this);
290 } break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700291 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700292 }
293
Dianne Hackbornad51be92016-08-16 16:27:36 -0700294 void ensureNotStartingBackgroundLocked(ServiceRecord r) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700295 if (mStartingBackground.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800296 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
297 "No longer background starting: " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -0700298 rescheduleDelayedStartsLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700299 }
Dianne Hackborn2e46bb52013-09-13 17:01:26 -0700300 if (mDelayedStartList.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800301 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700302 }
303 }
304
Dianne Hackbornad51be92016-08-16 16:27:36 -0700305 void rescheduleDelayedStartsLocked() {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700306 removeMessages(MSG_BG_START_TIMEOUT);
307 final long now = SystemClock.uptimeMillis();
308 for (int i=0, N=mStartingBackground.size(); i<N; i++) {
309 ServiceRecord r = mStartingBackground.get(i);
310 if (r.startingBgTimeout <= now) {
311 Slog.i(TAG, "Waited long enough for: " + r);
312 mStartingBackground.remove(i);
313 N--;
Junu Kimfcb87362014-02-19 16:25:21 +0900314 i--;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700315 }
316 }
317 while (mDelayedStartList.size() > 0
318 && mStartingBackground.size() < mMaxStartingBackground) {
319 ServiceRecord r = mDelayedStartList.remove(0);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800320 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
321 "REM FR DELAY LIST (exec next): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700322 if (r.pendingStarts.size() <= 0) {
323 Slog.w(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
324 + " delayedStop=" + r.delayedStop);
325 }
326 if (DEBUG_DELAYED_SERVICE) {
327 if (mDelayedStartList.size() > 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800328 Slog.v(TAG_SERVICE, "Remaining delayed list:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700329 for (int i=0; i<mDelayedStartList.size(); i++) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800330 Slog.v(TAG_SERVICE, " #" + i + ": " + mDelayedStartList.get(i));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700331 }
332 }
333 }
334 r.delayed = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700335 try {
336 startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false, true);
337 } catch (TransactionTooLargeException e) {
338 // Ignore, nobody upstack cares.
339 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700340 }
341 if (mStartingBackground.size() > 0) {
342 ServiceRecord next = mStartingBackground.get(0);
343 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800344 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700345 + ", can delay others up to " + when);
346 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
347 sendMessageAtTime(msg, when);
348 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700349 if (mStartingBackground.size() < mMaxStartingBackground) {
350 mAm.backgroundServicesFinishedLocked(mUserId);
351 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700352 }
353 }
354
355 public ActiveServices(ActivityManagerService service) {
356 mAm = service;
Dianne Hackborn23037412013-11-04 18:11:29 -0800357 int maxBg = 0;
358 try {
359 maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
360 } catch(RuntimeException e) {
361 }
Dianne Hackborn20d94742014-05-29 18:35:45 -0700362 mMaxStartingBackground = maxBg > 0
363 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700364 }
365
Christopher Tatec7933ac2018-03-12 17:57:09 -0700366 void systemServicesReady() {
367 AppStateTracker ast = LocalServices.getService(AppStateTracker.class);
368 ast.addListener(new ForcedStandbyListener());
369 }
370
Dianne Hackbornad51be92016-08-16 16:27:36 -0700371 ServiceRecord getServiceByNameLocked(ComponentName name, int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700372 // TODO: Deal with global services
373 if (DEBUG_MU)
Dianne Hackbornad51be92016-08-16 16:27:36 -0700374 Slog.v(TAG_MU, "getServiceByNameLocked(" + name + "), callingUser = " + callingUser);
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800375 return getServiceMapLocked(callingUser).mServicesByInstanceName.get(name);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700376 }
377
Dianne Hackbornad51be92016-08-16 16:27:36 -0700378 boolean hasBackgroundServicesLocked(int callingUser) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700379 ServiceMap smap = mServiceMap.get(callingUser);
380 return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
381 }
382
Dianne Hackbornad51be92016-08-16 16:27:36 -0700383 private ServiceMap getServiceMapLocked(int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700384 ServiceMap smap = mServiceMap.get(callingUser);
385 if (smap == null) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700386 smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700387 mServiceMap.put(callingUser, smap);
388 }
389 return smap;
390 }
391
Dianne Hackbornad51be92016-08-16 16:27:36 -0700392 ArrayMap<ComponentName, ServiceRecord> getServicesLocked(int callingUser) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800393 return getServiceMapLocked(callingUser).mServicesByInstanceName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700394 }
395
Christopher Tatec7933ac2018-03-12 17:57:09 -0700396 private boolean appRestrictedAnyInBackground(final int uid, final String packageName) {
397 final int mode = mAm.mAppOpsService.checkOperation(
398 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, uid, packageName);
399 return (mode != AppOpsManager.MODE_ALLOWED);
400 }
401
Svet Ganov99b60432015-06-27 13:15:22 -0700402 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
Christopher Tate242ba3e92017-04-14 15:07:06 -0700403 int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700404 throws TransactionTooLargeException {
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000405 return startServiceLocked(caller, service, resolvedType, callingPid, callingUid, fgRequired,
406 callingPackage, userId, false);
407 }
408
409 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
410 int callingPid, int callingUid, boolean fgRequired, String callingPackage,
411 final int userId, boolean allowBackgroundActivityStarts)
412 throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800413 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700414 + " type=" + resolvedType + " args=" + service.getExtras());
415
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700416 final boolean callerFg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700417 if (caller != null) {
418 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
419 if (callerApp == null) {
420 throw new SecurityException(
421 "Unable to find app for caller " + caller
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700422 + " (pid=" + callingPid
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700423 + ") when starting service " + service);
424 }
Dianne Hackborna49ad092016-03-03 13:39:10 -0800425 callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700426 } else {
427 callerFg = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700428 }
429
430 ServiceLookupResult res =
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800431 retrieveServiceLocked(service, null, resolvedType, callingPackage,
Svet Ganovd223db32017-12-22 09:43:48 -0800432 callingPid, callingUid, userId, true, callerFg, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700433 if (res == null) {
434 return null;
435 }
436 if (res.record == null) {
437 return new ComponentName("!", res.permission != null
438 ? res.permission : "private to package");
439 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700440
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700441 ServiceRecord r = res.record;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700442
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700443 if (!mAm.mUserController.exists(r.userId)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700444 Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700445 return null;
446 }
447
Christopher Tate85048282018-03-30 14:08:59 -0700448 // If we're starting indirectly (e.g. from PendingIntent), figure out whether
Christopher Tate45f06c792018-04-25 10:47:23 -0700449 // we're launching into an app in a background state. This keys off of the same
450 // idleness state tracking as e.g. O+ background service start policy.
451 final boolean bgLaunch = !mAm.isUidActiveLocked(r.appInfo.uid);
Christopher Tate85048282018-03-30 14:08:59 -0700452
453 // If the app has strict background restrictions, we treat any bg service
454 // start analogously to the legacy-app forced-restrictions case, regardless
455 // of its target SDK version.
Christopher Tatec7933ac2018-03-12 17:57:09 -0700456 boolean forcedStandby = false;
Christopher Tate85048282018-03-30 14:08:59 -0700457 if (bgLaunch && appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
Christopher Tatec7933ac2018-03-12 17:57:09 -0700458 if (DEBUG_FOREGROUND_SERVICE) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800459 Slog.d(TAG, "Forcing bg-only service start only for " + r.shortInstanceName
Christopher Tate85048282018-03-30 14:08:59 -0700460 + " : bgLaunch=" + bgLaunch + " callerFg=" + callerFg);
Christopher Tatec7933ac2018-03-12 17:57:09 -0700461 }
462 forcedStandby = true;
463 }
464
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700465 // If this is a direct-to-foreground start, make sure it is allowed as per the app op.
466 boolean forceSilentAbort = false;
467 if (fgRequired) {
468 final int mode = mAm.mAppOpsService.checkOperation(
469 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
470 switch (mode) {
471 case AppOpsManager.MODE_ALLOWED:
472 case AppOpsManager.MODE_DEFAULT:
473 // All okay.
474 break;
475 case AppOpsManager.MODE_IGNORED:
476 // Not allowed, fall back to normal start service, failing siliently
477 // if background check restricts that.
478 Slog.w(TAG, "startForegroundService not allowed due to app op: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800479 + service + " to " + r.shortInstanceName
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700480 + " from pid=" + callingPid + " uid=" + callingUid
481 + " pkg=" + callingPackage);
482 fgRequired = false;
483 forceSilentAbort = true;
484 break;
485 default:
486 return new ComponentName("!!", "foreground not allowed as per app op");
487 }
488 }
489
Christopher Tate08992ac2017-03-21 11:37:06 -0700490 // If this isn't a direct-to-foreground start, check our ability to kick off an
491 // arbitrary service
Christopher Tatec7933ac2018-03-12 17:57:09 -0700492 if (forcedStandby || (!r.startRequested && !fgRequired)) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700493 // Before going further -- if this app is not allowed to start services in the
494 // background, then at this point we aren't going to let it period.
495 final int allowed = mAm.getAppStartModeLocked(r.appInfo.uid, r.packageName,
Christopher Tatec7933ac2018-03-12 17:57:09 -0700496 r.appInfo.targetSdkVersion, callingPid, false, false, forcedStandby);
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700497 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
498 Slog.w(TAG, "Background start not allowed: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800499 + service + " to " + r.shortInstanceName
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700500 + " from pid=" + callingPid + " uid=" + callingUid
Christopher Tatee84ffd92018-05-16 12:59:43 -0700501 + " pkg=" + callingPackage + " startFg?=" + fgRequired);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700502 if (allowed == ActivityManager.APP_START_MODE_DELAYED || forceSilentAbort) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700503 // In this case we are silently disabling the app, to disrupt as
504 // little as possible existing apps.
505 return null;
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700506 }
Christopher Tatee84ffd92018-05-16 12:59:43 -0700507 if (forcedStandby) {
508 // This is an O+ app, but we might be here because the user has placed
509 // it under strict background restrictions. Don't punish the app if it's
510 // trying to do the right thing but we're denying it for that reason.
511 if (fgRequired) {
512 if (DEBUG_BACKGROUND_CHECK) {
513 Slog.v(TAG, "Silently dropping foreground service launch due to FAS");
514 }
515 return null;
516 }
517 }
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700518 // This app knows it is in the new model where this operation is not
519 // allowed, so tell it what has happened.
Amith Yamasaniaa746442019-01-10 10:09:12 -0800520 UidRecord uidRec = mAm.mProcessList.getUidRecordLocked(r.appInfo.uid);
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700521 return new ComponentName("?", "app is in background uid " + uidRec);
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700522 }
523 }
524
Christopher Tate0a826902018-05-25 15:15:44 -0700525 // At this point we've applied allowed-to-start policy based on whether this was
526 // an ordinary startService() or a startForegroundService(). Now, only require that
527 // the app follow through on the startForegroundService() -> startForeground()
528 // contract if it actually targets O+.
529 if (r.appInfo.targetSdkVersion < Build.VERSION_CODES.O && fgRequired) {
530 if (DEBUG_BACKGROUND_CHECK || DEBUG_FOREGROUND_SERVICE) {
531 Slog.i(TAG, "startForegroundService() but host targets "
532 + r.appInfo.targetSdkVersion + " - not requiring startForeground()");
533 }
534 fgRequired = false;
535 }
536
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700537 NeededUriGrants neededGrants = mAm.mUgmInternal.checkGrantUriPermissionFromIntent(
Nicolas Prevotc6cf95c2014-05-29 11:30:36 +0100538 callingUid, r.packageName, service, service.getFlags(), null, r.userId);
Svet Ganov9c165d72015-12-01 19:52:26 -0800539
540 // If permissions need a review before any of the app components can run,
541 // we do not start the service and launch a review activity if the calling app
542 // is in the foreground passing it a pending intent to start the service when
543 // review is completed.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700544
545 // XXX This is not dealing with fgRequired!
546 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage,
547 callingUid, service, callerFg, userId)) {
548 return null;
Svet Ganov9c165d72015-12-01 19:52:26 -0800549 }
550
Dianne Hackbornd6f5b622013-11-11 17:25:37 -0800551 if (unscheduleServiceRestartLocked(r, callingUid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800552 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700553 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700554 r.lastActivity = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700555 r.startRequested = true;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700556 r.delayedStop = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700557 r.fgRequired = fgRequired;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700558 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -0700559 service, neededGrants, callingUid));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700560
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700561 if (fgRequired) {
562 // We are now effectively running a foreground service.
Dianne Hackborn2aec55a2018-06-26 10:35:35 -0700563 ServiceState stracker = r.getTracker();
564 if (stracker != null) {
565 stracker.setForeground(true, mAm.mProcessStats.getMemFactorLocked(),
566 r.lastActivity);
567 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700568 mAm.mAppOpsService.startOperation(AppOpsManager.getToken(mAm.mAppOpsService),
569 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, true);
570 }
571
Dianne Hackbornad51be92016-08-16 16:27:36 -0700572 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700573 boolean addToStarting = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700574 if (!callerFg && !fgRequired && r.app == null
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700575 && mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700576 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700577 if (proc == null || proc.getCurProcState() > ActivityManager.PROCESS_STATE_RECEIVER) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700578 // If this is not coming from a foreground caller, then we may want
579 // to delay the start if there are already other background services
580 // that are starting. This is to avoid process start spam when lots
581 // of applications are all handling things like connectivity broadcasts.
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700582 // We only do this for cached processes, because otherwise an application
583 // can have assumptions about calling startService() for a service to run
584 // in its own process, and for that process to not be killed before the
585 // service is started. This is especially the case for receivers, which
586 // may start a service in onReceive() to do some additional work and have
587 // initialized some global state as part of that.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800588 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
589 + r + " in " + proc);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700590 if (r.delayed) {
591 // This service is already scheduled for a delayed start; just leave
592 // it still waiting.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800593 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700594 return r.name;
595 }
596 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
597 // Something else is starting, delay!
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800598 Slog.i(TAG_SERVICE, "Delaying start of: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700599 smap.mDelayedStartList.add(r);
600 r.delayed = true;
601 return r.name;
602 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800603 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700604 addToStarting = true;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700605 } else if (proc.getCurProcState() >= ActivityManager.PROCESS_STATE_SERVICE) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700606 // We slightly loosen when we will enqueue this new service as a background
607 // starting service we are waiting for, to also include processes that are
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700608 // currently running other services or receivers.
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700609 addToStarting = true;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800610 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
611 "Not delaying, but counting as bg: " + r);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800612 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn8e692572013-09-10 19:06:15 -0700613 StringBuilder sb = new StringBuilder(128);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700614 sb.append("Not potential delay (state=").append(proc.getCurProcState())
Dianne Hackborn8e692572013-09-10 19:06:15 -0700615 .append(' ').append(proc.adjType);
616 String reason = proc.makeAdjReason();
617 if (reason != null) {
618 sb.append(' ');
619 sb.append(reason);
620 }
621 sb.append("): ");
622 sb.append(r.toString());
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800623 Slog.v(TAG_SERVICE, sb.toString());
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700624 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800625 } else if (DEBUG_DELAYED_STARTS) {
Christopher Tate08992ac2017-03-21 11:37:06 -0700626 if (callerFg || fgRequired) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800627 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
Christopher Tate08992ac2017-03-21 11:37:06 -0700628 + callingUid + " pid=" + callingPid + " fgRequired=" + fgRequired + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700629 } else if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800630 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700631 } else {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800632 Slog.v(TAG_SERVICE,
633 "Not potential delay (user " + r.userId + " not started): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700634 }
635 }
636
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000637 if (allowBackgroundActivityStarts) {
638 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
639 if (proc != null) {
640 proc.addAllowBackgroundActivityStartsToken(r);
641 // schedule removal of the whitelisting token after the timeout
642 removeAllowBackgroundActivityStartsServiceToken(proc, r,
643 SERVICE_BG_ACTIVITY_START_TIMEOUT_MS);
644 }
645 }
Christopher Tate42a386b2016-11-07 12:21:21 -0800646 ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
Christopher Tate42a386b2016-11-07 12:21:21 -0800647 return cmp;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700648 }
649
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000650 private void removeAllowBackgroundActivityStartsServiceToken(ProcessRecord proc,
651 ServiceRecord r, int delayMillis) {
652 mAm.mHandler.postDelayed(() -> {
653 if (proc != null) {
654 proc.removeAllowBackgroundActivityStartsToken(r);
655 }
656 }, delayMillis);
657 }
658
Svet Ganov9c165d72015-12-01 19:52:26 -0800659 private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
660 String callingPackage, int callingUid, Intent service, boolean callerFg,
661 final int userId) {
662 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
663 r.packageName, r.userId)) {
664
665 // Show a permission review UI only for starting from a foreground app
666 if (!callerFg) {
667 Slog.w(TAG, "u" + r.userId + " Starting a service in package"
668 + r.packageName + " requires a permissions review");
669 return false;
670 }
671
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700672 IIntentSender target = mAm.mPendingIntentController.getIntentSender(
Svet Ganov9c165d72015-12-01 19:52:26 -0800673 ActivityManager.INTENT_SENDER_SERVICE, callingPackage,
674 callingUid, userId, null, null, 0, new Intent[]{service},
675 new String[]{service.resolveType(mAm.mContext.getContentResolver())},
676 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
677 | PendingIntent.FLAG_IMMUTABLE, null);
678
679 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
680 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
Philip P. Moltmann751e46ca2019-01-24 13:56:47 -0800681 | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
Svet Ganov9c165d72015-12-01 19:52:26 -0800682 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
683 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
684 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
685
686 if (DEBUG_PERMISSIONS_REVIEW) {
687 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
688 + r.packageName);
689 }
690
691 mAm.mHandler.post(new Runnable() {
692 @Override
693 public void run() {
694 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
695 }
696 });
697
698 return false;
699 }
700
701 return true;
702 }
703
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700704 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
705 boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
Joe Onorato4eb64fd2016-03-21 15:30:09 -0700706 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700707 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700708 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700709 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700710 r.callStart = false;
Chenjie Yu75b3c492018-10-06 21:45:19 -0700711 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid, r.name.getPackageName(),
712 r.name.getClassName(), StatsLog.SERVICE_STATE_CHANGED__STATE__START);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700713 synchronized (r.stats.getBatteryStats()) {
714 r.stats.startRunningLocked();
715 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800716 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700717 if (error != null) {
718 return new ComponentName("!!", error);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700719 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700720
721 if (r.startRequested && addToStarting) {
722 boolean first = smap.mStartingBackground.size() == 0;
723 smap.mStartingBackground.add(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700724 r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700725 if (DEBUG_DELAYED_SERVICE) {
726 RuntimeException here = new RuntimeException("here");
727 here.fillInStackTrace();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800728 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800729 } else if (DEBUG_DELAYED_STARTS) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800730 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700731 }
732 if (first) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700733 smap.rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700734 }
Christopher Tate08992ac2017-03-21 11:37:06 -0700735 } else if (callerFg || r.fgRequired) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700736 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700737 }
738
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700739 return r.name;
740 }
741
742 private void stopServiceLocked(ServiceRecord service) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700743 if (service.delayed) {
Mohammad Samiul Islame896c212019-01-10 12:14:23 +0000744 // If service isn't actually running, but is being held in the
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700745 // delayed list, then we need to keep it started but note that it
746 // should be stopped once no longer delayed.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800747 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700748 service.delayedStop = true;
749 return;
750 }
Chenjie Yu75b3c492018-10-06 21:45:19 -0700751 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, service.appInfo.uid,
752 service.name.getPackageName(), service.name.getClassName(),
753 StatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700754 synchronized (service.stats.getBatteryStats()) {
755 service.stats.stopRunningLocked();
756 }
757 service.startRequested = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700758 if (service.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700759 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700760 SystemClock.uptimeMillis());
761 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700762 service.callStart = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700763 bringDownServiceIfNeededLocked(service, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700764 }
765
766 int stopServiceLocked(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700767 String resolvedType, int userId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800768 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700769 + " type=" + resolvedType);
770
771 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
772 if (caller != null && callerApp == null) {
773 throw new SecurityException(
774 "Unable to find app for caller " + caller
775 + " (pid=" + Binder.getCallingPid()
776 + ") when stopping service " + service);
777 }
778
779 // If this service is active, make sure it is stopped.
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800780 ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, null,
Svet Ganovd223db32017-12-22 09:43:48 -0800781 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700782 if (r != null) {
783 if (r.record != null) {
784 final long origId = Binder.clearCallingIdentity();
785 try {
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000786 // immediately remove bg activity whitelisting token if there was one
787 removeAllowBackgroundActivityStartsServiceToken(callerApp, r.record,
788 0 /* delayMillis */);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700789 stopServiceLocked(r.record);
790 } finally {
791 Binder.restoreCallingIdentity(origId);
792 }
793 return 1;
794 }
795 return -1;
796 }
797
798 return 0;
799 }
800
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700801 void stopInBackgroundLocked(int uid) {
802 // Stop all services associated with this uid due to it going to the background
803 // stopped state.
804 ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
805 ArrayList<ServiceRecord> stopping = null;
806 if (services != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800807 for (int i = services.mServicesByInstanceName.size() - 1; i >= 0; i--) {
808 ServiceRecord service = services.mServicesByInstanceName.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700809 if (service.appInfo.uid == uid && service.startRequested) {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800810 if (mAm.getAppStartModeLocked(service.appInfo.uid, service.packageName,
Christopher Tatec7933ac2018-03-12 17:57:09 -0700811 service.appInfo.targetSdkVersion, -1, false, false, false)
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800812 != ActivityManager.APP_START_MODE_NORMAL) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700813 if (stopping == null) {
814 stopping = new ArrayList<>();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700815 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800816 String compName = service.shortInstanceName;
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700817 EventLogTags.writeAmStopIdleService(service.appInfo.uid, compName);
818 StringBuilder sb = new StringBuilder(64);
819 sb.append("Stopping service due to app idle: ");
820 UserHandle.formatUid(sb, service.appInfo.uid);
821 sb.append(" ");
Yi Jin6b514142017-10-30 14:54:12 -0700822 TimeUtils.formatDuration(service.createRealTime
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700823 - SystemClock.elapsedRealtime(), sb);
824 sb.append(" ");
825 sb.append(compName);
826 Slog.w(TAG, sb.toString());
827 stopping.add(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700828 }
829 }
830 }
831 if (stopping != null) {
832 for (int i=stopping.size()-1; i>=0; i--) {
833 ServiceRecord service = stopping.get(i);
834 service.delayed = false;
Dianne Hackbornad51be92016-08-16 16:27:36 -0700835 services.ensureNotStartingBackgroundLocked(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700836 stopServiceLocked(service);
837 }
838 }
839 }
840 }
841
Svet Ganov99b60432015-06-27 13:15:22 -0700842 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800843 ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, callingPackage,
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -0700844 Binder.getCallingPid(), Binder.getCallingUid(),
Svet Ganovd223db32017-12-22 09:43:48 -0800845 UserHandle.getCallingUserId(), false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700846
847 IBinder ret = null;
848 if (r != null) {
849 // r.record is null if findServiceLocked() failed the caller permission check
850 if (r.record == null) {
851 throw new SecurityException(
Christopher Desjardins5862c5f2015-05-19 11:25:40 +0000852 "Permission Denial: Accessing service"
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700853 + " from pid=" + Binder.getCallingPid()
854 + ", uid=" + Binder.getCallingUid()
855 + " requires " + r.permission);
856 }
857 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
858 if (ib != null) {
859 ret = ib.binder;
860 }
861 }
862
863 return ret;
864 }
865
866 boolean stopServiceTokenLocked(ComponentName className, IBinder token,
867 int startId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800868 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700869 + " " + token + " startId=" + startId);
Dianne Hackborn41203752012-08-31 14:05:51 -0700870 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700871 if (r != null) {
872 if (startId >= 0) {
873 // Asked to only stop if done with all work. Note that
874 // to avoid leaks, we will take this as dropping all
875 // start items up to and including this one.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -0700876 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700877 if (si != null) {
878 while (r.deliveredStarts.size() > 0) {
879 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
880 cur.removeUriPermissionsLocked();
881 if (cur == si) {
882 break;
883 }
884 }
885 }
886
887 if (r.getLastStartId() != startId) {
888 return false;
889 }
890
891 if (r.deliveredStarts.size() > 0) {
892 Slog.w(TAG, "stopServiceToken startId " + startId
893 + " is last, but have " + r.deliveredStarts.size()
894 + " remaining args");
895 }
896 }
897
Chenjie Yu75b3c492018-10-06 21:45:19 -0700898 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid, r.name.getPackageName(),
899 r.name.getClassName(), StatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700900 synchronized (r.stats.getBatteryStats()) {
901 r.stats.stopRunningLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700902 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700903 r.startRequested = false;
904 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700905 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700906 SystemClock.uptimeMillis());
907 }
908 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700909 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700910 bringDownServiceIfNeededLocked(r, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700911 Binder.restoreCallingIdentity(origId);
912 return true;
913 }
914 return false;
915 }
916
Sudheer Shankac9d94072017-02-22 22:13:55 +0000917 public void setServiceForegroundLocked(ComponentName className, IBinder token,
Hui Yu2d4207f2019-01-22 15:32:20 -0800918 int id, Notification notification, int flags, int foregroundServiceType) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700919 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700920 final long origId = Binder.clearCallingIdentity();
921 try {
Dianne Hackborn41203752012-08-31 14:05:51 -0700922 ServiceRecord r = findServiceLocked(className, token, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700923 if (r != null) {
Hui Yu2d4207f2019-01-22 15:32:20 -0800924 setServiceForegroundInnerLocked(r, id, notification, flags, foregroundServiceType);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700925 }
926 } finally {
927 Binder.restoreCallingIdentity(origId);
928 }
929 }
930
Dianne Hackborncb015632017-06-14 17:30:15 -0700931 boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) {
932 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid="
933 + aa.mUid);
934 boolean canRemove = false;
935 aa.mHideTime = Long.MAX_VALUE;
936 if (aa.mShownWhileTop) {
937 // If the app was ever at the top of the screen while the foreground
938 // service was running, then we can always just immediately remove it.
939 canRemove = true;
940 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown while on top");
941 } else if (mScreenOn || aa.mShownWhileScreenOn) {
942 final long minTime = aa.mStartVisibleTime
943 + (aa.mStartTime != aa.mStartVisibleTime
944 ? mAm.mConstants.FGSERVICE_SCREEN_ON_AFTER_TIME
945 : mAm.mConstants.FGSERVICE_MIN_SHOWN_TIME);
946 if (nowElapsed >= minTime) {
947 // If shown while the screen is on, and it has been shown for
948 // at least the minimum show time, then we can now remove it.
949 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown long enough with screen on");
950 canRemove = true;
951 } else {
952 // This is when we will be okay to stop telling the user.
953 long reportTime = nowElapsed + mAm.mConstants.FGSERVICE_MIN_REPORT_TIME;
954 aa.mHideTime = reportTime > minTime ? reportTime : minTime;
955 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
956 + " with screen on");
957 }
958 } else {
959 final long minTime = aa.mEndTime
960 + mAm.mConstants.FGSERVICE_SCREEN_ON_BEFORE_TIME;
961 if (nowElapsed >= minTime) {
962 // If the foreground service has only run while the screen is
963 // off, but it has been gone now for long enough that we won't
964 // care to tell the user about it when the screen comes back on,
965 // then we can remove it now.
966 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - gone long enough with screen off");
967 canRemove = true;
968 } else {
969 // This is when we won't care about this old fg service.
970 aa.mHideTime = minTime;
971 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
972 + " with screen off");
973 }
974 }
975 return canRemove;
976 }
977
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700978 void updateForegroundApps(ServiceMap smap) {
979 // This is called from the handler without the lock held.
980 ArrayList<ActiveForegroundApp> active = null;
981 synchronized (mAm) {
982 final long now = SystemClock.elapsedRealtime();
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700983 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700984 if (smap != null) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700985 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Updating foreground apps for user "
986 + smap.mUserId);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700987 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
988 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -0700989 if (aa.mEndTime != 0) {
990 boolean canRemove = foregroundAppShownEnoughLocked(aa, now);
991 if (canRemove) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700992 // This was up for longer than the timeout, so just remove immediately.
993 smap.mActiveForegroundApps.removeAt(i);
994 smap.mActiveForegroundAppsChanged = true;
995 continue;
996 }
Dianne Hackborncb015632017-06-14 17:30:15 -0700997 if (aa.mHideTime < nextUpdateTime) {
998 nextUpdateTime = aa.mHideTime;
999 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001000 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001001 if (!aa.mAppOnTop) {
1002 if (active == null) {
1003 active = new ArrayList<>();
1004 }
Dianne Hackborncb015632017-06-14 17:30:15 -07001005 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
1006 + aa.mPackageName + ", uid=" + aa.mUid);
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001007 active.add(aa);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001008 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001009 }
1010 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
1011 if (nextUpdateTime < Long.MAX_VALUE) {
Dianne Hackborncb015632017-06-14 17:30:15 -07001012 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Next update time in: "
1013 + (nextUpdateTime-now));
1014 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001015 smap.sendMessageAtTime(msg, nextUpdateTime
1016 + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001017 }
1018 }
1019 if (!smap.mActiveForegroundAppsChanged) {
1020 return;
1021 }
1022 smap.mActiveForegroundAppsChanged = false;
1023 }
1024
Dianne Hackborn070d1422018-05-02 13:48:30 -07001025 if (!SHOW_DUNGEON_NOTIFICATION) {
1026 return;
1027 }
1028
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001029 final NotificationManager nm = (NotificationManager) mAm.mContext.getSystemService(
1030 Context.NOTIFICATION_SERVICE);
1031 final Context context = mAm.mContext;
1032
1033 if (active != null) {
1034 for (int i = 0; i < active.size(); i++) {
1035 ActiveForegroundApp aa = active.get(i);
1036 if (aa.mLabel == null) {
1037 PackageManager pm = context.getPackageManager();
1038 try {
1039 ApplicationInfo ai = pm.getApplicationInfoAsUser(aa.mPackageName,
1040 PackageManager.MATCH_KNOWN_PACKAGES, smap.mUserId);
1041 aa.mLabel = ai.loadLabel(pm);
1042 } catch (PackageManager.NameNotFoundException e) {
1043 aa.mLabel = aa.mPackageName;
1044 }
1045 }
1046 }
1047
1048 Intent intent;
1049 String title;
1050 String msg;
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001051 String[] pkgs;
Dan Sandler886e0162017-06-06 14:23:43 -04001052 final long nowElapsed = SystemClock.elapsedRealtime();
1053 long oldestStartTime = nowElapsed;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001054 if (active.size() == 1) {
1055 intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
1056 intent.setData(Uri.fromParts("package", active.get(0).mPackageName, null));
1057 title = context.getString(
1058 R.string.foreground_service_app_in_background, active.get(0).mLabel);
1059 msg = context.getString(R.string.foreground_service_tap_for_details);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001060 pkgs = new String[] { active.get(0).mPackageName };
Dan Sandler2f36ab82017-05-25 00:15:49 -04001061 oldestStartTime = active.get(0).mStartTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001062 } else {
1063 intent = new Intent(Settings.ACTION_FOREGROUND_SERVICES_SETTINGS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001064 pkgs = new String[active.size()];
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001065 for (int i = 0; i < active.size(); i++) {
1066 pkgs[i] = active.get(i).mPackageName;
Dan Sandler2f36ab82017-05-25 00:15:49 -04001067 oldestStartTime = Math.min(oldestStartTime, active.get(i).mStartTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001068 }
1069 intent.putExtra("packages", pkgs);
1070 title = context.getString(
1071 R.string.foreground_service_apps_in_background, active.size());
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001072 msg = active.get(0).mLabel.toString();
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001073 for (int i = 1; i < active.size(); i++) {
1074 msg = context.getString(R.string.foreground_service_multiple_separator,
1075 msg, active.get(i).mLabel);
1076 }
1077 }
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001078 Bundle notificationBundle = new Bundle();
1079 notificationBundle.putStringArray(Notification.EXTRA_FOREGROUND_APPS, pkgs);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001080 Notification.Builder n =
1081 new Notification.Builder(context,
1082 SystemNotificationChannels.FOREGROUND_SERVICE)
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001083 .addExtras(notificationBundle)
Dan Sandler2f36ab82017-05-25 00:15:49 -04001084 .setSmallIcon(R.drawable.stat_sys_vitals)
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001085 .setOngoing(true)
Dan Sandler886e0162017-06-06 14:23:43 -04001086 .setShowWhen(oldestStartTime < nowElapsed)
1087 .setWhen(System.currentTimeMillis() - (nowElapsed - oldestStartTime))
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001088 .setColor(context.getColor(
1089 com.android.internal.R.color.system_notification_accent_color))
1090 .setContentTitle(title)
1091 .setContentText(msg)
1092 .setContentIntent(
1093 PendingIntent.getActivityAsUser(context, 0, intent,
1094 PendingIntent.FLAG_UPDATE_CURRENT,
1095 null, new UserHandle(smap.mUserId)));
1096 nm.notifyAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1097 n.build(), new UserHandle(smap.mUserId));
1098 } else {
1099 nm.cancelAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1100 new UserHandle(smap.mUserId));
1101 }
1102 }
1103
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001104 private void requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001105 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001106 if (timeElapsed != 0) {
1107 smap.sendMessageAtTime(msg,
1108 timeElapsed + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001109 } else {
1110 smap.mActiveForegroundAppsChanged = true;
1111 smap.sendMessage(msg);
1112 }
1113 }
1114
1115 private void decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r) {
1116 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1117 if (active != null) {
1118 active.mNumActive--;
1119 if (active.mNumActive <= 0) {
1120 active.mEndTime = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001121 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Ended running of service");
1122 if (foregroundAppShownEnoughLocked(active, active.mEndTime)) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001123 // Have been active for long enough that we will remove it immediately.
1124 smap.mActiveForegroundApps.remove(r.packageName);
1125 smap.mActiveForegroundAppsChanged = true;
1126 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001127 } else if (active.mHideTime < Long.MAX_VALUE){
1128 requestUpdateActiveForegroundAppsLocked(smap, active.mHideTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001129 }
1130 }
1131 }
1132 }
1133
1134 void updateScreenStateLocked(boolean screenOn) {
1135 if (mScreenOn != screenOn) {
1136 mScreenOn = screenOn;
1137
1138 // If screen is turning on, then we now reset the start time of any foreground
1139 // services that were started while the screen was off.
1140 if (screenOn) {
1141 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001142 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Screen turned on");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001143 for (int i = mServiceMap.size()-1; i >= 0; i--) {
1144 ServiceMap smap = mServiceMap.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -07001145 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001146 boolean changed = false;
1147 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1148 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
Dianne Hackborncb015632017-06-14 17:30:15 -07001149 if (active.mEndTime == 0) {
1150 if (!active.mShownWhileScreenOn) {
1151 active.mShownWhileScreenOn = true;
1152 active.mStartVisibleTime = nowElapsed;
1153 }
1154 } else {
1155 if (!active.mShownWhileScreenOn
1156 && active.mStartVisibleTime == active.mStartTime) {
1157 // If this was never shown while the screen was on, then we will
1158 // count the time it started being visible as now, to tell the user
1159 // about it now that they have a screen to look at.
1160 active.mEndTime = active.mStartVisibleTime = nowElapsed;
1161 }
1162 if (foregroundAppShownEnoughLocked(active, nowElapsed)) {
1163 // Have been active for long enough that we will remove it
1164 // immediately.
1165 smap.mActiveForegroundApps.remove(active.mPackageName);
1166 smap.mActiveForegroundAppsChanged = true;
1167 changed = true;
1168 } else {
1169 if (active.mHideTime < nextUpdateTime) {
1170 nextUpdateTime = active.mHideTime;
1171 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001172 }
1173 }
1174 }
1175 if (changed) {
Dianne Hackborncb015632017-06-14 17:30:15 -07001176 // Need to immediately update.
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001177 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001178 } else if (nextUpdateTime < Long.MAX_VALUE) {
1179 requestUpdateActiveForegroundAppsLocked(smap, nextUpdateTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001180 }
1181 }
1182 }
1183 }
1184 }
1185
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001186 void foregroundServiceProcStateChangedLocked(UidRecord uidRec) {
1187 ServiceMap smap = mServiceMap.get(UserHandle.getUserId(uidRec.uid));
1188 if (smap != null) {
1189 boolean changed = false;
1190 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1191 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
1192 if (active.mUid == uidRec.uid) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07001193 if (uidRec.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001194 if (!active.mAppOnTop) {
1195 active.mAppOnTop = true;
1196 changed = true;
1197 }
1198 active.mShownWhileTop = true;
1199 } else if (active.mAppOnTop) {
1200 active.mAppOnTop = false;
1201 changed = true;
1202 }
1203 }
1204 }
1205 if (changed) {
1206 requestUpdateActiveForegroundAppsLocked(smap, 0);
1207 }
1208 }
1209 }
1210
Christopher Tatec7933ac2018-03-12 17:57:09 -07001211 /**
1212 * @param id Notification ID. Zero === exit foreground state for the given service.
1213 */
1214 private void setServiceForegroundInnerLocked(final ServiceRecord r, int id,
Hui Yu2d4207f2019-01-22 15:32:20 -08001215 Notification notification, int flags, int foregroundServiceType) {
Christopher Tate42a386b2016-11-07 12:21:21 -08001216 if (id != 0) {
1217 if (notification == null) {
1218 throw new IllegalArgumentException("null notification");
1219 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001220 // Instant apps need permission to create foreground services.
1221 if (r.appInfo.isInstantApp()) {
1222 final int mode = mAm.mAppOpsService.checkOperation(
1223 AppOpsManager.OP_INSTANT_APP_START_FOREGROUND,
1224 r.appInfo.uid,
1225 r.appInfo.packageName);
1226 switch (mode) {
1227 case AppOpsManager.MODE_ALLOWED:
1228 break;
1229 case AppOpsManager.MODE_IGNORED:
1230 Slog.w(TAG, "Instant app " + r.appInfo.packageName
1231 + " does not have permission to create foreground services"
1232 + ", ignoring.");
Sudheer Shankac9d94072017-02-22 22:13:55 +00001233 return;
Chad Brubaker97b383f2017-02-02 15:04:35 -08001234 case AppOpsManager.MODE_ERRORED:
1235 throw new SecurityException("Instant app " + r.appInfo.packageName
1236 + " does not have permission to create foreground services");
1237 default:
Dianne Hackborndd027b32018-01-19 17:44:46 -08001238 mAm.enforcePermission(
1239 android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
1240 r.app.pid, r.appInfo.uid, "startForeground");
Chad Brubaker97b383f2017-02-02 15:04:35 -08001241 }
Hui Yu1ea85522018-12-06 16:59:18 -08001242 } else {
1243 if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
1244 mAm.enforcePermission(
1245 android.Manifest.permission.FOREGROUND_SERVICE,
1246 r.app.pid, r.appInfo.uid, "startForeground");
1247 }
Hui Yu2d4207f2019-01-22 15:32:20 -08001248
1249 int manifestType = r.serviceInfo.getForegroundServiceType();
1250 // If passed in foreground service type is FOREGROUND_SERVICE_TYPE_MANIFEST,
1251 // consider it is the same as manifest foreground service type.
1252 if (foregroundServiceType == FOREGROUND_SERVICE_TYPE_MANIFEST) {
1253 foregroundServiceType = manifestType;
1254 }
1255 // Check the passed in foreground service type flags is a subset of manifest
1256 // foreground service type flags.
1257 if ((foregroundServiceType & manifestType) != foregroundServiceType) {
1258 // STOPSHIP(b/120611119): replace log message with IllegalArgumentException.
1259 Slog.w(TAG, "foregroundServiceType must be a subset of "
1260 + "foregroundServiceType attribute in "
1261 + "service element of manifest file");
Hui Yu1ea85522018-12-06 16:59:18 -08001262 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001263 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001264 boolean alreadyStartedOp = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001265 boolean stopProcStatsOp = false;
Christopher Tate08992ac2017-03-21 11:37:06 -07001266 if (r.fgRequired) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001267 if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001268 Slog.i(TAG, "Service called startForeground() as required: " + r);
1269 }
1270 r.fgRequired = false;
1271 r.fgWaiting = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001272 alreadyStartedOp = stopProcStatsOp = true;
Christopher Tate08992ac2017-03-21 11:37:06 -07001273 mAm.mHandler.removeMessages(
1274 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
1275 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001276
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001277 try {
1278 boolean ignoreForeground = false;
1279 final int mode = mAm.mAppOpsService.checkOperation(
1280 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
1281 switch (mode) {
1282 case AppOpsManager.MODE_ALLOWED:
1283 case AppOpsManager.MODE_DEFAULT:
1284 // All okay.
1285 break;
1286 case AppOpsManager.MODE_IGNORED:
1287 // Whoops, silently ignore this.
1288 Slog.w(TAG, "Service.startForeground() not allowed due to app op: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001289 + r.shortInstanceName);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001290 ignoreForeground = true;
1291 break;
1292 default:
1293 throw new SecurityException("Foreground not allowed as per app op");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001294 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001295
1296 if (!ignoreForeground &&
1297 appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001298 Slog.w(TAG,
1299 "Service.startForeground() not allowed due to bg restriction: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001300 + r.shortInstanceName);
Christopher Tate45f06c792018-04-25 10:47:23 -07001301 // Back off of any foreground expectations around this service, since we've
1302 // just turned down its fg request.
1303 updateServiceForegroundLocked(r.app, false);
1304 ignoreForeground = true;
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001305 }
1306
1307 // Apps under strict background restrictions simply don't get to have foreground
1308 // services, so now that we've enforced the startForegroundService() contract
1309 // we only do the machinery of making the service foreground when the app
1310 // is not restricted.
1311 if (!ignoreForeground) {
1312 if (r.foregroundId != id) {
1313 cancelForegroundNotificationLocked(r);
1314 r.foregroundId = id;
Christopher Tatec7933ac2018-03-12 17:57:09 -07001315 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001316 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
1317 r.foregroundNoti = notification;
Hui Yu2d4207f2019-01-22 15:32:20 -08001318 r.foregroundServiceType = foregroundServiceType;
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001319 if (!r.isForeground) {
1320 final ServiceMap smap = getServiceMapLocked(r.userId);
1321 if (smap != null) {
1322 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1323 if (active == null) {
1324 active = new ActiveForegroundApp();
1325 active.mPackageName = r.packageName;
1326 active.mUid = r.appInfo.uid;
1327 active.mShownWhileScreenOn = mScreenOn;
1328 if (r.app != null) {
1329 active.mAppOnTop = active.mShownWhileTop =
Wale Ogunwalebff2df42018-10-18 17:09:19 -07001330 r.app.uidRecord.getCurProcState()
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001331 <= ActivityManager.PROCESS_STATE_TOP;
1332 }
1333 active.mStartTime = active.mStartVisibleTime
1334 = SystemClock.elapsedRealtime();
1335 smap.mActiveForegroundApps.put(r.packageName, active);
1336 requestUpdateActiveForegroundAppsLocked(smap, 0);
1337 }
1338 active.mNumActive++;
1339 }
1340 r.isForeground = true;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001341 if (!stopProcStatsOp) {
1342 ServiceState stracker = r.getTracker();
1343 if (stracker != null) {
1344 stracker.setForeground(true,
1345 mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
1346 }
1347 } else {
1348 stopProcStatsOp = false;
1349 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001350 mAm.mAppOpsService.startOperation(
1351 AppOpsManager.getToken(mAm.mAppOpsService),
1352 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName,
1353 true);
1354 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001355 r.appInfo.uid, r.shortInstanceName,
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001356 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER);
Hui Yue361a232018-10-04 15:05:21 -07001357 mAm.updateForegroundServiceUsageStats(r.name, r.userId, true);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001358 }
1359 r.postNotification();
1360 if (r.app != null) {
1361 updateServiceForegroundLocked(r.app, true);
1362 }
1363 getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
1364 mAm.notifyPackageUse(r.serviceInfo.packageName,
1365 PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
1366 } else {
1367 if (DEBUG_FOREGROUND_SERVICE) {
1368 Slog.d(TAG, "Suppressing startForeground() for FAS " + r);
1369 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001370 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001371 } finally {
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001372 if (stopProcStatsOp) {
1373 // We got through to this point with it actively being started foreground,
1374 // and never decided we wanted to keep it like that, so drop it.
1375 ServiceState stracker = r.getTracker();
1376 if (stracker != null) {
1377 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1378 r.lastActivity);
1379 }
1380 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001381 if (alreadyStartedOp) {
1382 // If we had previously done a start op for direct foreground start,
1383 // we have cleared the flag so can now drop it.
1384 mAm.mAppOpsService.finishOperation(
1385 AppOpsManager.getToken(mAm.mAppOpsService),
1386 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001387 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001388 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001389 } else {
1390 if (r.isForeground) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001391 final ServiceMap smap = getServiceMapLocked(r.userId);
1392 if (smap != null) {
1393 decActiveForegroundAppLocked(smap, r);
1394 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001395 r.isForeground = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001396 ServiceState stracker = r.getTracker();
1397 if (stracker != null) {
1398 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1399 r.lastActivity);
1400 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001401 mAm.mAppOpsService.finishOperation(
1402 AppOpsManager.getToken(mAm.mAppOpsService),
1403 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001404 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001405 r.appInfo.uid, r.shortInstanceName,
Chenjie Yuccfe6452018-01-30 11:33:21 -08001406 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Hui Yue361a232018-10-04 15:05:21 -07001407 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
Christopher Tate42a386b2016-11-07 12:21:21 -08001408 if (r.app != null) {
1409 mAm.updateLruProcessLocked(r.app, false, null);
1410 updateServiceForegroundLocked(r.app, true);
1411 }
1412 }
1413 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001414 cancelForegroundNotificationLocked(r);
Christopher Tate42a386b2016-11-07 12:21:21 -08001415 r.foregroundId = 0;
1416 r.foregroundNoti = null;
1417 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1418 r.stripForegroundServiceFlagFromNotification();
1419 if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
1420 r.foregroundId = 0;
1421 r.foregroundNoti = null;
1422 }
1423 }
1424 }
1425 }
1426
Christopher Tate08992ac2017-03-21 11:37:06 -07001427 private void cancelForegroundNotificationLocked(ServiceRecord r) {
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001428 if (r.foregroundId != 0) {
1429 // First check to see if this app has any other active foreground services
1430 // with the same notification ID. If so, we shouldn't actually cancel it,
1431 // because that would wipe away the notification that still needs to be shown
1432 // due the other service.
Dianne Hackbornad51be92016-08-16 16:27:36 -07001433 ServiceMap sm = getServiceMapLocked(r.userId);
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001434 if (sm != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001435 for (int i = sm.mServicesByInstanceName.size() - 1; i >= 0; i--) {
1436 ServiceRecord other = sm.mServicesByInstanceName.valueAt(i);
Dianne Hackborn569a4582016-08-04 14:00:22 -07001437 if (other != r && other.foregroundId == r.foregroundId
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001438 && other.packageName.equals(r.packageName)) {
1439 // Found one! Abort the cancel.
1440 return;
1441 }
1442 }
1443 }
1444 r.cancelNotification();
1445 }
1446 }
1447
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001448 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
1449 boolean anyForeground = false;
Amith Yamasania0a30a12019-01-22 11:38:06 -08001450 int fgServiceTypes = 0;
1451 for (int i = proc.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07001452 ServiceRecord sr = proc.services.valueAt(i);
Christopher Tatee23fa2b2017-04-20 14:48:13 -07001453 if (sr.isForeground || sr.fgRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001454 anyForeground = true;
Hui Yu2d4207f2019-01-22 15:32:20 -08001455 fgServiceTypes |= sr.foregroundServiceType;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001456 break;
1457 }
1458 }
Amith Yamasania0a30a12019-01-22 11:38:06 -08001459 mAm.updateProcessForegroundLocked(proc, anyForeground, fgServiceTypes, oomAdj);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001460 }
1461
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001462 private void updateWhitelistManagerLocked(ProcessRecord proc) {
1463 proc.whitelistManager = false;
1464 for (int i=proc.services.size()-1; i>=0; i--) {
1465 ServiceRecord sr = proc.services.valueAt(i);
1466 if (sr.whitelistManager) {
1467 proc.whitelistManager = true;
1468 break;
1469 }
1470 }
1471 }
1472
Dianne Hackborn465fa392014-09-14 14:21:18 -07001473 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
1474 ArraySet<ProcessRecord> updatedProcesses = null;
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001475 for (int i = 0; i < clientProc.connections.size(); i++) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001476 final ConnectionRecord conn = clientProc.connections.valueAt(i);
1477 final ProcessRecord proc = conn.binding.service.app;
1478 if (proc == null || proc == clientProc) {
1479 continue;
1480 } else if (updatedProcesses == null) {
1481 updatedProcesses = new ArraySet<>();
1482 } else if (updatedProcesses.contains(proc)) {
1483 continue;
1484 }
1485 updatedProcesses.add(proc);
1486 updateServiceClientActivitiesLocked(proc, null, false);
1487 }
1488 }
1489
Dianne Hackborndb926082013-10-31 16:32:44 -07001490 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
Dianne Hackborn465fa392014-09-14 14:21:18 -07001491 ConnectionRecord modCr, boolean updateLru) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001492 if (modCr != null && modCr.binding.client != null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001493 if (!modCr.binding.client.hasActivities()) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001494 // This connection is from a client without activities, so adding
1495 // and removing is not interesting.
1496 return false;
1497 }
1498 }
1499
1500 boolean anyClientActivities = false;
1501 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
1502 ServiceRecord sr = proc.services.valueAt(i);
1503 for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) {
1504 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni);
1505 for (int cri=clist.size()-1; cri>=0; cri--) {
1506 ConnectionRecord cr = clist.get(cri);
1507 if (cr.binding.client == null || cr.binding.client == proc) {
1508 // Binding to ourself is not interesting.
1509 continue;
1510 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001511 if (cr.binding.client.hasActivities()) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001512 anyClientActivities = true;
1513 break;
1514 }
1515 }
1516 }
1517 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001518 if (anyClientActivities != proc.hasClientActivities()) {
1519 proc.setHasClientActivities(anyClientActivities);
Dianne Hackborn465fa392014-09-14 14:21:18 -07001520 if (updateLru) {
1521 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
1522 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001523 return true;
1524 }
1525 return false;
1526 }
1527
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001528 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
Svet Ganov9c165d72015-12-01 19:52:26 -08001529 String resolvedType, final IServiceConnection connection, int flags,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001530 String instanceName, String callingPackage, final int userId)
1531 throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001532 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001533 + " type=" + resolvedType + " conn=" + connection.asBinder()
1534 + " flags=0x" + Integer.toHexString(flags));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001535 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
1536 if (callerApp == null) {
1537 throw new SecurityException(
1538 "Unable to find app for caller " + caller
1539 + " (pid=" + Binder.getCallingPid()
1540 + ") when binding service " + service);
1541 }
1542
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001543 ActivityServiceConnectionsHolder<ConnectionRecord> activity = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001544 if (token != null) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001545 activity = mAm.mAtmInternal.getServiceConnectionsHolder(token);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001546 if (activity == null) {
1547 Slog.w(TAG, "Binding with unknown activity: " + token);
1548 return 0;
1549 }
1550 }
1551
1552 int clientLabel = 0;
1553 PendingIntent clientIntent = null;
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001554 final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001555
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001556 if (isCallerSystem) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001557 // Hacky kind of thing -- allow system stuff to tell us
1558 // what they are, so we can report this elsewhere for
1559 // others to know why certain services are running.
Jeff Sharkeyf0ec2e02016-03-21 12:37:54 -06001560 service.setDefusable(true);
1561 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001562 if (clientIntent != null) {
1563 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
1564 if (clientLabel != 0) {
1565 // There are no useful extras in the intent, trash them.
1566 // System code calling with this stuff just needs to know
1567 // this will happen.
1568 service = service.cloneFilter();
1569 }
1570 }
1571 }
1572
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001573 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1574 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
1575 "BIND_TREAT_LIKE_ACTIVITY");
1576 }
1577
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001578 if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
1579 throw new SecurityException(
1580 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1581 + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
1582 }
1583
Svet Ganovd223db32017-12-22 09:43:48 -08001584 if ((flags & Context.BIND_ALLOW_INSTANT) != 0 && !isCallerSystem) {
1585 throw new SecurityException(
1586 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1587 + ") set BIND_ALLOW_INSTANT when binding service " + service);
1588 }
1589
Dianne Hackborna49ad092016-03-03 13:39:10 -08001590 final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Robert Sesekb9a86662015-12-09 16:22:45 -05001591 final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
Svet Ganovd223db32017-12-22 09:43:48 -08001592 final boolean allowInstant = (flags & Context.BIND_ALLOW_INSTANT) != 0;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001593
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001594 ServiceLookupResult res =
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001595 retrieveServiceLocked(service, instanceName, resolvedType, callingPackage,
1596 Binder.getCallingPid(), Binder.getCallingUid(), userId, true,
1597 callerFg, isBindExternal, allowInstant);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001598 if (res == null) {
1599 return 0;
1600 }
1601 if (res.record == null) {
1602 return -1;
1603 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001604 ServiceRecord s = res.record;
1605
Svet Ganov9c165d72015-12-01 19:52:26 -08001606 boolean permissionsReviewRequired = false;
1607
1608 // If permissions need a review before any of the app components can run,
1609 // we schedule binding to the service but do not start its process, then
1610 // we launch a review activity to which is passed a callback to invoke
1611 // when done to start the bound service's process to completing the binding.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001612 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
1613 s.packageName, s.userId)) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001614
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001615 permissionsReviewRequired = true;
Svet Ganov9c165d72015-12-01 19:52:26 -08001616
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001617 // Show a permission review UI only for binding from a foreground app
1618 if (!callerFg) {
1619 Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
1620 + s.packageName + " requires a permissions review");
1621 return 0;
1622 }
Svet Ganov9c165d72015-12-01 19:52:26 -08001623
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001624 final ServiceRecord serviceRecord = s;
1625 final Intent serviceIntent = service;
Svet Ganov9c165d72015-12-01 19:52:26 -08001626
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001627 RemoteCallback callback = new RemoteCallback(
1628 new RemoteCallback.OnResultListener() {
1629 @Override
1630 public void onResult(Bundle result) {
1631 synchronized(mAm) {
1632 final long identity = Binder.clearCallingIdentity();
1633 try {
1634 if (!mPendingServices.contains(serviceRecord)) {
1635 return;
Svet Ganov9c165d72015-12-01 19:52:26 -08001636 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001637 // If there is still a pending record, then the service
1638 // binding request is still valid, so hook them up. We
1639 // proceed only if the caller cleared the review requirement
1640 // otherwise we unbind because the user didn't approve.
1641 if (!mAm.getPackageManagerInternalLocked()
1642 .isPermissionsReviewRequired(
1643 serviceRecord.packageName,
1644 serviceRecord.userId)) {
1645 try {
1646 bringUpServiceLocked(serviceRecord,
1647 serviceIntent.getFlags(),
1648 callerFg, false, false);
1649 } catch (RemoteException e) {
1650 /* ignore - local call */
1651 }
1652 } else {
1653 unbindServiceLocked(connection);
1654 }
1655 } finally {
1656 Binder.restoreCallingIdentity(identity);
Svet Ganov9c165d72015-12-01 19:52:26 -08001657 }
1658 }
Svet Ganov9c165d72015-12-01 19:52:26 -08001659 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001660 });
Svet Ganov9c165d72015-12-01 19:52:26 -08001661
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001662 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
1663 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
Philip P. Moltmann751e46ca2019-01-24 13:56:47 -08001664 | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001665 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1666 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
1667 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
1668
1669 if (DEBUG_PERMISSIONS_REVIEW) {
1670 Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
1671 + s.packageName);
Svet Ganov9c165d72015-12-01 19:52:26 -08001672 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001673
1674 mAm.mHandler.post(new Runnable() {
1675 @Override
1676 public void run() {
1677 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
1678 }
1679 });
Svet Ganov9c165d72015-12-01 19:52:26 -08001680 }
1681
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001682 final long origId = Binder.clearCallingIdentity();
1683
1684 try {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001685 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001686 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001687 + s);
1688 }
1689
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001690 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1691 s.lastActivity = SystemClock.uptimeMillis();
1692 if (!s.hasAutoCreateConnections()) {
1693 // This is the first binding, let the tracker know.
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001694 ServiceState stracker = s.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001695 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001696 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001697 s.lastActivity);
1698 }
1699 }
1700 }
1701
Dianne Hackbornc390aa82019-01-09 16:38:22 -08001702 if ((flags & Context.BIND_RESTRICT_ASSOCIATIONS) != 0) {
1703 mAm.requireAllowedAssociationsLocked(s.appInfo.packageName);
1704 }
1705
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001706 mAm.startAssociationLocked(callerApp.uid, callerApp.processName,
1707 callerApp.getCurProcState(), s.appInfo.uid, s.appInfo.longVersionCode,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001708 s.instanceName, s.processName);
Jesse Evans02af3ea2017-05-03 09:57:16 -07001709 // Once the apps have become associated, if one of them is caller is ephemeral
1710 // the target app should now be able to see the calling app
1711 mAm.grantEphemeralAccessLocked(callerApp.userId, service,
Hai Zhangbb23d532018-08-27 16:00:35 -07001712 UserHandle.getAppId(s.appInfo.uid), UserHandle.getAppId(callerApp.uid));
Dianne Hackbornab2df062015-01-07 13:43:13 -08001713
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001714 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
1715 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001716 connection, flags, clientLabel, clientIntent,
Dianne Hackborn24bbe582018-12-17 11:58:31 -08001717 callerApp.uid, callerApp.processName, callingPackage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001718
1719 IBinder binder = connection.asBinder();
1720 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
1721 if (clist == null) {
1722 clist = new ArrayList<ConnectionRecord>();
1723 s.connections.put(binder, clist);
1724 }
1725 clist.add(c);
1726 b.connections.add(c);
1727 if (activity != null) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001728 activity.addConnection(c);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001729 }
1730 b.client.connections.add(c);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001731 c.startAssociationIfNeeded();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001732 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
1733 b.client.hasAboveClient = true;
1734 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001735 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
1736 s.whitelistManager = true;
1737 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001738 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001739 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07001740 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001741 clist = mServiceConnections.get(binder);
1742 if (clist == null) {
1743 clist = new ArrayList<ConnectionRecord>();
1744 mServiceConnections.put(binder, clist);
1745 }
1746 clist.add(c);
1747
1748 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1749 s.lastActivity = SystemClock.uptimeMillis();
Svet Ganov9c165d72015-12-01 19:52:26 -08001750 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
1751 permissionsReviewRequired) != null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001752 return 0;
1753 }
1754 }
1755
1756 if (s.app != null) {
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001757 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1758 s.app.treatLikeActivity = true;
1759 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001760 if (s.whitelistManager) {
1761 s.app.whitelistManager = true;
1762 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001763 // This could have made the service more important.
Dianne Hackborna631d562018-11-20 15:58:15 -08001764 mAm.updateLruProcessLocked(s.app,
1765 (callerApp.hasActivitiesOrRecentTasks() && s.app.hasClientActivities())
1766 || (callerApp.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP
1767 && (flags & Context.BIND_TREAT_LIKE_ACTIVITY) != 0),
1768 b.client);
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001769 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001770 }
1771
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001772 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001773 + ": received=" + b.intent.received
1774 + " apps=" + b.intent.apps.size()
1775 + " doRebind=" + b.intent.doRebind);
1776
1777 if (s.app != null && b.intent.received) {
1778 // Service is already running, so we can immediately
1779 // publish the connection.
1780 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001781 c.conn.connected(s.name, b.intent.binder, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001782 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001783 Slog.w(TAG, "Failure sending service " + s.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001784 + " to connection " + c.conn.asBinder()
1785 + " (in " + c.binding.client.processName + ")", e);
1786 }
1787
1788 // If this is the first app connected back to this binding,
1789 // and the service had previously asked to be told when
1790 // rebound, then do so.
1791 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001792 requestServiceBindingLocked(s, b.intent, callerFg, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001793 }
1794 } else if (!b.intent.requested) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001795 requestServiceBindingLocked(s, b.intent, callerFg, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001796 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001797
Dianne Hackbornad51be92016-08-16 16:27:36 -07001798 getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001799
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001800 } finally {
1801 Binder.restoreCallingIdentity(origId);
1802 }
1803
1804 return 1;
1805 }
1806
1807 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
1808 final long origId = Binder.clearCallingIdentity();
1809 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001810 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001811 + " " + intent + ": " + service);
1812 if (r != null) {
1813 Intent.FilterComparison filter
1814 = new Intent.FilterComparison(intent);
1815 IntentBindRecord b = r.bindings.get(filter);
1816 if (b != null && !b.received) {
1817 b.binder = service;
1818 b.requested = true;
1819 b.received = true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07001820 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1821 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
1822 for (int i=0; i<clist.size(); i++) {
1823 ConnectionRecord c = clist.get(i);
1824 if (!filter.equals(c.binding.intent.intent)) {
1825 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001826 TAG_SERVICE, "Not publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001827 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001828 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001829 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001830 TAG_SERVICE, "Published intent: " + intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001831 continue;
1832 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001833 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001834 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001835 c.conn.connected(r.name, service, false);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001836 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001837 Slog.w(TAG, "Failure sending service " + r.shortInstanceName
1838 + " to connection " + c.conn.asBinder()
1839 + " (in " + c.binding.client.processName + ")", e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001840 }
1841 }
1842 }
1843 }
1844
Dianne Hackborn164371f2013-10-01 19:10:13 -07001845 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001846 }
1847 } finally {
1848 Binder.restoreCallingIdentity(origId);
1849 }
1850 }
1851
Dianne Hackborna631d562018-11-20 15:58:15 -08001852 void updateServiceGroupLocked(IServiceConnection connection, int group, int importance) {
1853 final IBinder binder = connection.asBinder();
1854 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "updateServiceGroup: conn=" + binder);
1855 final ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1856 if (clist == null) {
1857 throw new IllegalArgumentException("Could not find connection for "
1858 + connection.asBinder());
1859 }
1860 for (int i = clist.size() - 1; i >= 0; i--) {
1861 final ConnectionRecord crec = clist.get(i);
1862 final ServiceRecord srec = crec.binding.service;
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08001863 if (srec != null && (srec.serviceInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) != 0) {
1864 if (srec.app != null) {
1865 if (group > 0) {
1866 srec.app.connectionService = srec;
1867 srec.app.connectionGroup = group;
1868 srec.app.connectionImportance = importance;
1869 } else {
1870 srec.app.connectionService = null;
1871 srec.app.connectionGroup = 0;
1872 srec.app.connectionImportance = 0;
1873 }
Dianne Hackborna631d562018-11-20 15:58:15 -08001874 } else {
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08001875 if (group > 0) {
1876 srec.pendingConnectionGroup = group;
1877 srec.pendingConnectionImportance = importance;
1878 } else {
1879 srec.pendingConnectionGroup = 0;
1880 srec.pendingConnectionImportance = 0;
1881 }
Dianne Hackborna631d562018-11-20 15:58:15 -08001882 }
1883 }
1884 }
1885 }
1886
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001887 boolean unbindServiceLocked(IServiceConnection connection) {
1888 IBinder binder = connection.asBinder();
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001889 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001890 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1891 if (clist == null) {
1892 Slog.w(TAG, "Unbind failed: could not find connection for "
1893 + connection.asBinder());
1894 return false;
1895 }
1896
1897 final long origId = Binder.clearCallingIdentity();
1898 try {
1899 while (clist.size() > 0) {
1900 ConnectionRecord r = clist.get(0);
1901 removeConnectionLocked(r, null, null);
Dianne Hackborn25e1eca2014-09-23 10:13:13 -07001902 if (clist.size() > 0 && clist.get(0) == r) {
1903 // In case it didn't get removed above, do it now.
1904 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
1905 clist.remove(0);
1906 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001907
1908 if (r.binding.service.app != null) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001909 if (r.binding.service.app.whitelistManager) {
Felipe Lemea7778b02016-06-28 10:38:59 -07001910 updateWhitelistManagerLocked(r.binding.service.app);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001911 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001912 // This could have made the service less important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001913 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1914 r.binding.service.app.treatLikeActivity = true;
1915 mAm.updateLruProcessLocked(r.binding.service.app,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001916 r.binding.service.app.hasClientActivities()
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001917 || r.binding.service.app.treatLikeActivity, null);
1918 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001919 mAm.updateOomAdjLocked(r.binding.service.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001920 }
1921 }
Amith Yamasanib2926b12017-05-11 11:13:52 -07001922
1923 mAm.updateOomAdjLocked();
1924
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001925 } finally {
1926 Binder.restoreCallingIdentity(origId);
1927 }
1928
1929 return true;
1930 }
1931
1932 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
1933 final long origId = Binder.clearCallingIdentity();
1934 try {
1935 if (r != null) {
1936 Intent.FilterComparison filter
1937 = new Intent.FilterComparison(intent);
1938 IntentBindRecord b = r.bindings.get(filter);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001939 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001940 + " at " + b + ": apps="
1941 + (b != null ? b.apps.size() : 0));
1942
Dianne Hackborn164371f2013-10-01 19:10:13 -07001943 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001944 if (b != null) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001945 if (b.apps.size() > 0 && !inDestroying) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001946 // Applications have already bound since the last
1947 // unbind, so just rebind right here.
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001948 boolean inFg = false;
1949 for (int i=b.apps.size()-1; i>=0; i--) {
1950 ProcessRecord client = b.apps.valueAt(i).client;
1951 if (client != null && client.setSchedGroup
Dianne Hackborna49ad092016-03-03 13:39:10 -08001952 != ProcessList.SCHED_GROUP_BACKGROUND) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001953 inFg = true;
1954 break;
1955 }
1956 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001957 try {
1958 requestServiceBindingLocked(r, b, inFg, true);
1959 } catch (TransactionTooLargeException e) {
1960 // Don't pass this back to ActivityThread, it's unrelated.
1961 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001962 } else {
1963 // Note to tell the service the next time there is
1964 // a new client.
1965 b.doRebind = true;
1966 }
1967 }
1968
Dianne Hackborn164371f2013-10-01 19:10:13 -07001969 serviceDoneExecutingLocked(r, inDestroying, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001970 }
1971 } finally {
1972 Binder.restoreCallingIdentity(origId);
1973 }
1974 }
1975
1976 private final ServiceRecord findServiceLocked(ComponentName name,
Dianne Hackborn41203752012-08-31 14:05:51 -07001977 IBinder token, int userId) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07001978 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001979 return r == token ? r : null;
1980 }
1981
1982 private final class ServiceLookupResult {
1983 final ServiceRecord record;
1984 final String permission;
1985
1986 ServiceLookupResult(ServiceRecord _record, String _permission) {
1987 record = _record;
1988 permission = _permission;
1989 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001990 }
1991
1992 private class ServiceRestarter implements Runnable {
1993 private ServiceRecord mService;
1994
1995 void setService(ServiceRecord service) {
1996 mService = service;
1997 }
1998
1999 public void run() {
2000 synchronized(mAm) {
2001 performServiceRestartLocked(mService);
2002 }
2003 }
2004 }
2005
2006 private ServiceLookupResult retrieveServiceLocked(Intent service,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002007 String instanceName, String resolvedType, String callingPackage,
2008 int callingPid, int callingUid, int userId,
Svet Ganovd223db32017-12-22 09:43:48 -08002009 boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
2010 boolean allowInstant) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002011 ServiceRecord r = null;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002012 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002013 + " type=" + resolvedType + " callingUid=" + callingUid);
2014
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07002015 userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
jovanaka6763a32018-12-03 17:23:20 -08002016 ActivityManagerInternal.ALLOW_NON_FULL_IN_PROFILE, "service",
2017 callingPackage);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002018
Dianne Hackbornad51be92016-08-16 16:27:36 -07002019 ServiceMap smap = getServiceMapLocked(userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002020 final ComponentName comp;
2021 if (instanceName == null) {
2022 comp = service.getComponent();
2023 } else {
2024 final ComponentName realComp = service.getComponent();
2025 if (realComp == null) {
2026 throw new IllegalArgumentException("Can't use custom instance name '" + instanceName
2027 + "' without expicit component in Intent");
2028 }
2029 comp = new ComponentName(realComp.getPackageName(),
2030 realComp.getClassName() + ":" + instanceName);
2031 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002032 if (comp != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002033 r = smap.mServicesByInstanceName.get(comp);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002034 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002035 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002036 if (r == null && !isBindExternal && instanceName == null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002037 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002038 r = smap.mServicesByIntent.get(filter);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002039 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002040 }
Robert Sesekb9a86662015-12-09 16:22:45 -05002041 if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
2042 && !callingPackage.equals(r.packageName)) {
2043 // If an external service is running within its own package, other packages
2044 // should not bind to that instance.
2045 r = null;
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002046 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Whoops, can't use existing external service");
Robert Sesekb9a86662015-12-09 16:22:45 -05002047 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002048 if (r == null) {
2049 try {
Svet Ganovd223db32017-12-22 09:43:48 -08002050 int flags = ActivityManagerService.STOCK_PM_FLAGS
2051 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
2052 if (allowInstant) {
2053 flags |= PackageManager.MATCH_INSTANT;
2054 }
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002055 // TODO: come back and remove this assumption to triage all services
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002056 ResolveInfo rInfo = mAm.getPackageManagerInternalLocked().resolveService(service,
Svet Ganovd223db32017-12-22 09:43:48 -08002057 resolvedType, flags, userId, callingUid);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002058 ServiceInfo sInfo = rInfo != null ? rInfo.serviceInfo : null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002059 if (sInfo == null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002060 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002061 ": not found");
2062 return null;
2063 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002064 if (instanceName != null
2065 && (sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
2066 throw new IllegalArgumentException("Can't use instance name '" + instanceName
2067 + "' with non-isolated service '" + sInfo.name + "'");
2068 }
2069 ComponentName className = new ComponentName(
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002070 sInfo.applicationInfo.packageName, sInfo.name);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002071 ComponentName name = comp != null ? comp : className;
Dianne Hackborn769b2e72018-12-05 08:51:20 -08002072 if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid,
2073 name.getPackageName(), sInfo.applicationInfo.uid)) {
2074 String msg = "association not allowed between packages "
Amith Yamasani9f96c2b2018-12-19 18:32:44 -08002075 + callingPackage + " and " + name.getPackageName();
Dianne Hackborn769b2e72018-12-05 08:51:20 -08002076 Slog.w(TAG, "Service lookup failed: " + msg);
2077 return new ServiceLookupResult(null, msg);
2078 }
Robert Sesekb9a86662015-12-09 16:22:45 -05002079 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
2080 if (isBindExternal) {
2081 if (!sInfo.exported) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002082 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
2083 + className + " is not exported");
Robert Sesekb9a86662015-12-09 16:22:45 -05002084 }
2085 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002086 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
2087 + className + " is not an isolatedProcess");
Robert Sesekb9a86662015-12-09 16:22:45 -05002088 }
2089 // Run the service under the calling package's application.
2090 ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
2091 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
2092 if (aInfo == null) {
2093 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
2094 "could not resolve client package " + callingPackage);
2095 }
2096 sInfo = new ServiceInfo(sInfo);
2097 sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
2098 sInfo.applicationInfo.packageName = aInfo.packageName;
2099 sInfo.applicationInfo.uid = aInfo.uid;
2100 name = new ComponentName(aInfo.packageName, name.getClassName());
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002101 className = new ComponentName(aInfo.packageName,
2102 instanceName == null ? className.getClassName()
2103 : (className.getClassName() + ":" + instanceName));
Robert Sesekb9a86662015-12-09 16:22:45 -05002104 service.setComponent(name);
2105 } else {
2106 throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
2107 name);
2108 }
2109 } else if (isBindExternal) {
2110 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
2111 " is not an externalService");
2112 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002113 if (userId > 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07002114 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
Amith Yamasani4b9d79c2014-05-21 19:14:21 -07002115 sInfo.name, sInfo.flags)
2116 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002117 userId = 0;
Dianne Hackbornad51be92016-08-16 16:27:36 -07002118 smap = getServiceMapLocked(0);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002119 }
2120 sInfo = new ServiceInfo(sInfo);
2121 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
2122 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002123 r = smap.mServicesByInstanceName.get(name);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002124 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE,
2125 "Retrieved via pm by intent: " + r);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002126 if (r == null && createIfNeeded) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002127 final Intent.FilterComparison filter
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002128 = new Intent.FilterComparison(service.cloneFilter());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002129 final ServiceRestarter res = new ServiceRestarter();
2130 final BatteryStatsImpl.Uid.Pkg.Serv ss;
2131 final BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002132 synchronized (stats) {
2133 ss = stats.getServiceStatsLocked(
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002134 sInfo.applicationInfo.uid, name.getPackageName(),
2135 name.getClassName());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002136 }
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08002137 r = new ServiceRecord(mAm, ss, className, name, filter, sInfo,
2138 callingFromFg, res);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002139 res.setService(r);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002140 smap.mServicesByInstanceName.put(name, r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002141 smap.mServicesByIntent.put(filter, r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002142
2143 // Make sure this component isn't in the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002144 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002145 final ServiceRecord pr = mPendingServices.get(i);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002146 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002147 && pr.instanceName.equals(name)) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002148 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002149 mPendingServices.remove(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002150 }
2151 }
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002152 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002153 }
2154 } catch (RemoteException ex) {
2155 // pm is in same process, this will never happen.
2156 }
2157 }
2158 if (r != null) {
Dianne Hackborn769b2e72018-12-05 08:51:20 -08002159 if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid, r.packageName,
2160 r.appInfo.uid)) {
2161 String msg = "association not allowed between packages "
2162 + callingPackage + " and " + r.packageName;
2163 Slog.w(TAG, "Service lookup failed: " + msg);
2164 return new ServiceLookupResult(null, msg);
2165 }
2166 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
2167 resolvedType, r.appInfo)) {
2168 return new ServiceLookupResult(null, "blocked by firewall");
2169 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002170 if (mAm.checkComponentPermission(r.permission,
Bryce Lee290e5782017-02-01 16:41:20 -08002171 callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002172 if (!r.exported) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002173 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002174 + " from pid=" + callingPid
2175 + ", uid=" + callingUid
2176 + " that is not exported from uid " + r.appInfo.uid);
2177 return new ServiceLookupResult(null, "not exported from uid "
2178 + r.appInfo.uid);
2179 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002180 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002181 + " from pid=" + callingPid
2182 + ", uid=" + callingUid
2183 + " requires " + r.permission);
2184 return new ServiceLookupResult(null, r.permission);
Svet Ganov99b60432015-06-27 13:15:22 -07002185 } else if (r.permission != null && callingPackage != null) {
2186 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
2187 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation(
2188 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002189 Slog.w(TAG, "Appop Denial: Accessing service " + r.shortInstanceName
Svet Ganov99b60432015-06-27 13:15:22 -07002190 + " from pid=" + callingPid
2191 + ", uid=" + callingUid
2192 + " requires appop " + AppOpsManager.opToName(opCode));
2193 return null;
2194 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002195 }
2196 return new ServiceLookupResult(r, null);
2197 }
2198 return null;
2199 }
2200
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002201 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002202 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002203 + why + " of " + r + " in app " + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002204 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002205 + why + " of " + r.shortInstanceName);
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002206
2207 // For b/34123235: Services within the system server won't start until SystemServer
2208 // does Looper.loop(), so we shouldn't try to start/bind to them too early in the boot
2209 // process. However, since there's a little point of showing the ANR dialog in that case,
2210 // let's suppress the timeout until PHASE_THIRD_PARTY_APPS_CAN_START.
2211 //
2212 // (Note there are multiple services start at PHASE_THIRD_PARTY_APPS_CAN_START too,
2213 // which technically could also trigger this timeout if there's a system server
2214 // that takes a long time to handle PHASE_THIRD_PARTY_APPS_CAN_START, but that shouldn't
2215 // happen.)
2216 boolean timeoutNeeded = true;
2217 if ((mAm.mBootPhase < SystemService.PHASE_THIRD_PARTY_APPS_CAN_START)
2218 && (r.app != null) && (r.app.pid == android.os.Process.myPid())) {
2219
2220 Slog.w(TAG, "Too early to start/bind service in system_server: Phase=" + mAm.mBootPhase
2221 + " " + r.getComponentName());
2222 timeoutNeeded = false;
2223 }
2224
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002225 long now = SystemClock.uptimeMillis();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002226 if (r.executeNesting == 0) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002227 r.executeFg = fg;
Joe Onorato4eb64fd2016-03-21 15:30:09 -07002228 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002229 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002230 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002231 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002232 if (r.app != null) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002233 r.app.executingServices.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002234 r.app.execServicesFg |= fg;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002235 if (timeoutNeeded && r.app.executingServices.size() == 1) {
Dianne Hackborn2be00932013-09-22 16:46:00 -07002236 scheduleServiceTimeoutLocked(r.app);
2237 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002238 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002239 } else if (r.app != null && fg && !r.app.execServicesFg) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002240 r.app.execServicesFg = true;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002241 if (timeoutNeeded) {
2242 scheduleServiceTimeoutLocked(r.app);
2243 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002244 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002245 r.executeFg |= fg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002246 r.executeNesting++;
2247 r.executingStart = now;
2248 }
2249
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002250 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
2251 boolean execInFg, boolean rebind) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002252 if (r.app == null || r.app.thread == null) {
2253 // If service is not currently running, can't yet bind.
2254 return false;
2255 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08002256 if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
2257 + " rebind=" + rebind);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002258 if ((!i.requested || rebind) && i.apps.size() > 0) {
2259 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002260 bumpServiceExecutingLocked(r, execInFg, "bind");
Dianne Hackborna413dc02013-07-12 12:02:55 -07002261 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
2262 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002263 r.app.getReportedProcState());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002264 if (!rebind) {
2265 i.requested = true;
2266 }
2267 i.hasBound = true;
2268 i.doRebind = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002269 } catch (TransactionTooLargeException e) {
2270 // Keep the executeNesting count accurate.
2271 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
2272 final boolean inDestroying = mDestroyingServices.contains(r);
2273 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2274 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002275 } catch (RemoteException e) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002276 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002277 // Keep the executeNesting count accurate.
2278 final boolean inDestroying = mDestroyingServices.contains(r);
2279 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002280 return false;
2281 }
2282 }
2283 return true;
2284 }
2285
Dianne Hackbornad51be92016-08-16 16:27:36 -07002286 private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002287 boolean canceled = false;
2288
Wale Ogunwalef6733932018-06-27 05:14:34 -07002289 if (mAm.mAtmInternal.isShuttingDown()) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002290 Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortInstanceName
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07002291 + " - system is shutting down");
2292 return false;
2293 }
2294
Dianne Hackbornad51be92016-08-16 16:27:36 -07002295 ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002296 if (smap.mServicesByInstanceName.get(r.instanceName) != r) {
2297 ServiceRecord cur = smap.mServicesByInstanceName.get(r.instanceName);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002298 Slog.wtf(TAG, "Attempting to schedule restart of " + r
2299 + " when found in map: " + cur);
2300 return false;
2301 }
2302
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002303 final long now = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002304
2305 if ((r.serviceInfo.applicationInfo.flags
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002306 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002307 long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION;
2308 long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002309
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002310 // Any delivered but not yet finished starts should be put back
2311 // on the pending list.
2312 final int N = r.deliveredStarts.size();
2313 if (N > 0) {
2314 for (int i=N-1; i>=0; i--) {
2315 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
2316 si.removeUriPermissionsLocked();
2317 if (si.intent == null) {
2318 // We'll generate this again if needed.
2319 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
2320 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
2321 r.pendingStarts.add(0, si);
2322 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
2323 dur *= 2;
2324 if (minDuration < dur) minDuration = dur;
2325 if (resetTime < dur) resetTime = dur;
2326 } else {
2327 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002328 + r.shortInstanceName);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002329 canceled = true;
2330 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002331 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002332 r.deliveredStarts.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002333 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002334
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002335 r.totalRestartCount++;
2336 if (r.restartDelay == 0) {
2337 r.restartCount++;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002338 r.restartDelay = minDuration;
Amith Yamasanib0c8a882017-08-28 09:36:42 -07002339 } else if (r.crashCount > 1) {
2340 r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
2341 * (r.crashCount - 1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002342 } else {
Varun Shah4311f212019-01-23 05:59:31 +00002343 // If it has been a "reasonably long time" since the service
2344 // was started, then reset our restart duration back to
2345 // the beginning, so we don't infinitely increase the duration
2346 // on a service that just occasionally gets killed (which is
2347 // a normal case, due to process being killed to reclaim memory).
2348 if (now > (r.restartTime+resetTime)) {
2349 r.restartCount = 1;
2350 r.restartDelay = minDuration;
Varun Shah16522412018-12-28 15:46:01 -08002351 } else {
Varun Shah4311f212019-01-23 05:59:31 +00002352 r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
2353 if (r.restartDelay < minDuration) {
2354 r.restartDelay = minDuration;
Varun Shah16522412018-12-28 15:46:01 -08002355 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002356 }
2357 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002358
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002359 r.nextRestartTime = now + r.restartDelay;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002360
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002361 // Make sure that we don't end up restarting a bunch of services
2362 // all at the same time.
Varun Shah4311f212019-01-23 05:59:31 +00002363 boolean repeat;
2364 do {
2365 repeat = false;
2366 final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
2367 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2368 ServiceRecord r2 = mRestartingServices.get(i);
2369 if (r2 != r && r.nextRestartTime >= (r2.nextRestartTime-restartTimeBetween)
2370 && r.nextRestartTime < (r2.nextRestartTime+restartTimeBetween)) {
2371 r.nextRestartTime = r2.nextRestartTime + restartTimeBetween;
2372 r.restartDelay = r.nextRestartTime - now;
2373 repeat = true;
2374 break;
2375 }
2376 }
2377 } while (repeat);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002378
2379 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07002380 // Persistent processes are immediately restarted, so there is no
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002381 // reason to hold of on restarting their services.
2382 r.totalRestartCount++;
2383 r.restartCount = 0;
2384 r.restartDelay = 0;
2385 r.nextRestartTime = now;
2386 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002387
2388 if (!mRestartingServices.contains(r)) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002389 r.createdFromFg = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002390 mRestartingServices.add(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002391 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002392 }
2393
Christopher Tate08992ac2017-03-21 11:37:06 -07002394 cancelForegroundNotificationLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002395
2396 mAm.mHandler.removeCallbacks(r.restarter);
2397 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
2398 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
2399 Slog.w(TAG, "Scheduling restart of crashed service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002400 + r.shortInstanceName + " in " + r.restartDelay + "ms");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002401 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002402 r.userId, r.shortInstanceName, r.restartDelay);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002403
2404 return canceled;
2405 }
2406
2407 final void performServiceRestartLocked(ServiceRecord r) {
2408 if (!mRestartingServices.contains(r)) {
2409 return;
2410 }
Dianne Hackbornad51be92016-08-16 16:27:36 -07002411 if (!isServiceNeededLocked(r, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002412 // Paranoia: is this service actually needed? In theory a service that is not
2413 // needed should never remain on the restart list. In practice... well, there
2414 // have been bugs where this happens, and bad things happen because the process
2415 // ends up just being cached, so quickly killed, then restarted again and again.
2416 // Let's not let that happen.
2417 Slog.wtf(TAG, "Restarting service that is not needed: " + r);
2418 return;
2419 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002420 try {
Svet Ganov9c165d72015-12-01 19:52:26 -08002421 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002422 } catch (TransactionTooLargeException e) {
2423 // Ignore, it's been logged and nothing upstack cares.
2424 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002425 }
2426
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002427 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
2428 boolean force) {
2429 if (!force && r.restartDelay == 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002430 return false;
2431 }
Dianne Hackborn7b492722013-11-01 09:58:45 -07002432 // Remove from the restarting list; if the service is currently on the
2433 // restarting list, or the call is coming from another app, then this
2434 // service has become of much more interest so we reset the restart interval.
2435 boolean removed = mRestartingServices.remove(r);
2436 if (removed || callingUid != r.appInfo.uid) {
2437 r.resetRestartCounter();
2438 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002439 if (removed) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002440 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002441 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002442 mAm.mHandler.removeCallbacks(r.restarter);
2443 return true;
2444 }
2445
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002446 private void clearRestartingIfNeededLocked(ServiceRecord r) {
2447 if (r.restartTracker != null) {
2448 // If this is the last restarting record with this tracker, then clear
2449 // the tracker's restarting state.
2450 boolean stillTracking = false;
2451 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2452 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
2453 stillTracking = true;
2454 break;
2455 }
2456 }
2457 if (!stillTracking) {
2458 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
2459 SystemClock.uptimeMillis());
2460 r.restartTracker = null;
2461 }
2462 }
2463 }
2464
Svet Ganov9c165d72015-12-01 19:52:26 -08002465 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
2466 boolean whileRestarting, boolean permissionsReviewRequired)
2467 throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002468 //Slog.i(TAG, "Bring up service:");
2469 //r.dump(" ");
2470
2471 if (r.app != null && r.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002472 sendServiceArgsLocked(r, execInFg, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002473 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002474 }
2475
Sudheer Shanka03d0f812017-04-20 16:57:50 -07002476 if (!whileRestarting && mRestartingServices.contains(r)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002477 // If waiting for a restart, then do nothing.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002478 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002479 }
2480
Christopher Tate08992ac2017-03-21 11:37:06 -07002481 if (DEBUG_SERVICE) {
2482 Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
2483 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002484
2485 // We are now bringing the service up, so no longer in the
2486 // restarting state.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002487 if (mRestartingServices.remove(r)) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002488 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002489 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002490
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002491 // Make sure this service is no longer considered delayed, we are starting it now.
2492 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002493 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002494 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002495 r.delayed = false;
2496 }
2497
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002498 // Make sure that the user who owns this service is started. If not,
2499 // we don't want to allow it to run.
Fyodor Kupolov610acda2015-10-19 18:44:07 -07002500 if (!mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002501 String msg = "Unable to launch app "
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002502 + r.appInfo.packageName + "/"
2503 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002504 + r.intent.getIntent() + ": user " + r.userId + " is stopped";
2505 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002506 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002507 return msg;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002508 }
2509
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002510 // Service is now being launched, its package can't be stopped.
2511 try {
2512 AppGlobals.getPackageManager().setPackageStoppedState(
2513 r.packageName, false, r.userId);
2514 } catch (RemoteException e) {
2515 } catch (IllegalArgumentException e) {
2516 Slog.w(TAG, "Failed trying to unstop package "
2517 + r.packageName + ": " + e);
2518 }
2519
2520 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
2521 final String procName = r.processName;
Robert Sesekc5f86642016-11-04 10:20:38 -04002522 String hostingType = "service";
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002523 ProcessRecord app;
2524
2525 if (!isolated) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07002526 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
2527 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
2528 + " app=" + app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002529 if (app != null && app.thread != null) {
2530 try {
Patrick Baumannc2def582018-04-04 12:14:15 -07002531 app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode, mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002532 realStartServiceLocked(r, app, execInFg);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002533 return null;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002534 } catch (TransactionTooLargeException e) {
2535 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002536 } catch (RemoteException e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002537 Slog.w(TAG, "Exception when starting service " + r.shortInstanceName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002538 }
2539
2540 // If a dead object exception was thrown -- fall through to
2541 // restart the application.
2542 }
2543 } else {
2544 // If this service runs in an isolated process, then each time
2545 // we call startProcessLocked() we will get a new isolated
2546 // process, starting another process if we are currently waiting
2547 // for a previous process to come up. To deal with this, we store
2548 // in the service any current isolated process it is running in or
2549 // waiting to have come up.
2550 app = r.isolatedProc;
Robert Sesekc5f86642016-11-04 10:20:38 -04002551 if (WebViewZygote.isMultiprocessEnabled()
2552 && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
2553 hostingType = "webview_service";
2554 }
Martijn Coenen7e6fa672018-11-05 11:45:26 +01002555 if ((r.serviceInfo.flags & ServiceInfo.FLAG_USE_APP_ZYGOTE) != 0) {
2556 hostingType = "app_zygote";
2557 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002558 }
2559
2560 // Not running -- get it started, and enqueue this service record
2561 // to be executed when the app comes up.
Svet Ganov9c165d72015-12-01 19:52:26 -08002562 if (app == null && !permissionsReviewRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002563 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002564 hostingType, r.instanceName, false, isolated, false)) == null) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002565 String msg = "Unable to launch app "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002566 + r.appInfo.packageName + "/"
2567 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002568 + r.intent.getIntent() + ": process is bad";
2569 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002570 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002571 return msg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002572 }
2573 if (isolated) {
2574 r.isolatedProc = app;
2575 }
2576 }
2577
Christopher Tate1536cc22017-09-18 16:43:30 -07002578 if (r.fgRequired) {
2579 if (DEBUG_FOREGROUND_SERVICE) {
2580 Slog.v(TAG, "Whitelisting " + UserHandle.formatUid(r.appInfo.uid)
2581 + " for fg-service launch");
2582 }
2583 mAm.tempWhitelistUidLocked(r.appInfo.uid,
2584 SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch");
2585 }
2586
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002587 if (!mPendingServices.contains(r)) {
2588 mPendingServices.add(r);
2589 }
2590
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002591 if (r.delayedStop) {
2592 // Oh and hey we've already been asked to stop!
2593 r.delayedStop = false;
2594 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002595 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2596 "Applying delayed stop (in bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002597 stopServiceLocked(r);
2598 }
2599 }
2600
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002601 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002602 }
2603
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002604 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
2605 throws TransactionTooLargeException {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002606 for (int i=r.bindings.size()-1; i>=0; i--) {
2607 IntentBindRecord ibr = r.bindings.valueAt(i);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002608 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002609 break;
2610 }
2611 }
2612 }
2613
2614 private final void realStartServiceLocked(ServiceRecord r,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002615 ProcessRecord app, boolean execInFg) throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002616 if (app.thread == null) {
2617 throw new RemoteException();
2618 }
2619 if (DEBUG_MU)
2620 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
2621 + ", ProcessRecord.uid = " + app.uid);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002622 r.setProcess(app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002623 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
2624
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002625 final boolean newService = app.services.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002626 bumpServiceExecutingLocked(r, execInFg, "create");
Dianne Hackborndb926082013-10-31 16:32:44 -07002627 mAm.updateLruProcessLocked(app, false, null);
Makoto Onuki0f421292017-04-28 15:03:33 -07002628 updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
2629 mAm.updateOomAdjLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002630
2631 boolean created = false;
2632 try {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002633 if (LOG_SERVICE_START_STOP) {
Dianne Hackbornab2df062015-01-07 13:43:13 -08002634 String nameTerm;
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002635 int lastPeriod = r.shortInstanceName.lastIndexOf('.');
2636 nameTerm = lastPeriod >= 0 ? r.shortInstanceName.substring(lastPeriod)
2637 : r.shortInstanceName;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002638 EventLogTags.writeAmCreateService(
2639 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
2640 }
Chenjie Yu75b3c492018-10-06 21:45:19 -07002641 StatsLog.write(StatsLog.SERVICE_LAUNCH_REPORTED, r.appInfo.uid, r.name.getPackageName(),
2642 r.name.getClassName());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002643 synchronized (r.stats.getBatteryStats()) {
2644 r.stats.startLaunchedLocked();
2645 }
Brian Carlstromca82e612016-04-19 23:16:08 -07002646 mAm.notifyPackageUse(r.serviceInfo.packageName,
2647 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
Dianne Hackborna413dc02013-07-12 12:02:55 -07002648 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002649 app.thread.scheduleCreateService(r, r.serviceInfo,
Wale Ogunwale53783742018-09-16 10:21:51 -07002650 mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002651 app.getReportedProcState());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002652 r.postNotification();
2653 created = true;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -07002654 } catch (DeadObjectException e) {
2655 Slog.w(TAG, "Application dead when creating service " + r);
2656 mAm.appDiedLocked(app);
Wale Ogunwalebfac4682015-04-08 14:33:21 -07002657 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002658 } finally {
2659 if (!created) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002660 // Keep the executeNesting count accurate.
2661 final boolean inDestroying = mDestroyingServices.contains(r);
2662 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2663
2664 // Cleanup.
2665 if (newService) {
2666 app.services.remove(r);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002667 r.setProcess(null);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002668 }
2669
2670 // Retry.
2671 if (!inDestroying) {
2672 scheduleServiceRestartLocked(r, false);
2673 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002674 }
2675 }
2676
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002677 if (r.whitelistManager) {
2678 app.whitelistManager = true;
2679 }
2680
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002681 requestServiceBindingsLocked(r, execInFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002682
Dianne Hackborn465fa392014-09-14 14:21:18 -07002683 updateServiceClientActivitiesLocked(app, null, true);
2684
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002685 // If the service is in the started state, and there are no
2686 // pending arguments, then fake up one so its onStartCommand() will
2687 // be called.
2688 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
2689 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002690 null, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002691 }
2692
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002693 sendServiceArgsLocked(r, execInFg, true);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002694
2695 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002696 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002697 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002698 r.delayed = false;
2699 }
2700
2701 if (r.delayedStop) {
2702 // Oh and hey we've already been asked to stop!
2703 r.delayedStop = false;
2704 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002705 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2706 "Applying delayed stop (from start): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002707 stopServiceLocked(r);
2708 }
2709 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002710 }
2711
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002712 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002713 boolean oomAdjusted) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002714 final int N = r.pendingStarts.size();
2715 if (N == 0) {
2716 return;
2717 }
2718
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002719 ArrayList<ServiceStartArgs> args = new ArrayList<>();
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002720
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002721 while (r.pendingStarts.size() > 0) {
2722 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
2723 if (DEBUG_SERVICE) {
2724 Slog.v(TAG_SERVICE, "Sending arguments to: "
2725 + r + " " + r.intent + " args=" + si.intent);
2726 }
2727 if (si.intent == null && N > 1) {
2728 // If somehow we got a dummy null intent in the middle,
2729 // then skip it. DO NOT skip a null intent when it is
2730 // the only one in the list -- this is to support the
2731 // onStartCommand(null) case.
2732 continue;
2733 }
2734 si.deliveredTime = SystemClock.uptimeMillis();
2735 r.deliveredStarts.add(si);
2736 si.deliveryCount++;
2737 if (si.neededGrants != null) {
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07002738 mAm.mUgmInternal.grantUriPermissionUncheckedFromIntent(si.neededGrants,
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002739 si.getUriPermissionsLocked());
2740 }
Hai Zhangbb23d532018-08-27 16:00:35 -07002741 mAm.grantEphemeralAccessLocked(r.userId, si.intent, UserHandle.getAppId(r.appInfo.uid),
2742 UserHandle.getAppId(si.callingId));
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002743 bumpServiceExecutingLocked(r, execInFg, "start");
2744 if (!oomAdjusted) {
2745 oomAdjusted = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002746 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002747 }
2748 if (r.fgRequired && !r.fgWaiting) {
2749 if (!r.isForeground) {
2750 if (DEBUG_BACKGROUND_CHECK) {
2751 Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r);
2752 }
2753 scheduleServiceForegroundTransitionTimeoutLocked(r);
2754 } else {
2755 if (DEBUG_BACKGROUND_CHECK) {
2756 Slog.i(TAG, "Service already foreground; no new timeout: " + r);
2757 }
2758 r.fgRequired = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002759 }
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002760 }
2761 int flags = 0;
2762 if (si.deliveryCount > 1) {
2763 flags |= Service.START_FLAG_RETRY;
2764 }
2765 if (si.doneExecutingCount > 0) {
2766 flags |= Service.START_FLAG_REDELIVERY;
2767 }
2768 args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
2769 }
2770
2771 ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
2772 slice.setInlineCountLimit(4);
2773 Exception caughtException = null;
2774 try {
2775 r.app.thread.scheduleServiceArgs(r, slice);
2776 } catch (TransactionTooLargeException e) {
2777 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
2778 + " args, first: " + args.get(0).args);
2779 Slog.w(TAG, "Failed delivering service starts", e);
2780 caughtException = e;
2781 } catch (RemoteException e) {
2782 // Remote process gone... we'll let the normal cleanup take care of this.
2783 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
2784 Slog.w(TAG, "Failed delivering service starts", e);
2785 caughtException = e;
2786 } catch (Exception e) {
2787 Slog.w(TAG, "Unexpected exception", e);
2788 caughtException = e;
2789 }
2790
2791 if (caughtException != null) {
2792 // Keep nesting count correct
2793 final boolean inDestroying = mDestroyingServices.contains(r);
2794 for (int i = 0; i < args.size(); i++) {
2795 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2796 }
2797 if (caughtException instanceof TransactionTooLargeException) {
2798 throw (TransactionTooLargeException)caughtException;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002799 }
2800 }
2801 }
2802
Dianne Hackbornad51be92016-08-16 16:27:36 -07002803 private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn,
2804 boolean hasConn) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002805 // Are we still explicitly being asked to run?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002806 if (r.startRequested) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002807 return true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002808 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002809
Dianne Hackborncb015632017-06-14 17:30:15 -07002810 // Is someone still bound to us keeping us running?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002811 if (!knowConn) {
2812 hasConn = r.hasAutoCreateConnections();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002813 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002814 if (hasConn) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002815 return true;
2816 }
2817
2818 return false;
2819 }
2820
2821 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
2822 boolean hasConn) {
2823 //Slog.i(TAG, "Bring down service:");
2824 //r.dump(" ");
2825
Dianne Hackbornad51be92016-08-16 16:27:36 -07002826 if (isServiceNeededLocked(r, knowConn, hasConn)) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002827 return;
2828 }
2829
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002830 // Are we in the process of launching?
2831 if (mPendingServices.contains(r)) {
2832 return;
2833 }
2834
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002835 bringDownServiceLocked(r);
2836 }
2837
2838 private final void bringDownServiceLocked(ServiceRecord r) {
2839 //Slog.i(TAG, "Bring down service:");
2840 //r.dump(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002841
Dianne Hackborn390517b2013-05-30 15:03:32 -07002842 // Report to all of the connections that the service is no longer
2843 // available.
2844 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2845 ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
2846 for (int i=0; i<c.size(); i++) {
2847 ConnectionRecord cr = c.get(i);
2848 // There is still a connection to the service that is
2849 // being brought down. Mark it as dead.
2850 cr.serviceDead = true;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002851 cr.stopAssociation();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002852 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07002853 cr.conn.connected(r.name, null, true);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002854 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002855 Slog.w(TAG, "Failure disconnecting service " + r.shortInstanceName
2856 + " to connection " + c.get(i).conn.asBinder()
2857 + " (in " + c.get(i).binding.client.processName + ")", e);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002858 }
2859 }
2860 }
2861
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002862 // Tell the service that it has been unbound.
Dianne Hackborn390517b2013-05-30 15:03:32 -07002863 if (r.app != null && r.app.thread != null) {
2864 for (int i=r.bindings.size()-1; i>=0; i--) {
2865 IntentBindRecord ibr = r.bindings.valueAt(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002866 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002867 + ": hasBound=" + ibr.hasBound);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002868 if (ibr.hasBound) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002869 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002870 bumpServiceExecutingLocked(r, false, "bring down unbind");
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002871 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002872 ibr.hasBound = false;
Dianne Hackborn85e35642017-01-12 15:10:57 -08002873 ibr.requested = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002874 r.app.thread.scheduleUnbindService(r,
2875 ibr.intent.getIntent());
2876 } catch (Exception e) {
2877 Slog.w(TAG, "Exception when unbinding service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002878 + r.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002879 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002880 }
2881 }
2882 }
2883 }
2884
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002885 // Check to see if the service had been started as foreground, but being
2886 // brought down before actually showing a notification. That is not allowed.
2887 if (r.fgRequired) {
2888 Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
2889 + r);
2890 r.fgRequired = false;
2891 r.fgWaiting = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002892 ServiceState stracker = r.getTracker();
2893 if (stracker != null) {
2894 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
2895 r.lastActivity);
2896 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07002897 mAm.mAppOpsService.finishOperation(AppOpsManager.getToken(mAm.mAppOpsService),
2898 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002899 mAm.mHandler.removeMessages(
2900 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
2901 if (r.app != null) {
2902 Message msg = mAm.mHandler.obtainMessage(
2903 ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
2904 msg.obj = r.app;
Kodlee Yin7e951262018-04-05 12:59:56 -07002905 msg.getData().putCharSequence(
2906 ActivityManagerService.SERVICE_RECORD_KEY, r.toString());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002907 mAm.mHandler.sendMessage(msg);
2908 }
2909 }
2910
2911 if (DEBUG_SERVICE) {
2912 RuntimeException here = new RuntimeException();
2913 here.fillInStackTrace();
2914 Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here);
2915 }
Craig Mautner66c4a822015-01-16 12:48:16 -08002916 r.destroyTime = SystemClock.uptimeMillis();
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002917 if (LOG_SERVICE_START_STOP) {
2918 EventLogTags.writeAmDestroyService(
2919 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
2920 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002921
Dianne Hackbornad51be92016-08-16 16:27:36 -07002922 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002923 ServiceRecord found = smap.mServicesByInstanceName.remove(r.instanceName);
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002924
2925 // Note when this method is called by bringUpServiceLocked(), the service is not found
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002926 // in mServicesByInstanceName and found will be null.
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002927 if (found != null && found != r) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002928 // This is not actually the service we think is running... this should not happen,
2929 // but if it does, fail hard.
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002930 smap.mServicesByInstanceName.put(r.instanceName, found);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002931 throw new IllegalStateException("Bringing down " + r + " but actually running "
2932 + found);
2933 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002934 smap.mServicesByIntent.remove(r.intent);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002935 r.totalRestartCount = 0;
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002936 unscheduleServiceRestartLocked(r, 0, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002937
2938 // Also make sure it is not on the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002939 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002940 if (mPendingServices.get(i) == r) {
2941 mPendingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002942 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002943 }
2944 }
2945
Christopher Tate08992ac2017-03-21 11:37:06 -07002946 cancelForegroundNotificationLocked(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002947 if (r.isForeground) {
2948 decActiveForegroundAppLocked(smap, r);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002949 ServiceState stracker = r.getTracker();
2950 if (stracker != null) {
2951 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
2952 r.lastActivity);
2953 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07002954 mAm.mAppOpsService.finishOperation(
2955 AppOpsManager.getToken(mAm.mAppOpsService),
2956 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002957 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED, r.appInfo.uid,
2958 r.shortInstanceName, StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Hui Yue361a232018-10-04 15:05:21 -07002959 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002960 }
Chenjie Yuccfe6452018-01-30 11:33:21 -08002961
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002962 r.isForeground = false;
2963 r.foregroundId = 0;
2964 r.foregroundNoti = null;
2965
2966 // Clear start entries.
2967 r.clearDeliveredStartsLocked();
2968 r.pendingStarts.clear();
2969
2970 if (r.app != null) {
2971 synchronized (r.stats.getBatteryStats()) {
2972 r.stats.stopLaunchedLocked();
2973 }
2974 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002975 if (r.whitelistManager) {
2976 updateWhitelistManagerLocked(r.app);
2977 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002978 if (r.app.thread != null) {
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002979 updateServiceForegroundLocked(r.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002980 try {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002981 bumpServiceExecutingLocked(r, false, "destroy");
2982 mDestroyingServices.add(r);
Dianne Hackborn455625e2015-01-21 09:55:13 -08002983 r.destroying = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002984 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002985 r.app.thread.scheduleStopService(r);
2986 } catch (Exception e) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002987 Slog.w(TAG, "Exception when destroying service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002988 + r.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002989 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002990 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002991 } else {
2992 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002993 TAG_SERVICE, "Removed service that has no process: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002994 }
2995 } else {
2996 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002997 TAG_SERVICE, "Removed service that is not running: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002998 }
2999
3000 if (r.bindings.size() > 0) {
3001 r.bindings.clear();
3002 }
3003
3004 if (r.restarter instanceof ServiceRestarter) {
3005 ((ServiceRestarter)r.restarter).setService(null);
3006 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003007
Dianne Hackbornd2932242013-08-05 18:18:42 -07003008 int memFactor = mAm.mProcessStats.getMemFactorLocked();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003009 long now = SystemClock.uptimeMillis();
3010 if (r.tracker != null) {
3011 r.tracker.setStarted(false, memFactor, now);
3012 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003013 if (r.executeNesting == 0) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07003014 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003015 r.tracker = null;
3016 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003017 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003018
Dianne Hackbornad51be92016-08-16 16:27:36 -07003019 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003020 }
3021
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07003022 void removeConnectionLocked(ConnectionRecord c, ProcessRecord skipApp,
3023 ActivityServiceConnectionsHolder skipAct) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003024 IBinder binder = c.conn.asBinder();
3025 AppBindRecord b = c.binding;
3026 ServiceRecord s = b.service;
3027 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
3028 if (clist != null) {
3029 clist.remove(c);
3030 if (clist.size() == 0) {
3031 s.connections.remove(binder);
3032 }
3033 }
3034 b.connections.remove(c);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003035 c.stopAssociation();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003036 if (c.activity != null && c.activity != skipAct) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07003037 c.activity.removeConnection(c);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003038 }
3039 if (b.client != skipApp) {
3040 b.client.connections.remove(c);
3041 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
3042 b.client.updateHasAboveClientLocked();
3043 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003044 // If this connection requested whitelist management, see if we should
3045 // now clear that state.
3046 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
3047 s.updateWhitelistManager();
3048 if (!s.whitelistManager && s.app != null) {
3049 updateWhitelistManagerLocked(s.app);
3050 }
3051 }
Dianne Hackborndb926082013-10-31 16:32:44 -07003052 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07003053 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07003054 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003055 }
3056 clist = mServiceConnections.get(binder);
3057 if (clist != null) {
3058 clist.remove(c);
3059 if (clist.size() == 0) {
3060 mServiceConnections.remove(binder);
3061 }
3062 }
3063
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003064 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003065 s.appInfo.longVersionCode, s.instanceName, s.processName);
Dianne Hackbornab2df062015-01-07 13:43:13 -08003066
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003067 if (b.connections.size() == 0) {
3068 b.intent.apps.remove(b.client);
3069 }
3070
3071 if (!c.serviceDead) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003072 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003073 + ": shouldUnbind=" + b.intent.hasBound);
3074 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
3075 && b.intent.hasBound) {
3076 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003077 bumpServiceExecutingLocked(s, false, "unbind");
Dianne Hackborndb926082013-10-31 16:32:44 -07003078 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
Dianne Hackbornf097d422017-12-15 16:32:19 -08003079 && s.app.setProcState <= ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
Dianne Hackborndb926082013-10-31 16:32:44 -07003080 // If this service's process is not already in the cached list,
3081 // then update it in the LRU list here because this may be causing
3082 // it to go down there and we want it to start out near the top.
3083 mAm.updateLruProcessLocked(s.app, false, null);
3084 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07003085 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003086 b.intent.hasBound = false;
3087 // Assume the client doesn't want to know about a rebind;
3088 // we will deal with that later if it asks for one.
3089 b.intent.doRebind = false;
3090 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
3091 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003092 Slog.w(TAG, "Exception when unbinding service " + s.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07003093 serviceProcessGoneLocked(s);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003094 }
3095 }
3096
Svet Ganov9c165d72015-12-01 19:52:26 -08003097 // If unbound while waiting to start, remove the pending service
3098 mPendingServices.remove(s);
3099
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003100 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003101 boolean hasAutoCreate = s.hasAutoCreateConnections();
3102 if (!hasAutoCreate) {
3103 if (s.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003104 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003105 SystemClock.uptimeMillis());
3106 }
3107 }
3108 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003109 }
3110 }
3111 }
3112
3113 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003114 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003115 if (r != null) {
Dianne Hackborn455625e2015-01-21 09:55:13 -08003116 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003117 // This is a call from a service start... take care of
3118 // book-keeping.
3119 r.callStart = true;
3120 switch (res) {
3121 case Service.START_STICKY_COMPATIBILITY:
3122 case Service.START_STICKY: {
3123 // We are done with the associated start arguments.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003124 r.findDeliveredStart(startId, false, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003125 // Don't stop if killed.
3126 r.stopIfKilled = false;
3127 break;
3128 }
3129 case Service.START_NOT_STICKY: {
3130 // We are done with the associated start arguments.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003131 r.findDeliveredStart(startId, false, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003132 if (r.getLastStartId() == startId) {
3133 // There is no more work, and this service
3134 // doesn't want to hang around if killed.
3135 r.stopIfKilled = true;
3136 }
3137 break;
3138 }
3139 case Service.START_REDELIVER_INTENT: {
3140 // We'll keep this item until they explicitly
3141 // call stop for it, but keep track of the fact
3142 // that it was delivered.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003143 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003144 if (si != null) {
3145 si.deliveryCount = 0;
3146 si.doneExecutingCount++;
3147 // Don't stop if killed.
3148 r.stopIfKilled = true;
3149 }
3150 break;
3151 }
3152 case Service.START_TASK_REMOVED_COMPLETE: {
3153 // Special processing for onTaskRemoved(). Don't
3154 // impact normal onStartCommand() processing.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003155 r.findDeliveredStart(startId, true, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003156 break;
3157 }
3158 default:
3159 throw new IllegalArgumentException(
3160 "Unknown service start result: " + res);
3161 }
3162 if (res == Service.START_STICKY_COMPATIBILITY) {
3163 r.callStart = false;
3164 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08003165 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
3166 // This is the final call from destroying the service... we should
3167 // actually be getting rid of the service at this point. Do some
3168 // validation of its state, and ensure it will be fully removed.
3169 if (!inDestroying) {
3170 // Not sure what else to do with this... if it is not actually in the
3171 // destroying list, we don't need to make sure to remove it from it.
Amith Yamasanid0418222016-05-10 15:49:51 -07003172 // If the app is null, then it was probably removed because the process died,
3173 // otherwise wtf
3174 if (r.app != null) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07003175 Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
Amith Yamasanid0418222016-05-10 15:49:51 -07003176 + r + ", app=" + r.app);
3177 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08003178 } else if (r.executeNesting != 1) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07003179 Slog.w(TAG, "Service done with onDestroy, but executeNesting="
Dianne Hackborn455625e2015-01-21 09:55:13 -08003180 + r.executeNesting + ": " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003181 // Fake it to keep from ANR due to orphaned entry.
Dianne Hackborn455625e2015-01-21 09:55:13 -08003182 r.executeNesting = 1;
3183 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003184 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003185 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn164371f2013-10-01 19:10:13 -07003186 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003187 Binder.restoreCallingIdentity(origId);
3188 } else {
3189 Slog.w(TAG, "Done executing unknown service from pid "
3190 + Binder.getCallingPid());
3191 }
3192 }
3193
Dianne Hackborn878deb32013-10-14 16:55:09 -07003194 private void serviceProcessGoneLocked(ServiceRecord r) {
3195 if (r.tracker != null) {
3196 int memFactor = mAm.mProcessStats.getMemFactorLocked();
3197 long now = SystemClock.uptimeMillis();
3198 r.tracker.setExecuting(false, memFactor, now);
3199 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbc72dce2013-11-11 10:43:38 -08003200 r.tracker.setStarted(false, memFactor, now);
Dianne Hackborn878deb32013-10-14 16:55:09 -07003201 }
3202 serviceDoneExecutingLocked(r, true, true);
3203 }
3204
Dianne Hackborn164371f2013-10-01 19:10:13 -07003205 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
3206 boolean finishing) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003207 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003208 + ": nesting=" + r.executeNesting
Dianne Hackborn164371f2013-10-01 19:10:13 -07003209 + ", inDestroying=" + inDestroying + ", app=" + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003210 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003211 "<<< DONE EXECUTING " + r.shortInstanceName);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003212 r.executeNesting--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003213 if (r.executeNesting <= 0) {
3214 if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003215 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003216 "Nesting at 0 of " + r.shortInstanceName);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003217 r.app.execServicesFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003218 r.app.executingServices.remove(r);
3219 if (r.app.executingServices.size() == 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003220 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003221 "No more executingServices of " + r.shortInstanceName);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003222 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003223 } else if (r.executeFg) {
3224 // Need to re-evaluate whether the app still needs to be in the foreground.
3225 for (int i=r.app.executingServices.size()-1; i>=0; i--) {
3226 if (r.app.executingServices.valueAt(i).executeFg) {
3227 r.app.execServicesFg = true;
3228 break;
3229 }
3230 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003231 }
Dianne Hackborn164371f2013-10-01 19:10:13 -07003232 if (inDestroying) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003233 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn164371f2013-10-01 19:10:13 -07003234 "doneExecuting remove destroying " + r);
3235 mDestroyingServices.remove(r);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003236 r.bindings.clear();
3237 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07003238 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003239 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003240 r.executeFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003241 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003242 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003243 SystemClock.uptimeMillis());
Dianne Hackborn164371f2013-10-01 19:10:13 -07003244 if (finishing) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07003245 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003246 r.tracker = null;
3247 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003248 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003249 if (finishing) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003250 if (r.app != null && !r.app.isPersistent()) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003251 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003252 if (r.whitelistManager) {
3253 updateWhitelistManagerLocked(r.app);
3254 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003255 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003256 r.setProcess(null);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003257 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003258 }
3259 }
3260
Dianne Hackbornff072722014-09-24 10:56:28 -07003261 boolean attachApplicationLocked(ProcessRecord proc, String processName)
3262 throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003263 boolean didSomething = false;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003264 // Collect any services that are waiting for this process to come up.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003265 if (mPendingServices.size() > 0) {
3266 ServiceRecord sr = null;
3267 try {
3268 for (int i=0; i<mPendingServices.size(); i++) {
3269 sr = mPendingServices.get(i);
3270 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3271 || !processName.equals(sr.processName))) {
3272 continue;
3273 }
3274
3275 mPendingServices.remove(i);
3276 i--;
Patrick Baumannc2def582018-04-04 12:14:15 -07003277 proc.addPackage(sr.appInfo.packageName, sr.appInfo.longVersionCode,
Dianne Hackbornf7097a52014-05-13 09:56:14 -07003278 mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003279 realStartServiceLocked(sr, proc, sr.createdFromFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003280 didSomething = true;
Dianne Hackbornad51be92016-08-16 16:27:36 -07003281 if (!isServiceNeededLocked(sr, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003282 // We were waiting for this service to start, but it is actually no
3283 // longer needed. This could happen because bringDownServiceIfNeeded
3284 // won't bring down a service that is pending... so now the pending
3285 // is done, so let's drop it.
3286 bringDownServiceLocked(sr);
3287 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003288 }
Dianne Hackbornff072722014-09-24 10:56:28 -07003289 } catch (RemoteException e) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003290 Slog.w(TAG, "Exception in new application when starting service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003291 + sr.shortInstanceName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003292 throw e;
3293 }
3294 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003295 // Also, if there are any services that are waiting to restart and
3296 // would run in this process, now is a good time to start them. It would
3297 // be weird to bring up the process but arbitrarily not let the services
3298 // run at this point just because their restart time hasn't come up.
3299 if (mRestartingServices.size() > 0) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003300 ServiceRecord sr;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003301 for (int i=0; i<mRestartingServices.size(); i++) {
3302 sr = mRestartingServices.get(i);
3303 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3304 || !processName.equals(sr.processName))) {
3305 continue;
3306 }
3307 mAm.mHandler.removeCallbacks(sr.restarter);
3308 mAm.mHandler.post(sr.restarter);
3309 }
3310 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003311 return didSomething;
3312 }
3313
3314 void processStartTimedOutLocked(ProcessRecord proc) {
3315 for (int i=0; i<mPendingServices.size(); i++) {
3316 ServiceRecord sr = mPendingServices.get(i);
3317 if ((proc.uid == sr.appInfo.uid
3318 && proc.processName.equals(sr.processName))
3319 || sr.isolatedProc == proc) {
3320 Slog.w(TAG, "Forcing bringing down service: " + sr);
3321 sr.isolatedProc = null;
3322 mPendingServices.remove(i);
3323 i--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003324 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003325 }
3326 }
3327 }
3328
Wale Ogunwale540e1232015-05-01 15:35:39 -07003329 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003330 boolean evenPersistent, boolean doit, ArrayMap<ComponentName, ServiceRecord> services) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003331 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003332 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003333 ServiceRecord service = services.valueAt(i);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003334 final boolean sameComponent = packageName == null
3335 || (service.packageName.equals(packageName)
3336 && (filterByClasses == null
3337 || filterByClasses.contains(service.name.getClassName())));
3338 if (sameComponent
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003339 && (service.app == null || evenPersistent || !service.app.isPersistent())) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003340 if (!doit) {
3341 return true;
3342 }
3343 didSomething = true;
3344 Slog.i(TAG, " Force stopping service " + service);
Riddle Hsuaaef7312019-01-24 19:00:58 +08003345 if (service.app != null && !service.app.isPersistent()) {
3346 service.app.services.remove(service);
3347 if (service.whitelistManager) {
3348 updateWhitelistManagerLocked(service.app);
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08003349 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003350 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003351 service.setProcess(null);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003352 service.isolatedProc = null;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003353 if (mTmpCollectionResults == null) {
3354 mTmpCollectionResults = new ArrayList<>();
3355 }
3356 mTmpCollectionResults.add(service);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003357 }
3358 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003359 return didSomething;
3360 }
3361
Wale Ogunwale540e1232015-05-01 15:35:39 -07003362 boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003363 int userId, boolean evenPersistent, boolean doit) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003364 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003365
3366 if (mTmpCollectionResults != null) {
3367 mTmpCollectionResults.clear();
3368 }
3369
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003370 if (userId == UserHandle.USER_ALL) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003371 for (int i = mServiceMap.size() - 1; i >= 0; i--) {
3372 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003373 evenPersistent, doit, mServiceMap.valueAt(i).mServicesByInstanceName);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003374 if (!doit && didSomething) {
3375 return true;
3376 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003377 if (doit && filterByClasses == null) {
3378 forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId);
3379 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003380 }
3381 } else {
Amith Yamasani540b6592013-10-01 13:02:52 -07003382 ServiceMap smap = mServiceMap.get(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003383 if (smap != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003384 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByInstanceName;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003385 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003386 evenPersistent, doit, items);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003387 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003388 if (doit && filterByClasses == null) {
3389 forceStopPackageLocked(packageName, userId);
3390 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003391 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003392
Wale Ogunwale540e1232015-05-01 15:35:39 -07003393 if (mTmpCollectionResults != null) {
3394 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
3395 bringDownServiceLocked(mTmpCollectionResults.get(i));
3396 }
3397 mTmpCollectionResults.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003398 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003399
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003400 return didSomething;
3401 }
3402
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003403 void forceStopPackageLocked(String packageName, int userId) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003404 ServiceMap smap = mServiceMap.get(userId);
3405 if (smap != null && smap.mActiveForegroundApps.size() > 0) {
Dianne Hackbornaf597682017-05-01 10:54:07 -07003406 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003407 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
3408 if (aa.mPackageName.equals(packageName)) {
3409 smap.mActiveForegroundApps.removeAt(i);
3410 smap.mActiveForegroundAppsChanged = true;
3411 }
3412 }
3413 if (smap.mActiveForegroundAppsChanged) {
3414 requestUpdateActiveForegroundAppsLocked(smap, 0);
3415 }
3416 }
3417 }
3418
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003419 void cleanUpServices(int userId, ComponentName component, Intent baseIntent) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003420 ArrayList<ServiceRecord> services = new ArrayList<>();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003421 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003422 for (int i = alls.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003423 ServiceRecord sr = alls.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003424 if (sr.packageName.equals(component.getPackageName())) {
3425 services.add(sr);
3426 }
3427 }
3428
3429 // Take care of any running services associated with the app.
Wale Ogunwale540e1232015-05-01 15:35:39 -07003430 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003431 ServiceRecord sr = services.get(i);
3432 if (sr.startRequested) {
3433 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003434 Slog.i(TAG, "Stopping service " + sr.shortInstanceName + ": remove task");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003435 stopServiceLocked(sr);
3436 } else {
3437 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003438 sr.getLastStartId(), baseIntent, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003439 if (sr.app != null && sr.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003440 // We always run in the foreground, since this is called as
3441 // part of the "remove task" UI operation.
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003442 try {
3443 sendServiceArgsLocked(sr, true, false);
3444 } catch (TransactionTooLargeException e) {
3445 // Ignore, keep going.
3446 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003447 }
3448 }
3449 }
3450 }
3451 }
3452
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003453 final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003454 // Report disconnected services.
3455 if (false) {
3456 // XXX we are letting the client link to the service for
3457 // death notifications.
3458 if (app.services.size() > 0) {
3459 Iterator<ServiceRecord> it = app.services.iterator();
3460 while (it.hasNext()) {
3461 ServiceRecord r = it.next();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003462 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3463 ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
3464 for (int i=0; i<cl.size(); i++) {
3465 ConnectionRecord c = cl.get(i);
3466 if (c.binding.client != app) {
3467 try {
3468 //c.conn.connected(r.className, null);
3469 } catch (Exception e) {
3470 // todo: this should be asynchronous!
3471 Slog.w(TAG, "Exception thrown disconnected servce "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003472 + r.shortInstanceName
Dianne Hackborn390517b2013-05-30 15:03:32 -07003473 + " from app " + app.processName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003474 }
3475 }
3476 }
3477 }
3478 }
3479 }
3480 }
3481
louis_chang40e259c2015-03-26 13:31:14 +08003482 // Clean up any connections this application has to other services.
3483 for (int i = app.connections.size() - 1; i >= 0; i--) {
3484 ConnectionRecord r = app.connections.valueAt(i);
3485 removeConnectionLocked(r, app, null);
3486 }
3487 updateServiceConnectionActivitiesLocked(app);
3488 app.connections.clear();
3489
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003490 app.whitelistManager = false;
3491
louis_chang40e259c2015-03-26 13:31:14 +08003492 // Clear app state from services.
3493 for (int i = app.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003494 ServiceRecord sr = app.services.valueAt(i);
3495 synchronized (sr.stats.getBatteryStats()) {
3496 sr.stats.stopLaunchedLocked();
3497 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003498 if (sr.app != app && sr.app != null && !sr.app.isPersistent()) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003499 sr.app.services.remove(sr);
3500 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003501 sr.setProcess(null);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003502 sr.isolatedProc = null;
3503 sr.executeNesting = 0;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003504 sr.forceClearTracker();
3505 if (mDestroyingServices.remove(sr)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003506 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003507 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003508
Dianne Hackbornc8230512013-07-13 21:32:12 -07003509 final int numClients = sr.bindings.size();
3510 for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
3511 IntentBindRecord b = sr.bindings.valueAt(bindingi);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003512 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
Dianne Hackbornc8230512013-07-13 21:32:12 -07003513 + ": shouldUnbind=" + b.hasBound);
3514 b.binder = null;
3515 b.requested = b.received = b.hasBound = false;
Dianne Hackborn465fa392014-09-14 14:21:18 -07003516 // If this binding is coming from a cached process and is asking to keep
3517 // the service created, then we'll kill the cached process as well -- we
3518 // don't want to be thrashing around restarting processes that are only
3519 // there to be cached.
3520 for (int appi=b.apps.size()-1; appi>=0; appi--) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003521 final ProcessRecord proc = b.apps.keyAt(appi);
3522 // If the process is already gone, skip it.
3523 if (proc.killedByAm || proc.thread == null) {
3524 continue;
3525 }
3526 // Only do this for processes that have an auto-create binding;
3527 // otherwise the binding can be left, because it won't cause the
3528 // service to restart.
3529 final AppBindRecord abind = b.apps.valueAt(appi);
3530 boolean hasCreate = false;
3531 for (int conni=abind.connections.size()-1; conni>=0; conni--) {
3532 ConnectionRecord conn = abind.connections.valueAt(conni);
Dianne Hackborn0fe3c252014-09-19 15:09:39 -07003533 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
3534 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003535 hasCreate = true;
3536 break;
3537 }
3538 }
3539 if (!hasCreate) {
3540 continue;
3541 }
Dianne Hackborncd97c962014-09-25 18:34:02 -07003542 // XXX turned off for now until we have more time to get a better policy.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003543 if (false && proc != null && !proc.isPersistent() && proc.thread != null
Dianne Hackborn465fa392014-09-14 14:21:18 -07003544 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
3545 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003546 proc.kill("bound to service " + sr.shortInstanceName
Dianne Hackborn465fa392014-09-14 14:21:18 -07003547 + " in dying proc " + (app != null ? app.processName : "??"), true);
3548 }
3549 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003550 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003551 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003552
Dianne Hackbornad51be92016-08-16 16:27:36 -07003553 ServiceMap smap = getServiceMapLocked(app.userId);
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003554
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003555 // Now do remaining service cleanup.
3556 for (int i=app.services.size()-1; i>=0; i--) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003557 ServiceRecord sr = app.services.valueAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003558
3559 // Unless the process is persistent, this process record is going away,
3560 // so make sure the service is cleaned out of it.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003561 if (!app.isPersistent()) {
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003562 app.services.removeAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003563 }
3564
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003565 // Sanity check: if the service listed for the app is not one
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003566 // we actually are maintaining, just let it drop.
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003567 final ServiceRecord curRec = smap.mServicesByInstanceName.get(sr.instanceName);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003568 if (curRec != sr) {
3569 if (curRec != null) {
3570 Slog.wtf(TAG, "Service " + sr + " in process " + app
3571 + " not same as in map: " + curRec);
3572 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003573 continue;
3574 }
3575
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003576 // Any services running in the application may need to be placed
3577 // back in the pending list.
Amith Yamasanib0c8a882017-08-28 09:36:42 -07003578 if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
3579 && (sr.serviceInfo.applicationInfo.flags
3580 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003581 Slog.w(TAG, "Service crashed " + sr.crashCount
3582 + " times, stopping: " + sr);
3583 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003584 sr.userId, sr.crashCount, sr.shortInstanceName, app.pid);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003585 bringDownServiceLocked(sr);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003586 } else if (!allowRestart
Fyodor Kupolov1b3edac2017-09-19 15:48:06 -07003587 || !mAm.mUserController.isUserRunning(sr.userId, 0)) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003588 bringDownServiceLocked(sr);
3589 } else {
3590 boolean canceled = scheduleServiceRestartLocked(sr, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003591
Dianne Hackbornc8230512013-07-13 21:32:12 -07003592 // Should the service remain running? Note that in the
3593 // extreme case of so many attempts to deliver a command
3594 // that it failed we also will stop it here.
3595 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
3596 if (sr.pendingStarts.size() == 0) {
3597 sr.startRequested = false;
3598 if (sr.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003599 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackbornc8230512013-07-13 21:32:12 -07003600 SystemClock.uptimeMillis());
3601 }
3602 if (!sr.hasAutoCreateConnections()) {
3603 // Whoops, no reason to restart!
3604 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003605 }
3606 }
3607 }
3608 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003609 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003610
Dianne Hackbornc8230512013-07-13 21:32:12 -07003611 if (!allowRestart) {
3612 app.services.clear();
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003613
3614 // Make sure there are no more restarting services for this process.
3615 for (int i=mRestartingServices.size()-1; i>=0; i--) {
3616 ServiceRecord r = mRestartingServices.get(i);
3617 if (r.processName.equals(app.processName) &&
3618 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3619 mRestartingServices.remove(i);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08003620 clearRestartingIfNeededLocked(r);
3621 }
3622 }
3623 for (int i=mPendingServices.size()-1; i>=0; i--) {
3624 ServiceRecord r = mPendingServices.get(i);
3625 if (r.processName.equals(app.processName) &&
3626 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3627 mPendingServices.remove(i);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003628 }
3629 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003630 }
3631
3632 // Make sure we have no more records on the stopping list.
Dianne Hackborn164371f2013-10-01 19:10:13 -07003633 int i = mDestroyingServices.size();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003634 while (i > 0) {
3635 i--;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003636 ServiceRecord sr = mDestroyingServices.get(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003637 if (sr.app == app) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003638 sr.forceClearTracker();
3639 mDestroyingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003640 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003641 }
3642 }
3643
3644 app.executingServices.clear();
3645 }
3646
3647 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
3648 ActivityManager.RunningServiceInfo info =
3649 new ActivityManager.RunningServiceInfo();
3650 info.service = r.name;
3651 if (r.app != null) {
3652 info.pid = r.app.pid;
3653 }
3654 info.uid = r.appInfo.uid;
3655 info.process = r.processName;
3656 info.foreground = r.isForeground;
Yi Jin6b514142017-10-30 14:54:12 -07003657 info.activeSince = r.createRealTime;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003658 info.started = r.startRequested;
3659 info.clientCount = r.connections.size();
3660 info.crashCount = r.crashCount;
3661 info.lastActivityTime = r.lastActivity;
3662 if (r.isForeground) {
3663 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
3664 }
3665 if (r.startRequested) {
3666 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
3667 }
3668 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
3669 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
3670 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003671 if (r.app != null && r.app.isPersistent()) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003672 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
3673 }
3674
Dianne Hackborn390517b2013-05-30 15:03:32 -07003675 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3676 ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003677 for (int i=0; i<connl.size(); i++) {
3678 ConnectionRecord conn = connl.get(i);
3679 if (conn.clientLabel != 0) {
3680 info.clientPackage = conn.binding.client.info.packageName;
3681 info.clientLabel = conn.clientLabel;
3682 return info;
3683 }
3684 }
3685 }
3686 return info;
3687 }
3688
Bryce Lee290e5782017-02-01 16:41:20 -08003689 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags,
Shunta Sato55af6c52016-10-19 15:58:52 +09003690 int callingUid, boolean allowed, boolean canInteractAcrossUsers) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003691 ArrayList<ActivityManager.RunningServiceInfo> res
3692 = new ArrayList<ActivityManager.RunningServiceInfo>();
3693
Dianne Hackborn0c380492012-08-20 17:23:30 -07003694 final long ident = Binder.clearCallingIdentity();
3695 try {
Shunta Sato55af6c52016-10-19 15:58:52 +09003696 if (canInteractAcrossUsers) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003697 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003698 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003699 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003700 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3701 ServiceRecord sr = alls.valueAt(i);
3702 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07003703 }
3704 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003705
Dianne Hackborn0c380492012-08-20 17:23:30 -07003706 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3707 ServiceRecord r = mRestartingServices.get(i);
3708 ActivityManager.RunningServiceInfo info =
3709 makeRunningServiceInfoLocked(r);
3710 info.restarting = r.nextRestartTime;
3711 res.add(info);
3712 }
3713 } else {
Bryce Lee290e5782017-02-01 16:41:20 -08003714 int userId = UserHandle.getUserId(callingUid);
Dianne Hackbornad51be92016-08-16 16:27:36 -07003715 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003716 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3717 ServiceRecord sr = alls.valueAt(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003718
3719 if (allowed || (sr.app != null && sr.app.uid == callingUid)) {
3720 res.add(makeRunningServiceInfoLocked(sr));
3721 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07003722 }
3723
3724 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3725 ServiceRecord r = mRestartingServices.get(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003726 if (r.userId == userId
3727 && (allowed || (r.app != null && r.app.uid == callingUid))) {
Dianne Hackborn0c380492012-08-20 17:23:30 -07003728 ActivityManager.RunningServiceInfo info =
3729 makeRunningServiceInfoLocked(r);
3730 info.restarting = r.nextRestartTime;
3731 res.add(info);
3732 }
3733 }
3734 }
3735 } finally {
3736 Binder.restoreCallingIdentity(ident);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003737 }
3738
3739 return res;
3740 }
3741
3742 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003743 int userId = UserHandle.getUserId(Binder.getCallingUid());
Dianne Hackbornad51be92016-08-16 16:27:36 -07003744 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003745 if (r != null) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003746 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3747 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003748 for (int i=0; i<conn.size(); i++) {
3749 if (conn.get(i).clientIntent != null) {
3750 return conn.get(i).clientIntent;
3751 }
3752 }
3753 }
3754 }
3755 return null;
3756 }
3757
3758 void serviceTimeout(ProcessRecord proc) {
3759 String anrMessage = null;
3760
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003761 synchronized(mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003762 if (proc.executingServices.size() == 0 || proc.thread == null) {
3763 return;
3764 }
Dianne Hackbornab2df062015-01-07 13:43:13 -08003765 final long now = SystemClock.uptimeMillis();
3766 final long maxTime = now -
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003767 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003768 ServiceRecord timeout = null;
3769 long nextTime = 0;
Dianne Hackbornc8230512013-07-13 21:32:12 -07003770 for (int i=proc.executingServices.size()-1; i>=0; i--) {
3771 ServiceRecord sr = proc.executingServices.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003772 if (sr.executingStart < maxTime) {
3773 timeout = sr;
3774 break;
3775 }
3776 if (sr.executingStart > nextTime) {
3777 nextTime = sr.executingStart;
3778 }
3779 }
Amith Yamasani98a00922018-08-21 12:50:30 -04003780 if (timeout != null && mAm.mProcessList.mLruProcesses.contains(proc)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003781 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08003782 StringWriter sw = new StringWriter();
3783 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
3784 pw.println(timeout);
3785 timeout.dump(pw, " ");
3786 pw.close();
3787 mLastAnrDump = sw.toString();
3788 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
3789 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003790 anrMessage = "executing service " + timeout.shortInstanceName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003791 } else {
3792 Message msg = mAm.mHandler.obtainMessage(
3793 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3794 msg.obj = proc;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003795 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
Dianne Hackborn2be00932013-09-22 16:46:00 -07003796 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003797 }
3798 }
3799
3800 if (anrMessage != null) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07003801 proc.appNotResponding(null, null, null, null, false, anrMessage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003802 }
3803 }
3804
Christopher Tate08992ac2017-03-21 11:37:06 -07003805 void serviceForegroundTimeout(ServiceRecord r) {
3806 ProcessRecord app;
3807 synchronized (mAm) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003808 if (!r.fgRequired || r.destroying) {
Christopher Tate08992ac2017-03-21 11:37:06 -07003809 return;
3810 }
3811
Christopher Tate54f51b02018-02-16 11:07:12 -08003812 app = r.app;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07003813 if (app != null && app.isDebugging()) {
Christopher Tate54f51b02018-02-16 11:07:12 -08003814 // The app's being debugged; let it ride
3815 return;
3816 }
3817
Christopher Tate08992ac2017-03-21 11:37:06 -07003818 if (DEBUG_BACKGROUND_CHECK) {
3819 Slog.i(TAG, "Service foreground-required timeout for " + r);
3820 }
Christopher Tate08992ac2017-03-21 11:37:06 -07003821 r.fgWaiting = false;
3822 stopServiceLocked(r);
3823 }
3824
3825 if (app != null) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07003826 app.appNotResponding(null, null, null, null, false,
Kodlee Yin7e951262018-04-05 12:59:56 -07003827 "Context.startForegroundService() did not then call Service.startForeground(): "
3828 + r);
Christopher Tate08992ac2017-03-21 11:37:06 -07003829 }
3830 }
3831
Fyodor Kupolovcc269d92018-05-14 14:20:29 -07003832 public void updateServiceApplicationInfoLocked(ApplicationInfo applicationInfo) {
3833 final int userId = UserHandle.getUserId(applicationInfo.uid);
3834 ServiceMap serviceMap = mServiceMap.get(userId);
3835 if (serviceMap != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003836 ArrayMap<ComponentName, ServiceRecord> servicesByName
3837 = serviceMap.mServicesByInstanceName;
Fyodor Kupolovcc269d92018-05-14 14:20:29 -07003838 for (int j = servicesByName.size() - 1; j >= 0; j--) {
3839 ServiceRecord serviceRecord = servicesByName.valueAt(j);
3840 if (applicationInfo.packageName.equals(serviceRecord.appInfo.packageName)) {
3841 serviceRecord.appInfo = applicationInfo;
3842 serviceRecord.serviceInfo.applicationInfo = applicationInfo;
3843 }
3844 }
3845 }
3846 }
3847
Kodlee Yin7e951262018-04-05 12:59:56 -07003848 void serviceForegroundCrash(ProcessRecord app, CharSequence serviceRecord) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003849 mAm.crashApplication(app.uid, app.pid, app.info.packageName, app.userId,
Kodlee Yin7e951262018-04-05 12:59:56 -07003850 "Context.startForegroundService() did not then call Service.startForeground(): "
3851 + serviceRecord);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003852 }
3853
Dianne Hackborn2be00932013-09-22 16:46:00 -07003854 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
3855 if (proc.executingServices.size() == 0 || proc.thread == null) {
3856 return;
3857 }
Dianne Hackborn2be00932013-09-22 16:46:00 -07003858 Message msg = mAm.mHandler.obtainMessage(
3859 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3860 msg.obj = proc;
Christopher Tate08992ac2017-03-21 11:37:06 -07003861 mAm.mHandler.sendMessageDelayed(msg,
3862 proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
3863 }
3864
3865 void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
3866 if (r.app.executingServices.size() == 0 || r.app.thread == null) {
3867 return;
3868 }
3869 Message msg = mAm.mHandler.obtainMessage(
3870 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG);
3871 msg.obj = r;
3872 r.fgWaiting = true;
3873 mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT);
Dianne Hackborn2be00932013-09-22 16:46:00 -07003874 }
3875
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003876 final class ServiceDumper {
3877 private final FileDescriptor fd;
3878 private final PrintWriter pw;
3879 private final String[] args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003880 private final boolean dumpAll;
3881 private final String dumpPackage;
3882 private final ItemMatcher matcher;
3883 private final ArrayList<ServiceRecord> services = new ArrayList<>();
3884
3885 private final long nowReal = SystemClock.elapsedRealtime();
3886
3887 private boolean needSep = false;
3888 private boolean printedAnything = false;
3889 private boolean printed = false;
3890
3891 /**
3892 * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
3893 * must be called with the lock held).
3894 */
3895 ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
3896 int opti, boolean dumpAll, String dumpPackage) {
3897 this.fd = fd;
3898 this.pw = pw;
3899 this.args = args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003900 this.dumpAll = dumpAll;
3901 this.dumpPackage = dumpPackage;
3902 matcher = new ItemMatcher();
3903 matcher.build(args, opti);
3904
3905 final int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003906 for (int user : users) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003907 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003908 if (smap.mServicesByInstanceName.size() > 0) {
3909 for (int si=0; si<smap.mServicesByInstanceName.size(); si++) {
3910 ServiceRecord r = smap.mServicesByInstanceName.valueAt(si);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003911 if (!matcher.match(r, r.name)) {
3912 continue;
3913 }
3914 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3915 continue;
3916 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003917 services.add(r);
3918 }
3919 }
3920 }
3921 }
3922
3923 private void dumpHeaderLocked() {
3924 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
3925 if (mLastAnrDump != null) {
3926 pw.println(" Last ANR service:");
3927 pw.print(mLastAnrDump);
3928 pw.println();
3929 }
3930 }
3931
3932 void dumpLocked() {
3933 dumpHeaderLocked();
3934
3935 try {
3936 int[] users = mAm.mUserController.getUsers();
3937 for (int user : users) {
3938 // Find the first service for this user.
3939 int serviceIdx = 0;
3940 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3941 serviceIdx++;
3942 }
3943 printed = false;
3944 if (serviceIdx < services.size()) {
3945 needSep = false;
3946 while (serviceIdx < services.size()) {
3947 ServiceRecord r = services.get(serviceIdx);
3948 serviceIdx++;
3949 if (r.userId != user) {
3950 break;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003951 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003952 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003953 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003954 needSep |= printed;
3955 }
3956
3957 dumpUserRemainsLocked(user);
3958 }
3959 } catch (Exception e) {
3960 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3961 }
3962
3963 dumpRemainsLocked();
3964 }
3965
3966 void dumpWithClient() {
3967 synchronized(mAm) {
3968 dumpHeaderLocked();
3969 }
3970
3971 try {
3972 int[] users = mAm.mUserController.getUsers();
3973 for (int user : users) {
3974 // Find the first service for this user.
3975 int serviceIdx = 0;
3976 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3977 serviceIdx++;
3978 }
3979 printed = false;
3980 if (serviceIdx < services.size()) {
3981 needSep = false;
3982 while (serviceIdx < services.size()) {
3983 ServiceRecord r = services.get(serviceIdx);
3984 serviceIdx++;
3985 if (r.userId != user) {
3986 break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003987 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003988 synchronized(mAm) {
3989 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003990 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003991 dumpServiceClient(r);
3992 }
3993 needSep |= printed;
3994 }
3995
3996 synchronized(mAm) {
3997 dumpUserRemainsLocked(user);
3998 }
3999 }
4000 } catch (Exception e) {
4001 Slog.w(TAG, "Exception in dumpServicesLocked", e);
4002 }
4003
4004 synchronized(mAm) {
4005 dumpRemainsLocked();
4006 }
4007 }
4008
4009 private void dumpUserHeaderLocked(int user) {
4010 if (!printed) {
4011 if (printedAnything) {
4012 pw.println();
4013 }
4014 pw.println(" User " + user + " active services:");
4015 printed = true;
4016 }
4017 printedAnything = true;
4018 if (needSep) {
4019 pw.println();
4020 }
4021 }
4022
4023 private void dumpServiceLocalLocked(ServiceRecord r) {
4024 dumpUserHeaderLocked(r.userId);
4025 pw.print(" * ");
4026 pw.println(r);
4027 if (dumpAll) {
4028 r.dump(pw, " ");
4029 needSep = true;
4030 } else {
4031 pw.print(" app=");
4032 pw.println(r.app);
4033 pw.print(" created=");
Yi Jin6b514142017-10-30 14:54:12 -07004034 TimeUtils.formatDuration(r.createRealTime, nowReal, pw);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004035 pw.print(" started=");
4036 pw.print(r.startRequested);
4037 pw.print(" connections=");
4038 pw.println(r.connections.size());
4039 if (r.connections.size() > 0) {
4040 pw.println(" Connections:");
4041 for (int conni=0; conni<r.connections.size(); conni++) {
4042 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
4043 for (int i = 0; i < clist.size(); i++) {
4044 ConnectionRecord conn = clist.get(i);
4045 pw.print(" ");
4046 pw.print(conn.binding.intent.intent.getIntent()
4047 .toShortString(false, false, false, false));
4048 pw.print(" -> ");
4049 ProcessRecord proc = conn.binding.client;
4050 pw.println(proc != null ? proc.toShortString() : "null");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004051 }
4052 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004053 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004054 }
4055 }
4056
4057 private void dumpServiceClient(ServiceRecord r) {
4058 final ProcessRecord proc = r.app;
4059 if (proc == null) {
4060 return;
4061 }
4062 final IApplicationThread thread = proc.thread;
4063 if (thread == null) {
4064 return;
4065 }
4066 pw.println(" Client:");
4067 pw.flush();
4068 try {
4069 TransferPipe tp = new TransferPipe();
4070 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004071 thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004072 tp.setBufferPrefix(" ");
4073 // Short timeout, since blocking here can
4074 // deadlock with the application.
4075 tp.go(fd, 2000);
4076 } finally {
4077 tp.kill();
4078 }
4079 } catch (IOException e) {
4080 pw.println(" Failure while dumping the service: " + e);
4081 } catch (RemoteException e) {
4082 pw.println(" Got a RemoteException while dumping the service");
4083 }
4084 needSep = true;
4085 }
4086
4087 private void dumpUserRemainsLocked(int user) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07004088 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004089 printed = false;
4090 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
4091 ServiceRecord r = smap.mDelayedStartList.get(si);
4092 if (!matcher.match(r, r.name)) {
4093 continue;
4094 }
4095 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4096 continue;
4097 }
4098 if (!printed) {
4099 if (printedAnything) {
4100 pw.println();
4101 }
4102 pw.println(" User " + user + " delayed start services:");
4103 printed = true;
4104 }
4105 printedAnything = true;
4106 pw.print(" * Delayed start "); pw.println(r);
4107 }
4108 printed = false;
4109 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
4110 ServiceRecord r = smap.mStartingBackground.get(si);
4111 if (!matcher.match(r, r.name)) {
4112 continue;
4113 }
4114 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4115 continue;
4116 }
4117 if (!printed) {
4118 if (printedAnything) {
4119 pw.println();
4120 }
4121 pw.println(" User " + user + " starting in background:");
4122 printed = true;
4123 }
4124 printedAnything = true;
4125 pw.print(" * Starting bg "); pw.println(r);
4126 }
4127 }
4128
4129 private void dumpRemainsLocked() {
4130 if (mPendingServices.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004131 printed = false;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004132 for (int i=0; i<mPendingServices.size(); i++) {
4133 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004134 if (!matcher.match(r, r.name)) {
4135 continue;
4136 }
4137 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4138 continue;
4139 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004140 printedAnything = true;
4141 if (!printed) {
4142 if (needSep) pw.println();
4143 needSep = true;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004144 pw.println(" Pending services:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004145 printed = true;
4146 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004147 pw.print(" * Pending "); pw.println(r);
4148 r.dump(pw, " ");
4149 }
4150 needSep = true;
4151 }
4152
4153 if (mRestartingServices.size() > 0) {
4154 printed = false;
4155 for (int i=0; i<mRestartingServices.size(); i++) {
4156 ServiceRecord r = mRestartingServices.get(i);
4157 if (!matcher.match(r, r.name)) {
4158 continue;
4159 }
4160 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4161 continue;
4162 }
4163 printedAnything = true;
4164 if (!printed) {
4165 if (needSep) pw.println();
4166 needSep = true;
4167 pw.println(" Restarting services:");
4168 printed = true;
4169 }
4170 pw.print(" * Restarting "); pw.println(r);
4171 r.dump(pw, " ");
4172 }
4173 needSep = true;
4174 }
4175
4176 if (mDestroyingServices.size() > 0) {
4177 printed = false;
4178 for (int i=0; i< mDestroyingServices.size(); i++) {
4179 ServiceRecord r = mDestroyingServices.get(i);
4180 if (!matcher.match(r, r.name)) {
4181 continue;
4182 }
4183 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4184 continue;
4185 }
4186 printedAnything = true;
4187 if (!printed) {
4188 if (needSep) pw.println();
4189 needSep = true;
4190 pw.println(" Destroying services:");
4191 printed = true;
4192 }
4193 pw.print(" * Destroy "); pw.println(r);
4194 r.dump(pw, " ");
4195 }
4196 needSep = true;
4197 }
4198
4199 if (dumpAll) {
4200 printed = false;
4201 for (int ic=0; ic<mServiceConnections.size(); ic++) {
4202 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
4203 for (int i=0; i<r.size(); i++) {
4204 ConnectionRecord cr = r.get(i);
4205 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
4206 continue;
4207 }
4208 if (dumpPackage != null && (cr.binding.client == null
4209 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
4210 continue;
4211 }
4212 printedAnything = true;
4213 if (!printed) {
4214 if (needSep) pw.println();
4215 needSep = true;
4216 pw.println(" Connection bindings to services:");
4217 printed = true;
4218 }
4219 pw.print(" * "); pw.println(cr);
4220 cr.dump(pw, " ");
4221 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004222 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004223 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004224
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004225 if (matcher.all) {
4226 final long nowElapsed = SystemClock.elapsedRealtime();
4227 final int[] users = mAm.mUserController.getUsers();
4228 for (int user : users) {
4229 boolean printedUser = false;
4230 ServiceMap smap = mServiceMap.get(user);
4231 if (smap == null) {
4232 continue;
4233 }
4234 for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) {
4235 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
4236 if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) {
4237 continue;
4238 }
4239 if (!printedUser) {
4240 printedUser = true;
4241 printedAnything = true;
4242 if (needSep) pw.println();
4243 needSep = true;
4244 pw.print("Active foreground apps - user ");
4245 pw.print(user);
4246 pw.println(":");
4247 }
4248 pw.print(" #");
4249 pw.print(i);
4250 pw.print(": ");
4251 pw.println(aa.mPackageName);
4252 if (aa.mLabel != null) {
4253 pw.print(" mLabel=");
4254 pw.println(aa.mLabel);
4255 }
4256 pw.print(" mNumActive=");
4257 pw.print(aa.mNumActive);
Dianne Hackbornbe68d492017-05-03 18:04:05 -07004258 pw.print(" mAppOnTop=");
4259 pw.print(aa.mAppOnTop);
4260 pw.print(" mShownWhileTop=");
4261 pw.print(aa.mShownWhileTop);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004262 pw.print(" mShownWhileScreenOn=");
4263 pw.println(aa.mShownWhileScreenOn);
4264 pw.print(" mStartTime=");
4265 TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw);
4266 pw.print(" mStartVisibleTime=");
4267 TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw);
4268 pw.println();
4269 if (aa.mEndTime != 0) {
4270 pw.print(" mEndTime=");
4271 TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw);
4272 pw.println();
4273 }
4274 }
Dianne Hackborncb015632017-06-14 17:30:15 -07004275 if (smap.hasMessagesOrCallbacks()) {
4276 if (needSep) {
4277 pw.println();
4278 }
4279 printedAnything = true;
4280 needSep = true;
4281 pw.print(" Handler - user ");
4282 pw.print(user);
4283 pw.println(":");
4284 smap.dumpMine(new PrintWriterPrinter(pw), " ");
4285 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004286 }
4287 }
4288
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004289 if (!printedAnything) {
4290 pw.println(" (nothing)");
4291 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07004292 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004293 }
4294
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004295 ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4296 int opti, boolean dumpAll, String dumpPackage) {
4297 return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
4298 }
4299
Yi Jin2b30f322018-02-20 15:41:47 -08004300 protected void writeToProto(ProtoOutputStream proto, long fieldId) {
Yi Jin6b514142017-10-30 14:54:12 -07004301 synchronized (mAm) {
Yi Jin2b30f322018-02-20 15:41:47 -08004302 final long outterToken = proto.start(fieldId);
Yi Jin6b514142017-10-30 14:54:12 -07004303 int[] users = mAm.mUserController.getUsers();
4304 for (int user : users) {
4305 ServiceMap smap = mServiceMap.get(user);
4306 if (smap == null) {
4307 continue;
4308 }
4309 long token = proto.start(ActiveServicesProto.SERVICES_BY_USERS);
4310 proto.write(ActiveServicesProto.ServicesByUser.USER_ID, user);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004311 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
Yi Jin6b514142017-10-30 14:54:12 -07004312 for (int i=0; i<alls.size(); i++) {
4313 alls.valueAt(i).writeToProto(proto,
4314 ActiveServicesProto.ServicesByUser.SERVICE_RECORDS);
4315 }
4316 proto.end(token);
4317 }
Yi Jin2b30f322018-02-20 15:41:47 -08004318 proto.end(outterToken);
Yi Jin6b514142017-10-30 14:54:12 -07004319 }
4320 }
4321
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004322 /**
4323 * There are three ways to call this:
4324 * - no service specified: dump all the services
4325 * - a flattened component name that matched an existing service was specified as the
4326 * first arg: dump that one service
4327 * - the first arg isn't the flattened component name of an existing service:
4328 * dump all services whose component contains the first arg as a substring
4329 */
Makoto Onuki0b575a32018-04-16 14:33:59 -07004330 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, final String name,
4331 String[] args, int opti, boolean dumpAll) {
4332 final ArrayList<ServiceRecord> services = new ArrayList<>();
4333
4334 final Predicate<ServiceRecord> filter = DumpUtils.filterRecord(name);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004335
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004336 synchronized (mAm) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07004337 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004338
Makoto Onuki0b575a32018-04-16 14:33:59 -07004339 for (int user : users) {
4340 ServiceMap smap = mServiceMap.get(user);
4341 if (smap == null) {
4342 continue;
4343 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004344 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
Makoto Onuki0b575a32018-04-16 14:33:59 -07004345 for (int i=0; i<alls.size(); i++) {
4346 ServiceRecord r1 = alls.valueAt(i);
4347
4348 if (filter.test(r1)) {
4349 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004350 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004351 }
4352 }
4353 }
4354
4355 if (services.size() <= 0) {
4356 return false;
4357 }
4358
Makoto Onuki0b575a32018-04-16 14:33:59 -07004359 // Sort by component name.
4360 services.sort(Comparator.comparing(WithComponentName::getComponentName));
4361
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004362 boolean needSep = false;
4363 for (int i=0; i<services.size(); i++) {
4364 if (needSep) {
4365 pw.println();
4366 }
4367 needSep = true;
4368 dumpService("", fd, pw, services.get(i), args, dumpAll);
4369 }
4370 return true;
4371 }
4372
4373 /**
4374 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
4375 * there is a thread associated with the service.
4376 */
4377 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
4378 final ServiceRecord r, String[] args, boolean dumpAll) {
4379 String innerPrefix = prefix + " ";
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004380 synchronized (mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004381 pw.print(prefix); pw.print("SERVICE ");
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004382 pw.print(r.shortInstanceName); pw.print(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004383 pw.print(Integer.toHexString(System.identityHashCode(r)));
4384 pw.print(" pid=");
4385 if (r.app != null) pw.println(r.app.pid);
4386 else pw.println("(not running)");
4387 if (dumpAll) {
4388 r.dump(pw, innerPrefix);
4389 }
4390 }
4391 if (r.app != null && r.app.thread != null) {
4392 pw.print(prefix); pw.println(" Client:");
4393 pw.flush();
4394 try {
4395 TransferPipe tp = new TransferPipe();
4396 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004397 r.app.thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004398 tp.setBufferPrefix(prefix + " ");
4399 tp.go(fd);
4400 } finally {
4401 tp.kill();
4402 }
4403 } catch (IOException e) {
4404 pw.println(prefix + " Failure while dumping the service: " + e);
4405 } catch (RemoteException e) {
4406 pw.println(prefix + " Got a RemoteException while dumping the service");
4407 }
4408 }
4409 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004410}