blob: d95604e91ca31e2a7ae295ad027e32a85adcf013 [file] [log] [blame]
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Bryce Lee290e5782017-02-01 16:41:20 -080019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwaled57969f2014-11-15 19:37:29 -080020
Hui Yue361a232018-10-04 15:05:21 -070021import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK;
22import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOREGROUND_SERVICE;
23import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
24import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
25import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE;
26import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE_EXECUTING;
27import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
28import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE;
29import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE_EXECUTING;
30import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
31import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070032
Hui Yue361a232018-10-04 15:05:21 -070033import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070034import android.app.ActivityManagerInternal;
Dianne Hackborn455625e2015-01-21 09:55:13 -080035import android.app.ActivityThread;
Hui Yue361a232018-10-04 15:05:21 -070036import android.app.AppGlobals;
Svet Ganov99b60432015-06-27 13:15:22 -070037import android.app.AppOpsManager;
Hui Yue361a232018-10-04 15:05:21 -070038import android.app.IApplicationThread;
39import android.app.IServiceConnection;
40import android.app.Notification;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070041import android.app.NotificationManager;
Hui Yue361a232018-10-04 15:05:21 -070042import android.app.PendingIntent;
43import android.app.Service;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070044import android.app.ServiceStartArgs;
Hui Yue361a232018-10-04 15:05:21 -070045import android.content.ComponentName;
Makoto Onuki0b575a32018-04-16 14:33:59 -070046import android.content.ComponentName.WithComponentName;
Hui Yue361a232018-10-04 15:05:21 -070047import android.content.Context;
Svet Ganov9c165d72015-12-01 19:52:26 -080048import android.content.IIntentSender;
Hui Yue361a232018-10-04 15:05:21 -070049import android.content.Intent;
Svet Ganov9c165d72015-12-01 19:52:26 -080050import android.content.IntentSender;
Hui Yue361a232018-10-04 15:05:21 -070051import android.content.pm.ApplicationInfo;
52import android.content.pm.PackageManager;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070053import android.content.pm.ParceledListSlice;
Hui Yue361a232018-10-04 15:05:21 -070054import android.content.pm.ResolveInfo;
55import android.content.pm.ServiceInfo;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070056import android.net.Uri;
Hui Yue361a232018-10-04 15:05:21 -070057import android.os.Binder;
Christoph Studer365e4c32014-09-18 20:35:36 +020058import android.os.Build;
Svet Ganov9c165d72015-12-01 19:52:26 -080059import android.os.Bundle;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -070060import android.os.DeadObjectException;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070061import android.os.Handler;
Hui Yue361a232018-10-04 15:05:21 -070062import android.os.IBinder;
Dianne Hackborn13c590d2013-10-07 14:32:00 -070063import android.os.Looper;
Hui Yue361a232018-10-04 15:05:21 -070064import android.os.Message;
65import android.os.Process;
Svet Ganov9c165d72015-12-01 19:52:26 -080066import android.os.RemoteCallback;
Hui Yue361a232018-10-04 15:05:21 -070067import android.os.RemoteException;
68import android.os.SystemClock;
Dianne Hackborn23037412013-11-04 18:11:29 -080069import android.os.SystemProperties;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -070070import android.os.TransactionTooLargeException;
Hui Yue361a232018-10-04 15:05:21 -070071import android.os.UserHandle;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070072import android.provider.Settings;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070073import android.util.ArrayMap;
Dianne Hackborn465fa392014-09-14 14:21:18 -070074import android.util.ArraySet;
Hui Yue361a232018-10-04 15:05:21 -070075import android.util.EventLog;
76import android.util.PrintWriterPrinter;
77import android.util.Slog;
78import android.util.SparseArray;
79import android.util.StatsLog;
80import android.util.TimeUtils;
81import android.util.proto.ProtoOutputStream;
82import android.webkit.WebViewZygote;
Wale Ogunwaled57969f2014-11-15 19:37:29 -080083
Dianne Hackborn83b40f62017-04-26 13:59:47 -070084import com.android.internal.R;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070085import com.android.internal.app.procstats.ServiceState;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070086import com.android.internal.messages.nano.SystemMessageProto;
87import com.android.internal.notification.SystemNotificationChannels;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070088import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborncbfd23e2013-06-11 14:26:53 -070089import com.android.internal.os.TransferPipe;
Makoto Onuki0b575a32018-04-16 14:33:59 -070090import com.android.internal.util.DumpUtils;
Dianne Hackborncff1bbf2015-01-20 13:43:32 -080091import com.android.internal.util.FastPrintWriter;
Christopher Tatec7933ac2018-03-12 17:57:09 -070092import com.android.server.AppStateTracker;
93import com.android.server.LocalServices;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -070094import com.android.server.SystemService;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070095import com.android.server.am.ActivityManagerService.ItemMatcher;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -070096import com.android.server.uri.NeededUriGrants;
Wale Ogunwale59507092018-10-29 09:00:30 -070097import com.android.server.wm.ActivityServiceConnectionsHolder;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070098
Hui Yue361a232018-10-04 15:05:21 -070099import java.io.FileDescriptor;
100import java.io.IOException;
101import java.io.PrintWriter;
102import java.io.StringWriter;
103import java.util.ArrayList;
104import java.util.Comparator;
105import java.util.Iterator;
106import java.util.List;
107import java.util.Set;
108import java.util.function.Predicate;
109
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -0700110public final class ActiveServices {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800111 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM;
112 private static final String TAG_MU = TAG + POSTFIX_MU;
113 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
114 private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING;
115
116 private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE;
117 private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE;
118
119 private static final boolean LOG_SERVICE_START_STOP = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700120
Dianne Hackborn070d1422018-05-02 13:48:30 -0700121 private static final boolean SHOW_DUNGEON_NOTIFICATION = false;
122
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700123 // How long we wait for a service to finish executing.
124 static final int SERVICE_TIMEOUT = 20*1000;
125
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700126 // How long we wait for a service to finish executing.
127 static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
128
Christopher Tate08992ac2017-03-21 11:37:06 -0700129 // How long the startForegroundService() grace period is to get around to
130 // calling startForeground() before we ANR + stop it.
Christopher Tate5e5c3452018-05-25 13:12:12 -0700131 static final int SERVICE_START_FOREGROUND_TIMEOUT = 10*1000;
Christopher Tate08992ac2017-03-21 11:37:06 -0700132
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000133 // For how long after a whitelisted service's start its process can start a background activity
134 private static final int SERVICE_BG_ACTIVITY_START_TIMEOUT_MS = 10*1000;
135
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700136 final ActivityManagerService mAm;
137
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700138 // Maximum number of services that we allow to start in the background
139 // at the same time.
140 final int mMaxStartingBackground;
141
Wale Ogunwale540e1232015-05-01 15:35:39 -0700142 final SparseArray<ServiceMap> mServiceMap = new SparseArray<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700143
144 /**
145 * All currently bound service connections. Keys are the IBinder of
146 * the client's IServiceConnection.
147 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700148 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700149
150 /**
151 * List of services that we have been asked to start,
152 * but haven't yet been able to. It is used to hold start requests
153 * while waiting for their corresponding application thread to get
154 * going.
155 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700156 final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700157
158 /**
159 * List of services that are scheduled to restart following a crash.
160 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700161 final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700162
163 /**
Dianne Hackborn164371f2013-10-01 19:10:13 -0700164 * List of services that are in the process of being destroyed.
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700165 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700166 final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>();
167
168 /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */
169 private ArrayList<ServiceRecord> mTmpCollectionResults = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700170
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700171 /**
172 * For keeping ActiveForegroundApps retaining state while the screen is off.
173 */
174 boolean mScreenOn = true;
175
Dianne Hackborncff1bbf2015-01-20 13:43:32 -0800176 /** Amount of time to allow a last ANR message to exist before freeing the memory. */
177 static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
178
179 String mLastAnrDump;
180
181 final Runnable mLastAnrDumpClearer = new Runnable() {
182 @Override public void run() {
183 synchronized (mAm) {
184 mLastAnrDump = null;
185 }
186 }
187 };
188
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700189 /**
Christopher Tatec7933ac2018-03-12 17:57:09 -0700190 * Watch for apps being put into forced app standby, so we can step their fg
191 * services down.
192 */
193 class ForcedStandbyListener extends AppStateTracker.Listener {
194 @Override
195 public void stopForegroundServicesForUidPackage(final int uid, final String packageName) {
196 synchronized (mAm) {
197 final ServiceMap smap = getServiceMapLocked(UserHandle.getUserId(uid));
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800198 final int N = smap.mServicesByInstanceName.size();
Christopher Tatec7933ac2018-03-12 17:57:09 -0700199 final ArrayList<ServiceRecord> toStop = new ArrayList<>(N);
200 for (int i = 0; i < N; i++) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800201 final ServiceRecord r = smap.mServicesByInstanceName.valueAt(i);
Christopher Tatec7933ac2018-03-12 17:57:09 -0700202 if (uid == r.serviceInfo.applicationInfo.uid
203 || packageName.equals(r.serviceInfo.packageName)) {
204 if (r.isForeground) {
205 toStop.add(r);
206 }
207 }
208 }
209
210 // Now stop them all
211 final int numToStop = toStop.size();
212 if (numToStop > 0 && DEBUG_FOREGROUND_SERVICE) {
213 Slog.i(TAG, "Package " + packageName + "/" + uid
214 + " entering FAS with foreground services");
215 }
216 for (int i = 0; i < numToStop; i++) {
217 final ServiceRecord r = toStop.get(i);
218 if (DEBUG_FOREGROUND_SERVICE) {
219 Slog.i(TAG, " Stopping fg for service " + r);
220 }
221 setServiceForegroundInnerLocked(r, 0, null, 0);
222 }
223 }
224 }
225 }
226
227 /**
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700228 * Information about an app that is currently running one or more foreground services.
Dan Sandler2f36ab82017-05-25 00:15:49 -0400229 * (This maps directly to the running apps we show in the notification.)
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700230 */
231 static final class ActiveForegroundApp {
232 String mPackageName;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700233 int mUid;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700234 CharSequence mLabel;
235 boolean mShownWhileScreenOn;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700236 boolean mAppOnTop;
237 boolean mShownWhileTop;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700238 long mStartTime;
239 long mStartVisibleTime;
240 long mEndTime;
241 int mNumActive;
Dianne Hackborncb015632017-06-14 17:30:15 -0700242
243 // Temp output of foregroundAppShownEnoughLocked
244 long mHideTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700245 }
246
247 /**
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700248 * Information about services for a single user.
249 */
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700250 final class ServiceMap extends Handler {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700251 final int mUserId;
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800252 final ArrayMap<ComponentName, ServiceRecord> mServicesByInstanceName = new ArrayMap<>();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700253 final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700254
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700255 final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700256 /* XXX eventually I'd like to have this based on processes instead of services.
257 * That is, if we try to start two services in a row both running in the same
258 * process, this should be one entry in mStartingBackground for that one process
259 * that remains until all services in it are done.
260 final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
261 = new ArrayMap<ProcessRecord, DelayingProcess>();
262 final ArrayList<DelayingProcess> mStartingProcessList
263 = new ArrayList<DelayingProcess>();
264 */
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700265
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700266 final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700267
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700268 final ArrayMap<String, ActiveForegroundApp> mActiveForegroundApps = new ArrayMap<>();
269 boolean mActiveForegroundAppsChanged;
270
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700271 static final int MSG_BG_START_TIMEOUT = 1;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700272 static final int MSG_UPDATE_FOREGROUND_APPS = 2;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700273
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700274 ServiceMap(Looper looper, int userId) {
275 super(looper);
Dianne Hackborn6285a322013-09-18 12:09:47 -0700276 mUserId = userId;
277 }
278
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700279 @Override
280 public void handleMessage(Message msg) {
281 switch (msg.what) {
282 case MSG_BG_START_TIMEOUT: {
283 synchronized (mAm) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700284 rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700285 }
286 } break;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700287 case MSG_UPDATE_FOREGROUND_APPS: {
288 updateForegroundApps(this);
289 } break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700290 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700291 }
292
Dianne Hackbornad51be92016-08-16 16:27:36 -0700293 void ensureNotStartingBackgroundLocked(ServiceRecord r) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700294 if (mStartingBackground.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800295 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
296 "No longer background starting: " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -0700297 rescheduleDelayedStartsLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700298 }
Dianne Hackborn2e46bb52013-09-13 17:01:26 -0700299 if (mDelayedStartList.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800300 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700301 }
302 }
303
Dianne Hackbornad51be92016-08-16 16:27:36 -0700304 void rescheduleDelayedStartsLocked() {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700305 removeMessages(MSG_BG_START_TIMEOUT);
306 final long now = SystemClock.uptimeMillis();
307 for (int i=0, N=mStartingBackground.size(); i<N; i++) {
308 ServiceRecord r = mStartingBackground.get(i);
309 if (r.startingBgTimeout <= now) {
310 Slog.i(TAG, "Waited long enough for: " + r);
311 mStartingBackground.remove(i);
312 N--;
Junu Kimfcb87362014-02-19 16:25:21 +0900313 i--;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700314 }
315 }
316 while (mDelayedStartList.size() > 0
317 && mStartingBackground.size() < mMaxStartingBackground) {
318 ServiceRecord r = mDelayedStartList.remove(0);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800319 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
320 "REM FR DELAY LIST (exec next): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700321 if (r.pendingStarts.size() <= 0) {
322 Slog.w(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
323 + " delayedStop=" + r.delayedStop);
324 }
325 if (DEBUG_DELAYED_SERVICE) {
326 if (mDelayedStartList.size() > 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800327 Slog.v(TAG_SERVICE, "Remaining delayed list:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700328 for (int i=0; i<mDelayedStartList.size(); i++) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800329 Slog.v(TAG_SERVICE, " #" + i + ": " + mDelayedStartList.get(i));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700330 }
331 }
332 }
333 r.delayed = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700334 try {
335 startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false, true);
336 } catch (TransactionTooLargeException e) {
337 // Ignore, nobody upstack cares.
338 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700339 }
340 if (mStartingBackground.size() > 0) {
341 ServiceRecord next = mStartingBackground.get(0);
342 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800343 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700344 + ", can delay others up to " + when);
345 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
346 sendMessageAtTime(msg, when);
347 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700348 if (mStartingBackground.size() < mMaxStartingBackground) {
349 mAm.backgroundServicesFinishedLocked(mUserId);
350 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700351 }
352 }
353
354 public ActiveServices(ActivityManagerService service) {
355 mAm = service;
Dianne Hackborn23037412013-11-04 18:11:29 -0800356 int maxBg = 0;
357 try {
358 maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
359 } catch(RuntimeException e) {
360 }
Dianne Hackborn20d94742014-05-29 18:35:45 -0700361 mMaxStartingBackground = maxBg > 0
362 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700363 }
364
Christopher Tatec7933ac2018-03-12 17:57:09 -0700365 void systemServicesReady() {
366 AppStateTracker ast = LocalServices.getService(AppStateTracker.class);
367 ast.addListener(new ForcedStandbyListener());
368 }
369
Dianne Hackbornad51be92016-08-16 16:27:36 -0700370 ServiceRecord getServiceByNameLocked(ComponentName name, int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700371 // TODO: Deal with global services
372 if (DEBUG_MU)
Dianne Hackbornad51be92016-08-16 16:27:36 -0700373 Slog.v(TAG_MU, "getServiceByNameLocked(" + name + "), callingUser = " + callingUser);
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800374 return getServiceMapLocked(callingUser).mServicesByInstanceName.get(name);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700375 }
376
Dianne Hackbornad51be92016-08-16 16:27:36 -0700377 boolean hasBackgroundServicesLocked(int callingUser) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700378 ServiceMap smap = mServiceMap.get(callingUser);
379 return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
380 }
381
Dianne Hackbornad51be92016-08-16 16:27:36 -0700382 private ServiceMap getServiceMapLocked(int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700383 ServiceMap smap = mServiceMap.get(callingUser);
384 if (smap == null) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700385 smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700386 mServiceMap.put(callingUser, smap);
387 }
388 return smap;
389 }
390
Dianne Hackbornad51be92016-08-16 16:27:36 -0700391 ArrayMap<ComponentName, ServiceRecord> getServicesLocked(int callingUser) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800392 return getServiceMapLocked(callingUser).mServicesByInstanceName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700393 }
394
Christopher Tatec7933ac2018-03-12 17:57:09 -0700395 private boolean appRestrictedAnyInBackground(final int uid, final String packageName) {
396 final int mode = mAm.mAppOpsService.checkOperation(
397 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, uid, packageName);
398 return (mode != AppOpsManager.MODE_ALLOWED);
399 }
400
Svet Ganov99b60432015-06-27 13:15:22 -0700401 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
Christopher Tate242ba3e92017-04-14 15:07:06 -0700402 int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700403 throws TransactionTooLargeException {
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000404 return startServiceLocked(caller, service, resolvedType, callingPid, callingUid, fgRequired,
405 callingPackage, userId, false);
406 }
407
408 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
409 int callingPid, int callingUid, boolean fgRequired, String callingPackage,
410 final int userId, boolean allowBackgroundActivityStarts)
411 throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800412 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700413 + " type=" + resolvedType + " args=" + service.getExtras());
414
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700415 final boolean callerFg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700416 if (caller != null) {
417 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
418 if (callerApp == null) {
419 throw new SecurityException(
420 "Unable to find app for caller " + caller
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700421 + " (pid=" + callingPid
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700422 + ") when starting service " + service);
423 }
Dianne Hackborna49ad092016-03-03 13:39:10 -0800424 callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700425 } else {
426 callerFg = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700427 }
428
429 ServiceLookupResult res =
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800430 retrieveServiceLocked(service, null, resolvedType, callingPackage,
Svet Ganovd223db32017-12-22 09:43:48 -0800431 callingPid, callingUid, userId, true, callerFg, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700432 if (res == null) {
433 return null;
434 }
435 if (res.record == null) {
436 return new ComponentName("!", res.permission != null
437 ? res.permission : "private to package");
438 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700439
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700440 ServiceRecord r = res.record;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700441
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700442 if (!mAm.mUserController.exists(r.userId)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700443 Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700444 return null;
445 }
446
Christopher Tate85048282018-03-30 14:08:59 -0700447 // If we're starting indirectly (e.g. from PendingIntent), figure out whether
Christopher Tate45f06c792018-04-25 10:47:23 -0700448 // we're launching into an app in a background state. This keys off of the same
449 // idleness state tracking as e.g. O+ background service start policy.
450 final boolean bgLaunch = !mAm.isUidActiveLocked(r.appInfo.uid);
Christopher Tate85048282018-03-30 14:08:59 -0700451
452 // If the app has strict background restrictions, we treat any bg service
453 // start analogously to the legacy-app forced-restrictions case, regardless
454 // of its target SDK version.
Christopher Tatec7933ac2018-03-12 17:57:09 -0700455 boolean forcedStandby = false;
Christopher Tate85048282018-03-30 14:08:59 -0700456 if (bgLaunch && appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
Christopher Tatec7933ac2018-03-12 17:57:09 -0700457 if (DEBUG_FOREGROUND_SERVICE) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800458 Slog.d(TAG, "Forcing bg-only service start only for " + r.shortInstanceName
Christopher Tate85048282018-03-30 14:08:59 -0700459 + " : bgLaunch=" + bgLaunch + " callerFg=" + callerFg);
Christopher Tatec7933ac2018-03-12 17:57:09 -0700460 }
461 forcedStandby = true;
462 }
463
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700464 // If this is a direct-to-foreground start, make sure it is allowed as per the app op.
465 boolean forceSilentAbort = false;
466 if (fgRequired) {
467 final int mode = mAm.mAppOpsService.checkOperation(
468 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
469 switch (mode) {
470 case AppOpsManager.MODE_ALLOWED:
471 case AppOpsManager.MODE_DEFAULT:
472 // All okay.
473 break;
474 case AppOpsManager.MODE_IGNORED:
475 // Not allowed, fall back to normal start service, failing siliently
476 // if background check restricts that.
477 Slog.w(TAG, "startForegroundService not allowed due to app op: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800478 + service + " to " + r.shortInstanceName
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700479 + " from pid=" + callingPid + " uid=" + callingUid
480 + " pkg=" + callingPackage);
481 fgRequired = false;
482 forceSilentAbort = true;
483 break;
484 default:
485 return new ComponentName("!!", "foreground not allowed as per app op");
486 }
487 }
488
Christopher Tate08992ac2017-03-21 11:37:06 -0700489 // If this isn't a direct-to-foreground start, check our ability to kick off an
490 // arbitrary service
Christopher Tatec7933ac2018-03-12 17:57:09 -0700491 if (forcedStandby || (!r.startRequested && !fgRequired)) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700492 // Before going further -- if this app is not allowed to start services in the
493 // background, then at this point we aren't going to let it period.
494 final int allowed = mAm.getAppStartModeLocked(r.appInfo.uid, r.packageName,
Christopher Tatec7933ac2018-03-12 17:57:09 -0700495 r.appInfo.targetSdkVersion, callingPid, false, false, forcedStandby);
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700496 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
497 Slog.w(TAG, "Background start not allowed: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800498 + service + " to " + r.shortInstanceName
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700499 + " from pid=" + callingPid + " uid=" + callingUid
Christopher Tatee84ffd92018-05-16 12:59:43 -0700500 + " pkg=" + callingPackage + " startFg?=" + fgRequired);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700501 if (allowed == ActivityManager.APP_START_MODE_DELAYED || forceSilentAbort) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700502 // In this case we are silently disabling the app, to disrupt as
503 // little as possible existing apps.
504 return null;
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700505 }
Christopher Tatee84ffd92018-05-16 12:59:43 -0700506 if (forcedStandby) {
507 // This is an O+ app, but we might be here because the user has placed
508 // it under strict background restrictions. Don't punish the app if it's
509 // trying to do the right thing but we're denying it for that reason.
510 if (fgRequired) {
511 if (DEBUG_BACKGROUND_CHECK) {
512 Slog.v(TAG, "Silently dropping foreground service launch due to FAS");
513 }
514 return null;
515 }
516 }
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700517 // This app knows it is in the new model where this operation is not
518 // allowed, so tell it what has happened.
Amith Yamasaniaa746442019-01-10 10:09:12 -0800519 UidRecord uidRec = mAm.mProcessList.getUidRecordLocked(r.appInfo.uid);
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700520 return new ComponentName("?", "app is in background uid " + uidRec);
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700521 }
522 }
523
Christopher Tate0a826902018-05-25 15:15:44 -0700524 // At this point we've applied allowed-to-start policy based on whether this was
525 // an ordinary startService() or a startForegroundService(). Now, only require that
526 // the app follow through on the startForegroundService() -> startForeground()
527 // contract if it actually targets O+.
528 if (r.appInfo.targetSdkVersion < Build.VERSION_CODES.O && fgRequired) {
529 if (DEBUG_BACKGROUND_CHECK || DEBUG_FOREGROUND_SERVICE) {
530 Slog.i(TAG, "startForegroundService() but host targets "
531 + r.appInfo.targetSdkVersion + " - not requiring startForeground()");
532 }
533 fgRequired = false;
534 }
535
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700536 NeededUriGrants neededGrants = mAm.mUgmInternal.checkGrantUriPermissionFromIntent(
Nicolas Prevotc6cf95c2014-05-29 11:30:36 +0100537 callingUid, r.packageName, service, service.getFlags(), null, r.userId);
Svet Ganov9c165d72015-12-01 19:52:26 -0800538
539 // If permissions need a review before any of the app components can run,
540 // we do not start the service and launch a review activity if the calling app
541 // is in the foreground passing it a pending intent to start the service when
542 // review is completed.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700543
544 // XXX This is not dealing with fgRequired!
545 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage,
546 callingUid, service, callerFg, userId)) {
547 return null;
Svet Ganov9c165d72015-12-01 19:52:26 -0800548 }
549
Dianne Hackbornd6f5b622013-11-11 17:25:37 -0800550 if (unscheduleServiceRestartLocked(r, callingUid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800551 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700552 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700553 r.lastActivity = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700554 r.startRequested = true;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700555 r.delayedStop = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700556 r.fgRequired = fgRequired;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700557 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -0700558 service, neededGrants, callingUid));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700559
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700560 if (fgRequired) {
561 // We are now effectively running a foreground service.
Dianne Hackborn2aec55a2018-06-26 10:35:35 -0700562 ServiceState stracker = r.getTracker();
563 if (stracker != null) {
564 stracker.setForeground(true, mAm.mProcessStats.getMemFactorLocked(),
565 r.lastActivity);
566 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700567 mAm.mAppOpsService.startOperation(AppOpsManager.getToken(mAm.mAppOpsService),
568 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, true);
569 }
570
Dianne Hackbornad51be92016-08-16 16:27:36 -0700571 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700572 boolean addToStarting = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700573 if (!callerFg && !fgRequired && r.app == null
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700574 && mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700575 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700576 if (proc == null || proc.getCurProcState() > ActivityManager.PROCESS_STATE_RECEIVER) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700577 // If this is not coming from a foreground caller, then we may want
578 // to delay the start if there are already other background services
579 // that are starting. This is to avoid process start spam when lots
580 // of applications are all handling things like connectivity broadcasts.
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700581 // We only do this for cached processes, because otherwise an application
582 // can have assumptions about calling startService() for a service to run
583 // in its own process, and for that process to not be killed before the
584 // service is started. This is especially the case for receivers, which
585 // may start a service in onReceive() to do some additional work and have
586 // initialized some global state as part of that.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800587 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
588 + r + " in " + proc);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700589 if (r.delayed) {
590 // This service is already scheduled for a delayed start; just leave
591 // it still waiting.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800592 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700593 return r.name;
594 }
595 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
596 // Something else is starting, delay!
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800597 Slog.i(TAG_SERVICE, "Delaying start of: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700598 smap.mDelayedStartList.add(r);
599 r.delayed = true;
600 return r.name;
601 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800602 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700603 addToStarting = true;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700604 } else if (proc.getCurProcState() >= ActivityManager.PROCESS_STATE_SERVICE) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700605 // We slightly loosen when we will enqueue this new service as a background
606 // starting service we are waiting for, to also include processes that are
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700607 // currently running other services or receivers.
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700608 addToStarting = true;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800609 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
610 "Not delaying, but counting as bg: " + r);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800611 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn8e692572013-09-10 19:06:15 -0700612 StringBuilder sb = new StringBuilder(128);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700613 sb.append("Not potential delay (state=").append(proc.getCurProcState())
Dianne Hackborn8e692572013-09-10 19:06:15 -0700614 .append(' ').append(proc.adjType);
615 String reason = proc.makeAdjReason();
616 if (reason != null) {
617 sb.append(' ');
618 sb.append(reason);
619 }
620 sb.append("): ");
621 sb.append(r.toString());
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800622 Slog.v(TAG_SERVICE, sb.toString());
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700623 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800624 } else if (DEBUG_DELAYED_STARTS) {
Christopher Tate08992ac2017-03-21 11:37:06 -0700625 if (callerFg || fgRequired) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800626 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
Christopher Tate08992ac2017-03-21 11:37:06 -0700627 + callingUid + " pid=" + callingPid + " fgRequired=" + fgRequired + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700628 } else if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800629 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700630 } else {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800631 Slog.v(TAG_SERVICE,
632 "Not potential delay (user " + r.userId + " not started): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700633 }
634 }
635
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000636 if (allowBackgroundActivityStarts) {
637 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
638 if (proc != null) {
639 proc.addAllowBackgroundActivityStartsToken(r);
640 // schedule removal of the whitelisting token after the timeout
641 removeAllowBackgroundActivityStartsServiceToken(proc, r,
642 SERVICE_BG_ACTIVITY_START_TIMEOUT_MS);
643 }
644 }
Christopher Tate42a386b2016-11-07 12:21:21 -0800645 ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
Christopher Tate42a386b2016-11-07 12:21:21 -0800646 return cmp;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700647 }
648
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000649 private void removeAllowBackgroundActivityStartsServiceToken(ProcessRecord proc,
650 ServiceRecord r, int delayMillis) {
651 mAm.mHandler.postDelayed(() -> {
652 if (proc != null) {
653 proc.removeAllowBackgroundActivityStartsToken(r);
654 }
655 }, delayMillis);
656 }
657
Svet Ganov9c165d72015-12-01 19:52:26 -0800658 private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
659 String callingPackage, int callingUid, Intent service, boolean callerFg,
660 final int userId) {
661 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
662 r.packageName, r.userId)) {
663
664 // Show a permission review UI only for starting from a foreground app
665 if (!callerFg) {
666 Slog.w(TAG, "u" + r.userId + " Starting a service in package"
667 + r.packageName + " requires a permissions review");
668 return false;
669 }
670
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700671 IIntentSender target = mAm.mPendingIntentController.getIntentSender(
Svet Ganov9c165d72015-12-01 19:52:26 -0800672 ActivityManager.INTENT_SENDER_SERVICE, callingPackage,
673 callingUid, userId, null, null, 0, new Intent[]{service},
674 new String[]{service.resolveType(mAm.mContext.getContentResolver())},
675 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
676 | PendingIntent.FLAG_IMMUTABLE, null);
677
678 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
679 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
Philip P. Moltmann751e46ca2019-01-24 13:56:47 -0800680 | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
Svet Ganov9c165d72015-12-01 19:52:26 -0800681 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
682 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
683 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
684
685 if (DEBUG_PERMISSIONS_REVIEW) {
686 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
687 + r.packageName);
688 }
689
690 mAm.mHandler.post(new Runnable() {
691 @Override
692 public void run() {
693 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
694 }
695 });
696
697 return false;
698 }
699
700 return true;
701 }
702
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700703 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
704 boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
Joe Onorato4eb64fd2016-03-21 15:30:09 -0700705 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700706 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700707 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700708 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700709 r.callStart = false;
Chenjie Yu75b3c492018-10-06 21:45:19 -0700710 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid, r.name.getPackageName(),
711 r.name.getClassName(), StatsLog.SERVICE_STATE_CHANGED__STATE__START);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700712 synchronized (r.stats.getBatteryStats()) {
713 r.stats.startRunningLocked();
714 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800715 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700716 if (error != null) {
717 return new ComponentName("!!", error);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700718 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700719
720 if (r.startRequested && addToStarting) {
721 boolean first = smap.mStartingBackground.size() == 0;
722 smap.mStartingBackground.add(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700723 r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700724 if (DEBUG_DELAYED_SERVICE) {
725 RuntimeException here = new RuntimeException("here");
726 here.fillInStackTrace();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800727 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800728 } else if (DEBUG_DELAYED_STARTS) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800729 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700730 }
731 if (first) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700732 smap.rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700733 }
Christopher Tate08992ac2017-03-21 11:37:06 -0700734 } else if (callerFg || r.fgRequired) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700735 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700736 }
737
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700738 return r.name;
739 }
740
741 private void stopServiceLocked(ServiceRecord service) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700742 if (service.delayed) {
Mohammad Samiul Islame896c212019-01-10 12:14:23 +0000743 // If service isn't actually running, but is being held in the
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700744 // delayed list, then we need to keep it started but note that it
745 // should be stopped once no longer delayed.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800746 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700747 service.delayedStop = true;
748 return;
749 }
Chenjie Yu75b3c492018-10-06 21:45:19 -0700750 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, service.appInfo.uid,
751 service.name.getPackageName(), service.name.getClassName(),
752 StatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700753 synchronized (service.stats.getBatteryStats()) {
754 service.stats.stopRunningLocked();
755 }
756 service.startRequested = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700757 if (service.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700758 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700759 SystemClock.uptimeMillis());
760 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700761 service.callStart = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700762 bringDownServiceIfNeededLocked(service, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700763 }
764
765 int stopServiceLocked(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700766 String resolvedType, int userId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800767 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700768 + " type=" + resolvedType);
769
770 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
771 if (caller != null && callerApp == null) {
772 throw new SecurityException(
773 "Unable to find app for caller " + caller
774 + " (pid=" + Binder.getCallingPid()
775 + ") when stopping service " + service);
776 }
777
778 // If this service is active, make sure it is stopped.
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800779 ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, null,
Svet Ganovd223db32017-12-22 09:43:48 -0800780 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700781 if (r != null) {
782 if (r.record != null) {
783 final long origId = Binder.clearCallingIdentity();
784 try {
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000785 // immediately remove bg activity whitelisting token if there was one
786 removeAllowBackgroundActivityStartsServiceToken(callerApp, r.record,
787 0 /* delayMillis */);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700788 stopServiceLocked(r.record);
789 } finally {
790 Binder.restoreCallingIdentity(origId);
791 }
792 return 1;
793 }
794 return -1;
795 }
796
797 return 0;
798 }
799
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700800 void stopInBackgroundLocked(int uid) {
801 // Stop all services associated with this uid due to it going to the background
802 // stopped state.
803 ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
804 ArrayList<ServiceRecord> stopping = null;
805 if (services != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800806 for (int i = services.mServicesByInstanceName.size() - 1; i >= 0; i--) {
807 ServiceRecord service = services.mServicesByInstanceName.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700808 if (service.appInfo.uid == uid && service.startRequested) {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800809 if (mAm.getAppStartModeLocked(service.appInfo.uid, service.packageName,
Christopher Tatec7933ac2018-03-12 17:57:09 -0700810 service.appInfo.targetSdkVersion, -1, false, false, false)
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800811 != ActivityManager.APP_START_MODE_NORMAL) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700812 if (stopping == null) {
813 stopping = new ArrayList<>();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700814 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800815 String compName = service.shortInstanceName;
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700816 EventLogTags.writeAmStopIdleService(service.appInfo.uid, compName);
817 StringBuilder sb = new StringBuilder(64);
818 sb.append("Stopping service due to app idle: ");
819 UserHandle.formatUid(sb, service.appInfo.uid);
820 sb.append(" ");
Yi Jin6b514142017-10-30 14:54:12 -0700821 TimeUtils.formatDuration(service.createRealTime
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700822 - SystemClock.elapsedRealtime(), sb);
823 sb.append(" ");
824 sb.append(compName);
825 Slog.w(TAG, sb.toString());
826 stopping.add(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700827 }
828 }
829 }
830 if (stopping != null) {
831 for (int i=stopping.size()-1; i>=0; i--) {
832 ServiceRecord service = stopping.get(i);
833 service.delayed = false;
Dianne Hackbornad51be92016-08-16 16:27:36 -0700834 services.ensureNotStartingBackgroundLocked(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700835 stopServiceLocked(service);
836 }
837 }
838 }
839 }
840
Svet Ganov99b60432015-06-27 13:15:22 -0700841 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800842 ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, callingPackage,
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -0700843 Binder.getCallingPid(), Binder.getCallingUid(),
Svet Ganovd223db32017-12-22 09:43:48 -0800844 UserHandle.getCallingUserId(), false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700845
846 IBinder ret = null;
847 if (r != null) {
848 // r.record is null if findServiceLocked() failed the caller permission check
849 if (r.record == null) {
850 throw new SecurityException(
Christopher Desjardins5862c5f2015-05-19 11:25:40 +0000851 "Permission Denial: Accessing service"
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700852 + " from pid=" + Binder.getCallingPid()
853 + ", uid=" + Binder.getCallingUid()
854 + " requires " + r.permission);
855 }
856 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
857 if (ib != null) {
858 ret = ib.binder;
859 }
860 }
861
862 return ret;
863 }
864
865 boolean stopServiceTokenLocked(ComponentName className, IBinder token,
866 int startId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800867 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700868 + " " + token + " startId=" + startId);
Dianne Hackborn41203752012-08-31 14:05:51 -0700869 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700870 if (r != null) {
871 if (startId >= 0) {
872 // Asked to only stop if done with all work. Note that
873 // to avoid leaks, we will take this as dropping all
874 // start items up to and including this one.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -0700875 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700876 if (si != null) {
877 while (r.deliveredStarts.size() > 0) {
878 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
879 cur.removeUriPermissionsLocked();
880 if (cur == si) {
881 break;
882 }
883 }
884 }
885
886 if (r.getLastStartId() != startId) {
887 return false;
888 }
889
890 if (r.deliveredStarts.size() > 0) {
891 Slog.w(TAG, "stopServiceToken startId " + startId
892 + " is last, but have " + r.deliveredStarts.size()
893 + " remaining args");
894 }
895 }
896
Chenjie Yu75b3c492018-10-06 21:45:19 -0700897 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid, r.name.getPackageName(),
898 r.name.getClassName(), StatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700899 synchronized (r.stats.getBatteryStats()) {
900 r.stats.stopRunningLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700901 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700902 r.startRequested = false;
903 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700904 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700905 SystemClock.uptimeMillis());
906 }
907 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700908 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700909 bringDownServiceIfNeededLocked(r, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700910 Binder.restoreCallingIdentity(origId);
911 return true;
912 }
913 return false;
914 }
915
Sudheer Shankac9d94072017-02-22 22:13:55 +0000916 public void setServiceForegroundLocked(ComponentName className, IBinder token,
Dianne Hackborn67324c92016-04-18 13:55:25 -0700917 int id, Notification notification, int flags) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700918 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700919 final long origId = Binder.clearCallingIdentity();
920 try {
Dianne Hackborn41203752012-08-31 14:05:51 -0700921 ServiceRecord r = findServiceLocked(className, token, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700922 if (r != null) {
Sudheer Shankac9d94072017-02-22 22:13:55 +0000923 setServiceForegroundInnerLocked(r, id, notification, flags);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700924 }
925 } finally {
926 Binder.restoreCallingIdentity(origId);
927 }
928 }
929
Dianne Hackborncb015632017-06-14 17:30:15 -0700930 boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) {
931 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid="
932 + aa.mUid);
933 boolean canRemove = false;
934 aa.mHideTime = Long.MAX_VALUE;
935 if (aa.mShownWhileTop) {
936 // If the app was ever at the top of the screen while the foreground
937 // service was running, then we can always just immediately remove it.
938 canRemove = true;
939 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown while on top");
940 } else if (mScreenOn || aa.mShownWhileScreenOn) {
941 final long minTime = aa.mStartVisibleTime
942 + (aa.mStartTime != aa.mStartVisibleTime
943 ? mAm.mConstants.FGSERVICE_SCREEN_ON_AFTER_TIME
944 : mAm.mConstants.FGSERVICE_MIN_SHOWN_TIME);
945 if (nowElapsed >= minTime) {
946 // If shown while the screen is on, and it has been shown for
947 // at least the minimum show time, then we can now remove it.
948 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown long enough with screen on");
949 canRemove = true;
950 } else {
951 // This is when we will be okay to stop telling the user.
952 long reportTime = nowElapsed + mAm.mConstants.FGSERVICE_MIN_REPORT_TIME;
953 aa.mHideTime = reportTime > minTime ? reportTime : minTime;
954 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
955 + " with screen on");
956 }
957 } else {
958 final long minTime = aa.mEndTime
959 + mAm.mConstants.FGSERVICE_SCREEN_ON_BEFORE_TIME;
960 if (nowElapsed >= minTime) {
961 // If the foreground service has only run while the screen is
962 // off, but it has been gone now for long enough that we won't
963 // care to tell the user about it when the screen comes back on,
964 // then we can remove it now.
965 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - gone long enough with screen off");
966 canRemove = true;
967 } else {
968 // This is when we won't care about this old fg service.
969 aa.mHideTime = minTime;
970 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
971 + " with screen off");
972 }
973 }
974 return canRemove;
975 }
976
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700977 void updateForegroundApps(ServiceMap smap) {
978 // This is called from the handler without the lock held.
979 ArrayList<ActiveForegroundApp> active = null;
980 synchronized (mAm) {
981 final long now = SystemClock.elapsedRealtime();
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700982 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700983 if (smap != null) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700984 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Updating foreground apps for user "
985 + smap.mUserId);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700986 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
987 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -0700988 if (aa.mEndTime != 0) {
989 boolean canRemove = foregroundAppShownEnoughLocked(aa, now);
990 if (canRemove) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700991 // This was up for longer than the timeout, so just remove immediately.
992 smap.mActiveForegroundApps.removeAt(i);
993 smap.mActiveForegroundAppsChanged = true;
994 continue;
995 }
Dianne Hackborncb015632017-06-14 17:30:15 -0700996 if (aa.mHideTime < nextUpdateTime) {
997 nextUpdateTime = aa.mHideTime;
998 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700999 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001000 if (!aa.mAppOnTop) {
1001 if (active == null) {
1002 active = new ArrayList<>();
1003 }
Dianne Hackborncb015632017-06-14 17:30:15 -07001004 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
1005 + aa.mPackageName + ", uid=" + aa.mUid);
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001006 active.add(aa);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001007 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001008 }
1009 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
1010 if (nextUpdateTime < Long.MAX_VALUE) {
Dianne Hackborncb015632017-06-14 17:30:15 -07001011 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Next update time in: "
1012 + (nextUpdateTime-now));
1013 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001014 smap.sendMessageAtTime(msg, nextUpdateTime
1015 + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001016 }
1017 }
1018 if (!smap.mActiveForegroundAppsChanged) {
1019 return;
1020 }
1021 smap.mActiveForegroundAppsChanged = false;
1022 }
1023
Dianne Hackborn070d1422018-05-02 13:48:30 -07001024 if (!SHOW_DUNGEON_NOTIFICATION) {
1025 return;
1026 }
1027
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001028 final NotificationManager nm = (NotificationManager) mAm.mContext.getSystemService(
1029 Context.NOTIFICATION_SERVICE);
1030 final Context context = mAm.mContext;
1031
1032 if (active != null) {
1033 for (int i = 0; i < active.size(); i++) {
1034 ActiveForegroundApp aa = active.get(i);
1035 if (aa.mLabel == null) {
1036 PackageManager pm = context.getPackageManager();
1037 try {
1038 ApplicationInfo ai = pm.getApplicationInfoAsUser(aa.mPackageName,
1039 PackageManager.MATCH_KNOWN_PACKAGES, smap.mUserId);
1040 aa.mLabel = ai.loadLabel(pm);
1041 } catch (PackageManager.NameNotFoundException e) {
1042 aa.mLabel = aa.mPackageName;
1043 }
1044 }
1045 }
1046
1047 Intent intent;
1048 String title;
1049 String msg;
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001050 String[] pkgs;
Dan Sandler886e0162017-06-06 14:23:43 -04001051 final long nowElapsed = SystemClock.elapsedRealtime();
1052 long oldestStartTime = nowElapsed;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001053 if (active.size() == 1) {
1054 intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
1055 intent.setData(Uri.fromParts("package", active.get(0).mPackageName, null));
1056 title = context.getString(
1057 R.string.foreground_service_app_in_background, active.get(0).mLabel);
1058 msg = context.getString(R.string.foreground_service_tap_for_details);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001059 pkgs = new String[] { active.get(0).mPackageName };
Dan Sandler2f36ab82017-05-25 00:15:49 -04001060 oldestStartTime = active.get(0).mStartTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001061 } else {
1062 intent = new Intent(Settings.ACTION_FOREGROUND_SERVICES_SETTINGS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001063 pkgs = new String[active.size()];
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001064 for (int i = 0; i < active.size(); i++) {
1065 pkgs[i] = active.get(i).mPackageName;
Dan Sandler2f36ab82017-05-25 00:15:49 -04001066 oldestStartTime = Math.min(oldestStartTime, active.get(i).mStartTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001067 }
1068 intent.putExtra("packages", pkgs);
1069 title = context.getString(
1070 R.string.foreground_service_apps_in_background, active.size());
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001071 msg = active.get(0).mLabel.toString();
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001072 for (int i = 1; i < active.size(); i++) {
1073 msg = context.getString(R.string.foreground_service_multiple_separator,
1074 msg, active.get(i).mLabel);
1075 }
1076 }
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001077 Bundle notificationBundle = new Bundle();
1078 notificationBundle.putStringArray(Notification.EXTRA_FOREGROUND_APPS, pkgs);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001079 Notification.Builder n =
1080 new Notification.Builder(context,
1081 SystemNotificationChannels.FOREGROUND_SERVICE)
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001082 .addExtras(notificationBundle)
Dan Sandler2f36ab82017-05-25 00:15:49 -04001083 .setSmallIcon(R.drawable.stat_sys_vitals)
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001084 .setOngoing(true)
Dan Sandler886e0162017-06-06 14:23:43 -04001085 .setShowWhen(oldestStartTime < nowElapsed)
1086 .setWhen(System.currentTimeMillis() - (nowElapsed - oldestStartTime))
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001087 .setColor(context.getColor(
1088 com.android.internal.R.color.system_notification_accent_color))
1089 .setContentTitle(title)
1090 .setContentText(msg)
1091 .setContentIntent(
1092 PendingIntent.getActivityAsUser(context, 0, intent,
1093 PendingIntent.FLAG_UPDATE_CURRENT,
1094 null, new UserHandle(smap.mUserId)));
1095 nm.notifyAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1096 n.build(), new UserHandle(smap.mUserId));
1097 } else {
1098 nm.cancelAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1099 new UserHandle(smap.mUserId));
1100 }
1101 }
1102
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001103 private void requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001104 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001105 if (timeElapsed != 0) {
1106 smap.sendMessageAtTime(msg,
1107 timeElapsed + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001108 } else {
1109 smap.mActiveForegroundAppsChanged = true;
1110 smap.sendMessage(msg);
1111 }
1112 }
1113
1114 private void decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r) {
1115 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1116 if (active != null) {
1117 active.mNumActive--;
1118 if (active.mNumActive <= 0) {
1119 active.mEndTime = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001120 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Ended running of service");
1121 if (foregroundAppShownEnoughLocked(active, active.mEndTime)) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001122 // Have been active for long enough that we will remove it immediately.
1123 smap.mActiveForegroundApps.remove(r.packageName);
1124 smap.mActiveForegroundAppsChanged = true;
1125 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001126 } else if (active.mHideTime < Long.MAX_VALUE){
1127 requestUpdateActiveForegroundAppsLocked(smap, active.mHideTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001128 }
1129 }
1130 }
1131 }
1132
1133 void updateScreenStateLocked(boolean screenOn) {
1134 if (mScreenOn != screenOn) {
1135 mScreenOn = screenOn;
1136
1137 // If screen is turning on, then we now reset the start time of any foreground
1138 // services that were started while the screen was off.
1139 if (screenOn) {
1140 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001141 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Screen turned on");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001142 for (int i = mServiceMap.size()-1; i >= 0; i--) {
1143 ServiceMap smap = mServiceMap.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -07001144 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001145 boolean changed = false;
1146 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1147 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
Dianne Hackborncb015632017-06-14 17:30:15 -07001148 if (active.mEndTime == 0) {
1149 if (!active.mShownWhileScreenOn) {
1150 active.mShownWhileScreenOn = true;
1151 active.mStartVisibleTime = nowElapsed;
1152 }
1153 } else {
1154 if (!active.mShownWhileScreenOn
1155 && active.mStartVisibleTime == active.mStartTime) {
1156 // If this was never shown while the screen was on, then we will
1157 // count the time it started being visible as now, to tell the user
1158 // about it now that they have a screen to look at.
1159 active.mEndTime = active.mStartVisibleTime = nowElapsed;
1160 }
1161 if (foregroundAppShownEnoughLocked(active, nowElapsed)) {
1162 // Have been active for long enough that we will remove it
1163 // immediately.
1164 smap.mActiveForegroundApps.remove(active.mPackageName);
1165 smap.mActiveForegroundAppsChanged = true;
1166 changed = true;
1167 } else {
1168 if (active.mHideTime < nextUpdateTime) {
1169 nextUpdateTime = active.mHideTime;
1170 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001171 }
1172 }
1173 }
1174 if (changed) {
Dianne Hackborncb015632017-06-14 17:30:15 -07001175 // Need to immediately update.
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001176 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001177 } else if (nextUpdateTime < Long.MAX_VALUE) {
1178 requestUpdateActiveForegroundAppsLocked(smap, nextUpdateTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001179 }
1180 }
1181 }
1182 }
1183 }
1184
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001185 void foregroundServiceProcStateChangedLocked(UidRecord uidRec) {
1186 ServiceMap smap = mServiceMap.get(UserHandle.getUserId(uidRec.uid));
1187 if (smap != null) {
1188 boolean changed = false;
1189 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1190 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
1191 if (active.mUid == uidRec.uid) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07001192 if (uidRec.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001193 if (!active.mAppOnTop) {
1194 active.mAppOnTop = true;
1195 changed = true;
1196 }
1197 active.mShownWhileTop = true;
1198 } else if (active.mAppOnTop) {
1199 active.mAppOnTop = false;
1200 changed = true;
1201 }
1202 }
1203 }
1204 if (changed) {
1205 requestUpdateActiveForegroundAppsLocked(smap, 0);
1206 }
1207 }
1208 }
1209
Christopher Tatec7933ac2018-03-12 17:57:09 -07001210 /**
1211 * @param id Notification ID. Zero === exit foreground state for the given service.
1212 */
1213 private void setServiceForegroundInnerLocked(final ServiceRecord r, int id,
Christopher Tate42a386b2016-11-07 12:21:21 -08001214 Notification notification, int flags) {
1215 if (id != 0) {
1216 if (notification == null) {
1217 throw new IllegalArgumentException("null notification");
1218 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001219 // Instant apps need permission to create foreground services.
1220 if (r.appInfo.isInstantApp()) {
1221 final int mode = mAm.mAppOpsService.checkOperation(
1222 AppOpsManager.OP_INSTANT_APP_START_FOREGROUND,
1223 r.appInfo.uid,
1224 r.appInfo.packageName);
1225 switch (mode) {
1226 case AppOpsManager.MODE_ALLOWED:
1227 break;
1228 case AppOpsManager.MODE_IGNORED:
1229 Slog.w(TAG, "Instant app " + r.appInfo.packageName
1230 + " does not have permission to create foreground services"
1231 + ", ignoring.");
Sudheer Shankac9d94072017-02-22 22:13:55 +00001232 return;
Chad Brubaker97b383f2017-02-02 15:04:35 -08001233 case AppOpsManager.MODE_ERRORED:
1234 throw new SecurityException("Instant app " + r.appInfo.packageName
1235 + " does not have permission to create foreground services");
1236 default:
Dianne Hackborndd027b32018-01-19 17:44:46 -08001237 mAm.enforcePermission(
1238 android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
1239 r.app.pid, r.appInfo.uid, "startForeground");
Chad Brubaker97b383f2017-02-02 15:04:35 -08001240 }
Hui Yu1ea85522018-12-06 16:59:18 -08001241 } else {
1242 if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
1243 mAm.enforcePermission(
1244 android.Manifest.permission.FOREGROUND_SERVICE,
1245 r.app.pid, r.appInfo.uid, "startForeground");
1246 }
1247 if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.Q) {
1248 if (r.serviceInfo.getForegroundServiceType()
1249 == ServiceInfo.FOREGROUND_SERVICE_TYPE_UNSPECIFIED) {
1250 // STOPSHIP(b/120611119): replace log message with SecurityException.
1251 Slog.w(TAG, "missing foregroundServiceType attribute in "
1252 + "service element of manifest file");
1253 }
1254 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001255 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001256 boolean alreadyStartedOp = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001257 boolean stopProcStatsOp = false;
Christopher Tate08992ac2017-03-21 11:37:06 -07001258 if (r.fgRequired) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001259 if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001260 Slog.i(TAG, "Service called startForeground() as required: " + r);
1261 }
1262 r.fgRequired = false;
1263 r.fgWaiting = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001264 alreadyStartedOp = stopProcStatsOp = true;
Christopher Tate08992ac2017-03-21 11:37:06 -07001265 mAm.mHandler.removeMessages(
1266 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
1267 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001268
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001269 try {
1270 boolean ignoreForeground = false;
1271 final int mode = mAm.mAppOpsService.checkOperation(
1272 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
1273 switch (mode) {
1274 case AppOpsManager.MODE_ALLOWED:
1275 case AppOpsManager.MODE_DEFAULT:
1276 // All okay.
1277 break;
1278 case AppOpsManager.MODE_IGNORED:
1279 // Whoops, silently ignore this.
1280 Slog.w(TAG, "Service.startForeground() not allowed due to app op: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001281 + r.shortInstanceName);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001282 ignoreForeground = true;
1283 break;
1284 default:
1285 throw new SecurityException("Foreground not allowed as per app op");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001286 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001287
1288 if (!ignoreForeground &&
1289 appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001290 Slog.w(TAG,
1291 "Service.startForeground() not allowed due to bg restriction: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001292 + r.shortInstanceName);
Christopher Tate45f06c792018-04-25 10:47:23 -07001293 // Back off of any foreground expectations around this service, since we've
1294 // just turned down its fg request.
1295 updateServiceForegroundLocked(r.app, false);
1296 ignoreForeground = true;
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001297 }
1298
1299 // Apps under strict background restrictions simply don't get to have foreground
1300 // services, so now that we've enforced the startForegroundService() contract
1301 // we only do the machinery of making the service foreground when the app
1302 // is not restricted.
1303 if (!ignoreForeground) {
1304 if (r.foregroundId != id) {
1305 cancelForegroundNotificationLocked(r);
1306 r.foregroundId = id;
Christopher Tatec7933ac2018-03-12 17:57:09 -07001307 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001308 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
1309 r.foregroundNoti = notification;
1310 if (!r.isForeground) {
1311 final ServiceMap smap = getServiceMapLocked(r.userId);
1312 if (smap != null) {
1313 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1314 if (active == null) {
1315 active = new ActiveForegroundApp();
1316 active.mPackageName = r.packageName;
1317 active.mUid = r.appInfo.uid;
1318 active.mShownWhileScreenOn = mScreenOn;
1319 if (r.app != null) {
1320 active.mAppOnTop = active.mShownWhileTop =
Wale Ogunwalebff2df42018-10-18 17:09:19 -07001321 r.app.uidRecord.getCurProcState()
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001322 <= ActivityManager.PROCESS_STATE_TOP;
1323 }
1324 active.mStartTime = active.mStartVisibleTime
1325 = SystemClock.elapsedRealtime();
1326 smap.mActiveForegroundApps.put(r.packageName, active);
1327 requestUpdateActiveForegroundAppsLocked(smap, 0);
1328 }
1329 active.mNumActive++;
1330 }
1331 r.isForeground = true;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001332 if (!stopProcStatsOp) {
1333 ServiceState stracker = r.getTracker();
1334 if (stracker != null) {
1335 stracker.setForeground(true,
1336 mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
1337 }
1338 } else {
1339 stopProcStatsOp = false;
1340 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001341 mAm.mAppOpsService.startOperation(
1342 AppOpsManager.getToken(mAm.mAppOpsService),
1343 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName,
1344 true);
1345 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001346 r.appInfo.uid, r.shortInstanceName,
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001347 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER);
Hui Yue361a232018-10-04 15:05:21 -07001348 mAm.updateForegroundServiceUsageStats(r.name, r.userId, true);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001349 }
1350 r.postNotification();
1351 if (r.app != null) {
1352 updateServiceForegroundLocked(r.app, true);
1353 }
1354 getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
1355 mAm.notifyPackageUse(r.serviceInfo.packageName,
1356 PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
1357 } else {
1358 if (DEBUG_FOREGROUND_SERVICE) {
1359 Slog.d(TAG, "Suppressing startForeground() for FAS " + r);
1360 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001361 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001362 } finally {
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001363 if (stopProcStatsOp) {
1364 // We got through to this point with it actively being started foreground,
1365 // and never decided we wanted to keep it like that, so drop it.
1366 ServiceState stracker = r.getTracker();
1367 if (stracker != null) {
1368 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1369 r.lastActivity);
1370 }
1371 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001372 if (alreadyStartedOp) {
1373 // If we had previously done a start op for direct foreground start,
1374 // we have cleared the flag so can now drop it.
1375 mAm.mAppOpsService.finishOperation(
1376 AppOpsManager.getToken(mAm.mAppOpsService),
1377 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001378 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001379 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001380 } else {
1381 if (r.isForeground) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001382 final ServiceMap smap = getServiceMapLocked(r.userId);
1383 if (smap != null) {
1384 decActiveForegroundAppLocked(smap, r);
1385 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001386 r.isForeground = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001387 ServiceState stracker = r.getTracker();
1388 if (stracker != null) {
1389 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1390 r.lastActivity);
1391 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001392 mAm.mAppOpsService.finishOperation(
1393 AppOpsManager.getToken(mAm.mAppOpsService),
1394 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001395 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001396 r.appInfo.uid, r.shortInstanceName,
Chenjie Yuccfe6452018-01-30 11:33:21 -08001397 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Hui Yue361a232018-10-04 15:05:21 -07001398 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
Christopher Tate42a386b2016-11-07 12:21:21 -08001399 if (r.app != null) {
1400 mAm.updateLruProcessLocked(r.app, false, null);
1401 updateServiceForegroundLocked(r.app, true);
1402 }
1403 }
1404 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001405 cancelForegroundNotificationLocked(r);
Christopher Tate42a386b2016-11-07 12:21:21 -08001406 r.foregroundId = 0;
1407 r.foregroundNoti = null;
1408 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1409 r.stripForegroundServiceFlagFromNotification();
1410 if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
1411 r.foregroundId = 0;
1412 r.foregroundNoti = null;
1413 }
1414 }
1415 }
1416 }
1417
Christopher Tate08992ac2017-03-21 11:37:06 -07001418 private void cancelForegroundNotificationLocked(ServiceRecord r) {
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001419 if (r.foregroundId != 0) {
1420 // First check to see if this app has any other active foreground services
1421 // with the same notification ID. If so, we shouldn't actually cancel it,
1422 // because that would wipe away the notification that still needs to be shown
1423 // due the other service.
Dianne Hackbornad51be92016-08-16 16:27:36 -07001424 ServiceMap sm = getServiceMapLocked(r.userId);
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001425 if (sm != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001426 for (int i = sm.mServicesByInstanceName.size() - 1; i >= 0; i--) {
1427 ServiceRecord other = sm.mServicesByInstanceName.valueAt(i);
Dianne Hackborn569a4582016-08-04 14:00:22 -07001428 if (other != r && other.foregroundId == r.foregroundId
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001429 && other.packageName.equals(r.packageName)) {
1430 // Found one! Abort the cancel.
1431 return;
1432 }
1433 }
1434 }
1435 r.cancelNotification();
1436 }
1437 }
1438
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001439 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
1440 boolean anyForeground = false;
Amith Yamasania0a30a12019-01-22 11:38:06 -08001441 int fgServiceTypes = 0;
1442 for (int i = proc.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07001443 ServiceRecord sr = proc.services.valueAt(i);
Christopher Tatee23fa2b2017-04-20 14:48:13 -07001444 if (sr.isForeground || sr.fgRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001445 anyForeground = true;
Amith Yamasania0a30a12019-01-22 11:38:06 -08001446 fgServiceTypes |= sr.serviceInfo.mForegroundServiceType;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001447 break;
1448 }
1449 }
Amith Yamasania0a30a12019-01-22 11:38:06 -08001450 mAm.updateProcessForegroundLocked(proc, anyForeground, fgServiceTypes, oomAdj);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001451 }
1452
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001453 private void updateWhitelistManagerLocked(ProcessRecord proc) {
1454 proc.whitelistManager = false;
1455 for (int i=proc.services.size()-1; i>=0; i--) {
1456 ServiceRecord sr = proc.services.valueAt(i);
1457 if (sr.whitelistManager) {
1458 proc.whitelistManager = true;
1459 break;
1460 }
1461 }
1462 }
1463
Dianne Hackborn465fa392014-09-14 14:21:18 -07001464 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
1465 ArraySet<ProcessRecord> updatedProcesses = null;
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001466 for (int i = 0; i < clientProc.connections.size(); i++) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001467 final ConnectionRecord conn = clientProc.connections.valueAt(i);
1468 final ProcessRecord proc = conn.binding.service.app;
1469 if (proc == null || proc == clientProc) {
1470 continue;
1471 } else if (updatedProcesses == null) {
1472 updatedProcesses = new ArraySet<>();
1473 } else if (updatedProcesses.contains(proc)) {
1474 continue;
1475 }
1476 updatedProcesses.add(proc);
1477 updateServiceClientActivitiesLocked(proc, null, false);
1478 }
1479 }
1480
Dianne Hackborndb926082013-10-31 16:32:44 -07001481 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
Dianne Hackborn465fa392014-09-14 14:21:18 -07001482 ConnectionRecord modCr, boolean updateLru) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001483 if (modCr != null && modCr.binding.client != null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001484 if (!modCr.binding.client.hasActivities()) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001485 // This connection is from a client without activities, so adding
1486 // and removing is not interesting.
1487 return false;
1488 }
1489 }
1490
1491 boolean anyClientActivities = false;
1492 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
1493 ServiceRecord sr = proc.services.valueAt(i);
1494 for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) {
1495 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni);
1496 for (int cri=clist.size()-1; cri>=0; cri--) {
1497 ConnectionRecord cr = clist.get(cri);
1498 if (cr.binding.client == null || cr.binding.client == proc) {
1499 // Binding to ourself is not interesting.
1500 continue;
1501 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001502 if (cr.binding.client.hasActivities()) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001503 anyClientActivities = true;
1504 break;
1505 }
1506 }
1507 }
1508 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001509 if (anyClientActivities != proc.hasClientActivities()) {
1510 proc.setHasClientActivities(anyClientActivities);
Dianne Hackborn465fa392014-09-14 14:21:18 -07001511 if (updateLru) {
1512 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
1513 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001514 return true;
1515 }
1516 return false;
1517 }
1518
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001519 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
Svet Ganov9c165d72015-12-01 19:52:26 -08001520 String resolvedType, final IServiceConnection connection, int flags,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001521 String instanceName, String callingPackage, final int userId)
1522 throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001523 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001524 + " type=" + resolvedType + " conn=" + connection.asBinder()
1525 + " flags=0x" + Integer.toHexString(flags));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001526 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
1527 if (callerApp == null) {
1528 throw new SecurityException(
1529 "Unable to find app for caller " + caller
1530 + " (pid=" + Binder.getCallingPid()
1531 + ") when binding service " + service);
1532 }
1533
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001534 ActivityServiceConnectionsHolder<ConnectionRecord> activity = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001535 if (token != null) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001536 activity = mAm.mAtmInternal.getServiceConnectionsHolder(token);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001537 if (activity == null) {
1538 Slog.w(TAG, "Binding with unknown activity: " + token);
1539 return 0;
1540 }
1541 }
1542
1543 int clientLabel = 0;
1544 PendingIntent clientIntent = null;
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001545 final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001546
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001547 if (isCallerSystem) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001548 // Hacky kind of thing -- allow system stuff to tell us
1549 // what they are, so we can report this elsewhere for
1550 // others to know why certain services are running.
Jeff Sharkeyf0ec2e02016-03-21 12:37:54 -06001551 service.setDefusable(true);
1552 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001553 if (clientIntent != null) {
1554 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
1555 if (clientLabel != 0) {
1556 // There are no useful extras in the intent, trash them.
1557 // System code calling with this stuff just needs to know
1558 // this will happen.
1559 service = service.cloneFilter();
1560 }
1561 }
1562 }
1563
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001564 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1565 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
1566 "BIND_TREAT_LIKE_ACTIVITY");
1567 }
1568
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001569 if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
1570 throw new SecurityException(
1571 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1572 + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
1573 }
1574
Svet Ganovd223db32017-12-22 09:43:48 -08001575 if ((flags & Context.BIND_ALLOW_INSTANT) != 0 && !isCallerSystem) {
1576 throw new SecurityException(
1577 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1578 + ") set BIND_ALLOW_INSTANT when binding service " + service);
1579 }
1580
Dianne Hackborna49ad092016-03-03 13:39:10 -08001581 final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Robert Sesekb9a86662015-12-09 16:22:45 -05001582 final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
Svet Ganovd223db32017-12-22 09:43:48 -08001583 final boolean allowInstant = (flags & Context.BIND_ALLOW_INSTANT) != 0;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001584
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001585 ServiceLookupResult res =
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001586 retrieveServiceLocked(service, instanceName, resolvedType, callingPackage,
1587 Binder.getCallingPid(), Binder.getCallingUid(), userId, true,
1588 callerFg, isBindExternal, allowInstant);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001589 if (res == null) {
1590 return 0;
1591 }
1592 if (res.record == null) {
1593 return -1;
1594 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001595 ServiceRecord s = res.record;
1596
Svet Ganov9c165d72015-12-01 19:52:26 -08001597 boolean permissionsReviewRequired = false;
1598
1599 // If permissions need a review before any of the app components can run,
1600 // we schedule binding to the service but do not start its process, then
1601 // we launch a review activity to which is passed a callback to invoke
1602 // when done to start the bound service's process to completing the binding.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001603 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
1604 s.packageName, s.userId)) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001605
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001606 permissionsReviewRequired = true;
Svet Ganov9c165d72015-12-01 19:52:26 -08001607
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001608 // Show a permission review UI only for binding from a foreground app
1609 if (!callerFg) {
1610 Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
1611 + s.packageName + " requires a permissions review");
1612 return 0;
1613 }
Svet Ganov9c165d72015-12-01 19:52:26 -08001614
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001615 final ServiceRecord serviceRecord = s;
1616 final Intent serviceIntent = service;
Svet Ganov9c165d72015-12-01 19:52:26 -08001617
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001618 RemoteCallback callback = new RemoteCallback(
1619 new RemoteCallback.OnResultListener() {
1620 @Override
1621 public void onResult(Bundle result) {
1622 synchronized(mAm) {
1623 final long identity = Binder.clearCallingIdentity();
1624 try {
1625 if (!mPendingServices.contains(serviceRecord)) {
1626 return;
Svet Ganov9c165d72015-12-01 19:52:26 -08001627 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001628 // If there is still a pending record, then the service
1629 // binding request is still valid, so hook them up. We
1630 // proceed only if the caller cleared the review requirement
1631 // otherwise we unbind because the user didn't approve.
1632 if (!mAm.getPackageManagerInternalLocked()
1633 .isPermissionsReviewRequired(
1634 serviceRecord.packageName,
1635 serviceRecord.userId)) {
1636 try {
1637 bringUpServiceLocked(serviceRecord,
1638 serviceIntent.getFlags(),
1639 callerFg, false, false);
1640 } catch (RemoteException e) {
1641 /* ignore - local call */
1642 }
1643 } else {
1644 unbindServiceLocked(connection);
1645 }
1646 } finally {
1647 Binder.restoreCallingIdentity(identity);
Svet Ganov9c165d72015-12-01 19:52:26 -08001648 }
1649 }
Svet Ganov9c165d72015-12-01 19:52:26 -08001650 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001651 });
Svet Ganov9c165d72015-12-01 19:52:26 -08001652
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001653 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
1654 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
Philip P. Moltmann751e46ca2019-01-24 13:56:47 -08001655 | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001656 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1657 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
1658 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
1659
1660 if (DEBUG_PERMISSIONS_REVIEW) {
1661 Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
1662 + s.packageName);
Svet Ganov9c165d72015-12-01 19:52:26 -08001663 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001664
1665 mAm.mHandler.post(new Runnable() {
1666 @Override
1667 public void run() {
1668 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
1669 }
1670 });
Svet Ganov9c165d72015-12-01 19:52:26 -08001671 }
1672
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001673 final long origId = Binder.clearCallingIdentity();
1674
1675 try {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001676 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001677 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001678 + s);
1679 }
1680
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001681 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1682 s.lastActivity = SystemClock.uptimeMillis();
1683 if (!s.hasAutoCreateConnections()) {
1684 // This is the first binding, let the tracker know.
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001685 ServiceState stracker = s.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001686 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001687 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001688 s.lastActivity);
1689 }
1690 }
1691 }
1692
Dianne Hackbornc390aa82019-01-09 16:38:22 -08001693 if ((flags & Context.BIND_RESTRICT_ASSOCIATIONS) != 0) {
1694 mAm.requireAllowedAssociationsLocked(s.appInfo.packageName);
1695 }
1696
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001697 mAm.startAssociationLocked(callerApp.uid, callerApp.processName,
1698 callerApp.getCurProcState(), s.appInfo.uid, s.appInfo.longVersionCode,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001699 s.instanceName, s.processName);
Jesse Evans02af3ea2017-05-03 09:57:16 -07001700 // Once the apps have become associated, if one of them is caller is ephemeral
1701 // the target app should now be able to see the calling app
1702 mAm.grantEphemeralAccessLocked(callerApp.userId, service,
Hai Zhangbb23d532018-08-27 16:00:35 -07001703 UserHandle.getAppId(s.appInfo.uid), UserHandle.getAppId(callerApp.uid));
Dianne Hackbornab2df062015-01-07 13:43:13 -08001704
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001705 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
1706 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001707 connection, flags, clientLabel, clientIntent,
Dianne Hackborn24bbe582018-12-17 11:58:31 -08001708 callerApp.uid, callerApp.processName, callingPackage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001709
1710 IBinder binder = connection.asBinder();
1711 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
1712 if (clist == null) {
1713 clist = new ArrayList<ConnectionRecord>();
1714 s.connections.put(binder, clist);
1715 }
1716 clist.add(c);
1717 b.connections.add(c);
1718 if (activity != null) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001719 activity.addConnection(c);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001720 }
1721 b.client.connections.add(c);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001722 c.startAssociationIfNeeded();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001723 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
1724 b.client.hasAboveClient = true;
1725 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001726 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
1727 s.whitelistManager = true;
1728 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001729 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001730 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07001731 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001732 clist = mServiceConnections.get(binder);
1733 if (clist == null) {
1734 clist = new ArrayList<ConnectionRecord>();
1735 mServiceConnections.put(binder, clist);
1736 }
1737 clist.add(c);
1738
1739 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1740 s.lastActivity = SystemClock.uptimeMillis();
Svet Ganov9c165d72015-12-01 19:52:26 -08001741 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
1742 permissionsReviewRequired) != null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001743 return 0;
1744 }
1745 }
1746
1747 if (s.app != null) {
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001748 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1749 s.app.treatLikeActivity = true;
1750 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001751 if (s.whitelistManager) {
1752 s.app.whitelistManager = true;
1753 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001754 // This could have made the service more important.
Dianne Hackborna631d562018-11-20 15:58:15 -08001755 mAm.updateLruProcessLocked(s.app,
1756 (callerApp.hasActivitiesOrRecentTasks() && s.app.hasClientActivities())
1757 || (callerApp.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP
1758 && (flags & Context.BIND_TREAT_LIKE_ACTIVITY) != 0),
1759 b.client);
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001760 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001761 }
1762
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001763 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001764 + ": received=" + b.intent.received
1765 + " apps=" + b.intent.apps.size()
1766 + " doRebind=" + b.intent.doRebind);
1767
1768 if (s.app != null && b.intent.received) {
1769 // Service is already running, so we can immediately
1770 // publish the connection.
1771 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001772 c.conn.connected(s.name, b.intent.binder, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001773 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001774 Slog.w(TAG, "Failure sending service " + s.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001775 + " to connection " + c.conn.asBinder()
1776 + " (in " + c.binding.client.processName + ")", e);
1777 }
1778
1779 // If this is the first app connected back to this binding,
1780 // and the service had previously asked to be told when
1781 // rebound, then do so.
1782 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001783 requestServiceBindingLocked(s, b.intent, callerFg, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001784 }
1785 } else if (!b.intent.requested) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001786 requestServiceBindingLocked(s, b.intent, callerFg, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001787 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001788
Dianne Hackbornad51be92016-08-16 16:27:36 -07001789 getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001790
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001791 } finally {
1792 Binder.restoreCallingIdentity(origId);
1793 }
1794
1795 return 1;
1796 }
1797
1798 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
1799 final long origId = Binder.clearCallingIdentity();
1800 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001801 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001802 + " " + intent + ": " + service);
1803 if (r != null) {
1804 Intent.FilterComparison filter
1805 = new Intent.FilterComparison(intent);
1806 IntentBindRecord b = r.bindings.get(filter);
1807 if (b != null && !b.received) {
1808 b.binder = service;
1809 b.requested = true;
1810 b.received = true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07001811 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1812 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
1813 for (int i=0; i<clist.size(); i++) {
1814 ConnectionRecord c = clist.get(i);
1815 if (!filter.equals(c.binding.intent.intent)) {
1816 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001817 TAG_SERVICE, "Not publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001818 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001819 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001820 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001821 TAG_SERVICE, "Published intent: " + intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001822 continue;
1823 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001824 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001825 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001826 c.conn.connected(r.name, service, false);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001827 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001828 Slog.w(TAG, "Failure sending service " + r.shortInstanceName
1829 + " to connection " + c.conn.asBinder()
1830 + " (in " + c.binding.client.processName + ")", e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001831 }
1832 }
1833 }
1834 }
1835
Dianne Hackborn164371f2013-10-01 19:10:13 -07001836 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001837 }
1838 } finally {
1839 Binder.restoreCallingIdentity(origId);
1840 }
1841 }
1842
Dianne Hackborna631d562018-11-20 15:58:15 -08001843 void updateServiceGroupLocked(IServiceConnection connection, int group, int importance) {
1844 final IBinder binder = connection.asBinder();
1845 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "updateServiceGroup: conn=" + binder);
1846 final ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1847 if (clist == null) {
1848 throw new IllegalArgumentException("Could not find connection for "
1849 + connection.asBinder());
1850 }
1851 for (int i = clist.size() - 1; i >= 0; i--) {
1852 final ConnectionRecord crec = clist.get(i);
1853 final ServiceRecord srec = crec.binding.service;
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08001854 if (srec != null && (srec.serviceInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) != 0) {
1855 if (srec.app != null) {
1856 if (group > 0) {
1857 srec.app.connectionService = srec;
1858 srec.app.connectionGroup = group;
1859 srec.app.connectionImportance = importance;
1860 } else {
1861 srec.app.connectionService = null;
1862 srec.app.connectionGroup = 0;
1863 srec.app.connectionImportance = 0;
1864 }
Dianne Hackborna631d562018-11-20 15:58:15 -08001865 } else {
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08001866 if (group > 0) {
1867 srec.pendingConnectionGroup = group;
1868 srec.pendingConnectionImportance = importance;
1869 } else {
1870 srec.pendingConnectionGroup = 0;
1871 srec.pendingConnectionImportance = 0;
1872 }
Dianne Hackborna631d562018-11-20 15:58:15 -08001873 }
1874 }
1875 }
1876 }
1877
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001878 boolean unbindServiceLocked(IServiceConnection connection) {
1879 IBinder binder = connection.asBinder();
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001880 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001881 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1882 if (clist == null) {
1883 Slog.w(TAG, "Unbind failed: could not find connection for "
1884 + connection.asBinder());
1885 return false;
1886 }
1887
1888 final long origId = Binder.clearCallingIdentity();
1889 try {
1890 while (clist.size() > 0) {
1891 ConnectionRecord r = clist.get(0);
1892 removeConnectionLocked(r, null, null);
Dianne Hackborn25e1eca2014-09-23 10:13:13 -07001893 if (clist.size() > 0 && clist.get(0) == r) {
1894 // In case it didn't get removed above, do it now.
1895 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
1896 clist.remove(0);
1897 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001898
1899 if (r.binding.service.app != null) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001900 if (r.binding.service.app.whitelistManager) {
Felipe Lemea7778b02016-06-28 10:38:59 -07001901 updateWhitelistManagerLocked(r.binding.service.app);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001902 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001903 // This could have made the service less important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001904 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1905 r.binding.service.app.treatLikeActivity = true;
1906 mAm.updateLruProcessLocked(r.binding.service.app,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001907 r.binding.service.app.hasClientActivities()
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001908 || r.binding.service.app.treatLikeActivity, null);
1909 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001910 mAm.updateOomAdjLocked(r.binding.service.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001911 }
1912 }
Amith Yamasanib2926b12017-05-11 11:13:52 -07001913
1914 mAm.updateOomAdjLocked();
1915
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001916 } finally {
1917 Binder.restoreCallingIdentity(origId);
1918 }
1919
1920 return true;
1921 }
1922
1923 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
1924 final long origId = Binder.clearCallingIdentity();
1925 try {
1926 if (r != null) {
1927 Intent.FilterComparison filter
1928 = new Intent.FilterComparison(intent);
1929 IntentBindRecord b = r.bindings.get(filter);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001930 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001931 + " at " + b + ": apps="
1932 + (b != null ? b.apps.size() : 0));
1933
Dianne Hackborn164371f2013-10-01 19:10:13 -07001934 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001935 if (b != null) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001936 if (b.apps.size() > 0 && !inDestroying) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001937 // Applications have already bound since the last
1938 // unbind, so just rebind right here.
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001939 boolean inFg = false;
1940 for (int i=b.apps.size()-1; i>=0; i--) {
1941 ProcessRecord client = b.apps.valueAt(i).client;
1942 if (client != null && client.setSchedGroup
Dianne Hackborna49ad092016-03-03 13:39:10 -08001943 != ProcessList.SCHED_GROUP_BACKGROUND) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001944 inFg = true;
1945 break;
1946 }
1947 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001948 try {
1949 requestServiceBindingLocked(r, b, inFg, true);
1950 } catch (TransactionTooLargeException e) {
1951 // Don't pass this back to ActivityThread, it's unrelated.
1952 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001953 } else {
1954 // Note to tell the service the next time there is
1955 // a new client.
1956 b.doRebind = true;
1957 }
1958 }
1959
Dianne Hackborn164371f2013-10-01 19:10:13 -07001960 serviceDoneExecutingLocked(r, inDestroying, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001961 }
1962 } finally {
1963 Binder.restoreCallingIdentity(origId);
1964 }
1965 }
1966
1967 private final ServiceRecord findServiceLocked(ComponentName name,
Dianne Hackborn41203752012-08-31 14:05:51 -07001968 IBinder token, int userId) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07001969 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001970 return r == token ? r : null;
1971 }
1972
1973 private final class ServiceLookupResult {
1974 final ServiceRecord record;
1975 final String permission;
1976
1977 ServiceLookupResult(ServiceRecord _record, String _permission) {
1978 record = _record;
1979 permission = _permission;
1980 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001981 }
1982
1983 private class ServiceRestarter implements Runnable {
1984 private ServiceRecord mService;
1985
1986 void setService(ServiceRecord service) {
1987 mService = service;
1988 }
1989
1990 public void run() {
1991 synchronized(mAm) {
1992 performServiceRestartLocked(mService);
1993 }
1994 }
1995 }
1996
1997 private ServiceLookupResult retrieveServiceLocked(Intent service,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001998 String instanceName, String resolvedType, String callingPackage,
1999 int callingPid, int callingUid, int userId,
Svet Ganovd223db32017-12-22 09:43:48 -08002000 boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
2001 boolean allowInstant) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002002 ServiceRecord r = null;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002003 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002004 + " type=" + resolvedType + " callingUid=" + callingUid);
2005
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07002006 userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
jovanaka6763a32018-12-03 17:23:20 -08002007 ActivityManagerInternal.ALLOW_NON_FULL_IN_PROFILE, "service",
2008 callingPackage);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002009
Dianne Hackbornad51be92016-08-16 16:27:36 -07002010 ServiceMap smap = getServiceMapLocked(userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002011 final ComponentName comp;
2012 if (instanceName == null) {
2013 comp = service.getComponent();
2014 } else {
2015 final ComponentName realComp = service.getComponent();
2016 if (realComp == null) {
2017 throw new IllegalArgumentException("Can't use custom instance name '" + instanceName
2018 + "' without expicit component in Intent");
2019 }
2020 comp = new ComponentName(realComp.getPackageName(),
2021 realComp.getClassName() + ":" + instanceName);
2022 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002023 if (comp != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002024 r = smap.mServicesByInstanceName.get(comp);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002025 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002026 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002027 if (r == null && !isBindExternal && instanceName == null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002028 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002029 r = smap.mServicesByIntent.get(filter);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002030 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002031 }
Robert Sesekb9a86662015-12-09 16:22:45 -05002032 if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
2033 && !callingPackage.equals(r.packageName)) {
2034 // If an external service is running within its own package, other packages
2035 // should not bind to that instance.
2036 r = null;
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002037 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Whoops, can't use existing external service");
Robert Sesekb9a86662015-12-09 16:22:45 -05002038 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002039 if (r == null) {
2040 try {
Svet Ganovd223db32017-12-22 09:43:48 -08002041 int flags = ActivityManagerService.STOCK_PM_FLAGS
2042 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
2043 if (allowInstant) {
2044 flags |= PackageManager.MATCH_INSTANT;
2045 }
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002046 // TODO: come back and remove this assumption to triage all services
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002047 ResolveInfo rInfo = mAm.getPackageManagerInternalLocked().resolveService(service,
Svet Ganovd223db32017-12-22 09:43:48 -08002048 resolvedType, flags, userId, callingUid);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002049 ServiceInfo sInfo = rInfo != null ? rInfo.serviceInfo : null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002050 if (sInfo == null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002051 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002052 ": not found");
2053 return null;
2054 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002055 if (instanceName != null
2056 && (sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
2057 throw new IllegalArgumentException("Can't use instance name '" + instanceName
2058 + "' with non-isolated service '" + sInfo.name + "'");
2059 }
2060 ComponentName className = new ComponentName(
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002061 sInfo.applicationInfo.packageName, sInfo.name);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002062 ComponentName name = comp != null ? comp : className;
Dianne Hackborn769b2e72018-12-05 08:51:20 -08002063 if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid,
2064 name.getPackageName(), sInfo.applicationInfo.uid)) {
2065 String msg = "association not allowed between packages "
Amith Yamasani9f96c2b2018-12-19 18:32:44 -08002066 + callingPackage + " and " + name.getPackageName();
Dianne Hackborn769b2e72018-12-05 08:51:20 -08002067 Slog.w(TAG, "Service lookup failed: " + msg);
2068 return new ServiceLookupResult(null, msg);
2069 }
Robert Sesekb9a86662015-12-09 16:22:45 -05002070 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
2071 if (isBindExternal) {
2072 if (!sInfo.exported) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002073 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
2074 + className + " is not exported");
Robert Sesekb9a86662015-12-09 16:22:45 -05002075 }
2076 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002077 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
2078 + className + " is not an isolatedProcess");
Robert Sesekb9a86662015-12-09 16:22:45 -05002079 }
2080 // Run the service under the calling package's application.
2081 ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
2082 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
2083 if (aInfo == null) {
2084 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
2085 "could not resolve client package " + callingPackage);
2086 }
2087 sInfo = new ServiceInfo(sInfo);
2088 sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
2089 sInfo.applicationInfo.packageName = aInfo.packageName;
2090 sInfo.applicationInfo.uid = aInfo.uid;
2091 name = new ComponentName(aInfo.packageName, name.getClassName());
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002092 className = new ComponentName(aInfo.packageName,
2093 instanceName == null ? className.getClassName()
2094 : (className.getClassName() + ":" + instanceName));
Robert Sesekb9a86662015-12-09 16:22:45 -05002095 service.setComponent(name);
2096 } else {
2097 throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
2098 name);
2099 }
2100 } else if (isBindExternal) {
2101 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
2102 " is not an externalService");
2103 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002104 if (userId > 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07002105 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
Amith Yamasani4b9d79c2014-05-21 19:14:21 -07002106 sInfo.name, sInfo.flags)
2107 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002108 userId = 0;
Dianne Hackbornad51be92016-08-16 16:27:36 -07002109 smap = getServiceMapLocked(0);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002110 }
2111 sInfo = new ServiceInfo(sInfo);
2112 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
2113 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002114 r = smap.mServicesByInstanceName.get(name);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002115 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE,
2116 "Retrieved via pm by intent: " + r);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002117 if (r == null && createIfNeeded) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002118 final Intent.FilterComparison filter
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002119 = new Intent.FilterComparison(service.cloneFilter());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002120 final ServiceRestarter res = new ServiceRestarter();
2121 final BatteryStatsImpl.Uid.Pkg.Serv ss;
2122 final BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002123 synchronized (stats) {
2124 ss = stats.getServiceStatsLocked(
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002125 sInfo.applicationInfo.uid, name.getPackageName(),
2126 name.getClassName());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002127 }
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08002128 r = new ServiceRecord(mAm, ss, className, name, filter, sInfo,
2129 callingFromFg, res);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002130 res.setService(r);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002131 smap.mServicesByInstanceName.put(name, r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002132 smap.mServicesByIntent.put(filter, r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002133
2134 // Make sure this component isn't in the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002135 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002136 final ServiceRecord pr = mPendingServices.get(i);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002137 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002138 && pr.instanceName.equals(name)) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002139 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002140 mPendingServices.remove(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002141 }
2142 }
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002143 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002144 }
2145 } catch (RemoteException ex) {
2146 // pm is in same process, this will never happen.
2147 }
2148 }
2149 if (r != null) {
Dianne Hackborn769b2e72018-12-05 08:51:20 -08002150 if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid, r.packageName,
2151 r.appInfo.uid)) {
2152 String msg = "association not allowed between packages "
2153 + callingPackage + " and " + r.packageName;
2154 Slog.w(TAG, "Service lookup failed: " + msg);
2155 return new ServiceLookupResult(null, msg);
2156 }
2157 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
2158 resolvedType, r.appInfo)) {
2159 return new ServiceLookupResult(null, "blocked by firewall");
2160 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002161 if (mAm.checkComponentPermission(r.permission,
Bryce Lee290e5782017-02-01 16:41:20 -08002162 callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002163 if (!r.exported) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002164 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002165 + " from pid=" + callingPid
2166 + ", uid=" + callingUid
2167 + " that is not exported from uid " + r.appInfo.uid);
2168 return new ServiceLookupResult(null, "not exported from uid "
2169 + r.appInfo.uid);
2170 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002171 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002172 + " from pid=" + callingPid
2173 + ", uid=" + callingUid
2174 + " requires " + r.permission);
2175 return new ServiceLookupResult(null, r.permission);
Svet Ganov99b60432015-06-27 13:15:22 -07002176 } else if (r.permission != null && callingPackage != null) {
2177 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
2178 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation(
2179 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002180 Slog.w(TAG, "Appop Denial: Accessing service " + r.shortInstanceName
Svet Ganov99b60432015-06-27 13:15:22 -07002181 + " from pid=" + callingPid
2182 + ", uid=" + callingUid
2183 + " requires appop " + AppOpsManager.opToName(opCode));
2184 return null;
2185 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002186 }
2187 return new ServiceLookupResult(r, null);
2188 }
2189 return null;
2190 }
2191
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002192 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002193 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002194 + why + " of " + r + " in app " + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002195 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002196 + why + " of " + r.shortInstanceName);
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002197
2198 // For b/34123235: Services within the system server won't start until SystemServer
2199 // does Looper.loop(), so we shouldn't try to start/bind to them too early in the boot
2200 // process. However, since there's a little point of showing the ANR dialog in that case,
2201 // let's suppress the timeout until PHASE_THIRD_PARTY_APPS_CAN_START.
2202 //
2203 // (Note there are multiple services start at PHASE_THIRD_PARTY_APPS_CAN_START too,
2204 // which technically could also trigger this timeout if there's a system server
2205 // that takes a long time to handle PHASE_THIRD_PARTY_APPS_CAN_START, but that shouldn't
2206 // happen.)
2207 boolean timeoutNeeded = true;
2208 if ((mAm.mBootPhase < SystemService.PHASE_THIRD_PARTY_APPS_CAN_START)
2209 && (r.app != null) && (r.app.pid == android.os.Process.myPid())) {
2210
2211 Slog.w(TAG, "Too early to start/bind service in system_server: Phase=" + mAm.mBootPhase
2212 + " " + r.getComponentName());
2213 timeoutNeeded = false;
2214 }
2215
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002216 long now = SystemClock.uptimeMillis();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002217 if (r.executeNesting == 0) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002218 r.executeFg = fg;
Joe Onorato4eb64fd2016-03-21 15:30:09 -07002219 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002220 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002221 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002222 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002223 if (r.app != null) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002224 r.app.executingServices.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002225 r.app.execServicesFg |= fg;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002226 if (timeoutNeeded && r.app.executingServices.size() == 1) {
Dianne Hackborn2be00932013-09-22 16:46:00 -07002227 scheduleServiceTimeoutLocked(r.app);
2228 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002229 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002230 } else if (r.app != null && fg && !r.app.execServicesFg) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002231 r.app.execServicesFg = true;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002232 if (timeoutNeeded) {
2233 scheduleServiceTimeoutLocked(r.app);
2234 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002235 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002236 r.executeFg |= fg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002237 r.executeNesting++;
2238 r.executingStart = now;
2239 }
2240
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002241 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
2242 boolean execInFg, boolean rebind) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002243 if (r.app == null || r.app.thread == null) {
2244 // If service is not currently running, can't yet bind.
2245 return false;
2246 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08002247 if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
2248 + " rebind=" + rebind);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002249 if ((!i.requested || rebind) && i.apps.size() > 0) {
2250 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002251 bumpServiceExecutingLocked(r, execInFg, "bind");
Dianne Hackborna413dc02013-07-12 12:02:55 -07002252 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
2253 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002254 r.app.getReportedProcState());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002255 if (!rebind) {
2256 i.requested = true;
2257 }
2258 i.hasBound = true;
2259 i.doRebind = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002260 } catch (TransactionTooLargeException e) {
2261 // Keep the executeNesting count accurate.
2262 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
2263 final boolean inDestroying = mDestroyingServices.contains(r);
2264 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2265 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002266 } catch (RemoteException e) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002267 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002268 // Keep the executeNesting count accurate.
2269 final boolean inDestroying = mDestroyingServices.contains(r);
2270 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002271 return false;
2272 }
2273 }
2274 return true;
2275 }
2276
Dianne Hackbornad51be92016-08-16 16:27:36 -07002277 private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002278 boolean canceled = false;
2279
Wale Ogunwalef6733932018-06-27 05:14:34 -07002280 if (mAm.mAtmInternal.isShuttingDown()) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002281 Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortInstanceName
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07002282 + " - system is shutting down");
2283 return false;
2284 }
2285
Dianne Hackbornad51be92016-08-16 16:27:36 -07002286 ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002287 if (smap.mServicesByInstanceName.get(r.instanceName) != r) {
2288 ServiceRecord cur = smap.mServicesByInstanceName.get(r.instanceName);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002289 Slog.wtf(TAG, "Attempting to schedule restart of " + r
2290 + " when found in map: " + cur);
2291 return false;
2292 }
2293
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002294 final long now = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002295
2296 if ((r.serviceInfo.applicationInfo.flags
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002297 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002298 long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION;
2299 long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002300
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002301 // Any delivered but not yet finished starts should be put back
2302 // on the pending list.
2303 final int N = r.deliveredStarts.size();
2304 if (N > 0) {
2305 for (int i=N-1; i>=0; i--) {
2306 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
2307 si.removeUriPermissionsLocked();
2308 if (si.intent == null) {
2309 // We'll generate this again if needed.
2310 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
2311 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
2312 r.pendingStarts.add(0, si);
2313 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
2314 dur *= 2;
2315 if (minDuration < dur) minDuration = dur;
2316 if (resetTime < dur) resetTime = dur;
2317 } else {
2318 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002319 + r.shortInstanceName);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002320 canceled = true;
2321 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002322 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002323 r.deliveredStarts.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002324 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002325
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002326 r.totalRestartCount++;
2327 if (r.restartDelay == 0) {
2328 r.restartCount++;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002329 r.restartDelay = minDuration;
Amith Yamasanib0c8a882017-08-28 09:36:42 -07002330 } else if (r.crashCount > 1) {
2331 r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
2332 * (r.crashCount - 1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002333 } else {
Varun Shah4311f212019-01-23 05:59:31 +00002334 // If it has been a "reasonably long time" since the service
2335 // was started, then reset our restart duration back to
2336 // the beginning, so we don't infinitely increase the duration
2337 // on a service that just occasionally gets killed (which is
2338 // a normal case, due to process being killed to reclaim memory).
2339 if (now > (r.restartTime+resetTime)) {
2340 r.restartCount = 1;
2341 r.restartDelay = minDuration;
Varun Shah16522412018-12-28 15:46:01 -08002342 } else {
Varun Shah4311f212019-01-23 05:59:31 +00002343 r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
2344 if (r.restartDelay < minDuration) {
2345 r.restartDelay = minDuration;
Varun Shah16522412018-12-28 15:46:01 -08002346 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002347 }
2348 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002349
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002350 r.nextRestartTime = now + r.restartDelay;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002351
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002352 // Make sure that we don't end up restarting a bunch of services
2353 // all at the same time.
Varun Shah4311f212019-01-23 05:59:31 +00002354 boolean repeat;
2355 do {
2356 repeat = false;
2357 final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
2358 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2359 ServiceRecord r2 = mRestartingServices.get(i);
2360 if (r2 != r && r.nextRestartTime >= (r2.nextRestartTime-restartTimeBetween)
2361 && r.nextRestartTime < (r2.nextRestartTime+restartTimeBetween)) {
2362 r.nextRestartTime = r2.nextRestartTime + restartTimeBetween;
2363 r.restartDelay = r.nextRestartTime - now;
2364 repeat = true;
2365 break;
2366 }
2367 }
2368 } while (repeat);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002369
2370 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07002371 // Persistent processes are immediately restarted, so there is no
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002372 // reason to hold of on restarting their services.
2373 r.totalRestartCount++;
2374 r.restartCount = 0;
2375 r.restartDelay = 0;
2376 r.nextRestartTime = now;
2377 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002378
2379 if (!mRestartingServices.contains(r)) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002380 r.createdFromFg = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002381 mRestartingServices.add(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002382 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002383 }
2384
Christopher Tate08992ac2017-03-21 11:37:06 -07002385 cancelForegroundNotificationLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002386
2387 mAm.mHandler.removeCallbacks(r.restarter);
2388 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
2389 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
2390 Slog.w(TAG, "Scheduling restart of crashed service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002391 + r.shortInstanceName + " in " + r.restartDelay + "ms");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002392 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002393 r.userId, r.shortInstanceName, r.restartDelay);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002394
2395 return canceled;
2396 }
2397
2398 final void performServiceRestartLocked(ServiceRecord r) {
2399 if (!mRestartingServices.contains(r)) {
2400 return;
2401 }
Dianne Hackbornad51be92016-08-16 16:27:36 -07002402 if (!isServiceNeededLocked(r, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002403 // Paranoia: is this service actually needed? In theory a service that is not
2404 // needed should never remain on the restart list. In practice... well, there
2405 // have been bugs where this happens, and bad things happen because the process
2406 // ends up just being cached, so quickly killed, then restarted again and again.
2407 // Let's not let that happen.
2408 Slog.wtf(TAG, "Restarting service that is not needed: " + r);
2409 return;
2410 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002411 try {
Svet Ganov9c165d72015-12-01 19:52:26 -08002412 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002413 } catch (TransactionTooLargeException e) {
2414 // Ignore, it's been logged and nothing upstack cares.
2415 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002416 }
2417
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002418 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
2419 boolean force) {
2420 if (!force && r.restartDelay == 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002421 return false;
2422 }
Dianne Hackborn7b492722013-11-01 09:58:45 -07002423 // Remove from the restarting list; if the service is currently on the
2424 // restarting list, or the call is coming from another app, then this
2425 // service has become of much more interest so we reset the restart interval.
2426 boolean removed = mRestartingServices.remove(r);
2427 if (removed || callingUid != r.appInfo.uid) {
2428 r.resetRestartCounter();
2429 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002430 if (removed) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002431 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002432 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002433 mAm.mHandler.removeCallbacks(r.restarter);
2434 return true;
2435 }
2436
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002437 private void clearRestartingIfNeededLocked(ServiceRecord r) {
2438 if (r.restartTracker != null) {
2439 // If this is the last restarting record with this tracker, then clear
2440 // the tracker's restarting state.
2441 boolean stillTracking = false;
2442 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2443 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
2444 stillTracking = true;
2445 break;
2446 }
2447 }
2448 if (!stillTracking) {
2449 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
2450 SystemClock.uptimeMillis());
2451 r.restartTracker = null;
2452 }
2453 }
2454 }
2455
Svet Ganov9c165d72015-12-01 19:52:26 -08002456 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
2457 boolean whileRestarting, boolean permissionsReviewRequired)
2458 throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002459 //Slog.i(TAG, "Bring up service:");
2460 //r.dump(" ");
2461
2462 if (r.app != null && r.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002463 sendServiceArgsLocked(r, execInFg, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002464 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002465 }
2466
Sudheer Shanka03d0f812017-04-20 16:57:50 -07002467 if (!whileRestarting && mRestartingServices.contains(r)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002468 // If waiting for a restart, then do nothing.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002469 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002470 }
2471
Christopher Tate08992ac2017-03-21 11:37:06 -07002472 if (DEBUG_SERVICE) {
2473 Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
2474 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002475
2476 // We are now bringing the service up, so no longer in the
2477 // restarting state.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002478 if (mRestartingServices.remove(r)) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002479 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002480 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002481
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002482 // Make sure this service is no longer considered delayed, we are starting it now.
2483 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002484 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002485 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002486 r.delayed = false;
2487 }
2488
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002489 // Make sure that the user who owns this service is started. If not,
2490 // we don't want to allow it to run.
Fyodor Kupolov610acda2015-10-19 18:44:07 -07002491 if (!mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002492 String msg = "Unable to launch app "
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002493 + r.appInfo.packageName + "/"
2494 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002495 + r.intent.getIntent() + ": user " + r.userId + " is stopped";
2496 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002497 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002498 return msg;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002499 }
2500
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002501 // Service is now being launched, its package can't be stopped.
2502 try {
2503 AppGlobals.getPackageManager().setPackageStoppedState(
2504 r.packageName, false, r.userId);
2505 } catch (RemoteException e) {
2506 } catch (IllegalArgumentException e) {
2507 Slog.w(TAG, "Failed trying to unstop package "
2508 + r.packageName + ": " + e);
2509 }
2510
2511 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
2512 final String procName = r.processName;
Robert Sesekc5f86642016-11-04 10:20:38 -04002513 String hostingType = "service";
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002514 ProcessRecord app;
2515
2516 if (!isolated) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07002517 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
2518 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
2519 + " app=" + app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002520 if (app != null && app.thread != null) {
2521 try {
Patrick Baumannc2def582018-04-04 12:14:15 -07002522 app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode, mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002523 realStartServiceLocked(r, app, execInFg);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002524 return null;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002525 } catch (TransactionTooLargeException e) {
2526 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002527 } catch (RemoteException e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002528 Slog.w(TAG, "Exception when starting service " + r.shortInstanceName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002529 }
2530
2531 // If a dead object exception was thrown -- fall through to
2532 // restart the application.
2533 }
2534 } else {
2535 // If this service runs in an isolated process, then each time
2536 // we call startProcessLocked() we will get a new isolated
2537 // process, starting another process if we are currently waiting
2538 // for a previous process to come up. To deal with this, we store
2539 // in the service any current isolated process it is running in or
2540 // waiting to have come up.
2541 app = r.isolatedProc;
Robert Sesekc5f86642016-11-04 10:20:38 -04002542 if (WebViewZygote.isMultiprocessEnabled()
2543 && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
2544 hostingType = "webview_service";
2545 }
Martijn Coenen7e6fa672018-11-05 11:45:26 +01002546 if ((r.serviceInfo.flags & ServiceInfo.FLAG_USE_APP_ZYGOTE) != 0) {
2547 hostingType = "app_zygote";
2548 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002549 }
2550
2551 // Not running -- get it started, and enqueue this service record
2552 // to be executed when the app comes up.
Svet Ganov9c165d72015-12-01 19:52:26 -08002553 if (app == null && !permissionsReviewRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002554 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002555 hostingType, r.instanceName, false, isolated, false)) == null) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002556 String msg = "Unable to launch app "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002557 + r.appInfo.packageName + "/"
2558 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002559 + r.intent.getIntent() + ": process is bad";
2560 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002561 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002562 return msg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002563 }
2564 if (isolated) {
2565 r.isolatedProc = app;
2566 }
2567 }
2568
Christopher Tate1536cc22017-09-18 16:43:30 -07002569 if (r.fgRequired) {
2570 if (DEBUG_FOREGROUND_SERVICE) {
2571 Slog.v(TAG, "Whitelisting " + UserHandle.formatUid(r.appInfo.uid)
2572 + " for fg-service launch");
2573 }
2574 mAm.tempWhitelistUidLocked(r.appInfo.uid,
2575 SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch");
2576 }
2577
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002578 if (!mPendingServices.contains(r)) {
2579 mPendingServices.add(r);
2580 }
2581
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002582 if (r.delayedStop) {
2583 // Oh and hey we've already been asked to stop!
2584 r.delayedStop = false;
2585 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002586 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2587 "Applying delayed stop (in bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002588 stopServiceLocked(r);
2589 }
2590 }
2591
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002592 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002593 }
2594
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002595 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
2596 throws TransactionTooLargeException {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002597 for (int i=r.bindings.size()-1; i>=0; i--) {
2598 IntentBindRecord ibr = r.bindings.valueAt(i);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002599 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002600 break;
2601 }
2602 }
2603 }
2604
2605 private final void realStartServiceLocked(ServiceRecord r,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002606 ProcessRecord app, boolean execInFg) throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002607 if (app.thread == null) {
2608 throw new RemoteException();
2609 }
2610 if (DEBUG_MU)
2611 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
2612 + ", ProcessRecord.uid = " + app.uid);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002613 r.setProcess(app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002614 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
2615
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002616 final boolean newService = app.services.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002617 bumpServiceExecutingLocked(r, execInFg, "create");
Dianne Hackborndb926082013-10-31 16:32:44 -07002618 mAm.updateLruProcessLocked(app, false, null);
Makoto Onuki0f421292017-04-28 15:03:33 -07002619 updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
2620 mAm.updateOomAdjLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002621
2622 boolean created = false;
2623 try {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002624 if (LOG_SERVICE_START_STOP) {
Dianne Hackbornab2df062015-01-07 13:43:13 -08002625 String nameTerm;
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002626 int lastPeriod = r.shortInstanceName.lastIndexOf('.');
2627 nameTerm = lastPeriod >= 0 ? r.shortInstanceName.substring(lastPeriod)
2628 : r.shortInstanceName;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002629 EventLogTags.writeAmCreateService(
2630 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
2631 }
Chenjie Yu75b3c492018-10-06 21:45:19 -07002632 StatsLog.write(StatsLog.SERVICE_LAUNCH_REPORTED, r.appInfo.uid, r.name.getPackageName(),
2633 r.name.getClassName());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002634 synchronized (r.stats.getBatteryStats()) {
2635 r.stats.startLaunchedLocked();
2636 }
Brian Carlstromca82e612016-04-19 23:16:08 -07002637 mAm.notifyPackageUse(r.serviceInfo.packageName,
2638 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
Dianne Hackborna413dc02013-07-12 12:02:55 -07002639 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002640 app.thread.scheduleCreateService(r, r.serviceInfo,
Wale Ogunwale53783742018-09-16 10:21:51 -07002641 mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002642 app.getReportedProcState());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002643 r.postNotification();
2644 created = true;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -07002645 } catch (DeadObjectException e) {
2646 Slog.w(TAG, "Application dead when creating service " + r);
2647 mAm.appDiedLocked(app);
Wale Ogunwalebfac4682015-04-08 14:33:21 -07002648 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002649 } finally {
2650 if (!created) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002651 // Keep the executeNesting count accurate.
2652 final boolean inDestroying = mDestroyingServices.contains(r);
2653 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2654
2655 // Cleanup.
2656 if (newService) {
2657 app.services.remove(r);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002658 r.setProcess(null);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002659 }
2660
2661 // Retry.
2662 if (!inDestroying) {
2663 scheduleServiceRestartLocked(r, false);
2664 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002665 }
2666 }
2667
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002668 if (r.whitelistManager) {
2669 app.whitelistManager = true;
2670 }
2671
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002672 requestServiceBindingsLocked(r, execInFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002673
Dianne Hackborn465fa392014-09-14 14:21:18 -07002674 updateServiceClientActivitiesLocked(app, null, true);
2675
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002676 // If the service is in the started state, and there are no
2677 // pending arguments, then fake up one so its onStartCommand() will
2678 // be called.
2679 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
2680 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002681 null, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002682 }
2683
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002684 sendServiceArgsLocked(r, execInFg, true);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002685
2686 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002687 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002688 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002689 r.delayed = false;
2690 }
2691
2692 if (r.delayedStop) {
2693 // Oh and hey we've already been asked to stop!
2694 r.delayedStop = false;
2695 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002696 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2697 "Applying delayed stop (from start): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002698 stopServiceLocked(r);
2699 }
2700 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002701 }
2702
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002703 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002704 boolean oomAdjusted) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002705 final int N = r.pendingStarts.size();
2706 if (N == 0) {
2707 return;
2708 }
2709
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002710 ArrayList<ServiceStartArgs> args = new ArrayList<>();
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002711
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002712 while (r.pendingStarts.size() > 0) {
2713 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
2714 if (DEBUG_SERVICE) {
2715 Slog.v(TAG_SERVICE, "Sending arguments to: "
2716 + r + " " + r.intent + " args=" + si.intent);
2717 }
2718 if (si.intent == null && N > 1) {
2719 // If somehow we got a dummy null intent in the middle,
2720 // then skip it. DO NOT skip a null intent when it is
2721 // the only one in the list -- this is to support the
2722 // onStartCommand(null) case.
2723 continue;
2724 }
2725 si.deliveredTime = SystemClock.uptimeMillis();
2726 r.deliveredStarts.add(si);
2727 si.deliveryCount++;
2728 if (si.neededGrants != null) {
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07002729 mAm.mUgmInternal.grantUriPermissionUncheckedFromIntent(si.neededGrants,
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002730 si.getUriPermissionsLocked());
2731 }
Hai Zhangbb23d532018-08-27 16:00:35 -07002732 mAm.grantEphemeralAccessLocked(r.userId, si.intent, UserHandle.getAppId(r.appInfo.uid),
2733 UserHandle.getAppId(si.callingId));
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002734 bumpServiceExecutingLocked(r, execInFg, "start");
2735 if (!oomAdjusted) {
2736 oomAdjusted = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002737 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002738 }
2739 if (r.fgRequired && !r.fgWaiting) {
2740 if (!r.isForeground) {
2741 if (DEBUG_BACKGROUND_CHECK) {
2742 Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r);
2743 }
2744 scheduleServiceForegroundTransitionTimeoutLocked(r);
2745 } else {
2746 if (DEBUG_BACKGROUND_CHECK) {
2747 Slog.i(TAG, "Service already foreground; no new timeout: " + r);
2748 }
2749 r.fgRequired = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002750 }
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002751 }
2752 int flags = 0;
2753 if (si.deliveryCount > 1) {
2754 flags |= Service.START_FLAG_RETRY;
2755 }
2756 if (si.doneExecutingCount > 0) {
2757 flags |= Service.START_FLAG_REDELIVERY;
2758 }
2759 args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
2760 }
2761
2762 ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
2763 slice.setInlineCountLimit(4);
2764 Exception caughtException = null;
2765 try {
2766 r.app.thread.scheduleServiceArgs(r, slice);
2767 } catch (TransactionTooLargeException e) {
2768 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
2769 + " args, first: " + args.get(0).args);
2770 Slog.w(TAG, "Failed delivering service starts", e);
2771 caughtException = e;
2772 } catch (RemoteException e) {
2773 // Remote process gone... we'll let the normal cleanup take care of this.
2774 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
2775 Slog.w(TAG, "Failed delivering service starts", e);
2776 caughtException = e;
2777 } catch (Exception e) {
2778 Slog.w(TAG, "Unexpected exception", e);
2779 caughtException = e;
2780 }
2781
2782 if (caughtException != null) {
2783 // Keep nesting count correct
2784 final boolean inDestroying = mDestroyingServices.contains(r);
2785 for (int i = 0; i < args.size(); i++) {
2786 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2787 }
2788 if (caughtException instanceof TransactionTooLargeException) {
2789 throw (TransactionTooLargeException)caughtException;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002790 }
2791 }
2792 }
2793
Dianne Hackbornad51be92016-08-16 16:27:36 -07002794 private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn,
2795 boolean hasConn) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002796 // Are we still explicitly being asked to run?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002797 if (r.startRequested) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002798 return true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002799 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002800
Dianne Hackborncb015632017-06-14 17:30:15 -07002801 // Is someone still bound to us keeping us running?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002802 if (!knowConn) {
2803 hasConn = r.hasAutoCreateConnections();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002804 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002805 if (hasConn) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002806 return true;
2807 }
2808
2809 return false;
2810 }
2811
2812 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
2813 boolean hasConn) {
2814 //Slog.i(TAG, "Bring down service:");
2815 //r.dump(" ");
2816
Dianne Hackbornad51be92016-08-16 16:27:36 -07002817 if (isServiceNeededLocked(r, knowConn, hasConn)) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002818 return;
2819 }
2820
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002821 // Are we in the process of launching?
2822 if (mPendingServices.contains(r)) {
2823 return;
2824 }
2825
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002826 bringDownServiceLocked(r);
2827 }
2828
2829 private final void bringDownServiceLocked(ServiceRecord r) {
2830 //Slog.i(TAG, "Bring down service:");
2831 //r.dump(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002832
Dianne Hackborn390517b2013-05-30 15:03:32 -07002833 // Report to all of the connections that the service is no longer
2834 // available.
2835 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2836 ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
2837 for (int i=0; i<c.size(); i++) {
2838 ConnectionRecord cr = c.get(i);
2839 // There is still a connection to the service that is
2840 // being brought down. Mark it as dead.
2841 cr.serviceDead = true;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002842 cr.stopAssociation();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002843 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07002844 cr.conn.connected(r.name, null, true);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002845 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002846 Slog.w(TAG, "Failure disconnecting service " + r.shortInstanceName
2847 + " to connection " + c.get(i).conn.asBinder()
2848 + " (in " + c.get(i).binding.client.processName + ")", e);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002849 }
2850 }
2851 }
2852
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002853 // Tell the service that it has been unbound.
Dianne Hackborn390517b2013-05-30 15:03:32 -07002854 if (r.app != null && r.app.thread != null) {
2855 for (int i=r.bindings.size()-1; i>=0; i--) {
2856 IntentBindRecord ibr = r.bindings.valueAt(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002857 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002858 + ": hasBound=" + ibr.hasBound);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002859 if (ibr.hasBound) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002860 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002861 bumpServiceExecutingLocked(r, false, "bring down unbind");
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002862 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002863 ibr.hasBound = false;
Dianne Hackborn85e35642017-01-12 15:10:57 -08002864 ibr.requested = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002865 r.app.thread.scheduleUnbindService(r,
2866 ibr.intent.getIntent());
2867 } catch (Exception e) {
2868 Slog.w(TAG, "Exception when unbinding service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002869 + r.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002870 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002871 }
2872 }
2873 }
2874 }
2875
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002876 // Check to see if the service had been started as foreground, but being
2877 // brought down before actually showing a notification. That is not allowed.
2878 if (r.fgRequired) {
2879 Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
2880 + r);
2881 r.fgRequired = false;
2882 r.fgWaiting = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002883 ServiceState stracker = r.getTracker();
2884 if (stracker != null) {
2885 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
2886 r.lastActivity);
2887 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07002888 mAm.mAppOpsService.finishOperation(AppOpsManager.getToken(mAm.mAppOpsService),
2889 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002890 mAm.mHandler.removeMessages(
2891 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
2892 if (r.app != null) {
2893 Message msg = mAm.mHandler.obtainMessage(
2894 ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
2895 msg.obj = r.app;
Kodlee Yin7e951262018-04-05 12:59:56 -07002896 msg.getData().putCharSequence(
2897 ActivityManagerService.SERVICE_RECORD_KEY, r.toString());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002898 mAm.mHandler.sendMessage(msg);
2899 }
2900 }
2901
2902 if (DEBUG_SERVICE) {
2903 RuntimeException here = new RuntimeException();
2904 here.fillInStackTrace();
2905 Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here);
2906 }
Craig Mautner66c4a822015-01-16 12:48:16 -08002907 r.destroyTime = SystemClock.uptimeMillis();
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002908 if (LOG_SERVICE_START_STOP) {
2909 EventLogTags.writeAmDestroyService(
2910 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
2911 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002912
Dianne Hackbornad51be92016-08-16 16:27:36 -07002913 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002914 ServiceRecord found = smap.mServicesByInstanceName.remove(r.instanceName);
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002915
2916 // Note when this method is called by bringUpServiceLocked(), the service is not found
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002917 // in mServicesByInstanceName and found will be null.
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002918 if (found != null && found != r) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002919 // This is not actually the service we think is running... this should not happen,
2920 // but if it does, fail hard.
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002921 smap.mServicesByInstanceName.put(r.instanceName, found);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002922 throw new IllegalStateException("Bringing down " + r + " but actually running "
2923 + found);
2924 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002925 smap.mServicesByIntent.remove(r.intent);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002926 r.totalRestartCount = 0;
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002927 unscheduleServiceRestartLocked(r, 0, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002928
2929 // Also make sure it is not on the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002930 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002931 if (mPendingServices.get(i) == r) {
2932 mPendingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002933 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002934 }
2935 }
2936
Christopher Tate08992ac2017-03-21 11:37:06 -07002937 cancelForegroundNotificationLocked(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002938 if (r.isForeground) {
2939 decActiveForegroundAppLocked(smap, r);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002940 ServiceState stracker = r.getTracker();
2941 if (stracker != null) {
2942 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
2943 r.lastActivity);
2944 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07002945 mAm.mAppOpsService.finishOperation(
2946 AppOpsManager.getToken(mAm.mAppOpsService),
2947 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002948 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED, r.appInfo.uid,
2949 r.shortInstanceName, StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Hui Yue361a232018-10-04 15:05:21 -07002950 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002951 }
Chenjie Yuccfe6452018-01-30 11:33:21 -08002952
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002953 r.isForeground = false;
2954 r.foregroundId = 0;
2955 r.foregroundNoti = null;
2956
2957 // Clear start entries.
2958 r.clearDeliveredStartsLocked();
2959 r.pendingStarts.clear();
2960
2961 if (r.app != null) {
2962 synchronized (r.stats.getBatteryStats()) {
2963 r.stats.stopLaunchedLocked();
2964 }
2965 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002966 if (r.whitelistManager) {
2967 updateWhitelistManagerLocked(r.app);
2968 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002969 if (r.app.thread != null) {
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002970 updateServiceForegroundLocked(r.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002971 try {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002972 bumpServiceExecutingLocked(r, false, "destroy");
2973 mDestroyingServices.add(r);
Dianne Hackborn455625e2015-01-21 09:55:13 -08002974 r.destroying = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002975 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002976 r.app.thread.scheduleStopService(r);
2977 } catch (Exception e) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002978 Slog.w(TAG, "Exception when destroying service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002979 + r.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002980 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002981 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002982 } else {
2983 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002984 TAG_SERVICE, "Removed service that has no process: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002985 }
2986 } else {
2987 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002988 TAG_SERVICE, "Removed service that is not running: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002989 }
2990
2991 if (r.bindings.size() > 0) {
2992 r.bindings.clear();
2993 }
2994
2995 if (r.restarter instanceof ServiceRestarter) {
2996 ((ServiceRestarter)r.restarter).setService(null);
2997 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002998
Dianne Hackbornd2932242013-08-05 18:18:42 -07002999 int memFactor = mAm.mProcessStats.getMemFactorLocked();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003000 long now = SystemClock.uptimeMillis();
3001 if (r.tracker != null) {
3002 r.tracker.setStarted(false, memFactor, now);
3003 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003004 if (r.executeNesting == 0) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07003005 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003006 r.tracker = null;
3007 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003008 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003009
Dianne Hackbornad51be92016-08-16 16:27:36 -07003010 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003011 }
3012
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07003013 void removeConnectionLocked(ConnectionRecord c, ProcessRecord skipApp,
3014 ActivityServiceConnectionsHolder skipAct) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003015 IBinder binder = c.conn.asBinder();
3016 AppBindRecord b = c.binding;
3017 ServiceRecord s = b.service;
3018 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
3019 if (clist != null) {
3020 clist.remove(c);
3021 if (clist.size() == 0) {
3022 s.connections.remove(binder);
3023 }
3024 }
3025 b.connections.remove(c);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003026 c.stopAssociation();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003027 if (c.activity != null && c.activity != skipAct) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07003028 c.activity.removeConnection(c);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003029 }
3030 if (b.client != skipApp) {
3031 b.client.connections.remove(c);
3032 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
3033 b.client.updateHasAboveClientLocked();
3034 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003035 // If this connection requested whitelist management, see if we should
3036 // now clear that state.
3037 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
3038 s.updateWhitelistManager();
3039 if (!s.whitelistManager && s.app != null) {
3040 updateWhitelistManagerLocked(s.app);
3041 }
3042 }
Dianne Hackborndb926082013-10-31 16:32:44 -07003043 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07003044 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07003045 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003046 }
3047 clist = mServiceConnections.get(binder);
3048 if (clist != null) {
3049 clist.remove(c);
3050 if (clist.size() == 0) {
3051 mServiceConnections.remove(binder);
3052 }
3053 }
3054
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003055 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003056 s.appInfo.longVersionCode, s.instanceName, s.processName);
Dianne Hackbornab2df062015-01-07 13:43:13 -08003057
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003058 if (b.connections.size() == 0) {
3059 b.intent.apps.remove(b.client);
3060 }
3061
3062 if (!c.serviceDead) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003063 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003064 + ": shouldUnbind=" + b.intent.hasBound);
3065 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
3066 && b.intent.hasBound) {
3067 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003068 bumpServiceExecutingLocked(s, false, "unbind");
Dianne Hackborndb926082013-10-31 16:32:44 -07003069 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
Dianne Hackbornf097d422017-12-15 16:32:19 -08003070 && s.app.setProcState <= ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
Dianne Hackborndb926082013-10-31 16:32:44 -07003071 // If this service's process is not already in the cached list,
3072 // then update it in the LRU list here because this may be causing
3073 // it to go down there and we want it to start out near the top.
3074 mAm.updateLruProcessLocked(s.app, false, null);
3075 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07003076 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003077 b.intent.hasBound = false;
3078 // Assume the client doesn't want to know about a rebind;
3079 // we will deal with that later if it asks for one.
3080 b.intent.doRebind = false;
3081 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
3082 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003083 Slog.w(TAG, "Exception when unbinding service " + s.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07003084 serviceProcessGoneLocked(s);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003085 }
3086 }
3087
Svet Ganov9c165d72015-12-01 19:52:26 -08003088 // If unbound while waiting to start, remove the pending service
3089 mPendingServices.remove(s);
3090
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003091 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003092 boolean hasAutoCreate = s.hasAutoCreateConnections();
3093 if (!hasAutoCreate) {
3094 if (s.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003095 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003096 SystemClock.uptimeMillis());
3097 }
3098 }
3099 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003100 }
3101 }
3102 }
3103
3104 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003105 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003106 if (r != null) {
Dianne Hackborn455625e2015-01-21 09:55:13 -08003107 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003108 // This is a call from a service start... take care of
3109 // book-keeping.
3110 r.callStart = true;
3111 switch (res) {
3112 case Service.START_STICKY_COMPATIBILITY:
3113 case Service.START_STICKY: {
3114 // We are done with the associated start arguments.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003115 r.findDeliveredStart(startId, false, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003116 // Don't stop if killed.
3117 r.stopIfKilled = false;
3118 break;
3119 }
3120 case Service.START_NOT_STICKY: {
3121 // We are done with the associated start arguments.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003122 r.findDeliveredStart(startId, false, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003123 if (r.getLastStartId() == startId) {
3124 // There is no more work, and this service
3125 // doesn't want to hang around if killed.
3126 r.stopIfKilled = true;
3127 }
3128 break;
3129 }
3130 case Service.START_REDELIVER_INTENT: {
3131 // We'll keep this item until they explicitly
3132 // call stop for it, but keep track of the fact
3133 // that it was delivered.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003134 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003135 if (si != null) {
3136 si.deliveryCount = 0;
3137 si.doneExecutingCount++;
3138 // Don't stop if killed.
3139 r.stopIfKilled = true;
3140 }
3141 break;
3142 }
3143 case Service.START_TASK_REMOVED_COMPLETE: {
3144 // Special processing for onTaskRemoved(). Don't
3145 // impact normal onStartCommand() processing.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003146 r.findDeliveredStart(startId, true, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003147 break;
3148 }
3149 default:
3150 throw new IllegalArgumentException(
3151 "Unknown service start result: " + res);
3152 }
3153 if (res == Service.START_STICKY_COMPATIBILITY) {
3154 r.callStart = false;
3155 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08003156 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
3157 // This is the final call from destroying the service... we should
3158 // actually be getting rid of the service at this point. Do some
3159 // validation of its state, and ensure it will be fully removed.
3160 if (!inDestroying) {
3161 // Not sure what else to do with this... if it is not actually in the
3162 // destroying list, we don't need to make sure to remove it from it.
Amith Yamasanid0418222016-05-10 15:49:51 -07003163 // If the app is null, then it was probably removed because the process died,
3164 // otherwise wtf
3165 if (r.app != null) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07003166 Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
Amith Yamasanid0418222016-05-10 15:49:51 -07003167 + r + ", app=" + r.app);
3168 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08003169 } else if (r.executeNesting != 1) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07003170 Slog.w(TAG, "Service done with onDestroy, but executeNesting="
Dianne Hackborn455625e2015-01-21 09:55:13 -08003171 + r.executeNesting + ": " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003172 // Fake it to keep from ANR due to orphaned entry.
Dianne Hackborn455625e2015-01-21 09:55:13 -08003173 r.executeNesting = 1;
3174 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003175 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003176 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn164371f2013-10-01 19:10:13 -07003177 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003178 Binder.restoreCallingIdentity(origId);
3179 } else {
3180 Slog.w(TAG, "Done executing unknown service from pid "
3181 + Binder.getCallingPid());
3182 }
3183 }
3184
Dianne Hackborn878deb32013-10-14 16:55:09 -07003185 private void serviceProcessGoneLocked(ServiceRecord r) {
3186 if (r.tracker != null) {
3187 int memFactor = mAm.mProcessStats.getMemFactorLocked();
3188 long now = SystemClock.uptimeMillis();
3189 r.tracker.setExecuting(false, memFactor, now);
3190 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbc72dce2013-11-11 10:43:38 -08003191 r.tracker.setStarted(false, memFactor, now);
Dianne Hackborn878deb32013-10-14 16:55:09 -07003192 }
3193 serviceDoneExecutingLocked(r, true, true);
3194 }
3195
Dianne Hackborn164371f2013-10-01 19:10:13 -07003196 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
3197 boolean finishing) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003198 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003199 + ": nesting=" + r.executeNesting
Dianne Hackborn164371f2013-10-01 19:10:13 -07003200 + ", inDestroying=" + inDestroying + ", app=" + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003201 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003202 "<<< DONE EXECUTING " + r.shortInstanceName);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003203 r.executeNesting--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003204 if (r.executeNesting <= 0) {
3205 if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003206 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003207 "Nesting at 0 of " + r.shortInstanceName);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003208 r.app.execServicesFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003209 r.app.executingServices.remove(r);
3210 if (r.app.executingServices.size() == 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003211 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003212 "No more executingServices of " + r.shortInstanceName);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003213 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003214 } else if (r.executeFg) {
3215 // Need to re-evaluate whether the app still needs to be in the foreground.
3216 for (int i=r.app.executingServices.size()-1; i>=0; i--) {
3217 if (r.app.executingServices.valueAt(i).executeFg) {
3218 r.app.execServicesFg = true;
3219 break;
3220 }
3221 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003222 }
Dianne Hackborn164371f2013-10-01 19:10:13 -07003223 if (inDestroying) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003224 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn164371f2013-10-01 19:10:13 -07003225 "doneExecuting remove destroying " + r);
3226 mDestroyingServices.remove(r);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003227 r.bindings.clear();
3228 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07003229 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003230 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003231 r.executeFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003232 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003233 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003234 SystemClock.uptimeMillis());
Dianne Hackborn164371f2013-10-01 19:10:13 -07003235 if (finishing) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07003236 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003237 r.tracker = null;
3238 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003239 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003240 if (finishing) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003241 if (r.app != null && !r.app.isPersistent()) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003242 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003243 if (r.whitelistManager) {
3244 updateWhitelistManagerLocked(r.app);
3245 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003246 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003247 r.setProcess(null);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003248 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003249 }
3250 }
3251
Dianne Hackbornff072722014-09-24 10:56:28 -07003252 boolean attachApplicationLocked(ProcessRecord proc, String processName)
3253 throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003254 boolean didSomething = false;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003255 // Collect any services that are waiting for this process to come up.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003256 if (mPendingServices.size() > 0) {
3257 ServiceRecord sr = null;
3258 try {
3259 for (int i=0; i<mPendingServices.size(); i++) {
3260 sr = mPendingServices.get(i);
3261 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3262 || !processName.equals(sr.processName))) {
3263 continue;
3264 }
3265
3266 mPendingServices.remove(i);
3267 i--;
Patrick Baumannc2def582018-04-04 12:14:15 -07003268 proc.addPackage(sr.appInfo.packageName, sr.appInfo.longVersionCode,
Dianne Hackbornf7097a52014-05-13 09:56:14 -07003269 mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003270 realStartServiceLocked(sr, proc, sr.createdFromFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003271 didSomething = true;
Dianne Hackbornad51be92016-08-16 16:27:36 -07003272 if (!isServiceNeededLocked(sr, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003273 // We were waiting for this service to start, but it is actually no
3274 // longer needed. This could happen because bringDownServiceIfNeeded
3275 // won't bring down a service that is pending... so now the pending
3276 // is done, so let's drop it.
3277 bringDownServiceLocked(sr);
3278 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003279 }
Dianne Hackbornff072722014-09-24 10:56:28 -07003280 } catch (RemoteException e) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003281 Slog.w(TAG, "Exception in new application when starting service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003282 + sr.shortInstanceName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003283 throw e;
3284 }
3285 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003286 // Also, if there are any services that are waiting to restart and
3287 // would run in this process, now is a good time to start them. It would
3288 // be weird to bring up the process but arbitrarily not let the services
3289 // run at this point just because their restart time hasn't come up.
3290 if (mRestartingServices.size() > 0) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003291 ServiceRecord sr;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003292 for (int i=0; i<mRestartingServices.size(); i++) {
3293 sr = mRestartingServices.get(i);
3294 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3295 || !processName.equals(sr.processName))) {
3296 continue;
3297 }
3298 mAm.mHandler.removeCallbacks(sr.restarter);
3299 mAm.mHandler.post(sr.restarter);
3300 }
3301 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003302 return didSomething;
3303 }
3304
3305 void processStartTimedOutLocked(ProcessRecord proc) {
3306 for (int i=0; i<mPendingServices.size(); i++) {
3307 ServiceRecord sr = mPendingServices.get(i);
3308 if ((proc.uid == sr.appInfo.uid
3309 && proc.processName.equals(sr.processName))
3310 || sr.isolatedProc == proc) {
3311 Slog.w(TAG, "Forcing bringing down service: " + sr);
3312 sr.isolatedProc = null;
3313 mPendingServices.remove(i);
3314 i--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003315 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003316 }
3317 }
3318 }
3319
Wale Ogunwale540e1232015-05-01 15:35:39 -07003320 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003321 boolean evenPersistent, boolean doit, ArrayMap<ComponentName, ServiceRecord> services) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003322 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003323 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003324 ServiceRecord service = services.valueAt(i);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003325 final boolean sameComponent = packageName == null
3326 || (service.packageName.equals(packageName)
3327 && (filterByClasses == null
3328 || filterByClasses.contains(service.name.getClassName())));
3329 if (sameComponent
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003330 && (service.app == null || evenPersistent || !service.app.isPersistent())) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003331 if (!doit) {
3332 return true;
3333 }
3334 didSomething = true;
3335 Slog.i(TAG, " Force stopping service " + service);
Riddle Hsuaaef7312019-01-24 19:00:58 +08003336 if (service.app != null && !service.app.isPersistent()) {
3337 service.app.services.remove(service);
3338 if (service.whitelistManager) {
3339 updateWhitelistManagerLocked(service.app);
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08003340 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003341 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003342 service.setProcess(null);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003343 service.isolatedProc = null;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003344 if (mTmpCollectionResults == null) {
3345 mTmpCollectionResults = new ArrayList<>();
3346 }
3347 mTmpCollectionResults.add(service);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003348 }
3349 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003350 return didSomething;
3351 }
3352
Wale Ogunwale540e1232015-05-01 15:35:39 -07003353 boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003354 int userId, boolean evenPersistent, boolean doit) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003355 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003356
3357 if (mTmpCollectionResults != null) {
3358 mTmpCollectionResults.clear();
3359 }
3360
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003361 if (userId == UserHandle.USER_ALL) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003362 for (int i = mServiceMap.size() - 1; i >= 0; i--) {
3363 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003364 evenPersistent, doit, mServiceMap.valueAt(i).mServicesByInstanceName);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003365 if (!doit && didSomething) {
3366 return true;
3367 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003368 if (doit && filterByClasses == null) {
3369 forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId);
3370 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003371 }
3372 } else {
Amith Yamasani540b6592013-10-01 13:02:52 -07003373 ServiceMap smap = mServiceMap.get(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003374 if (smap != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003375 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByInstanceName;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003376 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003377 evenPersistent, doit, items);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003378 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003379 if (doit && filterByClasses == null) {
3380 forceStopPackageLocked(packageName, userId);
3381 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003382 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003383
Wale Ogunwale540e1232015-05-01 15:35:39 -07003384 if (mTmpCollectionResults != null) {
3385 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
3386 bringDownServiceLocked(mTmpCollectionResults.get(i));
3387 }
3388 mTmpCollectionResults.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003389 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003390
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003391 return didSomething;
3392 }
3393
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003394 void forceStopPackageLocked(String packageName, int userId) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003395 ServiceMap smap = mServiceMap.get(userId);
3396 if (smap != null && smap.mActiveForegroundApps.size() > 0) {
Dianne Hackbornaf597682017-05-01 10:54:07 -07003397 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003398 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
3399 if (aa.mPackageName.equals(packageName)) {
3400 smap.mActiveForegroundApps.removeAt(i);
3401 smap.mActiveForegroundAppsChanged = true;
3402 }
3403 }
3404 if (smap.mActiveForegroundAppsChanged) {
3405 requestUpdateActiveForegroundAppsLocked(smap, 0);
3406 }
3407 }
3408 }
3409
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003410 void cleanUpServices(int userId, ComponentName component, Intent baseIntent) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003411 ArrayList<ServiceRecord> services = new ArrayList<>();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003412 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003413 for (int i = alls.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003414 ServiceRecord sr = alls.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003415 if (sr.packageName.equals(component.getPackageName())) {
3416 services.add(sr);
3417 }
3418 }
3419
3420 // Take care of any running services associated with the app.
Wale Ogunwale540e1232015-05-01 15:35:39 -07003421 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003422 ServiceRecord sr = services.get(i);
3423 if (sr.startRequested) {
3424 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003425 Slog.i(TAG, "Stopping service " + sr.shortInstanceName + ": remove task");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003426 stopServiceLocked(sr);
3427 } else {
3428 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003429 sr.getLastStartId(), baseIntent, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003430 if (sr.app != null && sr.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003431 // We always run in the foreground, since this is called as
3432 // part of the "remove task" UI operation.
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003433 try {
3434 sendServiceArgsLocked(sr, true, false);
3435 } catch (TransactionTooLargeException e) {
3436 // Ignore, keep going.
3437 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003438 }
3439 }
3440 }
3441 }
3442 }
3443
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003444 final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003445 // Report disconnected services.
3446 if (false) {
3447 // XXX we are letting the client link to the service for
3448 // death notifications.
3449 if (app.services.size() > 0) {
3450 Iterator<ServiceRecord> it = app.services.iterator();
3451 while (it.hasNext()) {
3452 ServiceRecord r = it.next();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003453 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3454 ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
3455 for (int i=0; i<cl.size(); i++) {
3456 ConnectionRecord c = cl.get(i);
3457 if (c.binding.client != app) {
3458 try {
3459 //c.conn.connected(r.className, null);
3460 } catch (Exception e) {
3461 // todo: this should be asynchronous!
3462 Slog.w(TAG, "Exception thrown disconnected servce "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003463 + r.shortInstanceName
Dianne Hackborn390517b2013-05-30 15:03:32 -07003464 + " from app " + app.processName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003465 }
3466 }
3467 }
3468 }
3469 }
3470 }
3471 }
3472
louis_chang40e259c2015-03-26 13:31:14 +08003473 // Clean up any connections this application has to other services.
3474 for (int i = app.connections.size() - 1; i >= 0; i--) {
3475 ConnectionRecord r = app.connections.valueAt(i);
3476 removeConnectionLocked(r, app, null);
3477 }
3478 updateServiceConnectionActivitiesLocked(app);
3479 app.connections.clear();
3480
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003481 app.whitelistManager = false;
3482
louis_chang40e259c2015-03-26 13:31:14 +08003483 // Clear app state from services.
3484 for (int i = app.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003485 ServiceRecord sr = app.services.valueAt(i);
3486 synchronized (sr.stats.getBatteryStats()) {
3487 sr.stats.stopLaunchedLocked();
3488 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003489 if (sr.app != app && sr.app != null && !sr.app.isPersistent()) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003490 sr.app.services.remove(sr);
3491 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003492 sr.setProcess(null);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003493 sr.isolatedProc = null;
3494 sr.executeNesting = 0;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003495 sr.forceClearTracker();
3496 if (mDestroyingServices.remove(sr)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003497 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003498 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003499
Dianne Hackbornc8230512013-07-13 21:32:12 -07003500 final int numClients = sr.bindings.size();
3501 for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
3502 IntentBindRecord b = sr.bindings.valueAt(bindingi);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003503 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
Dianne Hackbornc8230512013-07-13 21:32:12 -07003504 + ": shouldUnbind=" + b.hasBound);
3505 b.binder = null;
3506 b.requested = b.received = b.hasBound = false;
Dianne Hackborn465fa392014-09-14 14:21:18 -07003507 // If this binding is coming from a cached process and is asking to keep
3508 // the service created, then we'll kill the cached process as well -- we
3509 // don't want to be thrashing around restarting processes that are only
3510 // there to be cached.
3511 for (int appi=b.apps.size()-1; appi>=0; appi--) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003512 final ProcessRecord proc = b.apps.keyAt(appi);
3513 // If the process is already gone, skip it.
3514 if (proc.killedByAm || proc.thread == null) {
3515 continue;
3516 }
3517 // Only do this for processes that have an auto-create binding;
3518 // otherwise the binding can be left, because it won't cause the
3519 // service to restart.
3520 final AppBindRecord abind = b.apps.valueAt(appi);
3521 boolean hasCreate = false;
3522 for (int conni=abind.connections.size()-1; conni>=0; conni--) {
3523 ConnectionRecord conn = abind.connections.valueAt(conni);
Dianne Hackborn0fe3c252014-09-19 15:09:39 -07003524 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
3525 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003526 hasCreate = true;
3527 break;
3528 }
3529 }
3530 if (!hasCreate) {
3531 continue;
3532 }
Dianne Hackborncd97c962014-09-25 18:34:02 -07003533 // XXX turned off for now until we have more time to get a better policy.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003534 if (false && proc != null && !proc.isPersistent() && proc.thread != null
Dianne Hackborn465fa392014-09-14 14:21:18 -07003535 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
3536 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003537 proc.kill("bound to service " + sr.shortInstanceName
Dianne Hackborn465fa392014-09-14 14:21:18 -07003538 + " in dying proc " + (app != null ? app.processName : "??"), true);
3539 }
3540 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003541 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003542 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003543
Dianne Hackbornad51be92016-08-16 16:27:36 -07003544 ServiceMap smap = getServiceMapLocked(app.userId);
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003545
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003546 // Now do remaining service cleanup.
3547 for (int i=app.services.size()-1; i>=0; i--) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003548 ServiceRecord sr = app.services.valueAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003549
3550 // Unless the process is persistent, this process record is going away,
3551 // so make sure the service is cleaned out of it.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003552 if (!app.isPersistent()) {
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003553 app.services.removeAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003554 }
3555
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003556 // Sanity check: if the service listed for the app is not one
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003557 // we actually are maintaining, just let it drop.
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003558 final ServiceRecord curRec = smap.mServicesByInstanceName.get(sr.instanceName);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003559 if (curRec != sr) {
3560 if (curRec != null) {
3561 Slog.wtf(TAG, "Service " + sr + " in process " + app
3562 + " not same as in map: " + curRec);
3563 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003564 continue;
3565 }
3566
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003567 // Any services running in the application may need to be placed
3568 // back in the pending list.
Amith Yamasanib0c8a882017-08-28 09:36:42 -07003569 if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
3570 && (sr.serviceInfo.applicationInfo.flags
3571 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003572 Slog.w(TAG, "Service crashed " + sr.crashCount
3573 + " times, stopping: " + sr);
3574 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003575 sr.userId, sr.crashCount, sr.shortInstanceName, app.pid);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003576 bringDownServiceLocked(sr);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003577 } else if (!allowRestart
Fyodor Kupolov1b3edac2017-09-19 15:48:06 -07003578 || !mAm.mUserController.isUserRunning(sr.userId, 0)) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003579 bringDownServiceLocked(sr);
3580 } else {
3581 boolean canceled = scheduleServiceRestartLocked(sr, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003582
Dianne Hackbornc8230512013-07-13 21:32:12 -07003583 // Should the service remain running? Note that in the
3584 // extreme case of so many attempts to deliver a command
3585 // that it failed we also will stop it here.
3586 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
3587 if (sr.pendingStarts.size() == 0) {
3588 sr.startRequested = false;
3589 if (sr.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003590 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackbornc8230512013-07-13 21:32:12 -07003591 SystemClock.uptimeMillis());
3592 }
3593 if (!sr.hasAutoCreateConnections()) {
3594 // Whoops, no reason to restart!
3595 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003596 }
3597 }
3598 }
3599 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003600 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003601
Dianne Hackbornc8230512013-07-13 21:32:12 -07003602 if (!allowRestart) {
3603 app.services.clear();
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003604
3605 // Make sure there are no more restarting services for this process.
3606 for (int i=mRestartingServices.size()-1; i>=0; i--) {
3607 ServiceRecord r = mRestartingServices.get(i);
3608 if (r.processName.equals(app.processName) &&
3609 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3610 mRestartingServices.remove(i);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08003611 clearRestartingIfNeededLocked(r);
3612 }
3613 }
3614 for (int i=mPendingServices.size()-1; i>=0; i--) {
3615 ServiceRecord r = mPendingServices.get(i);
3616 if (r.processName.equals(app.processName) &&
3617 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3618 mPendingServices.remove(i);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003619 }
3620 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003621 }
3622
3623 // Make sure we have no more records on the stopping list.
Dianne Hackborn164371f2013-10-01 19:10:13 -07003624 int i = mDestroyingServices.size();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003625 while (i > 0) {
3626 i--;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003627 ServiceRecord sr = mDestroyingServices.get(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003628 if (sr.app == app) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003629 sr.forceClearTracker();
3630 mDestroyingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003631 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003632 }
3633 }
3634
3635 app.executingServices.clear();
3636 }
3637
3638 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
3639 ActivityManager.RunningServiceInfo info =
3640 new ActivityManager.RunningServiceInfo();
3641 info.service = r.name;
3642 if (r.app != null) {
3643 info.pid = r.app.pid;
3644 }
3645 info.uid = r.appInfo.uid;
3646 info.process = r.processName;
3647 info.foreground = r.isForeground;
Yi Jin6b514142017-10-30 14:54:12 -07003648 info.activeSince = r.createRealTime;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003649 info.started = r.startRequested;
3650 info.clientCount = r.connections.size();
3651 info.crashCount = r.crashCount;
3652 info.lastActivityTime = r.lastActivity;
3653 if (r.isForeground) {
3654 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
3655 }
3656 if (r.startRequested) {
3657 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
3658 }
3659 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
3660 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
3661 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003662 if (r.app != null && r.app.isPersistent()) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003663 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
3664 }
3665
Dianne Hackborn390517b2013-05-30 15:03:32 -07003666 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3667 ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003668 for (int i=0; i<connl.size(); i++) {
3669 ConnectionRecord conn = connl.get(i);
3670 if (conn.clientLabel != 0) {
3671 info.clientPackage = conn.binding.client.info.packageName;
3672 info.clientLabel = conn.clientLabel;
3673 return info;
3674 }
3675 }
3676 }
3677 return info;
3678 }
3679
Bryce Lee290e5782017-02-01 16:41:20 -08003680 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags,
Shunta Sato55af6c52016-10-19 15:58:52 +09003681 int callingUid, boolean allowed, boolean canInteractAcrossUsers) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003682 ArrayList<ActivityManager.RunningServiceInfo> res
3683 = new ArrayList<ActivityManager.RunningServiceInfo>();
3684
Dianne Hackborn0c380492012-08-20 17:23:30 -07003685 final long ident = Binder.clearCallingIdentity();
3686 try {
Shunta Sato55af6c52016-10-19 15:58:52 +09003687 if (canInteractAcrossUsers) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003688 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003689 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003690 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003691 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3692 ServiceRecord sr = alls.valueAt(i);
3693 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07003694 }
3695 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003696
Dianne Hackborn0c380492012-08-20 17:23:30 -07003697 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3698 ServiceRecord r = mRestartingServices.get(i);
3699 ActivityManager.RunningServiceInfo info =
3700 makeRunningServiceInfoLocked(r);
3701 info.restarting = r.nextRestartTime;
3702 res.add(info);
3703 }
3704 } else {
Bryce Lee290e5782017-02-01 16:41:20 -08003705 int userId = UserHandle.getUserId(callingUid);
Dianne Hackbornad51be92016-08-16 16:27:36 -07003706 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003707 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3708 ServiceRecord sr = alls.valueAt(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003709
3710 if (allowed || (sr.app != null && sr.app.uid == callingUid)) {
3711 res.add(makeRunningServiceInfoLocked(sr));
3712 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07003713 }
3714
3715 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3716 ServiceRecord r = mRestartingServices.get(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003717 if (r.userId == userId
3718 && (allowed || (r.app != null && r.app.uid == callingUid))) {
Dianne Hackborn0c380492012-08-20 17:23:30 -07003719 ActivityManager.RunningServiceInfo info =
3720 makeRunningServiceInfoLocked(r);
3721 info.restarting = r.nextRestartTime;
3722 res.add(info);
3723 }
3724 }
3725 }
3726 } finally {
3727 Binder.restoreCallingIdentity(ident);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003728 }
3729
3730 return res;
3731 }
3732
3733 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003734 int userId = UserHandle.getUserId(Binder.getCallingUid());
Dianne Hackbornad51be92016-08-16 16:27:36 -07003735 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003736 if (r != null) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003737 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3738 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003739 for (int i=0; i<conn.size(); i++) {
3740 if (conn.get(i).clientIntent != null) {
3741 return conn.get(i).clientIntent;
3742 }
3743 }
3744 }
3745 }
3746 return null;
3747 }
3748
3749 void serviceTimeout(ProcessRecord proc) {
3750 String anrMessage = null;
3751
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003752 synchronized(mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003753 if (proc.executingServices.size() == 0 || proc.thread == null) {
3754 return;
3755 }
Dianne Hackbornab2df062015-01-07 13:43:13 -08003756 final long now = SystemClock.uptimeMillis();
3757 final long maxTime = now -
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003758 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003759 ServiceRecord timeout = null;
3760 long nextTime = 0;
Dianne Hackbornc8230512013-07-13 21:32:12 -07003761 for (int i=proc.executingServices.size()-1; i>=0; i--) {
3762 ServiceRecord sr = proc.executingServices.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003763 if (sr.executingStart < maxTime) {
3764 timeout = sr;
3765 break;
3766 }
3767 if (sr.executingStart > nextTime) {
3768 nextTime = sr.executingStart;
3769 }
3770 }
Amith Yamasani98a00922018-08-21 12:50:30 -04003771 if (timeout != null && mAm.mProcessList.mLruProcesses.contains(proc)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003772 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08003773 StringWriter sw = new StringWriter();
3774 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
3775 pw.println(timeout);
3776 timeout.dump(pw, " ");
3777 pw.close();
3778 mLastAnrDump = sw.toString();
3779 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
3780 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003781 anrMessage = "executing service " + timeout.shortInstanceName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003782 } else {
3783 Message msg = mAm.mHandler.obtainMessage(
3784 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3785 msg.obj = proc;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003786 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
Dianne Hackborn2be00932013-09-22 16:46:00 -07003787 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003788 }
3789 }
3790
3791 if (anrMessage != null) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07003792 proc.appNotResponding(null, null, null, null, false, anrMessage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003793 }
3794 }
3795
Christopher Tate08992ac2017-03-21 11:37:06 -07003796 void serviceForegroundTimeout(ServiceRecord r) {
3797 ProcessRecord app;
3798 synchronized (mAm) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003799 if (!r.fgRequired || r.destroying) {
Christopher Tate08992ac2017-03-21 11:37:06 -07003800 return;
3801 }
3802
Christopher Tate54f51b02018-02-16 11:07:12 -08003803 app = r.app;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07003804 if (app != null && app.isDebugging()) {
Christopher Tate54f51b02018-02-16 11:07:12 -08003805 // The app's being debugged; let it ride
3806 return;
3807 }
3808
Christopher Tate08992ac2017-03-21 11:37:06 -07003809 if (DEBUG_BACKGROUND_CHECK) {
3810 Slog.i(TAG, "Service foreground-required timeout for " + r);
3811 }
Christopher Tate08992ac2017-03-21 11:37:06 -07003812 r.fgWaiting = false;
3813 stopServiceLocked(r);
3814 }
3815
3816 if (app != null) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07003817 app.appNotResponding(null, null, null, null, false,
Kodlee Yin7e951262018-04-05 12:59:56 -07003818 "Context.startForegroundService() did not then call Service.startForeground(): "
3819 + r);
Christopher Tate08992ac2017-03-21 11:37:06 -07003820 }
3821 }
3822
Fyodor Kupolovcc269d92018-05-14 14:20:29 -07003823 public void updateServiceApplicationInfoLocked(ApplicationInfo applicationInfo) {
3824 final int userId = UserHandle.getUserId(applicationInfo.uid);
3825 ServiceMap serviceMap = mServiceMap.get(userId);
3826 if (serviceMap != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003827 ArrayMap<ComponentName, ServiceRecord> servicesByName
3828 = serviceMap.mServicesByInstanceName;
Fyodor Kupolovcc269d92018-05-14 14:20:29 -07003829 for (int j = servicesByName.size() - 1; j >= 0; j--) {
3830 ServiceRecord serviceRecord = servicesByName.valueAt(j);
3831 if (applicationInfo.packageName.equals(serviceRecord.appInfo.packageName)) {
3832 serviceRecord.appInfo = applicationInfo;
3833 serviceRecord.serviceInfo.applicationInfo = applicationInfo;
3834 }
3835 }
3836 }
3837 }
3838
Kodlee Yin7e951262018-04-05 12:59:56 -07003839 void serviceForegroundCrash(ProcessRecord app, CharSequence serviceRecord) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003840 mAm.crashApplication(app.uid, app.pid, app.info.packageName, app.userId,
Kodlee Yin7e951262018-04-05 12:59:56 -07003841 "Context.startForegroundService() did not then call Service.startForeground(): "
3842 + serviceRecord);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003843 }
3844
Dianne Hackborn2be00932013-09-22 16:46:00 -07003845 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
3846 if (proc.executingServices.size() == 0 || proc.thread == null) {
3847 return;
3848 }
Dianne Hackborn2be00932013-09-22 16:46:00 -07003849 Message msg = mAm.mHandler.obtainMessage(
3850 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3851 msg.obj = proc;
Christopher Tate08992ac2017-03-21 11:37:06 -07003852 mAm.mHandler.sendMessageDelayed(msg,
3853 proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
3854 }
3855
3856 void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
3857 if (r.app.executingServices.size() == 0 || r.app.thread == null) {
3858 return;
3859 }
3860 Message msg = mAm.mHandler.obtainMessage(
3861 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG);
3862 msg.obj = r;
3863 r.fgWaiting = true;
3864 mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT);
Dianne Hackborn2be00932013-09-22 16:46:00 -07003865 }
3866
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003867 final class ServiceDumper {
3868 private final FileDescriptor fd;
3869 private final PrintWriter pw;
3870 private final String[] args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003871 private final boolean dumpAll;
3872 private final String dumpPackage;
3873 private final ItemMatcher matcher;
3874 private final ArrayList<ServiceRecord> services = new ArrayList<>();
3875
3876 private final long nowReal = SystemClock.elapsedRealtime();
3877
3878 private boolean needSep = false;
3879 private boolean printedAnything = false;
3880 private boolean printed = false;
3881
3882 /**
3883 * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
3884 * must be called with the lock held).
3885 */
3886 ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
3887 int opti, boolean dumpAll, String dumpPackage) {
3888 this.fd = fd;
3889 this.pw = pw;
3890 this.args = args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003891 this.dumpAll = dumpAll;
3892 this.dumpPackage = dumpPackage;
3893 matcher = new ItemMatcher();
3894 matcher.build(args, opti);
3895
3896 final int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003897 for (int user : users) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003898 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003899 if (smap.mServicesByInstanceName.size() > 0) {
3900 for (int si=0; si<smap.mServicesByInstanceName.size(); si++) {
3901 ServiceRecord r = smap.mServicesByInstanceName.valueAt(si);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003902 if (!matcher.match(r, r.name)) {
3903 continue;
3904 }
3905 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3906 continue;
3907 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003908 services.add(r);
3909 }
3910 }
3911 }
3912 }
3913
3914 private void dumpHeaderLocked() {
3915 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
3916 if (mLastAnrDump != null) {
3917 pw.println(" Last ANR service:");
3918 pw.print(mLastAnrDump);
3919 pw.println();
3920 }
3921 }
3922
3923 void dumpLocked() {
3924 dumpHeaderLocked();
3925
3926 try {
3927 int[] users = mAm.mUserController.getUsers();
3928 for (int user : users) {
3929 // Find the first service for this user.
3930 int serviceIdx = 0;
3931 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3932 serviceIdx++;
3933 }
3934 printed = false;
3935 if (serviceIdx < services.size()) {
3936 needSep = false;
3937 while (serviceIdx < services.size()) {
3938 ServiceRecord r = services.get(serviceIdx);
3939 serviceIdx++;
3940 if (r.userId != user) {
3941 break;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003942 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003943 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003944 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003945 needSep |= printed;
3946 }
3947
3948 dumpUserRemainsLocked(user);
3949 }
3950 } catch (Exception e) {
3951 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3952 }
3953
3954 dumpRemainsLocked();
3955 }
3956
3957 void dumpWithClient() {
3958 synchronized(mAm) {
3959 dumpHeaderLocked();
3960 }
3961
3962 try {
3963 int[] users = mAm.mUserController.getUsers();
3964 for (int user : users) {
3965 // Find the first service for this user.
3966 int serviceIdx = 0;
3967 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3968 serviceIdx++;
3969 }
3970 printed = false;
3971 if (serviceIdx < services.size()) {
3972 needSep = false;
3973 while (serviceIdx < services.size()) {
3974 ServiceRecord r = services.get(serviceIdx);
3975 serviceIdx++;
3976 if (r.userId != user) {
3977 break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003978 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003979 synchronized(mAm) {
3980 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003981 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003982 dumpServiceClient(r);
3983 }
3984 needSep |= printed;
3985 }
3986
3987 synchronized(mAm) {
3988 dumpUserRemainsLocked(user);
3989 }
3990 }
3991 } catch (Exception e) {
3992 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3993 }
3994
3995 synchronized(mAm) {
3996 dumpRemainsLocked();
3997 }
3998 }
3999
4000 private void dumpUserHeaderLocked(int user) {
4001 if (!printed) {
4002 if (printedAnything) {
4003 pw.println();
4004 }
4005 pw.println(" User " + user + " active services:");
4006 printed = true;
4007 }
4008 printedAnything = true;
4009 if (needSep) {
4010 pw.println();
4011 }
4012 }
4013
4014 private void dumpServiceLocalLocked(ServiceRecord r) {
4015 dumpUserHeaderLocked(r.userId);
4016 pw.print(" * ");
4017 pw.println(r);
4018 if (dumpAll) {
4019 r.dump(pw, " ");
4020 needSep = true;
4021 } else {
4022 pw.print(" app=");
4023 pw.println(r.app);
4024 pw.print(" created=");
Yi Jin6b514142017-10-30 14:54:12 -07004025 TimeUtils.formatDuration(r.createRealTime, nowReal, pw);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004026 pw.print(" started=");
4027 pw.print(r.startRequested);
4028 pw.print(" connections=");
4029 pw.println(r.connections.size());
4030 if (r.connections.size() > 0) {
4031 pw.println(" Connections:");
4032 for (int conni=0; conni<r.connections.size(); conni++) {
4033 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
4034 for (int i = 0; i < clist.size(); i++) {
4035 ConnectionRecord conn = clist.get(i);
4036 pw.print(" ");
4037 pw.print(conn.binding.intent.intent.getIntent()
4038 .toShortString(false, false, false, false));
4039 pw.print(" -> ");
4040 ProcessRecord proc = conn.binding.client;
4041 pw.println(proc != null ? proc.toShortString() : "null");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004042 }
4043 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004044 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004045 }
4046 }
4047
4048 private void dumpServiceClient(ServiceRecord r) {
4049 final ProcessRecord proc = r.app;
4050 if (proc == null) {
4051 return;
4052 }
4053 final IApplicationThread thread = proc.thread;
4054 if (thread == null) {
4055 return;
4056 }
4057 pw.println(" Client:");
4058 pw.flush();
4059 try {
4060 TransferPipe tp = new TransferPipe();
4061 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004062 thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004063 tp.setBufferPrefix(" ");
4064 // Short timeout, since blocking here can
4065 // deadlock with the application.
4066 tp.go(fd, 2000);
4067 } finally {
4068 tp.kill();
4069 }
4070 } catch (IOException e) {
4071 pw.println(" Failure while dumping the service: " + e);
4072 } catch (RemoteException e) {
4073 pw.println(" Got a RemoteException while dumping the service");
4074 }
4075 needSep = true;
4076 }
4077
4078 private void dumpUserRemainsLocked(int user) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07004079 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004080 printed = false;
4081 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
4082 ServiceRecord r = smap.mDelayedStartList.get(si);
4083 if (!matcher.match(r, r.name)) {
4084 continue;
4085 }
4086 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4087 continue;
4088 }
4089 if (!printed) {
4090 if (printedAnything) {
4091 pw.println();
4092 }
4093 pw.println(" User " + user + " delayed start services:");
4094 printed = true;
4095 }
4096 printedAnything = true;
4097 pw.print(" * Delayed start "); pw.println(r);
4098 }
4099 printed = false;
4100 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
4101 ServiceRecord r = smap.mStartingBackground.get(si);
4102 if (!matcher.match(r, r.name)) {
4103 continue;
4104 }
4105 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4106 continue;
4107 }
4108 if (!printed) {
4109 if (printedAnything) {
4110 pw.println();
4111 }
4112 pw.println(" User " + user + " starting in background:");
4113 printed = true;
4114 }
4115 printedAnything = true;
4116 pw.print(" * Starting bg "); pw.println(r);
4117 }
4118 }
4119
4120 private void dumpRemainsLocked() {
4121 if (mPendingServices.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004122 printed = false;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004123 for (int i=0; i<mPendingServices.size(); i++) {
4124 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004125 if (!matcher.match(r, r.name)) {
4126 continue;
4127 }
4128 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4129 continue;
4130 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004131 printedAnything = true;
4132 if (!printed) {
4133 if (needSep) pw.println();
4134 needSep = true;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004135 pw.println(" Pending services:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004136 printed = true;
4137 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004138 pw.print(" * Pending "); pw.println(r);
4139 r.dump(pw, " ");
4140 }
4141 needSep = true;
4142 }
4143
4144 if (mRestartingServices.size() > 0) {
4145 printed = false;
4146 for (int i=0; i<mRestartingServices.size(); i++) {
4147 ServiceRecord r = mRestartingServices.get(i);
4148 if (!matcher.match(r, r.name)) {
4149 continue;
4150 }
4151 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4152 continue;
4153 }
4154 printedAnything = true;
4155 if (!printed) {
4156 if (needSep) pw.println();
4157 needSep = true;
4158 pw.println(" Restarting services:");
4159 printed = true;
4160 }
4161 pw.print(" * Restarting "); pw.println(r);
4162 r.dump(pw, " ");
4163 }
4164 needSep = true;
4165 }
4166
4167 if (mDestroyingServices.size() > 0) {
4168 printed = false;
4169 for (int i=0; i< mDestroyingServices.size(); i++) {
4170 ServiceRecord r = mDestroyingServices.get(i);
4171 if (!matcher.match(r, r.name)) {
4172 continue;
4173 }
4174 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4175 continue;
4176 }
4177 printedAnything = true;
4178 if (!printed) {
4179 if (needSep) pw.println();
4180 needSep = true;
4181 pw.println(" Destroying services:");
4182 printed = true;
4183 }
4184 pw.print(" * Destroy "); pw.println(r);
4185 r.dump(pw, " ");
4186 }
4187 needSep = true;
4188 }
4189
4190 if (dumpAll) {
4191 printed = false;
4192 for (int ic=0; ic<mServiceConnections.size(); ic++) {
4193 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
4194 for (int i=0; i<r.size(); i++) {
4195 ConnectionRecord cr = r.get(i);
4196 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
4197 continue;
4198 }
4199 if (dumpPackage != null && (cr.binding.client == null
4200 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
4201 continue;
4202 }
4203 printedAnything = true;
4204 if (!printed) {
4205 if (needSep) pw.println();
4206 needSep = true;
4207 pw.println(" Connection bindings to services:");
4208 printed = true;
4209 }
4210 pw.print(" * "); pw.println(cr);
4211 cr.dump(pw, " ");
4212 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004213 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004214 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004215
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004216 if (matcher.all) {
4217 final long nowElapsed = SystemClock.elapsedRealtime();
4218 final int[] users = mAm.mUserController.getUsers();
4219 for (int user : users) {
4220 boolean printedUser = false;
4221 ServiceMap smap = mServiceMap.get(user);
4222 if (smap == null) {
4223 continue;
4224 }
4225 for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) {
4226 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
4227 if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) {
4228 continue;
4229 }
4230 if (!printedUser) {
4231 printedUser = true;
4232 printedAnything = true;
4233 if (needSep) pw.println();
4234 needSep = true;
4235 pw.print("Active foreground apps - user ");
4236 pw.print(user);
4237 pw.println(":");
4238 }
4239 pw.print(" #");
4240 pw.print(i);
4241 pw.print(": ");
4242 pw.println(aa.mPackageName);
4243 if (aa.mLabel != null) {
4244 pw.print(" mLabel=");
4245 pw.println(aa.mLabel);
4246 }
4247 pw.print(" mNumActive=");
4248 pw.print(aa.mNumActive);
Dianne Hackbornbe68d492017-05-03 18:04:05 -07004249 pw.print(" mAppOnTop=");
4250 pw.print(aa.mAppOnTop);
4251 pw.print(" mShownWhileTop=");
4252 pw.print(aa.mShownWhileTop);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004253 pw.print(" mShownWhileScreenOn=");
4254 pw.println(aa.mShownWhileScreenOn);
4255 pw.print(" mStartTime=");
4256 TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw);
4257 pw.print(" mStartVisibleTime=");
4258 TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw);
4259 pw.println();
4260 if (aa.mEndTime != 0) {
4261 pw.print(" mEndTime=");
4262 TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw);
4263 pw.println();
4264 }
4265 }
Dianne Hackborncb015632017-06-14 17:30:15 -07004266 if (smap.hasMessagesOrCallbacks()) {
4267 if (needSep) {
4268 pw.println();
4269 }
4270 printedAnything = true;
4271 needSep = true;
4272 pw.print(" Handler - user ");
4273 pw.print(user);
4274 pw.println(":");
4275 smap.dumpMine(new PrintWriterPrinter(pw), " ");
4276 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004277 }
4278 }
4279
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004280 if (!printedAnything) {
4281 pw.println(" (nothing)");
4282 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07004283 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004284 }
4285
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004286 ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4287 int opti, boolean dumpAll, String dumpPackage) {
4288 return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
4289 }
4290
Yi Jin2b30f322018-02-20 15:41:47 -08004291 protected void writeToProto(ProtoOutputStream proto, long fieldId) {
Yi Jin6b514142017-10-30 14:54:12 -07004292 synchronized (mAm) {
Yi Jin2b30f322018-02-20 15:41:47 -08004293 final long outterToken = proto.start(fieldId);
Yi Jin6b514142017-10-30 14:54:12 -07004294 int[] users = mAm.mUserController.getUsers();
4295 for (int user : users) {
4296 ServiceMap smap = mServiceMap.get(user);
4297 if (smap == null) {
4298 continue;
4299 }
4300 long token = proto.start(ActiveServicesProto.SERVICES_BY_USERS);
4301 proto.write(ActiveServicesProto.ServicesByUser.USER_ID, user);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004302 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
Yi Jin6b514142017-10-30 14:54:12 -07004303 for (int i=0; i<alls.size(); i++) {
4304 alls.valueAt(i).writeToProto(proto,
4305 ActiveServicesProto.ServicesByUser.SERVICE_RECORDS);
4306 }
4307 proto.end(token);
4308 }
Yi Jin2b30f322018-02-20 15:41:47 -08004309 proto.end(outterToken);
Yi Jin6b514142017-10-30 14:54:12 -07004310 }
4311 }
4312
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004313 /**
4314 * There are three ways to call this:
4315 * - no service specified: dump all the services
4316 * - a flattened component name that matched an existing service was specified as the
4317 * first arg: dump that one service
4318 * - the first arg isn't the flattened component name of an existing service:
4319 * dump all services whose component contains the first arg as a substring
4320 */
Makoto Onuki0b575a32018-04-16 14:33:59 -07004321 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, final String name,
4322 String[] args, int opti, boolean dumpAll) {
4323 final ArrayList<ServiceRecord> services = new ArrayList<>();
4324
4325 final Predicate<ServiceRecord> filter = DumpUtils.filterRecord(name);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004326
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004327 synchronized (mAm) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07004328 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004329
Makoto Onuki0b575a32018-04-16 14:33:59 -07004330 for (int user : users) {
4331 ServiceMap smap = mServiceMap.get(user);
4332 if (smap == null) {
4333 continue;
4334 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004335 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
Makoto Onuki0b575a32018-04-16 14:33:59 -07004336 for (int i=0; i<alls.size(); i++) {
4337 ServiceRecord r1 = alls.valueAt(i);
4338
4339 if (filter.test(r1)) {
4340 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004341 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004342 }
4343 }
4344 }
4345
4346 if (services.size() <= 0) {
4347 return false;
4348 }
4349
Makoto Onuki0b575a32018-04-16 14:33:59 -07004350 // Sort by component name.
4351 services.sort(Comparator.comparing(WithComponentName::getComponentName));
4352
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004353 boolean needSep = false;
4354 for (int i=0; i<services.size(); i++) {
4355 if (needSep) {
4356 pw.println();
4357 }
4358 needSep = true;
4359 dumpService("", fd, pw, services.get(i), args, dumpAll);
4360 }
4361 return true;
4362 }
4363
4364 /**
4365 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
4366 * there is a thread associated with the service.
4367 */
4368 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
4369 final ServiceRecord r, String[] args, boolean dumpAll) {
4370 String innerPrefix = prefix + " ";
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004371 synchronized (mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004372 pw.print(prefix); pw.print("SERVICE ");
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004373 pw.print(r.shortInstanceName); pw.print(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004374 pw.print(Integer.toHexString(System.identityHashCode(r)));
4375 pw.print(" pid=");
4376 if (r.app != null) pw.println(r.app.pid);
4377 else pw.println("(not running)");
4378 if (dumpAll) {
4379 r.dump(pw, innerPrefix);
4380 }
4381 }
4382 if (r.app != null && r.app.thread != null) {
4383 pw.print(prefix); pw.println(" Client:");
4384 pw.flush();
4385 try {
4386 TransferPipe tp = new TransferPipe();
4387 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004388 r.app.thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004389 tp.setBufferPrefix(prefix + " ");
4390 tp.go(fd);
4391 } finally {
4392 tp.kill();
4393 }
4394 } catch (IOException e) {
4395 pw.println(prefix + " Failure while dumping the service: " + e);
4396 } catch (RemoteException e) {
4397 pw.println(prefix + " Got a RemoteException while dumping the service");
4398 }
4399 }
4400 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004401}