blob: 6cbbcddc2b3f5eb55a8511fb34b43474bebf3fce [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
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700134 final ActivityManagerService mAm;
135
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700136 // Maximum number of services that we allow to start in the background
137 // at the same time.
138 final int mMaxStartingBackground;
139
Wale Ogunwale540e1232015-05-01 15:35:39 -0700140 final SparseArray<ServiceMap> mServiceMap = new SparseArray<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700141
142 /**
143 * All currently bound service connections. Keys are the IBinder of
144 * the client's IServiceConnection.
145 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700146 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700147
148 /**
149 * List of services that we have been asked to start,
150 * but haven't yet been able to. It is used to hold start requests
151 * while waiting for their corresponding application thread to get
152 * going.
153 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700154 final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700155
156 /**
157 * List of services that are scheduled to restart following a crash.
158 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700159 final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700160
161 /**
Dianne Hackborn164371f2013-10-01 19:10:13 -0700162 * List of services that are in the process of being destroyed.
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700163 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700164 final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>();
165
166 /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */
167 private ArrayList<ServiceRecord> mTmpCollectionResults = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700168
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700169 /**
170 * For keeping ActiveForegroundApps retaining state while the screen is off.
171 */
172 boolean mScreenOn = true;
173
Dianne Hackborncff1bbf2015-01-20 13:43:32 -0800174 /** Amount of time to allow a last ANR message to exist before freeing the memory. */
175 static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
176
177 String mLastAnrDump;
178
179 final Runnable mLastAnrDumpClearer = new Runnable() {
180 @Override public void run() {
181 synchronized (mAm) {
182 mLastAnrDump = null;
183 }
184 }
185 };
186
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700187 /**
Christopher Tatec7933ac2018-03-12 17:57:09 -0700188 * Watch for apps being put into forced app standby, so we can step their fg
189 * services down.
190 */
191 class ForcedStandbyListener extends AppStateTracker.Listener {
192 @Override
193 public void stopForegroundServicesForUidPackage(final int uid, final String packageName) {
194 synchronized (mAm) {
Christopher Tate0d9a81c2019-09-20 17:30:12 -0700195 stopAllForegroundServicesLocked(uid, packageName);
196 }
197 }
198 }
Christopher Tatec7933ac2018-03-12 17:57:09 -0700199
Christopher Tate0d9a81c2019-09-20 17:30:12 -0700200 void stopAllForegroundServicesLocked(final int uid, final String packageName) {
201 final ServiceMap smap = getServiceMapLocked(UserHandle.getUserId(uid));
202 final int N = smap.mServicesByInstanceName.size();
203 final ArrayList<ServiceRecord> toStop = new ArrayList<>(N);
204 for (int i = 0; i < N; i++) {
205 final ServiceRecord r = smap.mServicesByInstanceName.valueAt(i);
206 if (uid == r.serviceInfo.applicationInfo.uid
207 || packageName.equals(r.serviceInfo.packageName)) {
208 if (r.isForeground) {
209 toStop.add(r);
Christopher Tatec7933ac2018-03-12 17:57:09 -0700210 }
211 }
212 }
Christopher Tate0d9a81c2019-09-20 17:30:12 -0700213
214 // Now stop them all
215 final int numToStop = toStop.size();
216 if (numToStop > 0 && DEBUG_FOREGROUND_SERVICE) {
217 Slog.i(TAG, "Package " + packageName + "/" + uid
218 + " in FAS with foreground services");
219 }
220 for (int i = 0; i < numToStop; i++) {
221 final ServiceRecord r = toStop.get(i);
222 if (DEBUG_FOREGROUND_SERVICE) {
223 Slog.i(TAG, " Stopping fg for service " + r);
224 }
225 setServiceForegroundInnerLocked(r, 0, null, 0, 0);
226 }
Christopher Tatec7933ac2018-03-12 17:57:09 -0700227 }
228
229 /**
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700230 * Information about an app that is currently running one or more foreground services.
Dan Sandler2f36ab82017-05-25 00:15:49 -0400231 * (This maps directly to the running apps we show in the notification.)
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700232 */
233 static final class ActiveForegroundApp {
234 String mPackageName;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700235 int mUid;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700236 CharSequence mLabel;
237 boolean mShownWhileScreenOn;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700238 boolean mAppOnTop;
239 boolean mShownWhileTop;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700240 long mStartTime;
241 long mStartVisibleTime;
242 long mEndTime;
243 int mNumActive;
Dianne Hackborncb015632017-06-14 17:30:15 -0700244
245 // Temp output of foregroundAppShownEnoughLocked
246 long mHideTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700247 }
248
249 /**
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700250 * Information about services for a single user.
251 */
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700252 final class ServiceMap extends Handler {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700253 final int mUserId;
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800254 final ArrayMap<ComponentName, ServiceRecord> mServicesByInstanceName = new ArrayMap<>();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700255 final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700256
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700257 final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700258 /* XXX eventually I'd like to have this based on processes instead of services.
259 * That is, if we try to start two services in a row both running in the same
260 * process, this should be one entry in mStartingBackground for that one process
261 * that remains until all services in it are done.
262 final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
263 = new ArrayMap<ProcessRecord, DelayingProcess>();
264 final ArrayList<DelayingProcess> mStartingProcessList
265 = new ArrayList<DelayingProcess>();
266 */
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700267
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700268 final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700269
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700270 final ArrayMap<String, ActiveForegroundApp> mActiveForegroundApps = new ArrayMap<>();
271 boolean mActiveForegroundAppsChanged;
272
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700273 static final int MSG_BG_START_TIMEOUT = 1;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700274 static final int MSG_UPDATE_FOREGROUND_APPS = 2;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700275
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700276 ServiceMap(Looper looper, int userId) {
277 super(looper);
Dianne Hackborn6285a322013-09-18 12:09:47 -0700278 mUserId = userId;
279 }
280
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700281 @Override
282 public void handleMessage(Message msg) {
283 switch (msg.what) {
284 case MSG_BG_START_TIMEOUT: {
285 synchronized (mAm) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700286 rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700287 }
288 } break;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700289 case MSG_UPDATE_FOREGROUND_APPS: {
290 updateForegroundApps(this);
291 } break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700292 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700293 }
294
Dianne Hackbornad51be92016-08-16 16:27:36 -0700295 void ensureNotStartingBackgroundLocked(ServiceRecord r) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700296 if (mStartingBackground.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800297 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
298 "No longer background starting: " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -0700299 rescheduleDelayedStartsLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700300 }
Dianne Hackborn2e46bb52013-09-13 17:01:26 -0700301 if (mDelayedStartList.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800302 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700303 }
304 }
305
Dianne Hackbornad51be92016-08-16 16:27:36 -0700306 void rescheduleDelayedStartsLocked() {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700307 removeMessages(MSG_BG_START_TIMEOUT);
308 final long now = SystemClock.uptimeMillis();
309 for (int i=0, N=mStartingBackground.size(); i<N; i++) {
310 ServiceRecord r = mStartingBackground.get(i);
311 if (r.startingBgTimeout <= now) {
312 Slog.i(TAG, "Waited long enough for: " + r);
313 mStartingBackground.remove(i);
314 N--;
Junu Kimfcb87362014-02-19 16:25:21 +0900315 i--;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700316 }
317 }
318 while (mDelayedStartList.size() > 0
319 && mStartingBackground.size() < mMaxStartingBackground) {
320 ServiceRecord r = mDelayedStartList.remove(0);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800321 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
322 "REM FR DELAY LIST (exec next): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700323 if (DEBUG_DELAYED_SERVICE) {
324 if (mDelayedStartList.size() > 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800325 Slog.v(TAG_SERVICE, "Remaining delayed list:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700326 for (int i=0; i<mDelayedStartList.size(); i++) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800327 Slog.v(TAG_SERVICE, " #" + i + ": " + mDelayedStartList.get(i));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700328 }
329 }
330 }
331 r.delayed = false;
Christopher Tate752bc2a2019-02-15 16:48:22 -0800332 if (r.pendingStarts.size() <= 0) {
333 Slog.wtf(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
334 + " delayedStop=" + r.delayedStop);
335 } else {
336 try {
Michal Karpinskie069b002019-03-07 16:15:14 +0000337 startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false,
338 true);
Christopher Tate752bc2a2019-02-15 16:48:22 -0800339 } catch (TransactionTooLargeException e) {
340 // Ignore, nobody upstack cares.
341 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700342 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700343 }
344 if (mStartingBackground.size() > 0) {
345 ServiceRecord next = mStartingBackground.get(0);
346 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800347 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700348 + ", can delay others up to " + when);
349 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
350 sendMessageAtTime(msg, when);
351 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700352 if (mStartingBackground.size() < mMaxStartingBackground) {
353 mAm.backgroundServicesFinishedLocked(mUserId);
354 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700355 }
356 }
357
358 public ActiveServices(ActivityManagerService service) {
359 mAm = service;
Dianne Hackborn23037412013-11-04 18:11:29 -0800360 int maxBg = 0;
361 try {
362 maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
363 } catch(RuntimeException e) {
364 }
Dianne Hackborn20d94742014-05-29 18:35:45 -0700365 mMaxStartingBackground = maxBg > 0
366 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700367 }
368
Christopher Tatec7933ac2018-03-12 17:57:09 -0700369 void systemServicesReady() {
370 AppStateTracker ast = LocalServices.getService(AppStateTracker.class);
371 ast.addListener(new ForcedStandbyListener());
372 }
373
Dianne Hackbornad51be92016-08-16 16:27:36 -0700374 ServiceRecord getServiceByNameLocked(ComponentName name, int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700375 // TODO: Deal with global services
376 if (DEBUG_MU)
Dianne Hackbornad51be92016-08-16 16:27:36 -0700377 Slog.v(TAG_MU, "getServiceByNameLocked(" + name + "), callingUser = " + callingUser);
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800378 return getServiceMapLocked(callingUser).mServicesByInstanceName.get(name);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700379 }
380
Dianne Hackbornad51be92016-08-16 16:27:36 -0700381 boolean hasBackgroundServicesLocked(int callingUser) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700382 ServiceMap smap = mServiceMap.get(callingUser);
383 return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
384 }
385
Dianne Hackbornad51be92016-08-16 16:27:36 -0700386 private ServiceMap getServiceMapLocked(int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700387 ServiceMap smap = mServiceMap.get(callingUser);
388 if (smap == null) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700389 smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700390 mServiceMap.put(callingUser, smap);
391 }
392 return smap;
393 }
394
Dianne Hackbornad51be92016-08-16 16:27:36 -0700395 ArrayMap<ComponentName, ServiceRecord> getServicesLocked(int callingUser) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800396 return getServiceMapLocked(callingUser).mServicesByInstanceName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700397 }
398
Christopher Tatec7933ac2018-03-12 17:57:09 -0700399 private boolean appRestrictedAnyInBackground(final int uid, final String packageName) {
400 final int mode = mAm.mAppOpsService.checkOperation(
401 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, uid, packageName);
402 return (mode != AppOpsManager.MODE_ALLOWED);
403 }
404
Svet Ganov99b60432015-06-27 13:15:22 -0700405 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
Christopher Tate242ba3e92017-04-14 15:07:06 -0700406 int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700407 throws TransactionTooLargeException {
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000408 return startServiceLocked(caller, service, resolvedType, callingPid, callingUid, fgRequired,
409 callingPackage, userId, false);
410 }
411
412 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
413 int callingPid, int callingUid, boolean fgRequired, String callingPackage,
414 final int userId, boolean allowBackgroundActivityStarts)
415 throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800416 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700417 + " type=" + resolvedType + " args=" + service.getExtras());
418
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700419 final boolean callerFg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700420 if (caller != null) {
421 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
422 if (callerApp == null) {
423 throw new SecurityException(
424 "Unable to find app for caller " + caller
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700425 + " (pid=" + callingPid
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700426 + ") when starting service " + service);
427 }
Dianne Hackborna49ad092016-03-03 13:39:10 -0800428 callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700429 } else {
430 callerFg = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700431 }
432
433 ServiceLookupResult res =
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800434 retrieveServiceLocked(service, null, resolvedType, callingPackage,
Svet Ganovd223db32017-12-22 09:43:48 -0800435 callingPid, callingUid, userId, true, callerFg, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700436 if (res == null) {
437 return null;
438 }
439 if (res.record == null) {
440 return new ComponentName("!", res.permission != null
441 ? res.permission : "private to package");
442 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700443
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700444 ServiceRecord r = res.record;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700445
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700446 if (!mAm.mUserController.exists(r.userId)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700447 Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700448 return null;
449 }
450
Christopher Tate85048282018-03-30 14:08:59 -0700451 // If we're starting indirectly (e.g. from PendingIntent), figure out whether
Christopher Tate45f06c792018-04-25 10:47:23 -0700452 // we're launching into an app in a background state. This keys off of the same
453 // idleness state tracking as e.g. O+ background service start policy.
454 final boolean bgLaunch = !mAm.isUidActiveLocked(r.appInfo.uid);
Christopher Tate85048282018-03-30 14:08:59 -0700455
456 // If the app has strict background restrictions, we treat any bg service
457 // start analogously to the legacy-app forced-restrictions case, regardless
458 // of its target SDK version.
Christopher Tatec7933ac2018-03-12 17:57:09 -0700459 boolean forcedStandby = false;
Christopher Tate85048282018-03-30 14:08:59 -0700460 if (bgLaunch && appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
Christopher Tatec7933ac2018-03-12 17:57:09 -0700461 if (DEBUG_FOREGROUND_SERVICE) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800462 Slog.d(TAG, "Forcing bg-only service start only for " + r.shortInstanceName
Christopher Tate85048282018-03-30 14:08:59 -0700463 + " : bgLaunch=" + bgLaunch + " callerFg=" + callerFg);
Christopher Tatec7933ac2018-03-12 17:57:09 -0700464 }
465 forcedStandby = true;
466 }
467
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700468 // If this is a direct-to-foreground start, make sure it is allowed as per the app op.
469 boolean forceSilentAbort = false;
470 if (fgRequired) {
471 final int mode = mAm.mAppOpsService.checkOperation(
472 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
473 switch (mode) {
474 case AppOpsManager.MODE_ALLOWED:
475 case AppOpsManager.MODE_DEFAULT:
476 // All okay.
477 break;
478 case AppOpsManager.MODE_IGNORED:
479 // Not allowed, fall back to normal start service, failing siliently
480 // if background check restricts that.
481 Slog.w(TAG, "startForegroundService not allowed due to app op: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800482 + service + " to " + r.shortInstanceName
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700483 + " from pid=" + callingPid + " uid=" + callingUid
484 + " pkg=" + callingPackage);
485 fgRequired = false;
486 forceSilentAbort = true;
487 break;
488 default:
489 return new ComponentName("!!", "foreground not allowed as per app op");
490 }
491 }
492
Christopher Tate08992ac2017-03-21 11:37:06 -0700493 // If this isn't a direct-to-foreground start, check our ability to kick off an
494 // arbitrary service
Christopher Tatec7933ac2018-03-12 17:57:09 -0700495 if (forcedStandby || (!r.startRequested && !fgRequired)) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700496 // Before going further -- if this app is not allowed to start services in the
497 // background, then at this point we aren't going to let it period.
498 final int allowed = mAm.getAppStartModeLocked(r.appInfo.uid, r.packageName,
Christopher Tatec7933ac2018-03-12 17:57:09 -0700499 r.appInfo.targetSdkVersion, callingPid, false, false, forcedStandby);
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700500 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
501 Slog.w(TAG, "Background start not allowed: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800502 + service + " to " + r.shortInstanceName
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700503 + " from pid=" + callingPid + " uid=" + callingUid
Christopher Tatee84ffd92018-05-16 12:59:43 -0700504 + " pkg=" + callingPackage + " startFg?=" + fgRequired);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700505 if (allowed == ActivityManager.APP_START_MODE_DELAYED || forceSilentAbort) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700506 // In this case we are silently disabling the app, to disrupt as
507 // little as possible existing apps.
508 return null;
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700509 }
Christopher Tatee84ffd92018-05-16 12:59:43 -0700510 if (forcedStandby) {
511 // This is an O+ app, but we might be here because the user has placed
512 // it under strict background restrictions. Don't punish the app if it's
513 // trying to do the right thing but we're denying it for that reason.
514 if (fgRequired) {
515 if (DEBUG_BACKGROUND_CHECK) {
516 Slog.v(TAG, "Silently dropping foreground service launch due to FAS");
517 }
518 return null;
519 }
520 }
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700521 // This app knows it is in the new model where this operation is not
522 // allowed, so tell it what has happened.
Amith Yamasaniaa746442019-01-10 10:09:12 -0800523 UidRecord uidRec = mAm.mProcessList.getUidRecordLocked(r.appInfo.uid);
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700524 return new ComponentName("?", "app is in background uid " + uidRec);
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700525 }
526 }
527
Christopher Tate0a826902018-05-25 15:15:44 -0700528 // At this point we've applied allowed-to-start policy based on whether this was
529 // an ordinary startService() or a startForegroundService(). Now, only require that
530 // the app follow through on the startForegroundService() -> startForeground()
531 // contract if it actually targets O+.
532 if (r.appInfo.targetSdkVersion < Build.VERSION_CODES.O && fgRequired) {
533 if (DEBUG_BACKGROUND_CHECK || DEBUG_FOREGROUND_SERVICE) {
534 Slog.i(TAG, "startForegroundService() but host targets "
535 + r.appInfo.targetSdkVersion + " - not requiring startForeground()");
536 }
537 fgRequired = false;
538 }
539
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700540 NeededUriGrants neededGrants = mAm.mUgmInternal.checkGrantUriPermissionFromIntent(
Nicolas Prevotc6cf95c2014-05-29 11:30:36 +0100541 callingUid, r.packageName, service, service.getFlags(), null, r.userId);
Svet Ganov9c165d72015-12-01 19:52:26 -0800542
543 // If permissions need a review before any of the app components can run,
544 // we do not start the service and launch a review activity if the calling app
545 // is in the foreground passing it a pending intent to start the service when
546 // review is completed.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700547
548 // XXX This is not dealing with fgRequired!
549 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage,
550 callingUid, service, callerFg, userId)) {
551 return null;
Svet Ganov9c165d72015-12-01 19:52:26 -0800552 }
553
Dianne Hackbornd6f5b622013-11-11 17:25:37 -0800554 if (unscheduleServiceRestartLocked(r, callingUid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800555 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700556 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700557 r.lastActivity = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700558 r.startRequested = true;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700559 r.delayedStop = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700560 r.fgRequired = fgRequired;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700561 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -0700562 service, neededGrants, callingUid));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700563
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700564 if (fgRequired) {
565 // We are now effectively running a foreground service.
Dianne Hackborn2aec55a2018-06-26 10:35:35 -0700566 ServiceState stracker = r.getTracker();
567 if (stracker != null) {
568 stracker.setForeground(true, mAm.mProcessStats.getMemFactorLocked(),
569 r.lastActivity);
570 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700571 mAm.mAppOpsService.startOperation(AppOpsManager.getToken(mAm.mAppOpsService),
572 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, true);
573 }
574
Dianne Hackbornad51be92016-08-16 16:27:36 -0700575 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700576 boolean addToStarting = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700577 if (!callerFg && !fgRequired && r.app == null
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700578 && mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700579 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700580 if (proc == null || proc.getCurProcState() > ActivityManager.PROCESS_STATE_RECEIVER) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700581 // If this is not coming from a foreground caller, then we may want
582 // to delay the start if there are already other background services
583 // that are starting. This is to avoid process start spam when lots
584 // of applications are all handling things like connectivity broadcasts.
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700585 // We only do this for cached processes, because otherwise an application
586 // can have assumptions about calling startService() for a service to run
587 // in its own process, and for that process to not be killed before the
588 // service is started. This is especially the case for receivers, which
589 // may start a service in onReceive() to do some additional work and have
590 // initialized some global state as part of that.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800591 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
592 + r + " in " + proc);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700593 if (r.delayed) {
594 // This service is already scheduled for a delayed start; just leave
595 // it still waiting.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800596 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700597 return r.name;
598 }
599 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
600 // Something else is starting, delay!
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800601 Slog.i(TAG_SERVICE, "Delaying start of: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700602 smap.mDelayedStartList.add(r);
603 r.delayed = true;
604 return r.name;
605 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800606 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700607 addToStarting = true;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700608 } else if (proc.getCurProcState() >= ActivityManager.PROCESS_STATE_SERVICE) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700609 // We slightly loosen when we will enqueue this new service as a background
610 // starting service we are waiting for, to also include processes that are
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700611 // currently running other services or receivers.
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700612 addToStarting = true;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800613 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
614 "Not delaying, but counting as bg: " + r);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800615 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn8e692572013-09-10 19:06:15 -0700616 StringBuilder sb = new StringBuilder(128);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700617 sb.append("Not potential delay (state=").append(proc.getCurProcState())
Dianne Hackborn8e692572013-09-10 19:06:15 -0700618 .append(' ').append(proc.adjType);
619 String reason = proc.makeAdjReason();
620 if (reason != null) {
621 sb.append(' ');
622 sb.append(reason);
623 }
624 sb.append("): ");
625 sb.append(r.toString());
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800626 Slog.v(TAG_SERVICE, sb.toString());
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700627 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800628 } else if (DEBUG_DELAYED_STARTS) {
Christopher Tate08992ac2017-03-21 11:37:06 -0700629 if (callerFg || fgRequired) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800630 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
Christopher Tate08992ac2017-03-21 11:37:06 -0700631 + callingUid + " pid=" + callingPid + " fgRequired=" + fgRequired + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700632 } else if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800633 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700634 } else {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800635 Slog.v(TAG_SERVICE,
636 "Not potential delay (user " + r.userId + " not started): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700637 }
638 }
639
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000640 if (allowBackgroundActivityStarts) {
Alan Stokesb8137aa2019-04-30 11:42:20 +0100641 r.whitelistBgActivityStartsOnServiceStart();
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000642 }
Michal Karpinskie069b002019-03-07 16:15:14 +0000643
644 ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
Christopher Tate42a386b2016-11-07 12:21:21 -0800645 return cmp;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700646 }
647
Svet Ganov9c165d72015-12-01 19:52:26 -0800648 private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
649 String callingPackage, int callingUid, Intent service, boolean callerFg,
650 final int userId) {
651 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
652 r.packageName, r.userId)) {
653
654 // Show a permission review UI only for starting from a foreground app
655 if (!callerFg) {
656 Slog.w(TAG, "u" + r.userId + " Starting a service in package"
657 + r.packageName + " requires a permissions review");
658 return false;
659 }
660
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700661 IIntentSender target = mAm.mPendingIntentController.getIntentSender(
Svet Ganov9c165d72015-12-01 19:52:26 -0800662 ActivityManager.INTENT_SENDER_SERVICE, callingPackage,
663 callingUid, userId, null, null, 0, new Intent[]{service},
664 new String[]{service.resolveType(mAm.mContext.getContentResolver())},
665 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
666 | PendingIntent.FLAG_IMMUTABLE, null);
667
668 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
669 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
Philip P. Moltmann751e46ca2019-01-24 13:56:47 -0800670 | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
Svet Ganov9c165d72015-12-01 19:52:26 -0800671 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
672 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
673 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
674
675 if (DEBUG_PERMISSIONS_REVIEW) {
676 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
677 + r.packageName);
678 }
679
680 mAm.mHandler.post(new Runnable() {
681 @Override
682 public void run() {
683 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
684 }
685 });
686
687 return false;
688 }
689
690 return true;
691 }
692
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700693 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
Michal Karpinskie069b002019-03-07 16:15:14 +0000694 boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
Joe Onorato4eb64fd2016-03-21 15:30:09 -0700695 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700696 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700697 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700698 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700699 r.callStart = false;
Chenjie Yu75b3c492018-10-06 21:45:19 -0700700 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid, r.name.getPackageName(),
701 r.name.getClassName(), StatsLog.SERVICE_STATE_CHANGED__STATE__START);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700702 synchronized (r.stats.getBatteryStats()) {
703 r.stats.startRunningLocked();
704 }
Michal Karpinskie069b002019-03-07 16:15:14 +0000705 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700706 if (error != null) {
707 return new ComponentName("!!", error);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700708 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700709
710 if (r.startRequested && addToStarting) {
711 boolean first = smap.mStartingBackground.size() == 0;
712 smap.mStartingBackground.add(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700713 r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700714 if (DEBUG_DELAYED_SERVICE) {
715 RuntimeException here = new RuntimeException("here");
716 here.fillInStackTrace();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800717 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800718 } else if (DEBUG_DELAYED_STARTS) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800719 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700720 }
721 if (first) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700722 smap.rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700723 }
Christopher Tate08992ac2017-03-21 11:37:06 -0700724 } else if (callerFg || r.fgRequired) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700725 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700726 }
727
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700728 return r.name;
729 }
730
731 private void stopServiceLocked(ServiceRecord service) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700732 if (service.delayed) {
Mohammad Samiul Islame896c212019-01-10 12:14:23 +0000733 // If service isn't actually running, but is being held in the
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700734 // delayed list, then we need to keep it started but note that it
735 // should be stopped once no longer delayed.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800736 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700737 service.delayedStop = true;
738 return;
739 }
Chenjie Yu75b3c492018-10-06 21:45:19 -0700740 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, service.appInfo.uid,
741 service.name.getPackageName(), service.name.getClassName(),
742 StatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700743 synchronized (service.stats.getBatteryStats()) {
744 service.stats.stopRunningLocked();
745 }
746 service.startRequested = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700747 if (service.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700748 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700749 SystemClock.uptimeMillis());
750 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700751 service.callStart = false;
Michal Karpinskie069b002019-03-07 16:15:14 +0000752
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700753 bringDownServiceIfNeededLocked(service, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700754 }
755
756 int stopServiceLocked(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700757 String resolvedType, int userId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800758 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700759 + " type=" + resolvedType);
760
761 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
762 if (caller != null && callerApp == null) {
763 throw new SecurityException(
764 "Unable to find app for caller " + caller
765 + " (pid=" + Binder.getCallingPid()
766 + ") when stopping service " + service);
767 }
768
769 // If this service is active, make sure it is stopped.
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800770 ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, null,
Svet Ganovd223db32017-12-22 09:43:48 -0800771 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700772 if (r != null) {
773 if (r.record != null) {
774 final long origId = Binder.clearCallingIdentity();
775 try {
776 stopServiceLocked(r.record);
777 } finally {
778 Binder.restoreCallingIdentity(origId);
779 }
780 return 1;
781 }
782 return -1;
783 }
784
785 return 0;
786 }
787
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700788 void stopInBackgroundLocked(int uid) {
789 // Stop all services associated with this uid due to it going to the background
790 // stopped state.
791 ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
792 ArrayList<ServiceRecord> stopping = null;
793 if (services != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800794 for (int i = services.mServicesByInstanceName.size() - 1; i >= 0; i--) {
795 ServiceRecord service = services.mServicesByInstanceName.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700796 if (service.appInfo.uid == uid && service.startRequested) {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800797 if (mAm.getAppStartModeLocked(service.appInfo.uid, service.packageName,
Christopher Tatec7933ac2018-03-12 17:57:09 -0700798 service.appInfo.targetSdkVersion, -1, false, false, false)
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800799 != ActivityManager.APP_START_MODE_NORMAL) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700800 if (stopping == null) {
801 stopping = new ArrayList<>();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700802 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800803 String compName = service.shortInstanceName;
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700804 EventLogTags.writeAmStopIdleService(service.appInfo.uid, compName);
805 StringBuilder sb = new StringBuilder(64);
806 sb.append("Stopping service due to app idle: ");
807 UserHandle.formatUid(sb, service.appInfo.uid);
808 sb.append(" ");
Yi Jin6b514142017-10-30 14:54:12 -0700809 TimeUtils.formatDuration(service.createRealTime
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700810 - SystemClock.elapsedRealtime(), sb);
811 sb.append(" ");
812 sb.append(compName);
813 Slog.w(TAG, sb.toString());
814 stopping.add(service);
Christopher Tate6aab6232019-04-23 11:13:35 -0700815
816 // If the app is under bg restrictions, also make sure that
817 // any notification is dismissed
818 if (appRestrictedAnyInBackground(
819 service.appInfo.uid, service.packageName)) {
820 cancelForegroundNotificationLocked(service);
821 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700822 }
823 }
824 }
825 if (stopping != null) {
826 for (int i=stopping.size()-1; i>=0; i--) {
827 ServiceRecord service = stopping.get(i);
828 service.delayed = false;
Dianne Hackbornad51be92016-08-16 16:27:36 -0700829 services.ensureNotStartingBackgroundLocked(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700830 stopServiceLocked(service);
831 }
832 }
833 }
834 }
835
Svet Ganov99b60432015-06-27 13:15:22 -0700836 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800837 ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, callingPackage,
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -0700838 Binder.getCallingPid(), Binder.getCallingUid(),
Svet Ganovd223db32017-12-22 09:43:48 -0800839 UserHandle.getCallingUserId(), false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700840
841 IBinder ret = null;
842 if (r != null) {
843 // r.record is null if findServiceLocked() failed the caller permission check
844 if (r.record == null) {
845 throw new SecurityException(
Christopher Desjardins5862c5f2015-05-19 11:25:40 +0000846 "Permission Denial: Accessing service"
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700847 + " from pid=" + Binder.getCallingPid()
848 + ", uid=" + Binder.getCallingUid()
849 + " requires " + r.permission);
850 }
851 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
852 if (ib != null) {
853 ret = ib.binder;
854 }
855 }
856
857 return ret;
858 }
859
860 boolean stopServiceTokenLocked(ComponentName className, IBinder token,
861 int startId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800862 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700863 + " " + token + " startId=" + startId);
Dianne Hackborn41203752012-08-31 14:05:51 -0700864 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700865 if (r != null) {
866 if (startId >= 0) {
867 // Asked to only stop if done with all work. Note that
868 // to avoid leaks, we will take this as dropping all
869 // start items up to and including this one.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -0700870 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700871 if (si != null) {
872 while (r.deliveredStarts.size() > 0) {
873 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
874 cur.removeUriPermissionsLocked();
875 if (cur == si) {
876 break;
877 }
878 }
879 }
880
881 if (r.getLastStartId() != startId) {
882 return false;
883 }
884
885 if (r.deliveredStarts.size() > 0) {
886 Slog.w(TAG, "stopServiceToken startId " + startId
887 + " is last, but have " + r.deliveredStarts.size()
888 + " remaining args");
889 }
890 }
891
Chenjie Yu75b3c492018-10-06 21:45:19 -0700892 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid, r.name.getPackageName(),
893 r.name.getClassName(), StatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700894 synchronized (r.stats.getBatteryStats()) {
895 r.stats.stopRunningLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700896 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700897 r.startRequested = false;
898 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700899 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700900 SystemClock.uptimeMillis());
901 }
902 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700903 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700904 bringDownServiceIfNeededLocked(r, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700905 Binder.restoreCallingIdentity(origId);
906 return true;
907 }
908 return false;
909 }
910
Sudheer Shankac9d94072017-02-22 22:13:55 +0000911 public void setServiceForegroundLocked(ComponentName className, IBinder token,
Hui Yu2d4207f2019-01-22 15:32:20 -0800912 int id, Notification notification, int flags, int foregroundServiceType) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700913 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700914 final long origId = Binder.clearCallingIdentity();
915 try {
Dianne Hackborn41203752012-08-31 14:05:51 -0700916 ServiceRecord r = findServiceLocked(className, token, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700917 if (r != null) {
Hui Yu2d4207f2019-01-22 15:32:20 -0800918 setServiceForegroundInnerLocked(r, id, notification, flags, foregroundServiceType);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700919 }
920 } finally {
921 Binder.restoreCallingIdentity(origId);
922 }
923 }
924
Hui Yufb72b992019-02-20 10:04:07 -0800925 /**
926 * Return the current foregroundServiceType of the ServiceRecord.
927 * @param className ComponentName of the Service class.
928 * @param token IBinder token.
929 * @return current foreground service type.
930 */
931 public int getForegroundServiceTypeLocked(ComponentName className, IBinder token) {
932 final int userId = UserHandle.getCallingUserId();
933 final long origId = Binder.clearCallingIdentity();
934 int ret = ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE;
935 try {
936 ServiceRecord r = findServiceLocked(className, token, userId);
937 if (r != null) {
938 ret = r.foregroundServiceType;
939 }
940 } finally {
941 Binder.restoreCallingIdentity(origId);
942 }
943 return ret;
944 }
945
Dianne Hackborncb015632017-06-14 17:30:15 -0700946 boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) {
947 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid="
948 + aa.mUid);
949 boolean canRemove = false;
950 aa.mHideTime = Long.MAX_VALUE;
951 if (aa.mShownWhileTop) {
952 // If the app was ever at the top of the screen while the foreground
953 // service was running, then we can always just immediately remove it.
954 canRemove = true;
955 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown while on top");
956 } else if (mScreenOn || aa.mShownWhileScreenOn) {
957 final long minTime = aa.mStartVisibleTime
958 + (aa.mStartTime != aa.mStartVisibleTime
959 ? mAm.mConstants.FGSERVICE_SCREEN_ON_AFTER_TIME
960 : mAm.mConstants.FGSERVICE_MIN_SHOWN_TIME);
961 if (nowElapsed >= minTime) {
962 // If shown while the screen is on, and it has been shown for
963 // at least the minimum show time, then we can now remove it.
964 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown long enough with screen on");
965 canRemove = true;
966 } else {
967 // This is when we will be okay to stop telling the user.
968 long reportTime = nowElapsed + mAm.mConstants.FGSERVICE_MIN_REPORT_TIME;
969 aa.mHideTime = reportTime > minTime ? reportTime : minTime;
970 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
971 + " with screen on");
972 }
973 } else {
974 final long minTime = aa.mEndTime
975 + mAm.mConstants.FGSERVICE_SCREEN_ON_BEFORE_TIME;
976 if (nowElapsed >= minTime) {
977 // If the foreground service has only run while the screen is
978 // off, but it has been gone now for long enough that we won't
979 // care to tell the user about it when the screen comes back on,
980 // then we can remove it now.
981 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - gone long enough with screen off");
982 canRemove = true;
983 } else {
984 // This is when we won't care about this old fg service.
985 aa.mHideTime = minTime;
986 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
987 + " with screen off");
988 }
989 }
990 return canRemove;
991 }
992
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700993 void updateForegroundApps(ServiceMap smap) {
994 // This is called from the handler without the lock held.
995 ArrayList<ActiveForegroundApp> active = null;
996 synchronized (mAm) {
997 final long now = SystemClock.elapsedRealtime();
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700998 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700999 if (smap != null) {
Dianne Hackborncb015632017-06-14 17:30:15 -07001000 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Updating foreground apps for user "
1001 + smap.mUserId);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001002 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
1003 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -07001004 if (aa.mEndTime != 0) {
1005 boolean canRemove = foregroundAppShownEnoughLocked(aa, now);
1006 if (canRemove) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001007 // This was up for longer than the timeout, so just remove immediately.
1008 smap.mActiveForegroundApps.removeAt(i);
1009 smap.mActiveForegroundAppsChanged = true;
1010 continue;
1011 }
Dianne Hackborncb015632017-06-14 17:30:15 -07001012 if (aa.mHideTime < nextUpdateTime) {
1013 nextUpdateTime = aa.mHideTime;
1014 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001015 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001016 if (!aa.mAppOnTop) {
Christopher Tate0d9a81c2019-09-20 17:30:12 -07001017 // Transitioning a fg-service host app out of top: if it's bg restricted,
1018 // it loses the fg service state now.
1019 if (!appRestrictedAnyInBackground(aa.mUid, aa.mPackageName)) {
1020 if (active == null) {
1021 active = new ArrayList<>();
1022 }
1023 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
1024 + aa.mPackageName + ", uid=" + aa.mUid);
1025 active.add(aa);
1026 } else {
1027 if (DEBUG_FOREGROUND_SERVICE) {
1028 Slog.d(TAG, "bg-restricted app "
1029 + aa.mPackageName + "/" + aa.mUid
1030 + " exiting top; demoting fg services ");
1031 }
1032 stopAllForegroundServicesLocked(aa.mUid, aa.mPackageName);
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001033 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001034 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001035 }
1036 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
1037 if (nextUpdateTime < Long.MAX_VALUE) {
Dianne Hackborncb015632017-06-14 17:30:15 -07001038 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Next update time in: "
1039 + (nextUpdateTime-now));
1040 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001041 smap.sendMessageAtTime(msg, nextUpdateTime
1042 + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001043 }
1044 }
1045 if (!smap.mActiveForegroundAppsChanged) {
1046 return;
1047 }
1048 smap.mActiveForegroundAppsChanged = false;
1049 }
1050
Dianne Hackborn070d1422018-05-02 13:48:30 -07001051 if (!SHOW_DUNGEON_NOTIFICATION) {
1052 return;
1053 }
1054
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001055 final NotificationManager nm = (NotificationManager) mAm.mContext.getSystemService(
1056 Context.NOTIFICATION_SERVICE);
1057 final Context context = mAm.mContext;
1058
1059 if (active != null) {
1060 for (int i = 0; i < active.size(); i++) {
1061 ActiveForegroundApp aa = active.get(i);
1062 if (aa.mLabel == null) {
1063 PackageManager pm = context.getPackageManager();
1064 try {
1065 ApplicationInfo ai = pm.getApplicationInfoAsUser(aa.mPackageName,
1066 PackageManager.MATCH_KNOWN_PACKAGES, smap.mUserId);
1067 aa.mLabel = ai.loadLabel(pm);
1068 } catch (PackageManager.NameNotFoundException e) {
1069 aa.mLabel = aa.mPackageName;
1070 }
1071 }
1072 }
1073
1074 Intent intent;
1075 String title;
1076 String msg;
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001077 String[] pkgs;
Dan Sandler886e0162017-06-06 14:23:43 -04001078 final long nowElapsed = SystemClock.elapsedRealtime();
1079 long oldestStartTime = nowElapsed;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001080 if (active.size() == 1) {
1081 intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
1082 intent.setData(Uri.fromParts("package", active.get(0).mPackageName, null));
1083 title = context.getString(
1084 R.string.foreground_service_app_in_background, active.get(0).mLabel);
1085 msg = context.getString(R.string.foreground_service_tap_for_details);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001086 pkgs = new String[] { active.get(0).mPackageName };
Dan Sandler2f36ab82017-05-25 00:15:49 -04001087 oldestStartTime = active.get(0).mStartTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001088 } else {
1089 intent = new Intent(Settings.ACTION_FOREGROUND_SERVICES_SETTINGS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001090 pkgs = new String[active.size()];
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001091 for (int i = 0; i < active.size(); i++) {
1092 pkgs[i] = active.get(i).mPackageName;
Dan Sandler2f36ab82017-05-25 00:15:49 -04001093 oldestStartTime = Math.min(oldestStartTime, active.get(i).mStartTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001094 }
1095 intent.putExtra("packages", pkgs);
1096 title = context.getString(
1097 R.string.foreground_service_apps_in_background, active.size());
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001098 msg = active.get(0).mLabel.toString();
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001099 for (int i = 1; i < active.size(); i++) {
1100 msg = context.getString(R.string.foreground_service_multiple_separator,
1101 msg, active.get(i).mLabel);
1102 }
1103 }
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001104 Bundle notificationBundle = new Bundle();
1105 notificationBundle.putStringArray(Notification.EXTRA_FOREGROUND_APPS, pkgs);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001106 Notification.Builder n =
1107 new Notification.Builder(context,
1108 SystemNotificationChannels.FOREGROUND_SERVICE)
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001109 .addExtras(notificationBundle)
Dan Sandler2f36ab82017-05-25 00:15:49 -04001110 .setSmallIcon(R.drawable.stat_sys_vitals)
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001111 .setOngoing(true)
Dan Sandler886e0162017-06-06 14:23:43 -04001112 .setShowWhen(oldestStartTime < nowElapsed)
1113 .setWhen(System.currentTimeMillis() - (nowElapsed - oldestStartTime))
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001114 .setColor(context.getColor(
1115 com.android.internal.R.color.system_notification_accent_color))
1116 .setContentTitle(title)
1117 .setContentText(msg)
1118 .setContentIntent(
1119 PendingIntent.getActivityAsUser(context, 0, intent,
1120 PendingIntent.FLAG_UPDATE_CURRENT,
1121 null, new UserHandle(smap.mUserId)));
1122 nm.notifyAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1123 n.build(), new UserHandle(smap.mUserId));
1124 } else {
1125 nm.cancelAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1126 new UserHandle(smap.mUserId));
1127 }
1128 }
1129
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001130 private void requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001131 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001132 if (timeElapsed != 0) {
1133 smap.sendMessageAtTime(msg,
1134 timeElapsed + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001135 } else {
1136 smap.mActiveForegroundAppsChanged = true;
1137 smap.sendMessage(msg);
1138 }
1139 }
1140
1141 private void decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r) {
1142 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1143 if (active != null) {
1144 active.mNumActive--;
1145 if (active.mNumActive <= 0) {
1146 active.mEndTime = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001147 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Ended running of service");
1148 if (foregroundAppShownEnoughLocked(active, active.mEndTime)) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001149 // Have been active for long enough that we will remove it immediately.
1150 smap.mActiveForegroundApps.remove(r.packageName);
1151 smap.mActiveForegroundAppsChanged = true;
1152 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001153 } else if (active.mHideTime < Long.MAX_VALUE){
1154 requestUpdateActiveForegroundAppsLocked(smap, active.mHideTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001155 }
1156 }
1157 }
1158 }
1159
1160 void updateScreenStateLocked(boolean screenOn) {
1161 if (mScreenOn != screenOn) {
1162 mScreenOn = screenOn;
1163
1164 // If screen is turning on, then we now reset the start time of any foreground
1165 // services that were started while the screen was off.
1166 if (screenOn) {
1167 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001168 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Screen turned on");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001169 for (int i = mServiceMap.size()-1; i >= 0; i--) {
1170 ServiceMap smap = mServiceMap.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -07001171 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001172 boolean changed = false;
1173 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1174 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
Dianne Hackborncb015632017-06-14 17:30:15 -07001175 if (active.mEndTime == 0) {
1176 if (!active.mShownWhileScreenOn) {
1177 active.mShownWhileScreenOn = true;
1178 active.mStartVisibleTime = nowElapsed;
1179 }
1180 } else {
1181 if (!active.mShownWhileScreenOn
1182 && active.mStartVisibleTime == active.mStartTime) {
1183 // If this was never shown while the screen was on, then we will
1184 // count the time it started being visible as now, to tell the user
1185 // about it now that they have a screen to look at.
1186 active.mEndTime = active.mStartVisibleTime = nowElapsed;
1187 }
1188 if (foregroundAppShownEnoughLocked(active, nowElapsed)) {
1189 // Have been active for long enough that we will remove it
1190 // immediately.
1191 smap.mActiveForegroundApps.remove(active.mPackageName);
1192 smap.mActiveForegroundAppsChanged = true;
1193 changed = true;
1194 } else {
1195 if (active.mHideTime < nextUpdateTime) {
1196 nextUpdateTime = active.mHideTime;
1197 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001198 }
1199 }
1200 }
1201 if (changed) {
Dianne Hackborncb015632017-06-14 17:30:15 -07001202 // Need to immediately update.
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001203 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001204 } else if (nextUpdateTime < Long.MAX_VALUE) {
1205 requestUpdateActiveForegroundAppsLocked(smap, nextUpdateTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001206 }
1207 }
1208 }
1209 }
1210 }
1211
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001212 void foregroundServiceProcStateChangedLocked(UidRecord uidRec) {
1213 ServiceMap smap = mServiceMap.get(UserHandle.getUserId(uidRec.uid));
1214 if (smap != null) {
1215 boolean changed = false;
1216 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1217 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
1218 if (active.mUid == uidRec.uid) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07001219 if (uidRec.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001220 if (!active.mAppOnTop) {
1221 active.mAppOnTop = true;
1222 changed = true;
1223 }
1224 active.mShownWhileTop = true;
1225 } else if (active.mAppOnTop) {
1226 active.mAppOnTop = false;
1227 changed = true;
1228 }
1229 }
1230 }
1231 if (changed) {
1232 requestUpdateActiveForegroundAppsLocked(smap, 0);
1233 }
1234 }
1235 }
1236
Christopher Tate6aab6232019-04-23 11:13:35 -07001237 private boolean appIsTopLocked(int uid) {
1238 return mAm.getUidState(uid) <= ActivityManager.PROCESS_STATE_TOP;
1239 }
1240
Christopher Tatec7933ac2018-03-12 17:57:09 -07001241 /**
1242 * @param id Notification ID. Zero === exit foreground state for the given service.
1243 */
1244 private void setServiceForegroundInnerLocked(final ServiceRecord r, int id,
Hui Yu2d4207f2019-01-22 15:32:20 -08001245 Notification notification, int flags, int foregroundServiceType) {
Christopher Tate42a386b2016-11-07 12:21:21 -08001246 if (id != 0) {
1247 if (notification == null) {
1248 throw new IllegalArgumentException("null notification");
1249 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001250 // Instant apps need permission to create foreground services.
1251 if (r.appInfo.isInstantApp()) {
1252 final int mode = mAm.mAppOpsService.checkOperation(
1253 AppOpsManager.OP_INSTANT_APP_START_FOREGROUND,
1254 r.appInfo.uid,
1255 r.appInfo.packageName);
1256 switch (mode) {
1257 case AppOpsManager.MODE_ALLOWED:
1258 break;
1259 case AppOpsManager.MODE_IGNORED:
1260 Slog.w(TAG, "Instant app " + r.appInfo.packageName
1261 + " does not have permission to create foreground services"
1262 + ", ignoring.");
Sudheer Shankac9d94072017-02-22 22:13:55 +00001263 return;
Chad Brubaker97b383f2017-02-02 15:04:35 -08001264 case AppOpsManager.MODE_ERRORED:
1265 throw new SecurityException("Instant app " + r.appInfo.packageName
1266 + " does not have permission to create foreground services");
1267 default:
Dianne Hackborndd027b32018-01-19 17:44:46 -08001268 mAm.enforcePermission(
1269 android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
1270 r.app.pid, r.appInfo.uid, "startForeground");
Chad Brubaker97b383f2017-02-02 15:04:35 -08001271 }
Hui Yu1ea85522018-12-06 16:59:18 -08001272 } else {
1273 if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
1274 mAm.enforcePermission(
1275 android.Manifest.permission.FOREGROUND_SERVICE,
1276 r.app.pid, r.appInfo.uid, "startForeground");
1277 }
Hui Yu2d4207f2019-01-22 15:32:20 -08001278
1279 int manifestType = r.serviceInfo.getForegroundServiceType();
1280 // If passed in foreground service type is FOREGROUND_SERVICE_TYPE_MANIFEST,
1281 // consider it is the same as manifest foreground service type.
1282 if (foregroundServiceType == FOREGROUND_SERVICE_TYPE_MANIFEST) {
1283 foregroundServiceType = manifestType;
1284 }
1285 // Check the passed in foreground service type flags is a subset of manifest
1286 // foreground service type flags.
1287 if ((foregroundServiceType & manifestType) != foregroundServiceType) {
Hui Yufb72b992019-02-20 10:04:07 -08001288 throw new IllegalArgumentException("foregroundServiceType "
1289 + String.format("0x%08X", foregroundServiceType)
1290 + " is not a subset of foregroundServiceType attribute "
1291 + String.format("0x%08X", manifestType)
1292 + " in service element of manifest file");
Hui Yu1ea85522018-12-06 16:59:18 -08001293 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001294 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001295 boolean alreadyStartedOp = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001296 boolean stopProcStatsOp = false;
Christopher Tate08992ac2017-03-21 11:37:06 -07001297 if (r.fgRequired) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001298 if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001299 Slog.i(TAG, "Service called startForeground() as required: " + r);
1300 }
1301 r.fgRequired = false;
1302 r.fgWaiting = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001303 alreadyStartedOp = stopProcStatsOp = true;
Christopher Tate08992ac2017-03-21 11:37:06 -07001304 mAm.mHandler.removeMessages(
1305 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
1306 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001307
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001308 try {
1309 boolean ignoreForeground = false;
1310 final int mode = mAm.mAppOpsService.checkOperation(
1311 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
1312 switch (mode) {
1313 case AppOpsManager.MODE_ALLOWED:
1314 case AppOpsManager.MODE_DEFAULT:
1315 // All okay.
1316 break;
1317 case AppOpsManager.MODE_IGNORED:
1318 // Whoops, silently ignore this.
1319 Slog.w(TAG, "Service.startForeground() not allowed due to app op: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001320 + r.shortInstanceName);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001321 ignoreForeground = true;
1322 break;
1323 default:
1324 throw new SecurityException("Foreground not allowed as per app op");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001325 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001326
Christopher Tate6aab6232019-04-23 11:13:35 -07001327 // Apps that are TOP or effectively similar may call startForeground() on
1328 // their services even if they are restricted from doing that while in bg.
1329 if (!ignoreForeground
1330 && !appIsTopLocked(r.appInfo.uid)
1331 && appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001332 Slog.w(TAG,
1333 "Service.startForeground() not allowed due to bg restriction: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001334 + r.shortInstanceName);
Christopher Tate45f06c792018-04-25 10:47:23 -07001335 // Back off of any foreground expectations around this service, since we've
1336 // just turned down its fg request.
1337 updateServiceForegroundLocked(r.app, false);
1338 ignoreForeground = true;
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001339 }
1340
1341 // Apps under strict background restrictions simply don't get to have foreground
1342 // services, so now that we've enforced the startForegroundService() contract
1343 // we only do the machinery of making the service foreground when the app
1344 // is not restricted.
1345 if (!ignoreForeground) {
1346 if (r.foregroundId != id) {
1347 cancelForegroundNotificationLocked(r);
1348 r.foregroundId = id;
Christopher Tatec7933ac2018-03-12 17:57:09 -07001349 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001350 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
1351 r.foregroundNoti = notification;
Hui Yu2d4207f2019-01-22 15:32:20 -08001352 r.foregroundServiceType = foregroundServiceType;
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001353 if (!r.isForeground) {
1354 final ServiceMap smap = getServiceMapLocked(r.userId);
1355 if (smap != null) {
Amith Yamasanif235d0b2019-03-20 22:49:43 -07001356 ActiveForegroundApp active = smap.mActiveForegroundApps
1357 .get(r.packageName);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001358 if (active == null) {
1359 active = new ActiveForegroundApp();
1360 active.mPackageName = r.packageName;
1361 active.mUid = r.appInfo.uid;
1362 active.mShownWhileScreenOn = mScreenOn;
1363 if (r.app != null) {
1364 active.mAppOnTop = active.mShownWhileTop =
Wale Ogunwalebff2df42018-10-18 17:09:19 -07001365 r.app.uidRecord.getCurProcState()
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001366 <= ActivityManager.PROCESS_STATE_TOP;
1367 }
1368 active.mStartTime = active.mStartVisibleTime
1369 = SystemClock.elapsedRealtime();
1370 smap.mActiveForegroundApps.put(r.packageName, active);
1371 requestUpdateActiveForegroundAppsLocked(smap, 0);
1372 }
1373 active.mNumActive++;
1374 }
1375 r.isForeground = true;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001376 if (!stopProcStatsOp) {
1377 ServiceState stracker = r.getTracker();
1378 if (stracker != null) {
1379 stracker.setForeground(true,
1380 mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
1381 }
1382 } else {
1383 stopProcStatsOp = false;
1384 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001385 mAm.mAppOpsService.startOperation(
1386 AppOpsManager.getToken(mAm.mAppOpsService),
1387 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName,
1388 true);
1389 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001390 r.appInfo.uid, r.shortInstanceName,
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001391 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER);
Hui Yue361a232018-10-04 15:05:21 -07001392 mAm.updateForegroundServiceUsageStats(r.name, r.userId, true);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001393 }
1394 r.postNotification();
1395 if (r.app != null) {
1396 updateServiceForegroundLocked(r.app, true);
1397 }
1398 getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
1399 mAm.notifyPackageUse(r.serviceInfo.packageName,
1400 PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
1401 } else {
1402 if (DEBUG_FOREGROUND_SERVICE) {
1403 Slog.d(TAG, "Suppressing startForeground() for FAS " + r);
1404 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001405 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001406 } finally {
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001407 if (stopProcStatsOp) {
1408 // We got through to this point with it actively being started foreground,
1409 // and never decided we wanted to keep it like that, so drop it.
1410 ServiceState stracker = r.getTracker();
1411 if (stracker != null) {
1412 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1413 r.lastActivity);
1414 }
1415 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001416 if (alreadyStartedOp) {
1417 // If we had previously done a start op for direct foreground start,
1418 // we have cleared the flag so can now drop it.
1419 mAm.mAppOpsService.finishOperation(
1420 AppOpsManager.getToken(mAm.mAppOpsService),
1421 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001422 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001423 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001424 } else {
1425 if (r.isForeground) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001426 final ServiceMap smap = getServiceMapLocked(r.userId);
1427 if (smap != null) {
1428 decActiveForegroundAppLocked(smap, r);
1429 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001430 r.isForeground = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001431 ServiceState stracker = r.getTracker();
1432 if (stracker != null) {
1433 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1434 r.lastActivity);
1435 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001436 mAm.mAppOpsService.finishOperation(
1437 AppOpsManager.getToken(mAm.mAppOpsService),
1438 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001439 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001440 r.appInfo.uid, r.shortInstanceName,
Chenjie Yuccfe6452018-01-30 11:33:21 -08001441 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Hui Yue361a232018-10-04 15:05:21 -07001442 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
Christopher Tate42a386b2016-11-07 12:21:21 -08001443 if (r.app != null) {
1444 mAm.updateLruProcessLocked(r.app, false, null);
1445 updateServiceForegroundLocked(r.app, true);
1446 }
1447 }
1448 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001449 cancelForegroundNotificationLocked(r);
Christopher Tate42a386b2016-11-07 12:21:21 -08001450 r.foregroundId = 0;
1451 r.foregroundNoti = null;
1452 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1453 r.stripForegroundServiceFlagFromNotification();
1454 if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
1455 r.foregroundId = 0;
1456 r.foregroundNoti = null;
1457 }
1458 }
1459 }
1460 }
1461
Christopher Tate08992ac2017-03-21 11:37:06 -07001462 private void cancelForegroundNotificationLocked(ServiceRecord r) {
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001463 if (r.foregroundId != 0) {
1464 // First check to see if this app has any other active foreground services
1465 // with the same notification ID. If so, we shouldn't actually cancel it,
1466 // because that would wipe away the notification that still needs to be shown
1467 // due the other service.
Dianne Hackbornad51be92016-08-16 16:27:36 -07001468 ServiceMap sm = getServiceMapLocked(r.userId);
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001469 if (sm != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001470 for (int i = sm.mServicesByInstanceName.size() - 1; i >= 0; i--) {
1471 ServiceRecord other = sm.mServicesByInstanceName.valueAt(i);
Dianne Hackborn569a4582016-08-04 14:00:22 -07001472 if (other != r && other.foregroundId == r.foregroundId
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001473 && other.packageName.equals(r.packageName)) {
1474 // Found one! Abort the cancel.
1475 return;
1476 }
1477 }
1478 }
1479 r.cancelNotification();
1480 }
1481 }
1482
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001483 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
1484 boolean anyForeground = false;
Amith Yamasania0a30a12019-01-22 11:38:06 -08001485 int fgServiceTypes = 0;
1486 for (int i = proc.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07001487 ServiceRecord sr = proc.services.valueAt(i);
Christopher Tatee23fa2b2017-04-20 14:48:13 -07001488 if (sr.isForeground || sr.fgRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001489 anyForeground = true;
Hui Yu2d4207f2019-01-22 15:32:20 -08001490 fgServiceTypes |= sr.foregroundServiceType;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001491 }
1492 }
Amith Yamasania0a30a12019-01-22 11:38:06 -08001493 mAm.updateProcessForegroundLocked(proc, anyForeground, fgServiceTypes, oomAdj);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001494 }
1495
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001496 private void updateWhitelistManagerLocked(ProcessRecord proc) {
1497 proc.whitelistManager = false;
1498 for (int i=proc.services.size()-1; i>=0; i--) {
1499 ServiceRecord sr = proc.services.valueAt(i);
1500 if (sr.whitelistManager) {
1501 proc.whitelistManager = true;
1502 break;
1503 }
1504 }
1505 }
1506
Dianne Hackborn465fa392014-09-14 14:21:18 -07001507 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
1508 ArraySet<ProcessRecord> updatedProcesses = null;
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001509 for (int i = 0; i < clientProc.connections.size(); i++) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001510 final ConnectionRecord conn = clientProc.connections.valueAt(i);
1511 final ProcessRecord proc = conn.binding.service.app;
1512 if (proc == null || proc == clientProc) {
1513 continue;
1514 } else if (updatedProcesses == null) {
1515 updatedProcesses = new ArraySet<>();
1516 } else if (updatedProcesses.contains(proc)) {
1517 continue;
1518 }
1519 updatedProcesses.add(proc);
1520 updateServiceClientActivitiesLocked(proc, null, false);
1521 }
1522 }
1523
Dianne Hackborndb926082013-10-31 16:32:44 -07001524 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
Dianne Hackborn465fa392014-09-14 14:21:18 -07001525 ConnectionRecord modCr, boolean updateLru) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001526 if (modCr != null && modCr.binding.client != null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001527 if (!modCr.binding.client.hasActivities()) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001528 // This connection is from a client without activities, so adding
1529 // and removing is not interesting.
1530 return false;
1531 }
1532 }
1533
1534 boolean anyClientActivities = false;
1535 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
1536 ServiceRecord sr = proc.services.valueAt(i);
Michal Karpinskib7daac22019-03-25 10:12:41 +00001537 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = sr.getConnections();
1538 for (int conni = connections.size() - 1; conni >= 0 && !anyClientActivities; conni--) {
1539 ArrayList<ConnectionRecord> clist = connections.valueAt(conni);
Dianne Hackborndb926082013-10-31 16:32:44 -07001540 for (int cri=clist.size()-1; cri>=0; cri--) {
1541 ConnectionRecord cr = clist.get(cri);
1542 if (cr.binding.client == null || cr.binding.client == proc) {
1543 // Binding to ourself is not interesting.
1544 continue;
1545 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001546 if (cr.binding.client.hasActivities()) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001547 anyClientActivities = true;
1548 break;
1549 }
1550 }
1551 }
1552 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001553 if (anyClientActivities != proc.hasClientActivities()) {
1554 proc.setHasClientActivities(anyClientActivities);
Dianne Hackborn465fa392014-09-14 14:21:18 -07001555 if (updateLru) {
1556 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
1557 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001558 return true;
1559 }
1560 return false;
1561 }
1562
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001563 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
Svet Ganov9c165d72015-12-01 19:52:26 -08001564 String resolvedType, final IServiceConnection connection, int flags,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001565 String instanceName, String callingPackage, final int userId)
1566 throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001567 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001568 + " type=" + resolvedType + " conn=" + connection.asBinder()
1569 + " flags=0x" + Integer.toHexString(flags));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001570 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
1571 if (callerApp == null) {
1572 throw new SecurityException(
1573 "Unable to find app for caller " + caller
1574 + " (pid=" + Binder.getCallingPid()
1575 + ") when binding service " + service);
1576 }
1577
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001578 ActivityServiceConnectionsHolder<ConnectionRecord> activity = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001579 if (token != null) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001580 activity = mAm.mAtmInternal.getServiceConnectionsHolder(token);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001581 if (activity == null) {
1582 Slog.w(TAG, "Binding with unknown activity: " + token);
1583 return 0;
1584 }
1585 }
1586
1587 int clientLabel = 0;
1588 PendingIntent clientIntent = null;
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001589 final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001590
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001591 if (isCallerSystem) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001592 // Hacky kind of thing -- allow system stuff to tell us
1593 // what they are, so we can report this elsewhere for
1594 // others to know why certain services are running.
Jeff Sharkeyf0ec2e02016-03-21 12:37:54 -06001595 service.setDefusable(true);
1596 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001597 if (clientIntent != null) {
1598 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
1599 if (clientLabel != 0) {
1600 // There are no useful extras in the intent, trash them.
1601 // System code calling with this stuff just needs to know
1602 // this will happen.
1603 service = service.cloneFilter();
1604 }
1605 }
1606 }
1607
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001608 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1609 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
1610 "BIND_TREAT_LIKE_ACTIVITY");
1611 }
1612
Yohei Yukawa59730962019-03-18 10:47:22 -07001613 if ((flags & Context.BIND_SCHEDULE_LIKE_TOP_APP) != 0 && !isCallerSystem) {
1614 throw new SecurityException("Non-system caller (pid=" + Binder.getCallingPid()
1615 + ") set BIND_SCHEDULE_LIKE_TOP_APP when binding service " + service);
1616 }
1617
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001618 if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
1619 throw new SecurityException(
1620 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1621 + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
1622 }
1623
Svet Ganovd223db32017-12-22 09:43:48 -08001624 if ((flags & Context.BIND_ALLOW_INSTANT) != 0 && !isCallerSystem) {
1625 throw new SecurityException(
1626 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1627 + ") set BIND_ALLOW_INSTANT when binding service " + service);
1628 }
1629
Michal Karpinskie069b002019-03-07 16:15:14 +00001630 if ((flags & Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS) != 0) {
1631 mAm.enforceCallingPermission(
1632 android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND,
1633 "BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS");
1634 }
1635
Dianne Hackborna49ad092016-03-03 13:39:10 -08001636 final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Robert Sesekb9a86662015-12-09 16:22:45 -05001637 final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
Svet Ganovd223db32017-12-22 09:43:48 -08001638 final boolean allowInstant = (flags & Context.BIND_ALLOW_INSTANT) != 0;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001639
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001640 ServiceLookupResult res =
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001641 retrieveServiceLocked(service, instanceName, resolvedType, callingPackage,
1642 Binder.getCallingPid(), Binder.getCallingUid(), userId, true,
1643 callerFg, isBindExternal, allowInstant);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001644 if (res == null) {
1645 return 0;
1646 }
1647 if (res.record == null) {
1648 return -1;
1649 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001650 ServiceRecord s = res.record;
1651
Svet Ganov9c165d72015-12-01 19:52:26 -08001652 boolean permissionsReviewRequired = false;
1653
1654 // If permissions need a review before any of the app components can run,
1655 // we schedule binding to the service but do not start its process, then
1656 // we launch a review activity to which is passed a callback to invoke
1657 // when done to start the bound service's process to completing the binding.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001658 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
1659 s.packageName, s.userId)) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001660
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001661 permissionsReviewRequired = true;
Svet Ganov9c165d72015-12-01 19:52:26 -08001662
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001663 // Show a permission review UI only for binding from a foreground app
1664 if (!callerFg) {
1665 Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
1666 + s.packageName + " requires a permissions review");
1667 return 0;
1668 }
Svet Ganov9c165d72015-12-01 19:52:26 -08001669
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001670 final ServiceRecord serviceRecord = s;
1671 final Intent serviceIntent = service;
Svet Ganov9c165d72015-12-01 19:52:26 -08001672
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001673 RemoteCallback callback = new RemoteCallback(
1674 new RemoteCallback.OnResultListener() {
1675 @Override
1676 public void onResult(Bundle result) {
1677 synchronized(mAm) {
1678 final long identity = Binder.clearCallingIdentity();
1679 try {
1680 if (!mPendingServices.contains(serviceRecord)) {
1681 return;
Svet Ganov9c165d72015-12-01 19:52:26 -08001682 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001683 // If there is still a pending record, then the service
1684 // binding request is still valid, so hook them up. We
1685 // proceed only if the caller cleared the review requirement
1686 // otherwise we unbind because the user didn't approve.
1687 if (!mAm.getPackageManagerInternalLocked()
1688 .isPermissionsReviewRequired(
1689 serviceRecord.packageName,
1690 serviceRecord.userId)) {
1691 try {
1692 bringUpServiceLocked(serviceRecord,
1693 serviceIntent.getFlags(),
Michal Karpinskie069b002019-03-07 16:15:14 +00001694 callerFg, false, false);
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001695 } catch (RemoteException e) {
1696 /* ignore - local call */
1697 }
1698 } else {
1699 unbindServiceLocked(connection);
1700 }
1701 } finally {
1702 Binder.restoreCallingIdentity(identity);
Svet Ganov9c165d72015-12-01 19:52:26 -08001703 }
1704 }
Svet Ganov9c165d72015-12-01 19:52:26 -08001705 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001706 });
Svet Ganov9c165d72015-12-01 19:52:26 -08001707
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001708 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
1709 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
Philip P. Moltmann751e46ca2019-01-24 13:56:47 -08001710 | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001711 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1712 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
1713 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
1714
1715 if (DEBUG_PERMISSIONS_REVIEW) {
1716 Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
1717 + s.packageName);
Svet Ganov9c165d72015-12-01 19:52:26 -08001718 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001719
1720 mAm.mHandler.post(new Runnable() {
1721 @Override
1722 public void run() {
1723 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
1724 }
1725 });
Svet Ganov9c165d72015-12-01 19:52:26 -08001726 }
1727
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001728 final long origId = Binder.clearCallingIdentity();
1729
1730 try {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001731 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001732 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001733 + s);
1734 }
1735
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001736 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1737 s.lastActivity = SystemClock.uptimeMillis();
1738 if (!s.hasAutoCreateConnections()) {
1739 // This is the first binding, let the tracker know.
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001740 ServiceState stracker = s.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001741 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001742 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001743 s.lastActivity);
1744 }
1745 }
1746 }
1747
Dianne Hackbornc390aa82019-01-09 16:38:22 -08001748 if ((flags & Context.BIND_RESTRICT_ASSOCIATIONS) != 0) {
1749 mAm.requireAllowedAssociationsLocked(s.appInfo.packageName);
1750 }
1751
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001752 mAm.startAssociationLocked(callerApp.uid, callerApp.processName,
1753 callerApp.getCurProcState(), s.appInfo.uid, s.appInfo.longVersionCode,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001754 s.instanceName, s.processName);
Jesse Evans02af3ea2017-05-03 09:57:16 -07001755 // Once the apps have become associated, if one of them is caller is ephemeral
1756 // the target app should now be able to see the calling app
1757 mAm.grantEphemeralAccessLocked(callerApp.userId, service,
Hai Zhangbb23d532018-08-27 16:00:35 -07001758 UserHandle.getAppId(s.appInfo.uid), UserHandle.getAppId(callerApp.uid));
Dianne Hackbornab2df062015-01-07 13:43:13 -08001759
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001760 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
1761 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001762 connection, flags, clientLabel, clientIntent,
Dianne Hackborn24bbe582018-12-17 11:58:31 -08001763 callerApp.uid, callerApp.processName, callingPackage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001764
1765 IBinder binder = connection.asBinder();
Alan Stokes8473a2c2019-04-29 13:51:18 +01001766 s.addConnection(binder, c);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001767 b.connections.add(c);
1768 if (activity != null) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001769 activity.addConnection(c);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001770 }
1771 b.client.connections.add(c);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001772 c.startAssociationIfNeeded();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001773 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
1774 b.client.hasAboveClient = true;
1775 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001776 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
1777 s.whitelistManager = true;
1778 }
Michal Karpinskie069b002019-03-07 16:15:14 +00001779 if ((flags & Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS) != 0) {
1780 s.setHasBindingWhitelistingBgActivityStarts(true);
1781 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001782 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001783 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07001784 }
Alan Stokes8473a2c2019-04-29 13:51:18 +01001785 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001786 if (clist == null) {
Alan Stokes8473a2c2019-04-29 13:51:18 +01001787 clist = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001788 mServiceConnections.put(binder, clist);
1789 }
1790 clist.add(c);
1791
1792 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1793 s.lastActivity = SystemClock.uptimeMillis();
Svet Ganov9c165d72015-12-01 19:52:26 -08001794 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
Michal Karpinskie069b002019-03-07 16:15:14 +00001795 permissionsReviewRequired) != null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001796 return 0;
1797 }
1798 }
1799
1800 if (s.app != null) {
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001801 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1802 s.app.treatLikeActivity = true;
1803 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001804 if (s.whitelistManager) {
1805 s.app.whitelistManager = true;
1806 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001807 // This could have made the service more important.
Dianne Hackborna631d562018-11-20 15:58:15 -08001808 mAm.updateLruProcessLocked(s.app,
1809 (callerApp.hasActivitiesOrRecentTasks() && s.app.hasClientActivities())
1810 || (callerApp.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP
1811 && (flags & Context.BIND_TREAT_LIKE_ACTIVITY) != 0),
1812 b.client);
Amith Yamasanid2775cd2019-04-12 15:47:54 -07001813 mAm.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_BIND_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001814 }
1815
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001816 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001817 + ": received=" + b.intent.received
1818 + " apps=" + b.intent.apps.size()
1819 + " doRebind=" + b.intent.doRebind);
1820
1821 if (s.app != null && b.intent.received) {
1822 // Service is already running, so we can immediately
1823 // publish the connection.
1824 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001825 c.conn.connected(s.name, b.intent.binder, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001826 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001827 Slog.w(TAG, "Failure sending service " + s.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001828 + " to connection " + c.conn.asBinder()
1829 + " (in " + c.binding.client.processName + ")", e);
1830 }
1831
1832 // If this is the first app connected back to this binding,
1833 // and the service had previously asked to be told when
1834 // rebound, then do so.
1835 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001836 requestServiceBindingLocked(s, b.intent, callerFg, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001837 }
1838 } else if (!b.intent.requested) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001839 requestServiceBindingLocked(s, b.intent, callerFg, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001840 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001841
Dianne Hackbornad51be92016-08-16 16:27:36 -07001842 getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001843
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001844 } finally {
1845 Binder.restoreCallingIdentity(origId);
1846 }
1847
1848 return 1;
1849 }
1850
1851 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
1852 final long origId = Binder.clearCallingIdentity();
1853 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001854 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001855 + " " + intent + ": " + service);
1856 if (r != null) {
1857 Intent.FilterComparison filter
1858 = new Intent.FilterComparison(intent);
1859 IntentBindRecord b = r.bindings.get(filter);
1860 if (b != null && !b.received) {
1861 b.binder = service;
1862 b.requested = true;
1863 b.received = true;
Michal Karpinskib7daac22019-03-25 10:12:41 +00001864 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
1865 for (int conni = connections.size() - 1; conni >= 0; conni--) {
1866 ArrayList<ConnectionRecord> clist = connections.valueAt(conni);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001867 for (int i=0; i<clist.size(); i++) {
1868 ConnectionRecord c = clist.get(i);
1869 if (!filter.equals(c.binding.intent.intent)) {
1870 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001871 TAG_SERVICE, "Not publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001872 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001873 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001874 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001875 TAG_SERVICE, "Published intent: " + intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001876 continue;
1877 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001878 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001879 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001880 c.conn.connected(r.name, service, false);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001881 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001882 Slog.w(TAG, "Failure sending service " + r.shortInstanceName
1883 + " to connection " + c.conn.asBinder()
1884 + " (in " + c.binding.client.processName + ")", e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001885 }
1886 }
1887 }
1888 }
1889
Dianne Hackborn164371f2013-10-01 19:10:13 -07001890 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001891 }
1892 } finally {
1893 Binder.restoreCallingIdentity(origId);
1894 }
1895 }
1896
Dianne Hackborna631d562018-11-20 15:58:15 -08001897 void updateServiceGroupLocked(IServiceConnection connection, int group, int importance) {
1898 final IBinder binder = connection.asBinder();
1899 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "updateServiceGroup: conn=" + binder);
1900 final ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1901 if (clist == null) {
1902 throw new IllegalArgumentException("Could not find connection for "
1903 + connection.asBinder());
1904 }
1905 for (int i = clist.size() - 1; i >= 0; i--) {
1906 final ConnectionRecord crec = clist.get(i);
1907 final ServiceRecord srec = crec.binding.service;
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08001908 if (srec != null && (srec.serviceInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) != 0) {
1909 if (srec.app != null) {
1910 if (group > 0) {
1911 srec.app.connectionService = srec;
1912 srec.app.connectionGroup = group;
1913 srec.app.connectionImportance = importance;
1914 } else {
1915 srec.app.connectionService = null;
1916 srec.app.connectionGroup = 0;
1917 srec.app.connectionImportance = 0;
1918 }
Dianne Hackborna631d562018-11-20 15:58:15 -08001919 } else {
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08001920 if (group > 0) {
1921 srec.pendingConnectionGroup = group;
1922 srec.pendingConnectionImportance = importance;
1923 } else {
1924 srec.pendingConnectionGroup = 0;
1925 srec.pendingConnectionImportance = 0;
1926 }
Dianne Hackborna631d562018-11-20 15:58:15 -08001927 }
1928 }
1929 }
1930 }
1931
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001932 boolean unbindServiceLocked(IServiceConnection connection) {
1933 IBinder binder = connection.asBinder();
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001934 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001935 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1936 if (clist == null) {
1937 Slog.w(TAG, "Unbind failed: could not find connection for "
1938 + connection.asBinder());
1939 return false;
1940 }
1941
1942 final long origId = Binder.clearCallingIdentity();
1943 try {
1944 while (clist.size() > 0) {
1945 ConnectionRecord r = clist.get(0);
1946 removeConnectionLocked(r, null, null);
Dianne Hackborn25e1eca2014-09-23 10:13:13 -07001947 if (clist.size() > 0 && clist.get(0) == r) {
1948 // In case it didn't get removed above, do it now.
1949 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
1950 clist.remove(0);
1951 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001952
1953 if (r.binding.service.app != null) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001954 if (r.binding.service.app.whitelistManager) {
Felipe Lemea7778b02016-06-28 10:38:59 -07001955 updateWhitelistManagerLocked(r.binding.service.app);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001956 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001957 // This could have made the service less important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001958 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1959 r.binding.service.app.treatLikeActivity = true;
1960 mAm.updateLruProcessLocked(r.binding.service.app,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001961 r.binding.service.app.hasClientActivities()
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001962 || r.binding.service.app.treatLikeActivity, null);
1963 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001964 }
1965 }
Amith Yamasanib2926b12017-05-11 11:13:52 -07001966
Amith Yamasanid2775cd2019-04-12 15:47:54 -07001967 mAm.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
Amith Yamasanib2926b12017-05-11 11:13:52 -07001968
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001969 } finally {
1970 Binder.restoreCallingIdentity(origId);
1971 }
1972
1973 return true;
1974 }
1975
1976 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
1977 final long origId = Binder.clearCallingIdentity();
1978 try {
1979 if (r != null) {
1980 Intent.FilterComparison filter
1981 = new Intent.FilterComparison(intent);
1982 IntentBindRecord b = r.bindings.get(filter);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001983 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001984 + " at " + b + ": apps="
1985 + (b != null ? b.apps.size() : 0));
1986
Dianne Hackborn164371f2013-10-01 19:10:13 -07001987 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001988 if (b != null) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001989 if (b.apps.size() > 0 && !inDestroying) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001990 // Applications have already bound since the last
1991 // unbind, so just rebind right here.
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001992 boolean inFg = false;
1993 for (int i=b.apps.size()-1; i>=0; i--) {
1994 ProcessRecord client = b.apps.valueAt(i).client;
1995 if (client != null && client.setSchedGroup
Dianne Hackborna49ad092016-03-03 13:39:10 -08001996 != ProcessList.SCHED_GROUP_BACKGROUND) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001997 inFg = true;
1998 break;
1999 }
2000 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002001 try {
2002 requestServiceBindingLocked(r, b, inFg, true);
2003 } catch (TransactionTooLargeException e) {
2004 // Don't pass this back to ActivityThread, it's unrelated.
2005 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002006 } else {
2007 // Note to tell the service the next time there is
2008 // a new client.
2009 b.doRebind = true;
2010 }
2011 }
2012
Dianne Hackborn164371f2013-10-01 19:10:13 -07002013 serviceDoneExecutingLocked(r, inDestroying, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002014 }
2015 } finally {
2016 Binder.restoreCallingIdentity(origId);
2017 }
2018 }
2019
2020 private final ServiceRecord findServiceLocked(ComponentName name,
Dianne Hackborn41203752012-08-31 14:05:51 -07002021 IBinder token, int userId) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07002022 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002023 return r == token ? r : null;
2024 }
2025
2026 private final class ServiceLookupResult {
2027 final ServiceRecord record;
2028 final String permission;
2029
2030 ServiceLookupResult(ServiceRecord _record, String _permission) {
2031 record = _record;
2032 permission = _permission;
2033 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002034 }
2035
2036 private class ServiceRestarter implements Runnable {
2037 private ServiceRecord mService;
2038
2039 void setService(ServiceRecord service) {
2040 mService = service;
2041 }
2042
2043 public void run() {
2044 synchronized(mAm) {
2045 performServiceRestartLocked(mService);
2046 }
2047 }
2048 }
2049
2050 private ServiceLookupResult retrieveServiceLocked(Intent service,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002051 String instanceName, String resolvedType, String callingPackage,
2052 int callingPid, int callingUid, int userId,
Svet Ganovd223db32017-12-22 09:43:48 -08002053 boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
2054 boolean allowInstant) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002055 ServiceRecord r = null;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002056 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002057 + " type=" + resolvedType + " callingUid=" + callingUid);
2058
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07002059 userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
jovanaka6763a32018-12-03 17:23:20 -08002060 ActivityManagerInternal.ALLOW_NON_FULL_IN_PROFILE, "service",
2061 callingPackage);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002062
Dianne Hackbornad51be92016-08-16 16:27:36 -07002063 ServiceMap smap = getServiceMapLocked(userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002064 final ComponentName comp;
2065 if (instanceName == null) {
2066 comp = service.getComponent();
2067 } else {
2068 final ComponentName realComp = service.getComponent();
2069 if (realComp == null) {
2070 throw new IllegalArgumentException("Can't use custom instance name '" + instanceName
2071 + "' without expicit component in Intent");
2072 }
2073 comp = new ComponentName(realComp.getPackageName(),
2074 realComp.getClassName() + ":" + instanceName);
2075 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002076 if (comp != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002077 r = smap.mServicesByInstanceName.get(comp);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002078 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002079 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002080 if (r == null && !isBindExternal && instanceName == null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002081 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002082 r = smap.mServicesByIntent.get(filter);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002083 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002084 }
Robert Sesekb9a86662015-12-09 16:22:45 -05002085 if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
2086 && !callingPackage.equals(r.packageName)) {
2087 // If an external service is running within its own package, other packages
2088 // should not bind to that instance.
2089 r = null;
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002090 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Whoops, can't use existing external service");
Robert Sesekb9a86662015-12-09 16:22:45 -05002091 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002092 if (r == null) {
2093 try {
Svet Ganovd223db32017-12-22 09:43:48 -08002094 int flags = ActivityManagerService.STOCK_PM_FLAGS
2095 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
2096 if (allowInstant) {
2097 flags |= PackageManager.MATCH_INSTANT;
2098 }
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002099 // TODO: come back and remove this assumption to triage all services
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002100 ResolveInfo rInfo = mAm.getPackageManagerInternalLocked().resolveService(service,
Svet Ganovd223db32017-12-22 09:43:48 -08002101 resolvedType, flags, userId, callingUid);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002102 ServiceInfo sInfo = rInfo != null ? rInfo.serviceInfo : null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002103 if (sInfo == null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002104 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002105 ": not found");
2106 return null;
2107 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002108 if (instanceName != null
2109 && (sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
2110 throw new IllegalArgumentException("Can't use instance name '" + instanceName
2111 + "' with non-isolated service '" + sInfo.name + "'");
2112 }
2113 ComponentName className = new ComponentName(
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002114 sInfo.applicationInfo.packageName, sInfo.name);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002115 ComponentName name = comp != null ? comp : className;
Dianne Hackborn769b2e72018-12-05 08:51:20 -08002116 if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid,
2117 name.getPackageName(), sInfo.applicationInfo.uid)) {
2118 String msg = "association not allowed between packages "
Amith Yamasani9f96c2b2018-12-19 18:32:44 -08002119 + callingPackage + " and " + name.getPackageName();
Dianne Hackborn769b2e72018-12-05 08:51:20 -08002120 Slog.w(TAG, "Service lookup failed: " + msg);
2121 return new ServiceLookupResult(null, msg);
2122 }
Martijn Coenen572ed7f2019-03-28 19:50:44 +01002123
2124 // Store the defining packageName and uid, as they might be changed in
2125 // the ApplicationInfo for external services (which run with the package name
2126 // and uid of the caller).
2127 String definingPackageName = sInfo.applicationInfo.packageName;
2128 int definingUid = sInfo.applicationInfo.uid;
Robert Sesekb9a86662015-12-09 16:22:45 -05002129 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
2130 if (isBindExternal) {
2131 if (!sInfo.exported) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002132 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
2133 + className + " is not exported");
Robert Sesekb9a86662015-12-09 16:22:45 -05002134 }
2135 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002136 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
2137 + className + " is not an isolatedProcess");
Robert Sesekb9a86662015-12-09 16:22:45 -05002138 }
2139 // Run the service under the calling package's application.
2140 ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
2141 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
2142 if (aInfo == null) {
2143 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
2144 "could not resolve client package " + callingPackage);
2145 }
2146 sInfo = new ServiceInfo(sInfo);
2147 sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
2148 sInfo.applicationInfo.packageName = aInfo.packageName;
2149 sInfo.applicationInfo.uid = aInfo.uid;
2150 name = new ComponentName(aInfo.packageName, name.getClassName());
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002151 className = new ComponentName(aInfo.packageName,
2152 instanceName == null ? className.getClassName()
2153 : (className.getClassName() + ":" + instanceName));
Robert Sesekb9a86662015-12-09 16:22:45 -05002154 service.setComponent(name);
2155 } else {
2156 throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
2157 name);
2158 }
2159 } else if (isBindExternal) {
2160 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
2161 " is not an externalService");
2162 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002163 if (userId > 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07002164 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
Amith Yamasani4b9d79c2014-05-21 19:14:21 -07002165 sInfo.name, sInfo.flags)
2166 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002167 userId = 0;
Dianne Hackbornad51be92016-08-16 16:27:36 -07002168 smap = getServiceMapLocked(0);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002169 }
2170 sInfo = new ServiceInfo(sInfo);
2171 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
2172 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002173 r = smap.mServicesByInstanceName.get(name);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002174 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE,
2175 "Retrieved via pm by intent: " + r);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002176 if (r == null && createIfNeeded) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002177 final Intent.FilterComparison filter
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002178 = new Intent.FilterComparison(service.cloneFilter());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002179 final ServiceRestarter res = new ServiceRestarter();
2180 final BatteryStatsImpl.Uid.Pkg.Serv ss;
2181 final BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002182 synchronized (stats) {
2183 ss = stats.getServiceStatsLocked(
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002184 sInfo.applicationInfo.uid, name.getPackageName(),
2185 name.getClassName());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002186 }
Martijn Coenen572ed7f2019-03-28 19:50:44 +01002187 r = new ServiceRecord(mAm, ss, className, name, definingPackageName,
2188 definingUid, filter, sInfo, callingFromFg, res);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002189 res.setService(r);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002190 smap.mServicesByInstanceName.put(name, r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002191 smap.mServicesByIntent.put(filter, r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002192
2193 // Make sure this component isn't in the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002194 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002195 final ServiceRecord pr = mPendingServices.get(i);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002196 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002197 && pr.instanceName.equals(name)) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002198 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002199 mPendingServices.remove(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002200 }
2201 }
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002202 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002203 }
2204 } catch (RemoteException ex) {
2205 // pm is in same process, this will never happen.
2206 }
2207 }
2208 if (r != null) {
Dianne Hackborn769b2e72018-12-05 08:51:20 -08002209 if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid, r.packageName,
2210 r.appInfo.uid)) {
2211 String msg = "association not allowed between packages "
2212 + callingPackage + " and " + r.packageName;
2213 Slog.w(TAG, "Service lookup failed: " + msg);
2214 return new ServiceLookupResult(null, msg);
2215 }
2216 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
2217 resolvedType, r.appInfo)) {
2218 return new ServiceLookupResult(null, "blocked by firewall");
2219 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002220 if (mAm.checkComponentPermission(r.permission,
Bryce Lee290e5782017-02-01 16:41:20 -08002221 callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002222 if (!r.exported) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002223 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002224 + " from pid=" + callingPid
2225 + ", uid=" + callingUid
2226 + " that is not exported from uid " + r.appInfo.uid);
2227 return new ServiceLookupResult(null, "not exported from uid "
2228 + r.appInfo.uid);
2229 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002230 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002231 + " from pid=" + callingPid
2232 + ", uid=" + callingUid
2233 + " requires " + r.permission);
2234 return new ServiceLookupResult(null, r.permission);
Svet Ganov99b60432015-06-27 13:15:22 -07002235 } else if (r.permission != null && callingPackage != null) {
2236 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
Wei Wangac392732019-02-22 11:00:34 -08002237 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.checkOperation(
Svet Ganov99b60432015-06-27 13:15:22 -07002238 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002239 Slog.w(TAG, "Appop Denial: Accessing service " + r.shortInstanceName
Svet Ganov99b60432015-06-27 13:15:22 -07002240 + " from pid=" + callingPid
2241 + ", uid=" + callingUid
2242 + " requires appop " + AppOpsManager.opToName(opCode));
2243 return null;
2244 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002245 }
2246 return new ServiceLookupResult(r, null);
2247 }
2248 return null;
2249 }
2250
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002251 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002252 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002253 + why + " of " + r + " in app " + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002254 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002255 + why + " of " + r.shortInstanceName);
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002256
2257 // For b/34123235: Services within the system server won't start until SystemServer
2258 // does Looper.loop(), so we shouldn't try to start/bind to them too early in the boot
2259 // process. However, since there's a little point of showing the ANR dialog in that case,
2260 // let's suppress the timeout until PHASE_THIRD_PARTY_APPS_CAN_START.
2261 //
2262 // (Note there are multiple services start at PHASE_THIRD_PARTY_APPS_CAN_START too,
2263 // which technically could also trigger this timeout if there's a system server
2264 // that takes a long time to handle PHASE_THIRD_PARTY_APPS_CAN_START, but that shouldn't
2265 // happen.)
2266 boolean timeoutNeeded = true;
2267 if ((mAm.mBootPhase < SystemService.PHASE_THIRD_PARTY_APPS_CAN_START)
2268 && (r.app != null) && (r.app.pid == android.os.Process.myPid())) {
2269
2270 Slog.w(TAG, "Too early to start/bind service in system_server: Phase=" + mAm.mBootPhase
2271 + " " + r.getComponentName());
2272 timeoutNeeded = false;
2273 }
2274
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002275 long now = SystemClock.uptimeMillis();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002276 if (r.executeNesting == 0) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002277 r.executeFg = fg;
Joe Onorato4eb64fd2016-03-21 15:30:09 -07002278 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002279 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002280 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002281 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002282 if (r.app != null) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002283 r.app.executingServices.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002284 r.app.execServicesFg |= fg;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002285 if (timeoutNeeded && r.app.executingServices.size() == 1) {
Dianne Hackborn2be00932013-09-22 16:46:00 -07002286 scheduleServiceTimeoutLocked(r.app);
2287 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002288 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002289 } else if (r.app != null && fg && !r.app.execServicesFg) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002290 r.app.execServicesFg = true;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002291 if (timeoutNeeded) {
2292 scheduleServiceTimeoutLocked(r.app);
2293 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002294 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002295 r.executeFg |= fg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002296 r.executeNesting++;
2297 r.executingStart = now;
2298 }
2299
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002300 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
2301 boolean execInFg, boolean rebind) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002302 if (r.app == null || r.app.thread == null) {
2303 // If service is not currently running, can't yet bind.
2304 return false;
2305 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08002306 if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
2307 + " rebind=" + rebind);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002308 if ((!i.requested || rebind) && i.apps.size() > 0) {
2309 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002310 bumpServiceExecutingLocked(r, execInFg, "bind");
Dianne Hackborna413dc02013-07-12 12:02:55 -07002311 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
2312 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002313 r.app.getReportedProcState());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002314 if (!rebind) {
2315 i.requested = true;
2316 }
2317 i.hasBound = true;
2318 i.doRebind = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002319 } catch (TransactionTooLargeException e) {
2320 // Keep the executeNesting count accurate.
2321 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
2322 final boolean inDestroying = mDestroyingServices.contains(r);
2323 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2324 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002325 } catch (RemoteException e) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002326 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002327 // Keep the executeNesting count accurate.
2328 final boolean inDestroying = mDestroyingServices.contains(r);
2329 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002330 return false;
2331 }
2332 }
2333 return true;
2334 }
2335
Dianne Hackbornad51be92016-08-16 16:27:36 -07002336 private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002337 boolean canceled = false;
2338
Wale Ogunwalef6733932018-06-27 05:14:34 -07002339 if (mAm.mAtmInternal.isShuttingDown()) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002340 Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortInstanceName
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07002341 + " - system is shutting down");
2342 return false;
2343 }
2344
Dianne Hackbornad51be92016-08-16 16:27:36 -07002345 ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002346 if (smap.mServicesByInstanceName.get(r.instanceName) != r) {
2347 ServiceRecord cur = smap.mServicesByInstanceName.get(r.instanceName);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002348 Slog.wtf(TAG, "Attempting to schedule restart of " + r
2349 + " when found in map: " + cur);
2350 return false;
2351 }
2352
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002353 final long now = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002354
2355 if ((r.serviceInfo.applicationInfo.flags
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002356 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002357 long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION;
2358 long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002359
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002360 // Any delivered but not yet finished starts should be put back
2361 // on the pending list.
2362 final int N = r.deliveredStarts.size();
2363 if (N > 0) {
2364 for (int i=N-1; i>=0; i--) {
2365 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
2366 si.removeUriPermissionsLocked();
2367 if (si.intent == null) {
2368 // We'll generate this again if needed.
2369 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
2370 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
2371 r.pendingStarts.add(0, si);
2372 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
2373 dur *= 2;
2374 if (minDuration < dur) minDuration = dur;
2375 if (resetTime < dur) resetTime = dur;
2376 } else {
2377 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002378 + r.shortInstanceName);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002379 canceled = true;
2380 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002381 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002382 r.deliveredStarts.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002383 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002384
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002385 r.totalRestartCount++;
2386 if (r.restartDelay == 0) {
2387 r.restartCount++;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002388 r.restartDelay = minDuration;
Amith Yamasanib0c8a882017-08-28 09:36:42 -07002389 } else if (r.crashCount > 1) {
2390 r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
2391 * (r.crashCount - 1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002392 } else {
Varun Shah4311f212019-01-23 05:59:31 +00002393 // If it has been a "reasonably long time" since the service
2394 // was started, then reset our restart duration back to
2395 // the beginning, so we don't infinitely increase the duration
2396 // on a service that just occasionally gets killed (which is
2397 // a normal case, due to process being killed to reclaim memory).
2398 if (now > (r.restartTime+resetTime)) {
2399 r.restartCount = 1;
2400 r.restartDelay = minDuration;
Varun Shah16522412018-12-28 15:46:01 -08002401 } else {
Varun Shah4311f212019-01-23 05:59:31 +00002402 r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
2403 if (r.restartDelay < minDuration) {
2404 r.restartDelay = minDuration;
Varun Shah16522412018-12-28 15:46:01 -08002405 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002406 }
2407 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002408
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002409 r.nextRestartTime = now + r.restartDelay;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002410
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002411 // Make sure that we don't end up restarting a bunch of services
2412 // all at the same time.
Varun Shah4311f212019-01-23 05:59:31 +00002413 boolean repeat;
2414 do {
2415 repeat = false;
2416 final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
2417 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2418 ServiceRecord r2 = mRestartingServices.get(i);
2419 if (r2 != r && r.nextRestartTime >= (r2.nextRestartTime-restartTimeBetween)
2420 && r.nextRestartTime < (r2.nextRestartTime+restartTimeBetween)) {
2421 r.nextRestartTime = r2.nextRestartTime + restartTimeBetween;
2422 r.restartDelay = r.nextRestartTime - now;
2423 repeat = true;
2424 break;
2425 }
2426 }
2427 } while (repeat);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002428
2429 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07002430 // Persistent processes are immediately restarted, so there is no
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002431 // reason to hold of on restarting their services.
2432 r.totalRestartCount++;
2433 r.restartCount = 0;
2434 r.restartDelay = 0;
2435 r.nextRestartTime = now;
2436 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002437
2438 if (!mRestartingServices.contains(r)) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002439 r.createdFromFg = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002440 mRestartingServices.add(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002441 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002442 }
2443
Christopher Tate08992ac2017-03-21 11:37:06 -07002444 cancelForegroundNotificationLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002445
2446 mAm.mHandler.removeCallbacks(r.restarter);
2447 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
2448 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
2449 Slog.w(TAG, "Scheduling restart of crashed service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002450 + r.shortInstanceName + " in " + r.restartDelay + "ms");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002451 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002452 r.userId, r.shortInstanceName, r.restartDelay);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002453
2454 return canceled;
2455 }
2456
2457 final void performServiceRestartLocked(ServiceRecord r) {
2458 if (!mRestartingServices.contains(r)) {
2459 return;
2460 }
Dianne Hackbornad51be92016-08-16 16:27:36 -07002461 if (!isServiceNeededLocked(r, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002462 // Paranoia: is this service actually needed? In theory a service that is not
2463 // needed should never remain on the restart list. In practice... well, there
2464 // have been bugs where this happens, and bad things happen because the process
2465 // ends up just being cached, so quickly killed, then restarted again and again.
2466 // Let's not let that happen.
2467 Slog.wtf(TAG, "Restarting service that is not needed: " + r);
2468 return;
2469 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002470 try {
Michal Karpinskie069b002019-03-07 16:15:14 +00002471 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002472 } catch (TransactionTooLargeException e) {
2473 // Ignore, it's been logged and nothing upstack cares.
2474 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002475 }
2476
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002477 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
2478 boolean force) {
2479 if (!force && r.restartDelay == 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002480 return false;
2481 }
Dianne Hackborn7b492722013-11-01 09:58:45 -07002482 // Remove from the restarting list; if the service is currently on the
2483 // restarting list, or the call is coming from another app, then this
2484 // service has become of much more interest so we reset the restart interval.
2485 boolean removed = mRestartingServices.remove(r);
2486 if (removed || callingUid != r.appInfo.uid) {
2487 r.resetRestartCounter();
2488 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002489 if (removed) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002490 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002491 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002492 mAm.mHandler.removeCallbacks(r.restarter);
2493 return true;
2494 }
2495
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002496 private void clearRestartingIfNeededLocked(ServiceRecord r) {
2497 if (r.restartTracker != null) {
2498 // If this is the last restarting record with this tracker, then clear
2499 // the tracker's restarting state.
2500 boolean stillTracking = false;
2501 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2502 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
2503 stillTracking = true;
2504 break;
2505 }
2506 }
2507 if (!stillTracking) {
2508 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
2509 SystemClock.uptimeMillis());
2510 r.restartTracker = null;
2511 }
2512 }
2513 }
2514
Svet Ganov9c165d72015-12-01 19:52:26 -08002515 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
Michal Karpinskie069b002019-03-07 16:15:14 +00002516 boolean whileRestarting, boolean permissionsReviewRequired)
2517 throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002518 if (r.app != null && r.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002519 sendServiceArgsLocked(r, execInFg, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002520 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002521 }
2522
Sudheer Shanka03d0f812017-04-20 16:57:50 -07002523 if (!whileRestarting && mRestartingServices.contains(r)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002524 // If waiting for a restart, then do nothing.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002525 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002526 }
2527
Christopher Tate08992ac2017-03-21 11:37:06 -07002528 if (DEBUG_SERVICE) {
2529 Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
2530 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002531
2532 // We are now bringing the service up, so no longer in the
2533 // restarting state.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002534 if (mRestartingServices.remove(r)) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002535 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002536 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002537
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002538 // Make sure this service is no longer considered delayed, we are starting it now.
2539 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002540 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002541 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002542 r.delayed = false;
2543 }
2544
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002545 // Make sure that the user who owns this service is started. If not,
2546 // we don't want to allow it to run.
Fyodor Kupolov610acda2015-10-19 18:44:07 -07002547 if (!mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002548 String msg = "Unable to launch app "
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002549 + r.appInfo.packageName + "/"
2550 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002551 + r.intent.getIntent() + ": user " + r.userId + " is stopped";
2552 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002553 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002554 return msg;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002555 }
2556
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002557 // Service is now being launched, its package can't be stopped.
2558 try {
2559 AppGlobals.getPackageManager().setPackageStoppedState(
2560 r.packageName, false, r.userId);
2561 } catch (RemoteException e) {
2562 } catch (IllegalArgumentException e) {
2563 Slog.w(TAG, "Failed trying to unstop package "
2564 + r.packageName + ": " + e);
2565 }
2566
2567 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
2568 final String procName = r.processName;
Martijn Coenene8431c22019-03-28 14:09:38 +01002569 HostingRecord hostingRecord = new HostingRecord("service", r.instanceName);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002570 ProcessRecord app;
2571
2572 if (!isolated) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07002573 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
2574 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
2575 + " app=" + app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002576 if (app != null && app.thread != null) {
2577 try {
Patrick Baumannc2def582018-04-04 12:14:15 -07002578 app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode, mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002579 realStartServiceLocked(r, app, execInFg);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002580 return null;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002581 } catch (TransactionTooLargeException e) {
2582 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002583 } catch (RemoteException e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002584 Slog.w(TAG, "Exception when starting service " + r.shortInstanceName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002585 }
2586
2587 // If a dead object exception was thrown -- fall through to
2588 // restart the application.
2589 }
2590 } else {
2591 // If this service runs in an isolated process, then each time
2592 // we call startProcessLocked() we will get a new isolated
2593 // process, starting another process if we are currently waiting
2594 // for a previous process to come up. To deal with this, we store
2595 // in the service any current isolated process it is running in or
2596 // waiting to have come up.
2597 app = r.isolatedProc;
Robert Sesekc5f86642016-11-04 10:20:38 -04002598 if (WebViewZygote.isMultiprocessEnabled()
2599 && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
Martijn Coenene8431c22019-03-28 14:09:38 +01002600 hostingRecord = HostingRecord.byWebviewZygote(r.instanceName);
Robert Sesekc5f86642016-11-04 10:20:38 -04002601 }
Martijn Coenen7e6fa672018-11-05 11:45:26 +01002602 if ((r.serviceInfo.flags & ServiceInfo.FLAG_USE_APP_ZYGOTE) != 0) {
Martijn Coenen572ed7f2019-03-28 19:50:44 +01002603 hostingRecord = HostingRecord.byAppZygote(r.instanceName, r.definingPackageName,
2604 r.definingUid);
Martijn Coenen7e6fa672018-11-05 11:45:26 +01002605 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002606 }
2607
2608 // Not running -- get it started, and enqueue this service record
2609 // to be executed when the app comes up.
Svet Ganov9c165d72015-12-01 19:52:26 -08002610 if (app == null && !permissionsReviewRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002611 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
Martijn Coenene8431c22019-03-28 14:09:38 +01002612 hostingRecord, false, isolated, false)) == null) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002613 String msg = "Unable to launch app "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002614 + r.appInfo.packageName + "/"
2615 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002616 + r.intent.getIntent() + ": process is bad";
2617 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002618 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002619 return msg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002620 }
2621 if (isolated) {
2622 r.isolatedProc = app;
2623 }
2624 }
2625
Christopher Tate1536cc22017-09-18 16:43:30 -07002626 if (r.fgRequired) {
2627 if (DEBUG_FOREGROUND_SERVICE) {
2628 Slog.v(TAG, "Whitelisting " + UserHandle.formatUid(r.appInfo.uid)
2629 + " for fg-service launch");
2630 }
2631 mAm.tempWhitelistUidLocked(r.appInfo.uid,
2632 SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch");
2633 }
2634
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002635 if (!mPendingServices.contains(r)) {
2636 mPendingServices.add(r);
2637 }
2638
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002639 if (r.delayedStop) {
2640 // Oh and hey we've already been asked to stop!
2641 r.delayedStop = false;
2642 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002643 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2644 "Applying delayed stop (in bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002645 stopServiceLocked(r);
2646 }
2647 }
2648
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002649 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002650 }
2651
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002652 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
2653 throws TransactionTooLargeException {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002654 for (int i=r.bindings.size()-1; i>=0; i--) {
2655 IntentBindRecord ibr = r.bindings.valueAt(i);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002656 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002657 break;
2658 }
2659 }
2660 }
2661
Michal Karpinskie069b002019-03-07 16:15:14 +00002662 /**
2663 * Note the name of this method should not be confused with the started services concept.
2664 * The "start" here means bring up the instance in the client, and this method is called
2665 * from bindService() as well.
2666 */
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002667 private final void realStartServiceLocked(ServiceRecord r,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002668 ProcessRecord app, boolean execInFg) throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002669 if (app.thread == null) {
2670 throw new RemoteException();
2671 }
2672 if (DEBUG_MU)
2673 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
2674 + ", ProcessRecord.uid = " + app.uid);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002675 r.setProcess(app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002676 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
2677
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002678 final boolean newService = app.services.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002679 bumpServiceExecutingLocked(r, execInFg, "create");
Dianne Hackborndb926082013-10-31 16:32:44 -07002680 mAm.updateLruProcessLocked(app, false, null);
Makoto Onuki0f421292017-04-28 15:03:33 -07002681 updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
Amith Yamasanid2775cd2019-04-12 15:47:54 -07002682 mAm.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_START_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002683
2684 boolean created = false;
2685 try {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002686 if (LOG_SERVICE_START_STOP) {
Dianne Hackbornab2df062015-01-07 13:43:13 -08002687 String nameTerm;
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002688 int lastPeriod = r.shortInstanceName.lastIndexOf('.');
2689 nameTerm = lastPeriod >= 0 ? r.shortInstanceName.substring(lastPeriod)
2690 : r.shortInstanceName;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002691 EventLogTags.writeAmCreateService(
2692 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
2693 }
Chenjie Yu75b3c492018-10-06 21:45:19 -07002694 StatsLog.write(StatsLog.SERVICE_LAUNCH_REPORTED, r.appInfo.uid, r.name.getPackageName(),
2695 r.name.getClassName());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002696 synchronized (r.stats.getBatteryStats()) {
2697 r.stats.startLaunchedLocked();
2698 }
Brian Carlstromca82e612016-04-19 23:16:08 -07002699 mAm.notifyPackageUse(r.serviceInfo.packageName,
2700 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
Dianne Hackborna413dc02013-07-12 12:02:55 -07002701 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002702 app.thread.scheduleCreateService(r, r.serviceInfo,
Wale Ogunwale53783742018-09-16 10:21:51 -07002703 mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002704 app.getReportedProcState());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002705 r.postNotification();
2706 created = true;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -07002707 } catch (DeadObjectException e) {
2708 Slog.w(TAG, "Application dead when creating service " + r);
2709 mAm.appDiedLocked(app);
Wale Ogunwalebfac4682015-04-08 14:33:21 -07002710 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002711 } finally {
2712 if (!created) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002713 // Keep the executeNesting count accurate.
2714 final boolean inDestroying = mDestroyingServices.contains(r);
2715 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2716
2717 // Cleanup.
2718 if (newService) {
2719 app.services.remove(r);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002720 r.setProcess(null);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002721 }
2722
2723 // Retry.
2724 if (!inDestroying) {
2725 scheduleServiceRestartLocked(r, false);
2726 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002727 }
2728 }
2729
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002730 if (r.whitelistManager) {
2731 app.whitelistManager = true;
2732 }
2733
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002734 requestServiceBindingsLocked(r, execInFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002735
Dianne Hackborn465fa392014-09-14 14:21:18 -07002736 updateServiceClientActivitiesLocked(app, null, true);
2737
Michal Karpinskib7daac22019-03-25 10:12:41 +00002738 if (newService && created) {
2739 app.addBoundClientUidsOfNewService(r);
2740 }
2741
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002742 // If the service is in the started state, and there are no
2743 // pending arguments, then fake up one so its onStartCommand() will
2744 // be called.
2745 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
2746 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002747 null, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002748 }
2749
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002750 sendServiceArgsLocked(r, execInFg, true);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002751
2752 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002753 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002754 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002755 r.delayed = false;
2756 }
2757
2758 if (r.delayedStop) {
2759 // Oh and hey we've already been asked to stop!
2760 r.delayedStop = false;
2761 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002762 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2763 "Applying delayed stop (from start): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002764 stopServiceLocked(r);
2765 }
2766 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002767 }
2768
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002769 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002770 boolean oomAdjusted) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002771 final int N = r.pendingStarts.size();
2772 if (N == 0) {
2773 return;
2774 }
2775
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002776 ArrayList<ServiceStartArgs> args = new ArrayList<>();
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002777
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002778 while (r.pendingStarts.size() > 0) {
2779 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
2780 if (DEBUG_SERVICE) {
2781 Slog.v(TAG_SERVICE, "Sending arguments to: "
2782 + r + " " + r.intent + " args=" + si.intent);
2783 }
2784 if (si.intent == null && N > 1) {
2785 // If somehow we got a dummy null intent in the middle,
2786 // then skip it. DO NOT skip a null intent when it is
2787 // the only one in the list -- this is to support the
2788 // onStartCommand(null) case.
2789 continue;
2790 }
2791 si.deliveredTime = SystemClock.uptimeMillis();
2792 r.deliveredStarts.add(si);
2793 si.deliveryCount++;
2794 if (si.neededGrants != null) {
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07002795 mAm.mUgmInternal.grantUriPermissionUncheckedFromIntent(si.neededGrants,
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002796 si.getUriPermissionsLocked());
2797 }
Hai Zhangbb23d532018-08-27 16:00:35 -07002798 mAm.grantEphemeralAccessLocked(r.userId, si.intent, UserHandle.getAppId(r.appInfo.uid),
2799 UserHandle.getAppId(si.callingId));
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002800 bumpServiceExecutingLocked(r, execInFg, "start");
2801 if (!oomAdjusted) {
2802 oomAdjusted = true;
Amith Yamasanid2775cd2019-04-12 15:47:54 -07002803 mAm.updateOomAdjLocked(r.app, true, OomAdjuster.OOM_ADJ_REASON_START_SERVICE);
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002804 }
2805 if (r.fgRequired && !r.fgWaiting) {
2806 if (!r.isForeground) {
2807 if (DEBUG_BACKGROUND_CHECK) {
2808 Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r);
2809 }
2810 scheduleServiceForegroundTransitionTimeoutLocked(r);
2811 } else {
2812 if (DEBUG_BACKGROUND_CHECK) {
2813 Slog.i(TAG, "Service already foreground; no new timeout: " + r);
2814 }
2815 r.fgRequired = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002816 }
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002817 }
2818 int flags = 0;
2819 if (si.deliveryCount > 1) {
2820 flags |= Service.START_FLAG_RETRY;
2821 }
2822 if (si.doneExecutingCount > 0) {
2823 flags |= Service.START_FLAG_REDELIVERY;
2824 }
2825 args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
2826 }
2827
2828 ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
2829 slice.setInlineCountLimit(4);
2830 Exception caughtException = null;
2831 try {
2832 r.app.thread.scheduleServiceArgs(r, slice);
2833 } catch (TransactionTooLargeException e) {
2834 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
2835 + " args, first: " + args.get(0).args);
2836 Slog.w(TAG, "Failed delivering service starts", e);
2837 caughtException = e;
2838 } catch (RemoteException e) {
2839 // Remote process gone... we'll let the normal cleanup take care of this.
2840 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
2841 Slog.w(TAG, "Failed delivering service starts", e);
2842 caughtException = e;
2843 } catch (Exception e) {
2844 Slog.w(TAG, "Unexpected exception", e);
2845 caughtException = e;
2846 }
2847
2848 if (caughtException != null) {
2849 // Keep nesting count correct
2850 final boolean inDestroying = mDestroyingServices.contains(r);
2851 for (int i = 0; i < args.size(); i++) {
2852 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2853 }
2854 if (caughtException instanceof TransactionTooLargeException) {
2855 throw (TransactionTooLargeException)caughtException;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002856 }
2857 }
2858 }
2859
Dianne Hackbornad51be92016-08-16 16:27:36 -07002860 private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn,
2861 boolean hasConn) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002862 // Are we still explicitly being asked to run?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002863 if (r.startRequested) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002864 return true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002865 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002866
Dianne Hackborncb015632017-06-14 17:30:15 -07002867 // Is someone still bound to us keeping us running?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002868 if (!knowConn) {
2869 hasConn = r.hasAutoCreateConnections();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002870 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002871 if (hasConn) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002872 return true;
2873 }
2874
2875 return false;
2876 }
2877
2878 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
2879 boolean hasConn) {
2880 //Slog.i(TAG, "Bring down service:");
2881 //r.dump(" ");
2882
Dianne Hackbornad51be92016-08-16 16:27:36 -07002883 if (isServiceNeededLocked(r, knowConn, hasConn)) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002884 return;
2885 }
2886
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002887 // Are we in the process of launching?
2888 if (mPendingServices.contains(r)) {
2889 return;
2890 }
2891
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002892 bringDownServiceLocked(r);
2893 }
2894
2895 private final void bringDownServiceLocked(ServiceRecord r) {
2896 //Slog.i(TAG, "Bring down service:");
2897 //r.dump(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002898
Dianne Hackborn390517b2013-05-30 15:03:32 -07002899 // Report to all of the connections that the service is no longer
2900 // available.
Michal Karpinskib7daac22019-03-25 10:12:41 +00002901 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
2902 for (int conni = connections.size() - 1; conni >= 0; conni--) {
2903 ArrayList<ConnectionRecord> c = connections.valueAt(conni);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002904 for (int i=0; i<c.size(); i++) {
2905 ConnectionRecord cr = c.get(i);
2906 // There is still a connection to the service that is
2907 // being brought down. Mark it as dead.
2908 cr.serviceDead = true;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002909 cr.stopAssociation();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002910 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07002911 cr.conn.connected(r.name, null, true);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002912 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002913 Slog.w(TAG, "Failure disconnecting service " + r.shortInstanceName
2914 + " to connection " + c.get(i).conn.asBinder()
2915 + " (in " + c.get(i).binding.client.processName + ")", e);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002916 }
2917 }
2918 }
2919
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002920 // Tell the service that it has been unbound.
Dianne Hackborn390517b2013-05-30 15:03:32 -07002921 if (r.app != null && r.app.thread != null) {
Amith Yamasani66eb7852019-05-29 14:09:53 -07002922 boolean needOomAdj = false;
2923 for (int i = r.bindings.size() - 1; i >= 0; i--) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002924 IntentBindRecord ibr = r.bindings.valueAt(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002925 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002926 + ": hasBound=" + ibr.hasBound);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002927 if (ibr.hasBound) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002928 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002929 bumpServiceExecutingLocked(r, false, "bring down unbind");
Amith Yamasani66eb7852019-05-29 14:09:53 -07002930 needOomAdj = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002931 ibr.hasBound = false;
Dianne Hackborn85e35642017-01-12 15:10:57 -08002932 ibr.requested = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002933 r.app.thread.scheduleUnbindService(r,
2934 ibr.intent.getIntent());
2935 } catch (Exception e) {
2936 Slog.w(TAG, "Exception when unbinding service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002937 + r.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002938 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002939 }
2940 }
2941 }
Amith Yamasani66eb7852019-05-29 14:09:53 -07002942 if (needOomAdj) {
2943 mAm.updateOomAdjLocked(r.app, true,
2944 OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
2945 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002946 }
2947
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002948 // Check to see if the service had been started as foreground, but being
2949 // brought down before actually showing a notification. That is not allowed.
2950 if (r.fgRequired) {
2951 Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
2952 + r);
2953 r.fgRequired = false;
2954 r.fgWaiting = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002955 ServiceState stracker = r.getTracker();
2956 if (stracker != null) {
2957 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
2958 r.lastActivity);
2959 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07002960 mAm.mAppOpsService.finishOperation(AppOpsManager.getToken(mAm.mAppOpsService),
2961 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002962 mAm.mHandler.removeMessages(
2963 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
2964 if (r.app != null) {
2965 Message msg = mAm.mHandler.obtainMessage(
2966 ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
2967 msg.obj = r.app;
Kodlee Yin7e951262018-04-05 12:59:56 -07002968 msg.getData().putCharSequence(
2969 ActivityManagerService.SERVICE_RECORD_KEY, r.toString());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002970 mAm.mHandler.sendMessage(msg);
2971 }
2972 }
2973
2974 if (DEBUG_SERVICE) {
2975 RuntimeException here = new RuntimeException();
2976 here.fillInStackTrace();
2977 Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here);
2978 }
Craig Mautner66c4a822015-01-16 12:48:16 -08002979 r.destroyTime = SystemClock.uptimeMillis();
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002980 if (LOG_SERVICE_START_STOP) {
2981 EventLogTags.writeAmDestroyService(
2982 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
2983 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002984
Dianne Hackbornad51be92016-08-16 16:27:36 -07002985 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002986 ServiceRecord found = smap.mServicesByInstanceName.remove(r.instanceName);
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002987
2988 // Note when this method is called by bringUpServiceLocked(), the service is not found
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002989 // in mServicesByInstanceName and found will be null.
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002990 if (found != null && found != r) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002991 // This is not actually the service we think is running... this should not happen,
2992 // but if it does, fail hard.
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002993 smap.mServicesByInstanceName.put(r.instanceName, found);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002994 throw new IllegalStateException("Bringing down " + r + " but actually running "
2995 + found);
2996 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002997 smap.mServicesByIntent.remove(r.intent);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002998 r.totalRestartCount = 0;
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002999 unscheduleServiceRestartLocked(r, 0, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003000
3001 // Also make sure it is not on the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08003002 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003003 if (mPendingServices.get(i) == r) {
3004 mPendingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003005 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003006 }
3007 }
3008
Christopher Tate08992ac2017-03-21 11:37:06 -07003009 cancelForegroundNotificationLocked(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003010 if (r.isForeground) {
3011 decActiveForegroundAppLocked(smap, r);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003012 ServiceState stracker = r.getTracker();
3013 if (stracker != null) {
3014 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
3015 r.lastActivity);
3016 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07003017 mAm.mAppOpsService.finishOperation(
3018 AppOpsManager.getToken(mAm.mAppOpsService),
3019 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003020 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED, r.appInfo.uid,
3021 r.shortInstanceName, StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Hui Yue361a232018-10-04 15:05:21 -07003022 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003023 }
Chenjie Yuccfe6452018-01-30 11:33:21 -08003024
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003025 r.isForeground = false;
3026 r.foregroundId = 0;
3027 r.foregroundNoti = null;
3028
3029 // Clear start entries.
3030 r.clearDeliveredStartsLocked();
3031 r.pendingStarts.clear();
Christopher Tate752bc2a2019-02-15 16:48:22 -08003032 smap.mDelayedStartList.remove(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003033
3034 if (r.app != null) {
3035 synchronized (r.stats.getBatteryStats()) {
3036 r.stats.stopLaunchedLocked();
3037 }
3038 r.app.services.remove(r);
Michal Karpinskib7daac22019-03-25 10:12:41 +00003039 r.app.updateBoundClientUids();
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003040 if (r.whitelistManager) {
3041 updateWhitelistManagerLocked(r.app);
3042 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003043 if (r.app.thread != null) {
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003044 updateServiceForegroundLocked(r.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003045 try {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003046 bumpServiceExecutingLocked(r, false, "destroy");
3047 mDestroyingServices.add(r);
Dianne Hackborn455625e2015-01-21 09:55:13 -08003048 r.destroying = true;
Amith Yamasanid2775cd2019-04-12 15:47:54 -07003049 mAm.updateOomAdjLocked(r.app, true,
3050 OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003051 r.app.thread.scheduleStopService(r);
3052 } catch (Exception e) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003053 Slog.w(TAG, "Exception when destroying service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003054 + r.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07003055 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003056 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003057 } else {
3058 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003059 TAG_SERVICE, "Removed service that has no process: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003060 }
3061 } else {
3062 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003063 TAG_SERVICE, "Removed service that is not running: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003064 }
3065
3066 if (r.bindings.size() > 0) {
3067 r.bindings.clear();
3068 }
3069
3070 if (r.restarter instanceof ServiceRestarter) {
3071 ((ServiceRestarter)r.restarter).setService(null);
3072 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003073
Dianne Hackbornd2932242013-08-05 18:18:42 -07003074 int memFactor = mAm.mProcessStats.getMemFactorLocked();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003075 long now = SystemClock.uptimeMillis();
3076 if (r.tracker != null) {
3077 r.tracker.setStarted(false, memFactor, now);
3078 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003079 if (r.executeNesting == 0) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07003080 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003081 r.tracker = null;
3082 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003083 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003084
Dianne Hackbornad51be92016-08-16 16:27:36 -07003085 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003086 }
3087
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07003088 void removeConnectionLocked(ConnectionRecord c, ProcessRecord skipApp,
3089 ActivityServiceConnectionsHolder skipAct) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003090 IBinder binder = c.conn.asBinder();
3091 AppBindRecord b = c.binding;
3092 ServiceRecord s = b.service;
Michal Karpinskib7daac22019-03-25 10:12:41 +00003093 ArrayList<ConnectionRecord> clist = s.getConnections().get(binder);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003094 if (clist != null) {
3095 clist.remove(c);
3096 if (clist.size() == 0) {
Michal Karpinskib7daac22019-03-25 10:12:41 +00003097 s.removeConnection(binder);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003098 }
3099 }
3100 b.connections.remove(c);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003101 c.stopAssociation();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003102 if (c.activity != null && c.activity != skipAct) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07003103 c.activity.removeConnection(c);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003104 }
3105 if (b.client != skipApp) {
3106 b.client.connections.remove(c);
3107 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
3108 b.client.updateHasAboveClientLocked();
3109 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003110 // If this connection requested whitelist management, see if we should
3111 // now clear that state.
3112 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
3113 s.updateWhitelistManager();
3114 if (!s.whitelistManager && s.app != null) {
3115 updateWhitelistManagerLocked(s.app);
3116 }
3117 }
Michal Karpinskie069b002019-03-07 16:15:14 +00003118 // And do the same for bg activity starts whitelisting.
3119 if ((c.flags & Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS) != 0) {
3120 s.updateHasBindingWhitelistingBgActivityStarts();
3121 }
Dianne Hackborndb926082013-10-31 16:32:44 -07003122 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07003123 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07003124 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003125 }
3126 clist = mServiceConnections.get(binder);
3127 if (clist != null) {
3128 clist.remove(c);
3129 if (clist.size() == 0) {
3130 mServiceConnections.remove(binder);
3131 }
3132 }
3133
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003134 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003135 s.appInfo.longVersionCode, s.instanceName, s.processName);
Dianne Hackbornab2df062015-01-07 13:43:13 -08003136
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003137 if (b.connections.size() == 0) {
3138 b.intent.apps.remove(b.client);
3139 }
3140
3141 if (!c.serviceDead) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003142 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003143 + ": shouldUnbind=" + b.intent.hasBound);
3144 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
3145 && b.intent.hasBound) {
3146 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003147 bumpServiceExecutingLocked(s, false, "unbind");
Dianne Hackborndb926082013-10-31 16:32:44 -07003148 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
Dianne Hackbornf097d422017-12-15 16:32:19 -08003149 && s.app.setProcState <= ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
Dianne Hackborndb926082013-10-31 16:32:44 -07003150 // If this service's process is not already in the cached list,
3151 // then update it in the LRU list here because this may be causing
3152 // it to go down there and we want it to start out near the top.
3153 mAm.updateLruProcessLocked(s.app, false, null);
3154 }
Amith Yamasanid2775cd2019-04-12 15:47:54 -07003155 mAm.updateOomAdjLocked(s.app, true,
3156 OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003157 b.intent.hasBound = false;
3158 // Assume the client doesn't want to know about a rebind;
3159 // we will deal with that later if it asks for one.
3160 b.intent.doRebind = false;
3161 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
3162 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003163 Slog.w(TAG, "Exception when unbinding service " + s.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07003164 serviceProcessGoneLocked(s);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003165 }
3166 }
3167
Svet Ganov9c165d72015-12-01 19:52:26 -08003168 // If unbound while waiting to start, remove the pending service
3169 mPendingServices.remove(s);
3170
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003171 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003172 boolean hasAutoCreate = s.hasAutoCreateConnections();
3173 if (!hasAutoCreate) {
3174 if (s.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003175 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003176 SystemClock.uptimeMillis());
3177 }
3178 }
3179 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003180 }
3181 }
3182 }
3183
3184 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003185 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003186 if (r != null) {
Dianne Hackborn455625e2015-01-21 09:55:13 -08003187 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003188 // This is a call from a service start... take care of
3189 // book-keeping.
3190 r.callStart = true;
3191 switch (res) {
3192 case Service.START_STICKY_COMPATIBILITY:
3193 case Service.START_STICKY: {
3194 // We are done with the associated start arguments.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003195 r.findDeliveredStart(startId, false, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003196 // Don't stop if killed.
3197 r.stopIfKilled = false;
3198 break;
3199 }
3200 case Service.START_NOT_STICKY: {
3201 // We are done with the associated start arguments.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003202 r.findDeliveredStart(startId, false, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003203 if (r.getLastStartId() == startId) {
3204 // There is no more work, and this service
3205 // doesn't want to hang around if killed.
3206 r.stopIfKilled = true;
3207 }
3208 break;
3209 }
3210 case Service.START_REDELIVER_INTENT: {
3211 // We'll keep this item until they explicitly
3212 // call stop for it, but keep track of the fact
3213 // that it was delivered.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003214 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003215 if (si != null) {
3216 si.deliveryCount = 0;
3217 si.doneExecutingCount++;
3218 // Don't stop if killed.
3219 r.stopIfKilled = true;
3220 }
3221 break;
3222 }
3223 case Service.START_TASK_REMOVED_COMPLETE: {
3224 // Special processing for onTaskRemoved(). Don't
3225 // impact normal onStartCommand() processing.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003226 r.findDeliveredStart(startId, true, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003227 break;
3228 }
3229 default:
3230 throw new IllegalArgumentException(
3231 "Unknown service start result: " + res);
3232 }
3233 if (res == Service.START_STICKY_COMPATIBILITY) {
3234 r.callStart = false;
3235 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08003236 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
3237 // This is the final call from destroying the service... we should
3238 // actually be getting rid of the service at this point. Do some
3239 // validation of its state, and ensure it will be fully removed.
3240 if (!inDestroying) {
3241 // Not sure what else to do with this... if it is not actually in the
3242 // destroying list, we don't need to make sure to remove it from it.
Amith Yamasanid0418222016-05-10 15:49:51 -07003243 // If the app is null, then it was probably removed because the process died,
3244 // otherwise wtf
3245 if (r.app != null) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07003246 Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
Amith Yamasanid0418222016-05-10 15:49:51 -07003247 + r + ", app=" + r.app);
3248 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08003249 } else if (r.executeNesting != 1) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07003250 Slog.w(TAG, "Service done with onDestroy, but executeNesting="
Dianne Hackborn455625e2015-01-21 09:55:13 -08003251 + r.executeNesting + ": " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003252 // Fake it to keep from ANR due to orphaned entry.
Dianne Hackborn455625e2015-01-21 09:55:13 -08003253 r.executeNesting = 1;
3254 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003255 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003256 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn164371f2013-10-01 19:10:13 -07003257 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003258 Binder.restoreCallingIdentity(origId);
3259 } else {
3260 Slog.w(TAG, "Done executing unknown service from pid "
3261 + Binder.getCallingPid());
3262 }
3263 }
3264
Dianne Hackborn878deb32013-10-14 16:55:09 -07003265 private void serviceProcessGoneLocked(ServiceRecord r) {
3266 if (r.tracker != null) {
3267 int memFactor = mAm.mProcessStats.getMemFactorLocked();
3268 long now = SystemClock.uptimeMillis();
3269 r.tracker.setExecuting(false, memFactor, now);
Christopher Tateaaf2ac42019-05-29 15:52:47 -07003270 r.tracker.setForeground(false, memFactor, now);
Dianne Hackborn878deb32013-10-14 16:55:09 -07003271 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbc72dce2013-11-11 10:43:38 -08003272 r.tracker.setStarted(false, memFactor, now);
Dianne Hackborn878deb32013-10-14 16:55:09 -07003273 }
3274 serviceDoneExecutingLocked(r, true, true);
3275 }
3276
Dianne Hackborn164371f2013-10-01 19:10:13 -07003277 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
3278 boolean finishing) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003279 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003280 + ": nesting=" + r.executeNesting
Dianne Hackborn164371f2013-10-01 19:10:13 -07003281 + ", inDestroying=" + inDestroying + ", app=" + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003282 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003283 "<<< DONE EXECUTING " + r.shortInstanceName);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003284 r.executeNesting--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003285 if (r.executeNesting <= 0) {
3286 if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003287 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003288 "Nesting at 0 of " + r.shortInstanceName);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003289 r.app.execServicesFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003290 r.app.executingServices.remove(r);
3291 if (r.app.executingServices.size() == 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003292 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003293 "No more executingServices of " + r.shortInstanceName);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003294 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003295 } else if (r.executeFg) {
3296 // Need to re-evaluate whether the app still needs to be in the foreground.
3297 for (int i=r.app.executingServices.size()-1; i>=0; i--) {
3298 if (r.app.executingServices.valueAt(i).executeFg) {
3299 r.app.execServicesFg = true;
3300 break;
3301 }
3302 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003303 }
Dianne Hackborn164371f2013-10-01 19:10:13 -07003304 if (inDestroying) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003305 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn164371f2013-10-01 19:10:13 -07003306 "doneExecuting remove destroying " + r);
3307 mDestroyingServices.remove(r);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003308 r.bindings.clear();
3309 }
Amith Yamasanid2775cd2019-04-12 15:47:54 -07003310 mAm.updateOomAdjLocked(r.app, true, OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003311 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003312 r.executeFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003313 if (r.tracker != null) {
Christopher Tateaaf2ac42019-05-29 15:52:47 -07003314 final int memFactor = mAm.mProcessStats.getMemFactorLocked();
3315 final long now = SystemClock.uptimeMillis();
3316 r.tracker.setExecuting(false, memFactor, now);
3317 r.tracker.setForeground(false, memFactor, now);
Dianne Hackborn164371f2013-10-01 19:10:13 -07003318 if (finishing) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07003319 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003320 r.tracker = null;
3321 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003322 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003323 if (finishing) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003324 if (r.app != null && !r.app.isPersistent()) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003325 r.app.services.remove(r);
Michal Karpinskib7daac22019-03-25 10:12:41 +00003326 r.app.updateBoundClientUids();
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003327 if (r.whitelistManager) {
3328 updateWhitelistManagerLocked(r.app);
3329 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003330 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003331 r.setProcess(null);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003332 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003333 }
3334 }
3335
Dianne Hackbornff072722014-09-24 10:56:28 -07003336 boolean attachApplicationLocked(ProcessRecord proc, String processName)
3337 throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003338 boolean didSomething = false;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003339 // Collect any services that are waiting for this process to come up.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003340 if (mPendingServices.size() > 0) {
3341 ServiceRecord sr = null;
3342 try {
3343 for (int i=0; i<mPendingServices.size(); i++) {
3344 sr = mPendingServices.get(i);
3345 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3346 || !processName.equals(sr.processName))) {
3347 continue;
3348 }
3349
3350 mPendingServices.remove(i);
3351 i--;
Patrick Baumannc2def582018-04-04 12:14:15 -07003352 proc.addPackage(sr.appInfo.packageName, sr.appInfo.longVersionCode,
Dianne Hackbornf7097a52014-05-13 09:56:14 -07003353 mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003354 realStartServiceLocked(sr, proc, sr.createdFromFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003355 didSomething = true;
Dianne Hackbornad51be92016-08-16 16:27:36 -07003356 if (!isServiceNeededLocked(sr, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003357 // We were waiting for this service to start, but it is actually no
3358 // longer needed. This could happen because bringDownServiceIfNeeded
3359 // won't bring down a service that is pending... so now the pending
3360 // is done, so let's drop it.
3361 bringDownServiceLocked(sr);
3362 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003363 }
Dianne Hackbornff072722014-09-24 10:56:28 -07003364 } catch (RemoteException e) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003365 Slog.w(TAG, "Exception in new application when starting service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003366 + sr.shortInstanceName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003367 throw e;
3368 }
3369 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003370 // Also, if there are any services that are waiting to restart and
3371 // would run in this process, now is a good time to start them. It would
3372 // be weird to bring up the process but arbitrarily not let the services
3373 // run at this point just because their restart time hasn't come up.
3374 if (mRestartingServices.size() > 0) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003375 ServiceRecord sr;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003376 for (int i=0; i<mRestartingServices.size(); i++) {
3377 sr = mRestartingServices.get(i);
3378 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3379 || !processName.equals(sr.processName))) {
3380 continue;
3381 }
3382 mAm.mHandler.removeCallbacks(sr.restarter);
3383 mAm.mHandler.post(sr.restarter);
3384 }
3385 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003386 return didSomething;
3387 }
3388
3389 void processStartTimedOutLocked(ProcessRecord proc) {
3390 for (int i=0; i<mPendingServices.size(); i++) {
3391 ServiceRecord sr = mPendingServices.get(i);
3392 if ((proc.uid == sr.appInfo.uid
3393 && proc.processName.equals(sr.processName))
3394 || sr.isolatedProc == proc) {
3395 Slog.w(TAG, "Forcing bringing down service: " + sr);
3396 sr.isolatedProc = null;
3397 mPendingServices.remove(i);
3398 i--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003399 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003400 }
3401 }
3402 }
3403
Wale Ogunwale540e1232015-05-01 15:35:39 -07003404 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003405 boolean evenPersistent, boolean doit, ArrayMap<ComponentName, ServiceRecord> services) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003406 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003407 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003408 ServiceRecord service = services.valueAt(i);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003409 final boolean sameComponent = packageName == null
3410 || (service.packageName.equals(packageName)
3411 && (filterByClasses == null
3412 || filterByClasses.contains(service.name.getClassName())));
3413 if (sameComponent
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003414 && (service.app == null || evenPersistent || !service.app.isPersistent())) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003415 if (!doit) {
3416 return true;
3417 }
3418 didSomething = true;
3419 Slog.i(TAG, " Force stopping service " + service);
Riddle Hsuaaef7312019-01-24 19:00:58 +08003420 if (service.app != null && !service.app.isPersistent()) {
3421 service.app.services.remove(service);
Michal Karpinskib7daac22019-03-25 10:12:41 +00003422 service.app.updateBoundClientUids();
Riddle Hsuaaef7312019-01-24 19:00:58 +08003423 if (service.whitelistManager) {
3424 updateWhitelistManagerLocked(service.app);
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08003425 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003426 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003427 service.setProcess(null);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003428 service.isolatedProc = null;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003429 if (mTmpCollectionResults == null) {
3430 mTmpCollectionResults = new ArrayList<>();
3431 }
3432 mTmpCollectionResults.add(service);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003433 }
3434 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003435 return didSomething;
3436 }
3437
Wale Ogunwale540e1232015-05-01 15:35:39 -07003438 boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003439 int userId, boolean evenPersistent, boolean doit) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003440 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003441
3442 if (mTmpCollectionResults != null) {
3443 mTmpCollectionResults.clear();
3444 }
3445
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003446 if (userId == UserHandle.USER_ALL) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003447 for (int i = mServiceMap.size() - 1; i >= 0; i--) {
3448 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003449 evenPersistent, doit, mServiceMap.valueAt(i).mServicesByInstanceName);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003450 if (!doit && didSomething) {
3451 return true;
3452 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003453 if (doit && filterByClasses == null) {
3454 forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId);
3455 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003456 }
3457 } else {
Amith Yamasani540b6592013-10-01 13:02:52 -07003458 ServiceMap smap = mServiceMap.get(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003459 if (smap != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003460 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByInstanceName;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003461 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003462 evenPersistent, doit, items);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003463 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003464 if (doit && filterByClasses == null) {
3465 forceStopPackageLocked(packageName, userId);
3466 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003467 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003468
Wale Ogunwale540e1232015-05-01 15:35:39 -07003469 if (mTmpCollectionResults != null) {
3470 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
3471 bringDownServiceLocked(mTmpCollectionResults.get(i));
3472 }
3473 mTmpCollectionResults.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003474 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003475
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003476 return didSomething;
3477 }
3478
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003479 void forceStopPackageLocked(String packageName, int userId) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003480 ServiceMap smap = mServiceMap.get(userId);
3481 if (smap != null && smap.mActiveForegroundApps.size() > 0) {
Dianne Hackbornaf597682017-05-01 10:54:07 -07003482 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003483 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
3484 if (aa.mPackageName.equals(packageName)) {
3485 smap.mActiveForegroundApps.removeAt(i);
3486 smap.mActiveForegroundAppsChanged = true;
3487 }
3488 }
3489 if (smap.mActiveForegroundAppsChanged) {
3490 requestUpdateActiveForegroundAppsLocked(smap, 0);
3491 }
3492 }
3493 }
3494
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003495 void cleanUpServices(int userId, ComponentName component, Intent baseIntent) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003496 ArrayList<ServiceRecord> services = new ArrayList<>();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003497 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003498 for (int i = alls.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003499 ServiceRecord sr = alls.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003500 if (sr.packageName.equals(component.getPackageName())) {
3501 services.add(sr);
3502 }
3503 }
3504
3505 // Take care of any running services associated with the app.
Wale Ogunwale540e1232015-05-01 15:35:39 -07003506 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003507 ServiceRecord sr = services.get(i);
3508 if (sr.startRequested) {
3509 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003510 Slog.i(TAG, "Stopping service " + sr.shortInstanceName + ": remove task");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003511 stopServiceLocked(sr);
3512 } else {
3513 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003514 sr.getLastStartId(), baseIntent, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003515 if (sr.app != null && sr.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003516 // We always run in the foreground, since this is called as
3517 // part of the "remove task" UI operation.
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003518 try {
3519 sendServiceArgsLocked(sr, true, false);
3520 } catch (TransactionTooLargeException e) {
3521 // Ignore, keep going.
3522 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003523 }
3524 }
3525 }
3526 }
3527 }
3528
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003529 final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003530 // Report disconnected services.
3531 if (false) {
3532 // XXX we are letting the client link to the service for
3533 // death notifications.
3534 if (app.services.size() > 0) {
3535 Iterator<ServiceRecord> it = app.services.iterator();
3536 while (it.hasNext()) {
3537 ServiceRecord r = it.next();
Michal Karpinskib7daac22019-03-25 10:12:41 +00003538 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
3539 for (int conni=connections.size()-1; conni>=0; conni--) {
3540 ArrayList<ConnectionRecord> cl = connections.valueAt(conni);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003541 for (int i=0; i<cl.size(); i++) {
3542 ConnectionRecord c = cl.get(i);
3543 if (c.binding.client != app) {
3544 try {
3545 //c.conn.connected(r.className, null);
3546 } catch (Exception e) {
3547 // todo: this should be asynchronous!
3548 Slog.w(TAG, "Exception thrown disconnected servce "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003549 + r.shortInstanceName
Dianne Hackborn390517b2013-05-30 15:03:32 -07003550 + " from app " + app.processName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003551 }
3552 }
3553 }
3554 }
3555 }
3556 }
3557 }
3558
louis_chang40e259c2015-03-26 13:31:14 +08003559 // Clean up any connections this application has to other services.
3560 for (int i = app.connections.size() - 1; i >= 0; i--) {
3561 ConnectionRecord r = app.connections.valueAt(i);
3562 removeConnectionLocked(r, app, null);
3563 }
3564 updateServiceConnectionActivitiesLocked(app);
3565 app.connections.clear();
3566
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003567 app.whitelistManager = false;
3568
louis_chang40e259c2015-03-26 13:31:14 +08003569 // Clear app state from services.
3570 for (int i = app.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003571 ServiceRecord sr = app.services.valueAt(i);
3572 synchronized (sr.stats.getBatteryStats()) {
3573 sr.stats.stopLaunchedLocked();
3574 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003575 if (sr.app != app && sr.app != null && !sr.app.isPersistent()) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003576 sr.app.services.remove(sr);
Michal Karpinskib7daac22019-03-25 10:12:41 +00003577 sr.app.updateBoundClientUids();
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003578 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003579 sr.setProcess(null);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003580 sr.isolatedProc = null;
3581 sr.executeNesting = 0;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003582 sr.forceClearTracker();
3583 if (mDestroyingServices.remove(sr)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003584 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003585 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003586
Dianne Hackbornc8230512013-07-13 21:32:12 -07003587 final int numClients = sr.bindings.size();
3588 for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
3589 IntentBindRecord b = sr.bindings.valueAt(bindingi);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003590 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
Dianne Hackbornc8230512013-07-13 21:32:12 -07003591 + ": shouldUnbind=" + b.hasBound);
3592 b.binder = null;
3593 b.requested = b.received = b.hasBound = false;
Dianne Hackborn465fa392014-09-14 14:21:18 -07003594 // If this binding is coming from a cached process and is asking to keep
3595 // the service created, then we'll kill the cached process as well -- we
3596 // don't want to be thrashing around restarting processes that are only
3597 // there to be cached.
3598 for (int appi=b.apps.size()-1; appi>=0; appi--) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003599 final ProcessRecord proc = b.apps.keyAt(appi);
3600 // If the process is already gone, skip it.
3601 if (proc.killedByAm || proc.thread == null) {
3602 continue;
3603 }
3604 // Only do this for processes that have an auto-create binding;
3605 // otherwise the binding can be left, because it won't cause the
3606 // service to restart.
3607 final AppBindRecord abind = b.apps.valueAt(appi);
3608 boolean hasCreate = false;
3609 for (int conni=abind.connections.size()-1; conni>=0; conni--) {
3610 ConnectionRecord conn = abind.connections.valueAt(conni);
Dianne Hackborn0fe3c252014-09-19 15:09:39 -07003611 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
3612 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003613 hasCreate = true;
3614 break;
3615 }
3616 }
3617 if (!hasCreate) {
3618 continue;
3619 }
Dianne Hackborncd97c962014-09-25 18:34:02 -07003620 // XXX turned off for now until we have more time to get a better policy.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003621 if (false && proc != null && !proc.isPersistent() && proc.thread != null
Dianne Hackborn465fa392014-09-14 14:21:18 -07003622 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
3623 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003624 proc.kill("bound to service " + sr.shortInstanceName
Dianne Hackborn465fa392014-09-14 14:21:18 -07003625 + " in dying proc " + (app != null ? app.processName : "??"), true);
3626 }
3627 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003628 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003629 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003630
Dianne Hackbornad51be92016-08-16 16:27:36 -07003631 ServiceMap smap = getServiceMapLocked(app.userId);
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003632
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003633 // Now do remaining service cleanup.
3634 for (int i=app.services.size()-1; i>=0; i--) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003635 ServiceRecord sr = app.services.valueAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003636
3637 // Unless the process is persistent, this process record is going away,
3638 // so make sure the service is cleaned out of it.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003639 if (!app.isPersistent()) {
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003640 app.services.removeAt(i);
Michal Karpinskib7daac22019-03-25 10:12:41 +00003641 app.updateBoundClientUids();
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003642 }
3643
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003644 // Sanity check: if the service listed for the app is not one
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003645 // we actually are maintaining, just let it drop.
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003646 final ServiceRecord curRec = smap.mServicesByInstanceName.get(sr.instanceName);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003647 if (curRec != sr) {
3648 if (curRec != null) {
3649 Slog.wtf(TAG, "Service " + sr + " in process " + app
3650 + " not same as in map: " + curRec);
3651 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003652 continue;
3653 }
3654
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003655 // Any services running in the application may need to be placed
3656 // back in the pending list.
Amith Yamasanib0c8a882017-08-28 09:36:42 -07003657 if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
3658 && (sr.serviceInfo.applicationInfo.flags
3659 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003660 Slog.w(TAG, "Service crashed " + sr.crashCount
3661 + " times, stopping: " + sr);
3662 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003663 sr.userId, sr.crashCount, sr.shortInstanceName, app.pid);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003664 bringDownServiceLocked(sr);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003665 } else if (!allowRestart
Fyodor Kupolov1b3edac2017-09-19 15:48:06 -07003666 || !mAm.mUserController.isUserRunning(sr.userId, 0)) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003667 bringDownServiceLocked(sr);
3668 } else {
3669 boolean canceled = scheduleServiceRestartLocked(sr, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003670
Dianne Hackbornc8230512013-07-13 21:32:12 -07003671 // Should the service remain running? Note that in the
3672 // extreme case of so many attempts to deliver a command
3673 // that it failed we also will stop it here.
3674 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
3675 if (sr.pendingStarts.size() == 0) {
3676 sr.startRequested = false;
3677 if (sr.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003678 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackbornc8230512013-07-13 21:32:12 -07003679 SystemClock.uptimeMillis());
3680 }
3681 if (!sr.hasAutoCreateConnections()) {
3682 // Whoops, no reason to restart!
3683 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003684 }
3685 }
3686 }
3687 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003688 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003689
Dianne Hackbornc8230512013-07-13 21:32:12 -07003690 if (!allowRestart) {
3691 app.services.clear();
Michal Karpinskib7daac22019-03-25 10:12:41 +00003692 app.clearBoundClientUids();
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003693
3694 // Make sure there are no more restarting services for this process.
3695 for (int i=mRestartingServices.size()-1; i>=0; i--) {
3696 ServiceRecord r = mRestartingServices.get(i);
3697 if (r.processName.equals(app.processName) &&
3698 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3699 mRestartingServices.remove(i);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08003700 clearRestartingIfNeededLocked(r);
3701 }
3702 }
3703 for (int i=mPendingServices.size()-1; i>=0; i--) {
3704 ServiceRecord r = mPendingServices.get(i);
3705 if (r.processName.equals(app.processName) &&
3706 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3707 mPendingServices.remove(i);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003708 }
3709 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003710 }
3711
3712 // Make sure we have no more records on the stopping list.
Dianne Hackborn164371f2013-10-01 19:10:13 -07003713 int i = mDestroyingServices.size();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003714 while (i > 0) {
3715 i--;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003716 ServiceRecord sr = mDestroyingServices.get(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003717 if (sr.app == app) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003718 sr.forceClearTracker();
3719 mDestroyingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003720 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003721 }
3722 }
3723
3724 app.executingServices.clear();
3725 }
3726
3727 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
3728 ActivityManager.RunningServiceInfo info =
3729 new ActivityManager.RunningServiceInfo();
3730 info.service = r.name;
3731 if (r.app != null) {
3732 info.pid = r.app.pid;
3733 }
3734 info.uid = r.appInfo.uid;
3735 info.process = r.processName;
3736 info.foreground = r.isForeground;
Yi Jin6b514142017-10-30 14:54:12 -07003737 info.activeSince = r.createRealTime;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003738 info.started = r.startRequested;
Michal Karpinskib7daac22019-03-25 10:12:41 +00003739 info.clientCount = r.getConnections().size();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003740 info.crashCount = r.crashCount;
3741 info.lastActivityTime = r.lastActivity;
3742 if (r.isForeground) {
3743 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
3744 }
3745 if (r.startRequested) {
3746 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
3747 }
3748 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
3749 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
3750 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003751 if (r.app != null && r.app.isPersistent()) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003752 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
3753 }
3754
Michal Karpinskib7daac22019-03-25 10:12:41 +00003755 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
3756 for (int conni = connections.size() - 1; conni >= 0; conni--) {
3757 ArrayList<ConnectionRecord> connl = connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003758 for (int i=0; i<connl.size(); i++) {
3759 ConnectionRecord conn = connl.get(i);
3760 if (conn.clientLabel != 0) {
3761 info.clientPackage = conn.binding.client.info.packageName;
3762 info.clientLabel = conn.clientLabel;
3763 return info;
3764 }
3765 }
3766 }
3767 return info;
3768 }
3769
Bryce Lee290e5782017-02-01 16:41:20 -08003770 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags,
Shunta Sato55af6c52016-10-19 15:58:52 +09003771 int callingUid, boolean allowed, boolean canInteractAcrossUsers) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003772 ArrayList<ActivityManager.RunningServiceInfo> res
3773 = new ArrayList<ActivityManager.RunningServiceInfo>();
3774
Dianne Hackborn0c380492012-08-20 17:23:30 -07003775 final long ident = Binder.clearCallingIdentity();
3776 try {
Shunta Sato55af6c52016-10-19 15:58:52 +09003777 if (canInteractAcrossUsers) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003778 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003779 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003780 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003781 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3782 ServiceRecord sr = alls.valueAt(i);
3783 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07003784 }
3785 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003786
Dianne Hackborn0c380492012-08-20 17:23:30 -07003787 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3788 ServiceRecord r = mRestartingServices.get(i);
3789 ActivityManager.RunningServiceInfo info =
3790 makeRunningServiceInfoLocked(r);
3791 info.restarting = r.nextRestartTime;
3792 res.add(info);
3793 }
3794 } else {
Bryce Lee290e5782017-02-01 16:41:20 -08003795 int userId = UserHandle.getUserId(callingUid);
Dianne Hackbornad51be92016-08-16 16:27:36 -07003796 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003797 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3798 ServiceRecord sr = alls.valueAt(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003799
3800 if (allowed || (sr.app != null && sr.app.uid == callingUid)) {
3801 res.add(makeRunningServiceInfoLocked(sr));
3802 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07003803 }
3804
3805 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3806 ServiceRecord r = mRestartingServices.get(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003807 if (r.userId == userId
3808 && (allowed || (r.app != null && r.app.uid == callingUid))) {
Dianne Hackborn0c380492012-08-20 17:23:30 -07003809 ActivityManager.RunningServiceInfo info =
3810 makeRunningServiceInfoLocked(r);
3811 info.restarting = r.nextRestartTime;
3812 res.add(info);
3813 }
3814 }
3815 }
3816 } finally {
3817 Binder.restoreCallingIdentity(ident);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003818 }
3819
3820 return res;
3821 }
3822
3823 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003824 int userId = UserHandle.getUserId(Binder.getCallingUid());
Dianne Hackbornad51be92016-08-16 16:27:36 -07003825 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003826 if (r != null) {
Alan Stokes8473a2c2019-04-29 13:51:18 +01003827 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
Michal Karpinskib7daac22019-03-25 10:12:41 +00003828 for (int conni = connections.size() - 1; conni >= 0; conni--) {
3829 ArrayList<ConnectionRecord> conn = connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003830 for (int i=0; i<conn.size(); i++) {
3831 if (conn.get(i).clientIntent != null) {
3832 return conn.get(i).clientIntent;
3833 }
3834 }
3835 }
3836 }
3837 return null;
3838 }
3839
3840 void serviceTimeout(ProcessRecord proc) {
3841 String anrMessage = null;
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003842 synchronized(mAm) {
Hui Yu8e3e4452019-04-11 10:57:51 -07003843 if (proc.isDebugging()) {
3844 // The app's being debugged, ignore timeout.
3845 return;
3846 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003847 if (proc.executingServices.size() == 0 || proc.thread == null) {
3848 return;
3849 }
Dianne Hackbornab2df062015-01-07 13:43:13 -08003850 final long now = SystemClock.uptimeMillis();
3851 final long maxTime = now -
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003852 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003853 ServiceRecord timeout = null;
3854 long nextTime = 0;
Dianne Hackbornc8230512013-07-13 21:32:12 -07003855 for (int i=proc.executingServices.size()-1; i>=0; i--) {
3856 ServiceRecord sr = proc.executingServices.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003857 if (sr.executingStart < maxTime) {
3858 timeout = sr;
3859 break;
3860 }
3861 if (sr.executingStart > nextTime) {
3862 nextTime = sr.executingStart;
3863 }
3864 }
Amith Yamasani98a00922018-08-21 12:50:30 -04003865 if (timeout != null && mAm.mProcessList.mLruProcesses.contains(proc)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003866 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08003867 StringWriter sw = new StringWriter();
3868 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
3869 pw.println(timeout);
3870 timeout.dump(pw, " ");
3871 pw.close();
3872 mLastAnrDump = sw.toString();
3873 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
3874 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003875 anrMessage = "executing service " + timeout.shortInstanceName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003876 } else {
3877 Message msg = mAm.mHandler.obtainMessage(
3878 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3879 msg.obj = proc;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003880 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
Dianne Hackborn2be00932013-09-22 16:46:00 -07003881 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003882 }
3883 }
3884
3885 if (anrMessage != null) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07003886 proc.appNotResponding(null, null, null, null, false, anrMessage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003887 }
3888 }
3889
Christopher Tate08992ac2017-03-21 11:37:06 -07003890 void serviceForegroundTimeout(ServiceRecord r) {
3891 ProcessRecord app;
3892 synchronized (mAm) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003893 if (!r.fgRequired || r.destroying) {
Christopher Tate08992ac2017-03-21 11:37:06 -07003894 return;
3895 }
3896
Christopher Tate54f51b02018-02-16 11:07:12 -08003897 app = r.app;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07003898 if (app != null && app.isDebugging()) {
Christopher Tate54f51b02018-02-16 11:07:12 -08003899 // The app's being debugged; let it ride
3900 return;
3901 }
3902
Christopher Tate08992ac2017-03-21 11:37:06 -07003903 if (DEBUG_BACKGROUND_CHECK) {
3904 Slog.i(TAG, "Service foreground-required timeout for " + r);
3905 }
Christopher Tate08992ac2017-03-21 11:37:06 -07003906 r.fgWaiting = false;
3907 stopServiceLocked(r);
3908 }
3909
3910 if (app != null) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07003911 app.appNotResponding(null, null, null, null, false,
Kodlee Yin7e951262018-04-05 12:59:56 -07003912 "Context.startForegroundService() did not then call Service.startForeground(): "
3913 + r);
Christopher Tate08992ac2017-03-21 11:37:06 -07003914 }
3915 }
3916
Fyodor Kupolovcc269d92018-05-14 14:20:29 -07003917 public void updateServiceApplicationInfoLocked(ApplicationInfo applicationInfo) {
3918 final int userId = UserHandle.getUserId(applicationInfo.uid);
3919 ServiceMap serviceMap = mServiceMap.get(userId);
3920 if (serviceMap != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003921 ArrayMap<ComponentName, ServiceRecord> servicesByName
3922 = serviceMap.mServicesByInstanceName;
Fyodor Kupolovcc269d92018-05-14 14:20:29 -07003923 for (int j = servicesByName.size() - 1; j >= 0; j--) {
3924 ServiceRecord serviceRecord = servicesByName.valueAt(j);
3925 if (applicationInfo.packageName.equals(serviceRecord.appInfo.packageName)) {
3926 serviceRecord.appInfo = applicationInfo;
3927 serviceRecord.serviceInfo.applicationInfo = applicationInfo;
3928 }
3929 }
3930 }
3931 }
3932
Kodlee Yin7e951262018-04-05 12:59:56 -07003933 void serviceForegroundCrash(ProcessRecord app, CharSequence serviceRecord) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003934 mAm.crashApplication(app.uid, app.pid, app.info.packageName, app.userId,
Kodlee Yin7e951262018-04-05 12:59:56 -07003935 "Context.startForegroundService() did not then call Service.startForeground(): "
3936 + serviceRecord);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003937 }
3938
Dianne Hackborn2be00932013-09-22 16:46:00 -07003939 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
3940 if (proc.executingServices.size() == 0 || proc.thread == null) {
3941 return;
3942 }
Dianne Hackborn2be00932013-09-22 16:46:00 -07003943 Message msg = mAm.mHandler.obtainMessage(
3944 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3945 msg.obj = proc;
Christopher Tate08992ac2017-03-21 11:37:06 -07003946 mAm.mHandler.sendMessageDelayed(msg,
3947 proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
3948 }
3949
3950 void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
3951 if (r.app.executingServices.size() == 0 || r.app.thread == null) {
3952 return;
3953 }
3954 Message msg = mAm.mHandler.obtainMessage(
3955 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG);
3956 msg.obj = r;
3957 r.fgWaiting = true;
3958 mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT);
Dianne Hackborn2be00932013-09-22 16:46:00 -07003959 }
3960
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003961 final class ServiceDumper {
3962 private final FileDescriptor fd;
3963 private final PrintWriter pw;
3964 private final String[] args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003965 private final boolean dumpAll;
3966 private final String dumpPackage;
3967 private final ItemMatcher matcher;
3968 private final ArrayList<ServiceRecord> services = new ArrayList<>();
3969
3970 private final long nowReal = SystemClock.elapsedRealtime();
3971
3972 private boolean needSep = false;
3973 private boolean printedAnything = false;
3974 private boolean printed = false;
3975
3976 /**
3977 * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
3978 * must be called with the lock held).
3979 */
3980 ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
3981 int opti, boolean dumpAll, String dumpPackage) {
3982 this.fd = fd;
3983 this.pw = pw;
3984 this.args = args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003985 this.dumpAll = dumpAll;
3986 this.dumpPackage = dumpPackage;
3987 matcher = new ItemMatcher();
3988 matcher.build(args, opti);
3989
3990 final int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003991 for (int user : users) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003992 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003993 if (smap.mServicesByInstanceName.size() > 0) {
3994 for (int si=0; si<smap.mServicesByInstanceName.size(); si++) {
3995 ServiceRecord r = smap.mServicesByInstanceName.valueAt(si);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003996 if (!matcher.match(r, r.name)) {
3997 continue;
3998 }
3999 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4000 continue;
4001 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004002 services.add(r);
4003 }
4004 }
4005 }
4006 }
4007
4008 private void dumpHeaderLocked() {
4009 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
4010 if (mLastAnrDump != null) {
4011 pw.println(" Last ANR service:");
4012 pw.print(mLastAnrDump);
4013 pw.println();
4014 }
4015 }
4016
4017 void dumpLocked() {
4018 dumpHeaderLocked();
4019
4020 try {
4021 int[] users = mAm.mUserController.getUsers();
4022 for (int user : users) {
4023 // Find the first service for this user.
4024 int serviceIdx = 0;
4025 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
4026 serviceIdx++;
4027 }
4028 printed = false;
4029 if (serviceIdx < services.size()) {
4030 needSep = false;
4031 while (serviceIdx < services.size()) {
4032 ServiceRecord r = services.get(serviceIdx);
4033 serviceIdx++;
4034 if (r.userId != user) {
4035 break;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07004036 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004037 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004038 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004039 needSep |= printed;
4040 }
4041
4042 dumpUserRemainsLocked(user);
4043 }
4044 } catch (Exception e) {
4045 Slog.w(TAG, "Exception in dumpServicesLocked", e);
4046 }
4047
4048 dumpRemainsLocked();
4049 }
4050
4051 void dumpWithClient() {
4052 synchronized(mAm) {
4053 dumpHeaderLocked();
4054 }
4055
4056 try {
4057 int[] users = mAm.mUserController.getUsers();
4058 for (int user : users) {
4059 // Find the first service for this user.
4060 int serviceIdx = 0;
4061 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
4062 serviceIdx++;
4063 }
4064 printed = false;
4065 if (serviceIdx < services.size()) {
4066 needSep = false;
4067 while (serviceIdx < services.size()) {
4068 ServiceRecord r = services.get(serviceIdx);
4069 serviceIdx++;
4070 if (r.userId != user) {
4071 break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004072 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004073 synchronized(mAm) {
4074 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004075 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004076 dumpServiceClient(r);
4077 }
4078 needSep |= printed;
4079 }
4080
4081 synchronized(mAm) {
4082 dumpUserRemainsLocked(user);
4083 }
4084 }
4085 } catch (Exception e) {
4086 Slog.w(TAG, "Exception in dumpServicesLocked", e);
4087 }
4088
4089 synchronized(mAm) {
4090 dumpRemainsLocked();
4091 }
4092 }
4093
4094 private void dumpUserHeaderLocked(int user) {
4095 if (!printed) {
4096 if (printedAnything) {
4097 pw.println();
4098 }
4099 pw.println(" User " + user + " active services:");
4100 printed = true;
4101 }
4102 printedAnything = true;
4103 if (needSep) {
4104 pw.println();
4105 }
4106 }
4107
4108 private void dumpServiceLocalLocked(ServiceRecord r) {
4109 dumpUserHeaderLocked(r.userId);
4110 pw.print(" * ");
4111 pw.println(r);
4112 if (dumpAll) {
4113 r.dump(pw, " ");
4114 needSep = true;
4115 } else {
4116 pw.print(" app=");
4117 pw.println(r.app);
4118 pw.print(" created=");
Yi Jin6b514142017-10-30 14:54:12 -07004119 TimeUtils.formatDuration(r.createRealTime, nowReal, pw);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004120 pw.print(" started=");
4121 pw.print(r.startRequested);
4122 pw.print(" connections=");
Michal Karpinskib7daac22019-03-25 10:12:41 +00004123 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
4124 pw.println(connections.size());
4125 if (connections.size() > 0) {
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004126 pw.println(" Connections:");
Michal Karpinskib7daac22019-03-25 10:12:41 +00004127 for (int conni = 0; conni < connections.size(); conni++) {
4128 ArrayList<ConnectionRecord> clist = connections.valueAt(conni);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004129 for (int i = 0; i < clist.size(); i++) {
4130 ConnectionRecord conn = clist.get(i);
4131 pw.print(" ");
4132 pw.print(conn.binding.intent.intent.getIntent()
4133 .toShortString(false, false, false, false));
4134 pw.print(" -> ");
4135 ProcessRecord proc = conn.binding.client;
4136 pw.println(proc != null ? proc.toShortString() : "null");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004137 }
4138 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004139 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004140 }
4141 }
4142
4143 private void dumpServiceClient(ServiceRecord r) {
4144 final ProcessRecord proc = r.app;
4145 if (proc == null) {
4146 return;
4147 }
4148 final IApplicationThread thread = proc.thread;
4149 if (thread == null) {
4150 return;
4151 }
4152 pw.println(" Client:");
4153 pw.flush();
4154 try {
4155 TransferPipe tp = new TransferPipe();
4156 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004157 thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004158 tp.setBufferPrefix(" ");
4159 // Short timeout, since blocking here can
4160 // deadlock with the application.
4161 tp.go(fd, 2000);
4162 } finally {
4163 tp.kill();
4164 }
4165 } catch (IOException e) {
4166 pw.println(" Failure while dumping the service: " + e);
4167 } catch (RemoteException e) {
4168 pw.println(" Got a RemoteException while dumping the service");
4169 }
4170 needSep = true;
4171 }
4172
4173 private void dumpUserRemainsLocked(int user) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07004174 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004175 printed = false;
4176 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
4177 ServiceRecord r = smap.mDelayedStartList.get(si);
4178 if (!matcher.match(r, r.name)) {
4179 continue;
4180 }
4181 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4182 continue;
4183 }
4184 if (!printed) {
4185 if (printedAnything) {
4186 pw.println();
4187 }
4188 pw.println(" User " + user + " delayed start services:");
4189 printed = true;
4190 }
4191 printedAnything = true;
4192 pw.print(" * Delayed start "); pw.println(r);
4193 }
4194 printed = false;
4195 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
4196 ServiceRecord r = smap.mStartingBackground.get(si);
4197 if (!matcher.match(r, r.name)) {
4198 continue;
4199 }
4200 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4201 continue;
4202 }
4203 if (!printed) {
4204 if (printedAnything) {
4205 pw.println();
4206 }
4207 pw.println(" User " + user + " starting in background:");
4208 printed = true;
4209 }
4210 printedAnything = true;
4211 pw.print(" * Starting bg "); pw.println(r);
4212 }
4213 }
4214
4215 private void dumpRemainsLocked() {
4216 if (mPendingServices.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004217 printed = false;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004218 for (int i=0; i<mPendingServices.size(); i++) {
4219 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004220 if (!matcher.match(r, r.name)) {
4221 continue;
4222 }
4223 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4224 continue;
4225 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004226 printedAnything = true;
4227 if (!printed) {
4228 if (needSep) pw.println();
4229 needSep = true;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004230 pw.println(" Pending services:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004231 printed = true;
4232 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004233 pw.print(" * Pending "); pw.println(r);
4234 r.dump(pw, " ");
4235 }
4236 needSep = true;
4237 }
4238
4239 if (mRestartingServices.size() > 0) {
4240 printed = false;
4241 for (int i=0; i<mRestartingServices.size(); i++) {
4242 ServiceRecord r = mRestartingServices.get(i);
4243 if (!matcher.match(r, r.name)) {
4244 continue;
4245 }
4246 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4247 continue;
4248 }
4249 printedAnything = true;
4250 if (!printed) {
4251 if (needSep) pw.println();
4252 needSep = true;
4253 pw.println(" Restarting services:");
4254 printed = true;
4255 }
4256 pw.print(" * Restarting "); pw.println(r);
4257 r.dump(pw, " ");
4258 }
4259 needSep = true;
4260 }
4261
4262 if (mDestroyingServices.size() > 0) {
4263 printed = false;
4264 for (int i=0; i< mDestroyingServices.size(); i++) {
4265 ServiceRecord r = mDestroyingServices.get(i);
4266 if (!matcher.match(r, r.name)) {
4267 continue;
4268 }
4269 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4270 continue;
4271 }
4272 printedAnything = true;
4273 if (!printed) {
4274 if (needSep) pw.println();
4275 needSep = true;
4276 pw.println(" Destroying services:");
4277 printed = true;
4278 }
4279 pw.print(" * Destroy "); pw.println(r);
4280 r.dump(pw, " ");
4281 }
4282 needSep = true;
4283 }
4284
4285 if (dumpAll) {
4286 printed = false;
4287 for (int ic=0; ic<mServiceConnections.size(); ic++) {
4288 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
4289 for (int i=0; i<r.size(); i++) {
4290 ConnectionRecord cr = r.get(i);
4291 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
4292 continue;
4293 }
4294 if (dumpPackage != null && (cr.binding.client == null
4295 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
4296 continue;
4297 }
4298 printedAnything = true;
4299 if (!printed) {
4300 if (needSep) pw.println();
4301 needSep = true;
4302 pw.println(" Connection bindings to services:");
4303 printed = true;
4304 }
4305 pw.print(" * "); pw.println(cr);
4306 cr.dump(pw, " ");
4307 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004308 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004309 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004310
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004311 if (matcher.all) {
4312 final long nowElapsed = SystemClock.elapsedRealtime();
4313 final int[] users = mAm.mUserController.getUsers();
4314 for (int user : users) {
4315 boolean printedUser = false;
4316 ServiceMap smap = mServiceMap.get(user);
4317 if (smap == null) {
4318 continue;
4319 }
4320 for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) {
4321 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
4322 if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) {
4323 continue;
4324 }
4325 if (!printedUser) {
4326 printedUser = true;
4327 printedAnything = true;
4328 if (needSep) pw.println();
4329 needSep = true;
4330 pw.print("Active foreground apps - user ");
4331 pw.print(user);
4332 pw.println(":");
4333 }
4334 pw.print(" #");
4335 pw.print(i);
4336 pw.print(": ");
4337 pw.println(aa.mPackageName);
4338 if (aa.mLabel != null) {
4339 pw.print(" mLabel=");
4340 pw.println(aa.mLabel);
4341 }
4342 pw.print(" mNumActive=");
4343 pw.print(aa.mNumActive);
Dianne Hackbornbe68d492017-05-03 18:04:05 -07004344 pw.print(" mAppOnTop=");
4345 pw.print(aa.mAppOnTop);
4346 pw.print(" mShownWhileTop=");
4347 pw.print(aa.mShownWhileTop);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004348 pw.print(" mShownWhileScreenOn=");
4349 pw.println(aa.mShownWhileScreenOn);
4350 pw.print(" mStartTime=");
4351 TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw);
4352 pw.print(" mStartVisibleTime=");
4353 TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw);
4354 pw.println();
4355 if (aa.mEndTime != 0) {
4356 pw.print(" mEndTime=");
4357 TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw);
4358 pw.println();
4359 }
4360 }
Dianne Hackborncb015632017-06-14 17:30:15 -07004361 if (smap.hasMessagesOrCallbacks()) {
4362 if (needSep) {
4363 pw.println();
4364 }
4365 printedAnything = true;
4366 needSep = true;
4367 pw.print(" Handler - user ");
4368 pw.print(user);
4369 pw.println(":");
4370 smap.dumpMine(new PrintWriterPrinter(pw), " ");
4371 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004372 }
4373 }
4374
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004375 if (!printedAnything) {
4376 pw.println(" (nothing)");
4377 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07004378 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004379 }
4380
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004381 ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4382 int opti, boolean dumpAll, String dumpPackage) {
4383 return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
4384 }
4385
Yi Jin2b30f322018-02-20 15:41:47 -08004386 protected void writeToProto(ProtoOutputStream proto, long fieldId) {
Yi Jin6b514142017-10-30 14:54:12 -07004387 synchronized (mAm) {
Yi Jin2b30f322018-02-20 15:41:47 -08004388 final long outterToken = proto.start(fieldId);
Yi Jin6b514142017-10-30 14:54:12 -07004389 int[] users = mAm.mUserController.getUsers();
4390 for (int user : users) {
4391 ServiceMap smap = mServiceMap.get(user);
4392 if (smap == null) {
4393 continue;
4394 }
4395 long token = proto.start(ActiveServicesProto.SERVICES_BY_USERS);
4396 proto.write(ActiveServicesProto.ServicesByUser.USER_ID, user);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004397 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
Yi Jin6b514142017-10-30 14:54:12 -07004398 for (int i=0; i<alls.size(); i++) {
4399 alls.valueAt(i).writeToProto(proto,
4400 ActiveServicesProto.ServicesByUser.SERVICE_RECORDS);
4401 }
4402 proto.end(token);
4403 }
Yi Jin2b30f322018-02-20 15:41:47 -08004404 proto.end(outterToken);
Yi Jin6b514142017-10-30 14:54:12 -07004405 }
4406 }
4407
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004408 /**
4409 * There are three ways to call this:
4410 * - no service specified: dump all the services
4411 * - a flattened component name that matched an existing service was specified as the
4412 * first arg: dump that one service
4413 * - the first arg isn't the flattened component name of an existing service:
4414 * dump all services whose component contains the first arg as a substring
4415 */
Makoto Onuki0b575a32018-04-16 14:33:59 -07004416 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, final String name,
4417 String[] args, int opti, boolean dumpAll) {
4418 final ArrayList<ServiceRecord> services = new ArrayList<>();
4419
4420 final Predicate<ServiceRecord> filter = DumpUtils.filterRecord(name);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004421
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004422 synchronized (mAm) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07004423 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004424
Makoto Onuki0b575a32018-04-16 14:33:59 -07004425 for (int user : users) {
4426 ServiceMap smap = mServiceMap.get(user);
4427 if (smap == null) {
4428 continue;
4429 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004430 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
Makoto Onuki0b575a32018-04-16 14:33:59 -07004431 for (int i=0; i<alls.size(); i++) {
4432 ServiceRecord r1 = alls.valueAt(i);
4433
4434 if (filter.test(r1)) {
4435 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004436 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004437 }
4438 }
4439 }
4440
4441 if (services.size() <= 0) {
4442 return false;
4443 }
4444
Makoto Onuki0b575a32018-04-16 14:33:59 -07004445 // Sort by component name.
4446 services.sort(Comparator.comparing(WithComponentName::getComponentName));
4447
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004448 boolean needSep = false;
4449 for (int i=0; i<services.size(); i++) {
4450 if (needSep) {
4451 pw.println();
4452 }
4453 needSep = true;
4454 dumpService("", fd, pw, services.get(i), args, dumpAll);
4455 }
4456 return true;
4457 }
4458
4459 /**
4460 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
4461 * there is a thread associated with the service.
4462 */
4463 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
4464 final ServiceRecord r, String[] args, boolean dumpAll) {
4465 String innerPrefix = prefix + " ";
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004466 synchronized (mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004467 pw.print(prefix); pw.print("SERVICE ");
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004468 pw.print(r.shortInstanceName); pw.print(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004469 pw.print(Integer.toHexString(System.identityHashCode(r)));
4470 pw.print(" pid=");
4471 if (r.app != null) pw.println(r.app.pid);
4472 else pw.println("(not running)");
4473 if (dumpAll) {
4474 r.dump(pw, innerPrefix);
4475 }
4476 }
4477 if (r.app != null && r.app.thread != null) {
4478 pw.print(prefix); pw.println(" Client:");
4479 pw.flush();
4480 try {
4481 TransferPipe tp = new TransferPipe();
4482 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004483 r.app.thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004484 tp.setBufferPrefix(prefix + " ");
4485 tp.go(fd);
4486 } finally {
4487 tp.kill();
4488 }
4489 } catch (IOException e) {
4490 pw.println(prefix + " Failure while dumping the service: " + e);
4491 } catch (RemoteException e) {
4492 pw.println(prefix + " Got a RemoteException while dumping the service");
4493 }
4494 }
4495 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004496}