blob: a96676e5fc5f6b5f9f0328d7b87b8791f1dbf1dc [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
680 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
681 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
682 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
683
684 if (DEBUG_PERMISSIONS_REVIEW) {
685 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
686 + r.packageName);
687 }
688
689 mAm.mHandler.post(new Runnable() {
690 @Override
691 public void run() {
692 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
693 }
694 });
695
696 return false;
697 }
698
699 return true;
700 }
701
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700702 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
703 boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
Joe Onorato4eb64fd2016-03-21 15:30:09 -0700704 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700705 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700706 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700707 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700708 r.callStart = false;
Chenjie Yu75b3c492018-10-06 21:45:19 -0700709 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid, r.name.getPackageName(),
710 r.name.getClassName(), StatsLog.SERVICE_STATE_CHANGED__STATE__START);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700711 synchronized (r.stats.getBatteryStats()) {
712 r.stats.startRunningLocked();
713 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800714 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700715 if (error != null) {
716 return new ComponentName("!!", error);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700717 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700718
719 if (r.startRequested && addToStarting) {
720 boolean first = smap.mStartingBackground.size() == 0;
721 smap.mStartingBackground.add(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700722 r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700723 if (DEBUG_DELAYED_SERVICE) {
724 RuntimeException here = new RuntimeException("here");
725 here.fillInStackTrace();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800726 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800727 } else if (DEBUG_DELAYED_STARTS) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800728 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700729 }
730 if (first) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700731 smap.rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700732 }
Christopher Tate08992ac2017-03-21 11:37:06 -0700733 } else if (callerFg || r.fgRequired) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700734 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700735 }
736
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700737 return r.name;
738 }
739
740 private void stopServiceLocked(ServiceRecord service) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700741 if (service.delayed) {
Mohammad Samiul Islame896c212019-01-10 12:14:23 +0000742 // If service isn't actually running, but is being held in the
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700743 // delayed list, then we need to keep it started but note that it
744 // should be stopped once no longer delayed.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800745 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700746 service.delayedStop = true;
747 return;
748 }
Chenjie Yu75b3c492018-10-06 21:45:19 -0700749 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, service.appInfo.uid,
750 service.name.getPackageName(), service.name.getClassName(),
751 StatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700752 synchronized (service.stats.getBatteryStats()) {
753 service.stats.stopRunningLocked();
754 }
755 service.startRequested = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700756 if (service.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700757 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700758 SystemClock.uptimeMillis());
759 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700760 service.callStart = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700761 bringDownServiceIfNeededLocked(service, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700762 }
763
764 int stopServiceLocked(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700765 String resolvedType, int userId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800766 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700767 + " type=" + resolvedType);
768
769 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
770 if (caller != null && callerApp == null) {
771 throw new SecurityException(
772 "Unable to find app for caller " + caller
773 + " (pid=" + Binder.getCallingPid()
774 + ") when stopping service " + service);
775 }
776
777 // If this service is active, make sure it is stopped.
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800778 ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, null,
Svet Ganovd223db32017-12-22 09:43:48 -0800779 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700780 if (r != null) {
781 if (r.record != null) {
782 final long origId = Binder.clearCallingIdentity();
783 try {
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000784 // immediately remove bg activity whitelisting token if there was one
785 removeAllowBackgroundActivityStartsServiceToken(callerApp, r.record,
786 0 /* delayMillis */);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700787 stopServiceLocked(r.record);
788 } finally {
789 Binder.restoreCallingIdentity(origId);
790 }
791 return 1;
792 }
793 return -1;
794 }
795
796 return 0;
797 }
798
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700799 void stopInBackgroundLocked(int uid) {
800 // Stop all services associated with this uid due to it going to the background
801 // stopped state.
802 ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
803 ArrayList<ServiceRecord> stopping = null;
804 if (services != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800805 for (int i = services.mServicesByInstanceName.size() - 1; i >= 0; i--) {
806 ServiceRecord service = services.mServicesByInstanceName.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700807 if (service.appInfo.uid == uid && service.startRequested) {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800808 if (mAm.getAppStartModeLocked(service.appInfo.uid, service.packageName,
Christopher Tatec7933ac2018-03-12 17:57:09 -0700809 service.appInfo.targetSdkVersion, -1, false, false, false)
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800810 != ActivityManager.APP_START_MODE_NORMAL) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700811 if (stopping == null) {
812 stopping = new ArrayList<>();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700813 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800814 String compName = service.shortInstanceName;
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700815 EventLogTags.writeAmStopIdleService(service.appInfo.uid, compName);
816 StringBuilder sb = new StringBuilder(64);
817 sb.append("Stopping service due to app idle: ");
818 UserHandle.formatUid(sb, service.appInfo.uid);
819 sb.append(" ");
Yi Jin6b514142017-10-30 14:54:12 -0700820 TimeUtils.formatDuration(service.createRealTime
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700821 - SystemClock.elapsedRealtime(), sb);
822 sb.append(" ");
823 sb.append(compName);
824 Slog.w(TAG, sb.toString());
825 stopping.add(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700826 }
827 }
828 }
829 if (stopping != null) {
830 for (int i=stopping.size()-1; i>=0; i--) {
831 ServiceRecord service = stopping.get(i);
832 service.delayed = false;
Dianne Hackbornad51be92016-08-16 16:27:36 -0700833 services.ensureNotStartingBackgroundLocked(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700834 stopServiceLocked(service);
835 }
836 }
837 }
838 }
839
Svet Ganov99b60432015-06-27 13:15:22 -0700840 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800841 ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, callingPackage,
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -0700842 Binder.getCallingPid(), Binder.getCallingUid(),
Svet Ganovd223db32017-12-22 09:43:48 -0800843 UserHandle.getCallingUserId(), false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700844
845 IBinder ret = null;
846 if (r != null) {
847 // r.record is null if findServiceLocked() failed the caller permission check
848 if (r.record == null) {
849 throw new SecurityException(
Christopher Desjardins5862c5f2015-05-19 11:25:40 +0000850 "Permission Denial: Accessing service"
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700851 + " from pid=" + Binder.getCallingPid()
852 + ", uid=" + Binder.getCallingUid()
853 + " requires " + r.permission);
854 }
855 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
856 if (ib != null) {
857 ret = ib.binder;
858 }
859 }
860
861 return ret;
862 }
863
864 boolean stopServiceTokenLocked(ComponentName className, IBinder token,
865 int startId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800866 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700867 + " " + token + " startId=" + startId);
Dianne Hackborn41203752012-08-31 14:05:51 -0700868 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700869 if (r != null) {
870 if (startId >= 0) {
871 // Asked to only stop if done with all work. Note that
872 // to avoid leaks, we will take this as dropping all
873 // start items up to and including this one.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -0700874 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700875 if (si != null) {
876 while (r.deliveredStarts.size() > 0) {
877 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
878 cur.removeUriPermissionsLocked();
879 if (cur == si) {
880 break;
881 }
882 }
883 }
884
885 if (r.getLastStartId() != startId) {
886 return false;
887 }
888
889 if (r.deliveredStarts.size() > 0) {
890 Slog.w(TAG, "stopServiceToken startId " + startId
891 + " is last, but have " + r.deliveredStarts.size()
892 + " remaining args");
893 }
894 }
895
Chenjie Yu75b3c492018-10-06 21:45:19 -0700896 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid, r.name.getPackageName(),
897 r.name.getClassName(), StatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700898 synchronized (r.stats.getBatteryStats()) {
899 r.stats.stopRunningLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700900 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700901 r.startRequested = false;
902 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700903 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700904 SystemClock.uptimeMillis());
905 }
906 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700907 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700908 bringDownServiceIfNeededLocked(r, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700909 Binder.restoreCallingIdentity(origId);
910 return true;
911 }
912 return false;
913 }
914
Sudheer Shankac9d94072017-02-22 22:13:55 +0000915 public void setServiceForegroundLocked(ComponentName className, IBinder token,
Dianne Hackborn67324c92016-04-18 13:55:25 -0700916 int id, Notification notification, int flags) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700917 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700918 final long origId = Binder.clearCallingIdentity();
919 try {
Dianne Hackborn41203752012-08-31 14:05:51 -0700920 ServiceRecord r = findServiceLocked(className, token, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700921 if (r != null) {
Sudheer Shankac9d94072017-02-22 22:13:55 +0000922 setServiceForegroundInnerLocked(r, id, notification, flags);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700923 }
924 } finally {
925 Binder.restoreCallingIdentity(origId);
926 }
927 }
928
Dianne Hackborncb015632017-06-14 17:30:15 -0700929 boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) {
930 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid="
931 + aa.mUid);
932 boolean canRemove = false;
933 aa.mHideTime = Long.MAX_VALUE;
934 if (aa.mShownWhileTop) {
935 // If the app was ever at the top of the screen while the foreground
936 // service was running, then we can always just immediately remove it.
937 canRemove = true;
938 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown while on top");
939 } else if (mScreenOn || aa.mShownWhileScreenOn) {
940 final long minTime = aa.mStartVisibleTime
941 + (aa.mStartTime != aa.mStartVisibleTime
942 ? mAm.mConstants.FGSERVICE_SCREEN_ON_AFTER_TIME
943 : mAm.mConstants.FGSERVICE_MIN_SHOWN_TIME);
944 if (nowElapsed >= minTime) {
945 // If shown while the screen is on, and it has been shown for
946 // at least the minimum show time, then we can now remove it.
947 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown long enough with screen on");
948 canRemove = true;
949 } else {
950 // This is when we will be okay to stop telling the user.
951 long reportTime = nowElapsed + mAm.mConstants.FGSERVICE_MIN_REPORT_TIME;
952 aa.mHideTime = reportTime > minTime ? reportTime : minTime;
953 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
954 + " with screen on");
955 }
956 } else {
957 final long minTime = aa.mEndTime
958 + mAm.mConstants.FGSERVICE_SCREEN_ON_BEFORE_TIME;
959 if (nowElapsed >= minTime) {
960 // If the foreground service has only run while the screen is
961 // off, but it has been gone now for long enough that we won't
962 // care to tell the user about it when the screen comes back on,
963 // then we can remove it now.
964 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - gone long enough with screen off");
965 canRemove = true;
966 } else {
967 // This is when we won't care about this old fg service.
968 aa.mHideTime = minTime;
969 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
970 + " with screen off");
971 }
972 }
973 return canRemove;
974 }
975
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700976 void updateForegroundApps(ServiceMap smap) {
977 // This is called from the handler without the lock held.
978 ArrayList<ActiveForegroundApp> active = null;
979 synchronized (mAm) {
980 final long now = SystemClock.elapsedRealtime();
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700981 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700982 if (smap != null) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700983 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Updating foreground apps for user "
984 + smap.mUserId);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700985 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
986 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -0700987 if (aa.mEndTime != 0) {
988 boolean canRemove = foregroundAppShownEnoughLocked(aa, now);
989 if (canRemove) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700990 // This was up for longer than the timeout, so just remove immediately.
991 smap.mActiveForegroundApps.removeAt(i);
992 smap.mActiveForegroundAppsChanged = true;
993 continue;
994 }
Dianne Hackborncb015632017-06-14 17:30:15 -0700995 if (aa.mHideTime < nextUpdateTime) {
996 nextUpdateTime = aa.mHideTime;
997 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700998 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700999 if (!aa.mAppOnTop) {
1000 if (active == null) {
1001 active = new ArrayList<>();
1002 }
Dianne Hackborncb015632017-06-14 17:30:15 -07001003 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
1004 + aa.mPackageName + ", uid=" + aa.mUid);
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001005 active.add(aa);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001006 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001007 }
1008 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
1009 if (nextUpdateTime < Long.MAX_VALUE) {
Dianne Hackborncb015632017-06-14 17:30:15 -07001010 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Next update time in: "
1011 + (nextUpdateTime-now));
1012 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001013 smap.sendMessageAtTime(msg, nextUpdateTime
1014 + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001015 }
1016 }
1017 if (!smap.mActiveForegroundAppsChanged) {
1018 return;
1019 }
1020 smap.mActiveForegroundAppsChanged = false;
1021 }
1022
Dianne Hackborn070d1422018-05-02 13:48:30 -07001023 if (!SHOW_DUNGEON_NOTIFICATION) {
1024 return;
1025 }
1026
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001027 final NotificationManager nm = (NotificationManager) mAm.mContext.getSystemService(
1028 Context.NOTIFICATION_SERVICE);
1029 final Context context = mAm.mContext;
1030
1031 if (active != null) {
1032 for (int i = 0; i < active.size(); i++) {
1033 ActiveForegroundApp aa = active.get(i);
1034 if (aa.mLabel == null) {
1035 PackageManager pm = context.getPackageManager();
1036 try {
1037 ApplicationInfo ai = pm.getApplicationInfoAsUser(aa.mPackageName,
1038 PackageManager.MATCH_KNOWN_PACKAGES, smap.mUserId);
1039 aa.mLabel = ai.loadLabel(pm);
1040 } catch (PackageManager.NameNotFoundException e) {
1041 aa.mLabel = aa.mPackageName;
1042 }
1043 }
1044 }
1045
1046 Intent intent;
1047 String title;
1048 String msg;
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001049 String[] pkgs;
Dan Sandler886e0162017-06-06 14:23:43 -04001050 final long nowElapsed = SystemClock.elapsedRealtime();
1051 long oldestStartTime = nowElapsed;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001052 if (active.size() == 1) {
1053 intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
1054 intent.setData(Uri.fromParts("package", active.get(0).mPackageName, null));
1055 title = context.getString(
1056 R.string.foreground_service_app_in_background, active.get(0).mLabel);
1057 msg = context.getString(R.string.foreground_service_tap_for_details);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001058 pkgs = new String[] { active.get(0).mPackageName };
Dan Sandler2f36ab82017-05-25 00:15:49 -04001059 oldestStartTime = active.get(0).mStartTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001060 } else {
1061 intent = new Intent(Settings.ACTION_FOREGROUND_SERVICES_SETTINGS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001062 pkgs = new String[active.size()];
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001063 for (int i = 0; i < active.size(); i++) {
1064 pkgs[i] = active.get(i).mPackageName;
Dan Sandler2f36ab82017-05-25 00:15:49 -04001065 oldestStartTime = Math.min(oldestStartTime, active.get(i).mStartTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001066 }
1067 intent.putExtra("packages", pkgs);
1068 title = context.getString(
1069 R.string.foreground_service_apps_in_background, active.size());
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001070 msg = active.get(0).mLabel.toString();
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001071 for (int i = 1; i < active.size(); i++) {
1072 msg = context.getString(R.string.foreground_service_multiple_separator,
1073 msg, active.get(i).mLabel);
1074 }
1075 }
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001076 Bundle notificationBundle = new Bundle();
1077 notificationBundle.putStringArray(Notification.EXTRA_FOREGROUND_APPS, pkgs);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001078 Notification.Builder n =
1079 new Notification.Builder(context,
1080 SystemNotificationChannels.FOREGROUND_SERVICE)
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001081 .addExtras(notificationBundle)
Dan Sandler2f36ab82017-05-25 00:15:49 -04001082 .setSmallIcon(R.drawable.stat_sys_vitals)
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001083 .setOngoing(true)
Dan Sandler886e0162017-06-06 14:23:43 -04001084 .setShowWhen(oldestStartTime < nowElapsed)
1085 .setWhen(System.currentTimeMillis() - (nowElapsed - oldestStartTime))
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001086 .setColor(context.getColor(
1087 com.android.internal.R.color.system_notification_accent_color))
1088 .setContentTitle(title)
1089 .setContentText(msg)
1090 .setContentIntent(
1091 PendingIntent.getActivityAsUser(context, 0, intent,
1092 PendingIntent.FLAG_UPDATE_CURRENT,
1093 null, new UserHandle(smap.mUserId)));
1094 nm.notifyAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1095 n.build(), new UserHandle(smap.mUserId));
1096 } else {
1097 nm.cancelAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1098 new UserHandle(smap.mUserId));
1099 }
1100 }
1101
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001102 private void requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001103 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001104 if (timeElapsed != 0) {
1105 smap.sendMessageAtTime(msg,
1106 timeElapsed + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001107 } else {
1108 smap.mActiveForegroundAppsChanged = true;
1109 smap.sendMessage(msg);
1110 }
1111 }
1112
1113 private void decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r) {
1114 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1115 if (active != null) {
1116 active.mNumActive--;
1117 if (active.mNumActive <= 0) {
1118 active.mEndTime = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001119 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Ended running of service");
1120 if (foregroundAppShownEnoughLocked(active, active.mEndTime)) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001121 // Have been active for long enough that we will remove it immediately.
1122 smap.mActiveForegroundApps.remove(r.packageName);
1123 smap.mActiveForegroundAppsChanged = true;
1124 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001125 } else if (active.mHideTime < Long.MAX_VALUE){
1126 requestUpdateActiveForegroundAppsLocked(smap, active.mHideTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001127 }
1128 }
1129 }
1130 }
1131
1132 void updateScreenStateLocked(boolean screenOn) {
1133 if (mScreenOn != screenOn) {
1134 mScreenOn = screenOn;
1135
1136 // If screen is turning on, then we now reset the start time of any foreground
1137 // services that were started while the screen was off.
1138 if (screenOn) {
1139 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001140 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Screen turned on");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001141 for (int i = mServiceMap.size()-1; i >= 0; i--) {
1142 ServiceMap smap = mServiceMap.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -07001143 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001144 boolean changed = false;
1145 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1146 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
Dianne Hackborncb015632017-06-14 17:30:15 -07001147 if (active.mEndTime == 0) {
1148 if (!active.mShownWhileScreenOn) {
1149 active.mShownWhileScreenOn = true;
1150 active.mStartVisibleTime = nowElapsed;
1151 }
1152 } else {
1153 if (!active.mShownWhileScreenOn
1154 && active.mStartVisibleTime == active.mStartTime) {
1155 // If this was never shown while the screen was on, then we will
1156 // count the time it started being visible as now, to tell the user
1157 // about it now that they have a screen to look at.
1158 active.mEndTime = active.mStartVisibleTime = nowElapsed;
1159 }
1160 if (foregroundAppShownEnoughLocked(active, nowElapsed)) {
1161 // Have been active for long enough that we will remove it
1162 // immediately.
1163 smap.mActiveForegroundApps.remove(active.mPackageName);
1164 smap.mActiveForegroundAppsChanged = true;
1165 changed = true;
1166 } else {
1167 if (active.mHideTime < nextUpdateTime) {
1168 nextUpdateTime = active.mHideTime;
1169 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001170 }
1171 }
1172 }
1173 if (changed) {
Dianne Hackborncb015632017-06-14 17:30:15 -07001174 // Need to immediately update.
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001175 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001176 } else if (nextUpdateTime < Long.MAX_VALUE) {
1177 requestUpdateActiveForegroundAppsLocked(smap, nextUpdateTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001178 }
1179 }
1180 }
1181 }
1182 }
1183
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001184 void foregroundServiceProcStateChangedLocked(UidRecord uidRec) {
1185 ServiceMap smap = mServiceMap.get(UserHandle.getUserId(uidRec.uid));
1186 if (smap != null) {
1187 boolean changed = false;
1188 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1189 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
1190 if (active.mUid == uidRec.uid) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07001191 if (uidRec.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001192 if (!active.mAppOnTop) {
1193 active.mAppOnTop = true;
1194 changed = true;
1195 }
1196 active.mShownWhileTop = true;
1197 } else if (active.mAppOnTop) {
1198 active.mAppOnTop = false;
1199 changed = true;
1200 }
1201 }
1202 }
1203 if (changed) {
1204 requestUpdateActiveForegroundAppsLocked(smap, 0);
1205 }
1206 }
1207 }
1208
Christopher Tatec7933ac2018-03-12 17:57:09 -07001209 /**
1210 * @param id Notification ID. Zero === exit foreground state for the given service.
1211 */
1212 private void setServiceForegroundInnerLocked(final ServiceRecord r, int id,
Christopher Tate42a386b2016-11-07 12:21:21 -08001213 Notification notification, int flags) {
1214 if (id != 0) {
1215 if (notification == null) {
1216 throw new IllegalArgumentException("null notification");
1217 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001218 // Instant apps need permission to create foreground services.
1219 if (r.appInfo.isInstantApp()) {
1220 final int mode = mAm.mAppOpsService.checkOperation(
1221 AppOpsManager.OP_INSTANT_APP_START_FOREGROUND,
1222 r.appInfo.uid,
1223 r.appInfo.packageName);
1224 switch (mode) {
1225 case AppOpsManager.MODE_ALLOWED:
1226 break;
1227 case AppOpsManager.MODE_IGNORED:
1228 Slog.w(TAG, "Instant app " + r.appInfo.packageName
1229 + " does not have permission to create foreground services"
1230 + ", ignoring.");
Sudheer Shankac9d94072017-02-22 22:13:55 +00001231 return;
Chad Brubaker97b383f2017-02-02 15:04:35 -08001232 case AppOpsManager.MODE_ERRORED:
1233 throw new SecurityException("Instant app " + r.appInfo.packageName
1234 + " does not have permission to create foreground services");
1235 default:
Dianne Hackborndd027b32018-01-19 17:44:46 -08001236 mAm.enforcePermission(
1237 android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
1238 r.app.pid, r.appInfo.uid, "startForeground");
Chad Brubaker97b383f2017-02-02 15:04:35 -08001239 }
Hui Yu1ea85522018-12-06 16:59:18 -08001240 } else {
1241 if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
1242 mAm.enforcePermission(
1243 android.Manifest.permission.FOREGROUND_SERVICE,
1244 r.app.pid, r.appInfo.uid, "startForeground");
1245 }
1246 if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.Q) {
1247 if (r.serviceInfo.getForegroundServiceType()
1248 == ServiceInfo.FOREGROUND_SERVICE_TYPE_UNSPECIFIED) {
1249 // STOPSHIP(b/120611119): replace log message with SecurityException.
1250 Slog.w(TAG, "missing foregroundServiceType attribute in "
1251 + "service element of manifest file");
1252 }
1253 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001254 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001255 boolean alreadyStartedOp = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001256 boolean stopProcStatsOp = false;
Christopher Tate08992ac2017-03-21 11:37:06 -07001257 if (r.fgRequired) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001258 if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001259 Slog.i(TAG, "Service called startForeground() as required: " + r);
1260 }
1261 r.fgRequired = false;
1262 r.fgWaiting = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001263 alreadyStartedOp = stopProcStatsOp = true;
Christopher Tate08992ac2017-03-21 11:37:06 -07001264 mAm.mHandler.removeMessages(
1265 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
1266 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001267
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001268 try {
1269 boolean ignoreForeground = false;
1270 final int mode = mAm.mAppOpsService.checkOperation(
1271 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
1272 switch (mode) {
1273 case AppOpsManager.MODE_ALLOWED:
1274 case AppOpsManager.MODE_DEFAULT:
1275 // All okay.
1276 break;
1277 case AppOpsManager.MODE_IGNORED:
1278 // Whoops, silently ignore this.
1279 Slog.w(TAG, "Service.startForeground() not allowed due to app op: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001280 + r.shortInstanceName);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001281 ignoreForeground = true;
1282 break;
1283 default:
1284 throw new SecurityException("Foreground not allowed as per app op");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001285 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001286
1287 if (!ignoreForeground &&
1288 appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001289 Slog.w(TAG,
1290 "Service.startForeground() not allowed due to bg restriction: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001291 + r.shortInstanceName);
Christopher Tate45f06c792018-04-25 10:47:23 -07001292 // Back off of any foreground expectations around this service, since we've
1293 // just turned down its fg request.
1294 updateServiceForegroundLocked(r.app, false);
1295 ignoreForeground = true;
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001296 }
1297
1298 // Apps under strict background restrictions simply don't get to have foreground
1299 // services, so now that we've enforced the startForegroundService() contract
1300 // we only do the machinery of making the service foreground when the app
1301 // is not restricted.
1302 if (!ignoreForeground) {
1303 if (r.foregroundId != id) {
1304 cancelForegroundNotificationLocked(r);
1305 r.foregroundId = id;
Christopher Tatec7933ac2018-03-12 17:57:09 -07001306 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001307 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
1308 r.foregroundNoti = notification;
1309 if (!r.isForeground) {
1310 final ServiceMap smap = getServiceMapLocked(r.userId);
1311 if (smap != null) {
1312 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1313 if (active == null) {
1314 active = new ActiveForegroundApp();
1315 active.mPackageName = r.packageName;
1316 active.mUid = r.appInfo.uid;
1317 active.mShownWhileScreenOn = mScreenOn;
1318 if (r.app != null) {
1319 active.mAppOnTop = active.mShownWhileTop =
Wale Ogunwalebff2df42018-10-18 17:09:19 -07001320 r.app.uidRecord.getCurProcState()
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001321 <= ActivityManager.PROCESS_STATE_TOP;
1322 }
1323 active.mStartTime = active.mStartVisibleTime
1324 = SystemClock.elapsedRealtime();
1325 smap.mActiveForegroundApps.put(r.packageName, active);
1326 requestUpdateActiveForegroundAppsLocked(smap, 0);
1327 }
1328 active.mNumActive++;
1329 }
1330 r.isForeground = true;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001331 if (!stopProcStatsOp) {
1332 ServiceState stracker = r.getTracker();
1333 if (stracker != null) {
1334 stracker.setForeground(true,
1335 mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
1336 }
1337 } else {
1338 stopProcStatsOp = false;
1339 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001340 mAm.mAppOpsService.startOperation(
1341 AppOpsManager.getToken(mAm.mAppOpsService),
1342 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName,
1343 true);
1344 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001345 r.appInfo.uid, r.shortInstanceName,
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001346 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER);
Hui Yue361a232018-10-04 15:05:21 -07001347 mAm.updateForegroundServiceUsageStats(r.name, r.userId, true);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001348 }
1349 r.postNotification();
1350 if (r.app != null) {
1351 updateServiceForegroundLocked(r.app, true);
1352 }
1353 getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
1354 mAm.notifyPackageUse(r.serviceInfo.packageName,
1355 PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
1356 } else {
1357 if (DEBUG_FOREGROUND_SERVICE) {
1358 Slog.d(TAG, "Suppressing startForeground() for FAS " + r);
1359 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001360 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001361 } finally {
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001362 if (stopProcStatsOp) {
1363 // We got through to this point with it actively being started foreground,
1364 // and never decided we wanted to keep it like that, so drop it.
1365 ServiceState stracker = r.getTracker();
1366 if (stracker != null) {
1367 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1368 r.lastActivity);
1369 }
1370 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001371 if (alreadyStartedOp) {
1372 // If we had previously done a start op for direct foreground start,
1373 // we have cleared the flag so can now drop it.
1374 mAm.mAppOpsService.finishOperation(
1375 AppOpsManager.getToken(mAm.mAppOpsService),
1376 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001377 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001378 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001379 } else {
1380 if (r.isForeground) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001381 final ServiceMap smap = getServiceMapLocked(r.userId);
1382 if (smap != null) {
1383 decActiveForegroundAppLocked(smap, r);
1384 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001385 r.isForeground = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001386 ServiceState stracker = r.getTracker();
1387 if (stracker != null) {
1388 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1389 r.lastActivity);
1390 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001391 mAm.mAppOpsService.finishOperation(
1392 AppOpsManager.getToken(mAm.mAppOpsService),
1393 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001394 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001395 r.appInfo.uid, r.shortInstanceName,
Chenjie Yuccfe6452018-01-30 11:33:21 -08001396 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Hui Yue361a232018-10-04 15:05:21 -07001397 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
Christopher Tate42a386b2016-11-07 12:21:21 -08001398 if (r.app != null) {
1399 mAm.updateLruProcessLocked(r.app, false, null);
1400 updateServiceForegroundLocked(r.app, true);
1401 }
1402 }
1403 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001404 cancelForegroundNotificationLocked(r);
Christopher Tate42a386b2016-11-07 12:21:21 -08001405 r.foregroundId = 0;
1406 r.foregroundNoti = null;
1407 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1408 r.stripForegroundServiceFlagFromNotification();
1409 if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
1410 r.foregroundId = 0;
1411 r.foregroundNoti = null;
1412 }
1413 }
1414 }
1415 }
1416
Christopher Tate08992ac2017-03-21 11:37:06 -07001417 private void cancelForegroundNotificationLocked(ServiceRecord r) {
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001418 if (r.foregroundId != 0) {
1419 // First check to see if this app has any other active foreground services
1420 // with the same notification ID. If so, we shouldn't actually cancel it,
1421 // because that would wipe away the notification that still needs to be shown
1422 // due the other service.
Dianne Hackbornad51be92016-08-16 16:27:36 -07001423 ServiceMap sm = getServiceMapLocked(r.userId);
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001424 if (sm != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001425 for (int i = sm.mServicesByInstanceName.size() - 1; i >= 0; i--) {
1426 ServiceRecord other = sm.mServicesByInstanceName.valueAt(i);
Dianne Hackborn569a4582016-08-04 14:00:22 -07001427 if (other != r && other.foregroundId == r.foregroundId
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001428 && other.packageName.equals(r.packageName)) {
1429 // Found one! Abort the cancel.
1430 return;
1431 }
1432 }
1433 }
1434 r.cancelNotification();
1435 }
1436 }
1437
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001438 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
1439 boolean anyForeground = false;
Dianne Hackbornc8230512013-07-13 21:32:12 -07001440 for (int i=proc.services.size()-1; i>=0; i--) {
1441 ServiceRecord sr = proc.services.valueAt(i);
Christopher Tatee23fa2b2017-04-20 14:48:13 -07001442 if (sr.isForeground || sr.fgRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001443 anyForeground = true;
1444 break;
1445 }
1446 }
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08001447 mAm.updateProcessForegroundLocked(proc, anyForeground, oomAdj);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001448 }
1449
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001450 private void updateWhitelistManagerLocked(ProcessRecord proc) {
1451 proc.whitelistManager = false;
1452 for (int i=proc.services.size()-1; i>=0; i--) {
1453 ServiceRecord sr = proc.services.valueAt(i);
1454 if (sr.whitelistManager) {
1455 proc.whitelistManager = true;
1456 break;
1457 }
1458 }
1459 }
1460
Dianne Hackborn465fa392014-09-14 14:21:18 -07001461 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
1462 ArraySet<ProcessRecord> updatedProcesses = null;
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001463 for (int i = 0; i < clientProc.connections.size(); i++) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001464 final ConnectionRecord conn = clientProc.connections.valueAt(i);
1465 final ProcessRecord proc = conn.binding.service.app;
1466 if (proc == null || proc == clientProc) {
1467 continue;
1468 } else if (updatedProcesses == null) {
1469 updatedProcesses = new ArraySet<>();
1470 } else if (updatedProcesses.contains(proc)) {
1471 continue;
1472 }
1473 updatedProcesses.add(proc);
1474 updateServiceClientActivitiesLocked(proc, null, false);
1475 }
1476 }
1477
Dianne Hackborndb926082013-10-31 16:32:44 -07001478 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
Dianne Hackborn465fa392014-09-14 14:21:18 -07001479 ConnectionRecord modCr, boolean updateLru) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001480 if (modCr != null && modCr.binding.client != null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001481 if (!modCr.binding.client.hasActivities()) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001482 // This connection is from a client without activities, so adding
1483 // and removing is not interesting.
1484 return false;
1485 }
1486 }
1487
1488 boolean anyClientActivities = false;
1489 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
1490 ServiceRecord sr = proc.services.valueAt(i);
1491 for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) {
1492 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni);
1493 for (int cri=clist.size()-1; cri>=0; cri--) {
1494 ConnectionRecord cr = clist.get(cri);
1495 if (cr.binding.client == null || cr.binding.client == proc) {
1496 // Binding to ourself is not interesting.
1497 continue;
1498 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001499 if (cr.binding.client.hasActivities()) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001500 anyClientActivities = true;
1501 break;
1502 }
1503 }
1504 }
1505 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001506 if (anyClientActivities != proc.hasClientActivities()) {
1507 proc.setHasClientActivities(anyClientActivities);
Dianne Hackborn465fa392014-09-14 14:21:18 -07001508 if (updateLru) {
1509 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
1510 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001511 return true;
1512 }
1513 return false;
1514 }
1515
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001516 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
Svet Ganov9c165d72015-12-01 19:52:26 -08001517 String resolvedType, final IServiceConnection connection, int flags,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001518 String instanceName, String callingPackage, final int userId)
1519 throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001520 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001521 + " type=" + resolvedType + " conn=" + connection.asBinder()
1522 + " flags=0x" + Integer.toHexString(flags));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001523 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
1524 if (callerApp == null) {
1525 throw new SecurityException(
1526 "Unable to find app for caller " + caller
1527 + " (pid=" + Binder.getCallingPid()
1528 + ") when binding service " + service);
1529 }
1530
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001531 ActivityServiceConnectionsHolder<ConnectionRecord> activity = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001532 if (token != null) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001533 activity = mAm.mAtmInternal.getServiceConnectionsHolder(token);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001534 if (activity == null) {
1535 Slog.w(TAG, "Binding with unknown activity: " + token);
1536 return 0;
1537 }
1538 }
1539
1540 int clientLabel = 0;
1541 PendingIntent clientIntent = null;
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001542 final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001543
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001544 if (isCallerSystem) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001545 // Hacky kind of thing -- allow system stuff to tell us
1546 // what they are, so we can report this elsewhere for
1547 // others to know why certain services are running.
Jeff Sharkeyf0ec2e02016-03-21 12:37:54 -06001548 service.setDefusable(true);
1549 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001550 if (clientIntent != null) {
1551 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
1552 if (clientLabel != 0) {
1553 // There are no useful extras in the intent, trash them.
1554 // System code calling with this stuff just needs to know
1555 // this will happen.
1556 service = service.cloneFilter();
1557 }
1558 }
1559 }
1560
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001561 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1562 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
1563 "BIND_TREAT_LIKE_ACTIVITY");
1564 }
1565
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001566 if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
1567 throw new SecurityException(
1568 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1569 + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
1570 }
1571
Svet Ganovd223db32017-12-22 09:43:48 -08001572 if ((flags & Context.BIND_ALLOW_INSTANT) != 0 && !isCallerSystem) {
1573 throw new SecurityException(
1574 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1575 + ") set BIND_ALLOW_INSTANT when binding service " + service);
1576 }
1577
Dianne Hackborna49ad092016-03-03 13:39:10 -08001578 final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Robert Sesekb9a86662015-12-09 16:22:45 -05001579 final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
Svet Ganovd223db32017-12-22 09:43:48 -08001580 final boolean allowInstant = (flags & Context.BIND_ALLOW_INSTANT) != 0;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001581
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001582 ServiceLookupResult res =
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001583 retrieveServiceLocked(service, instanceName, resolvedType, callingPackage,
1584 Binder.getCallingPid(), Binder.getCallingUid(), userId, true,
1585 callerFg, isBindExternal, allowInstant);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001586 if (res == null) {
1587 return 0;
1588 }
1589 if (res.record == null) {
1590 return -1;
1591 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001592 ServiceRecord s = res.record;
1593
Svet Ganov9c165d72015-12-01 19:52:26 -08001594 boolean permissionsReviewRequired = false;
1595
1596 // If permissions need a review before any of the app components can run,
1597 // we schedule binding to the service but do not start its process, then
1598 // we launch a review activity to which is passed a callback to invoke
1599 // when done to start the bound service's process to completing the binding.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001600 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
1601 s.packageName, s.userId)) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001602
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001603 permissionsReviewRequired = true;
Svet Ganov9c165d72015-12-01 19:52:26 -08001604
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001605 // Show a permission review UI only for binding from a foreground app
1606 if (!callerFg) {
1607 Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
1608 + s.packageName + " requires a permissions review");
1609 return 0;
1610 }
Svet Ganov9c165d72015-12-01 19:52:26 -08001611
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001612 final ServiceRecord serviceRecord = s;
1613 final Intent serviceIntent = service;
Svet Ganov9c165d72015-12-01 19:52:26 -08001614
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001615 RemoteCallback callback = new RemoteCallback(
1616 new RemoteCallback.OnResultListener() {
1617 @Override
1618 public void onResult(Bundle result) {
1619 synchronized(mAm) {
1620 final long identity = Binder.clearCallingIdentity();
1621 try {
1622 if (!mPendingServices.contains(serviceRecord)) {
1623 return;
Svet Ganov9c165d72015-12-01 19:52:26 -08001624 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001625 // If there is still a pending record, then the service
1626 // binding request is still valid, so hook them up. We
1627 // proceed only if the caller cleared the review requirement
1628 // otherwise we unbind because the user didn't approve.
1629 if (!mAm.getPackageManagerInternalLocked()
1630 .isPermissionsReviewRequired(
1631 serviceRecord.packageName,
1632 serviceRecord.userId)) {
1633 try {
1634 bringUpServiceLocked(serviceRecord,
1635 serviceIntent.getFlags(),
1636 callerFg, false, false);
1637 } catch (RemoteException e) {
1638 /* ignore - local call */
1639 }
1640 } else {
1641 unbindServiceLocked(connection);
1642 }
1643 } finally {
1644 Binder.restoreCallingIdentity(identity);
Svet Ganov9c165d72015-12-01 19:52:26 -08001645 }
1646 }
Svet Ganov9c165d72015-12-01 19:52:26 -08001647 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001648 });
Svet Ganov9c165d72015-12-01 19:52:26 -08001649
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001650 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
1651 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1652 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1653 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
1654 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
1655
1656 if (DEBUG_PERMISSIONS_REVIEW) {
1657 Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
1658 + s.packageName);
Svet Ganov9c165d72015-12-01 19:52:26 -08001659 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001660
1661 mAm.mHandler.post(new Runnable() {
1662 @Override
1663 public void run() {
1664 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
1665 }
1666 });
Svet Ganov9c165d72015-12-01 19:52:26 -08001667 }
1668
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001669 final long origId = Binder.clearCallingIdentity();
1670
1671 try {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001672 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001673 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001674 + s);
1675 }
1676
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001677 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1678 s.lastActivity = SystemClock.uptimeMillis();
1679 if (!s.hasAutoCreateConnections()) {
1680 // This is the first binding, let the tracker know.
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001681 ServiceState stracker = s.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001682 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001683 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001684 s.lastActivity);
1685 }
1686 }
1687 }
1688
Dianne Hackbornc390aa82019-01-09 16:38:22 -08001689 if ((flags & Context.BIND_RESTRICT_ASSOCIATIONS) != 0) {
1690 mAm.requireAllowedAssociationsLocked(s.appInfo.packageName);
1691 }
1692
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001693 mAm.startAssociationLocked(callerApp.uid, callerApp.processName,
1694 callerApp.getCurProcState(), s.appInfo.uid, s.appInfo.longVersionCode,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001695 s.instanceName, s.processName);
Jesse Evans02af3ea2017-05-03 09:57:16 -07001696 // Once the apps have become associated, if one of them is caller is ephemeral
1697 // the target app should now be able to see the calling app
1698 mAm.grantEphemeralAccessLocked(callerApp.userId, service,
Hai Zhangbb23d532018-08-27 16:00:35 -07001699 UserHandle.getAppId(s.appInfo.uid), UserHandle.getAppId(callerApp.uid));
Dianne Hackbornab2df062015-01-07 13:43:13 -08001700
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001701 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
1702 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001703 connection, flags, clientLabel, clientIntent,
Dianne Hackborn24bbe582018-12-17 11:58:31 -08001704 callerApp.uid, callerApp.processName, callingPackage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001705
1706 IBinder binder = connection.asBinder();
1707 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
1708 if (clist == null) {
1709 clist = new ArrayList<ConnectionRecord>();
1710 s.connections.put(binder, clist);
1711 }
1712 clist.add(c);
1713 b.connections.add(c);
1714 if (activity != null) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001715 activity.addConnection(c);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001716 }
1717 b.client.connections.add(c);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001718 c.startAssociationIfNeeded();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001719 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
1720 b.client.hasAboveClient = true;
1721 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001722 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
1723 s.whitelistManager = true;
1724 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001725 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001726 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07001727 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001728 clist = mServiceConnections.get(binder);
1729 if (clist == null) {
1730 clist = new ArrayList<ConnectionRecord>();
1731 mServiceConnections.put(binder, clist);
1732 }
1733 clist.add(c);
1734
1735 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1736 s.lastActivity = SystemClock.uptimeMillis();
Svet Ganov9c165d72015-12-01 19:52:26 -08001737 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
1738 permissionsReviewRequired) != null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001739 return 0;
1740 }
1741 }
1742
1743 if (s.app != null) {
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001744 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1745 s.app.treatLikeActivity = true;
1746 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001747 if (s.whitelistManager) {
1748 s.app.whitelistManager = true;
1749 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001750 // This could have made the service more important.
Dianne Hackborna631d562018-11-20 15:58:15 -08001751 mAm.updateLruProcessLocked(s.app,
1752 (callerApp.hasActivitiesOrRecentTasks() && s.app.hasClientActivities())
1753 || (callerApp.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP
1754 && (flags & Context.BIND_TREAT_LIKE_ACTIVITY) != 0),
1755 b.client);
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001756 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001757 }
1758
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001759 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001760 + ": received=" + b.intent.received
1761 + " apps=" + b.intent.apps.size()
1762 + " doRebind=" + b.intent.doRebind);
1763
1764 if (s.app != null && b.intent.received) {
1765 // Service is already running, so we can immediately
1766 // publish the connection.
1767 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001768 c.conn.connected(s.name, b.intent.binder, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001769 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001770 Slog.w(TAG, "Failure sending service " + s.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001771 + " to connection " + c.conn.asBinder()
1772 + " (in " + c.binding.client.processName + ")", e);
1773 }
1774
1775 // If this is the first app connected back to this binding,
1776 // and the service had previously asked to be told when
1777 // rebound, then do so.
1778 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001779 requestServiceBindingLocked(s, b.intent, callerFg, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001780 }
1781 } else if (!b.intent.requested) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001782 requestServiceBindingLocked(s, b.intent, callerFg, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001783 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001784
Dianne Hackbornad51be92016-08-16 16:27:36 -07001785 getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001786
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001787 } finally {
1788 Binder.restoreCallingIdentity(origId);
1789 }
1790
1791 return 1;
1792 }
1793
1794 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
1795 final long origId = Binder.clearCallingIdentity();
1796 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001797 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001798 + " " + intent + ": " + service);
1799 if (r != null) {
1800 Intent.FilterComparison filter
1801 = new Intent.FilterComparison(intent);
1802 IntentBindRecord b = r.bindings.get(filter);
1803 if (b != null && !b.received) {
1804 b.binder = service;
1805 b.requested = true;
1806 b.received = true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07001807 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1808 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
1809 for (int i=0; i<clist.size(); i++) {
1810 ConnectionRecord c = clist.get(i);
1811 if (!filter.equals(c.binding.intent.intent)) {
1812 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001813 TAG_SERVICE, "Not publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001814 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001815 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001816 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001817 TAG_SERVICE, "Published intent: " + intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001818 continue;
1819 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001820 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001821 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001822 c.conn.connected(r.name, service, false);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001823 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001824 Slog.w(TAG, "Failure sending service " + r.shortInstanceName
1825 + " to connection " + c.conn.asBinder()
1826 + " (in " + c.binding.client.processName + ")", e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001827 }
1828 }
1829 }
1830 }
1831
Dianne Hackborn164371f2013-10-01 19:10:13 -07001832 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001833 }
1834 } finally {
1835 Binder.restoreCallingIdentity(origId);
1836 }
1837 }
1838
Dianne Hackborna631d562018-11-20 15:58:15 -08001839 void updateServiceGroupLocked(IServiceConnection connection, int group, int importance) {
1840 final IBinder binder = connection.asBinder();
1841 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "updateServiceGroup: conn=" + binder);
1842 final ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1843 if (clist == null) {
1844 throw new IllegalArgumentException("Could not find connection for "
1845 + connection.asBinder());
1846 }
1847 for (int i = clist.size() - 1; i >= 0; i--) {
1848 final ConnectionRecord crec = clist.get(i);
1849 final ServiceRecord srec = crec.binding.service;
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08001850 if (srec != null && (srec.serviceInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) != 0) {
1851 if (srec.app != null) {
1852 if (group > 0) {
1853 srec.app.connectionService = srec;
1854 srec.app.connectionGroup = group;
1855 srec.app.connectionImportance = importance;
1856 } else {
1857 srec.app.connectionService = null;
1858 srec.app.connectionGroup = 0;
1859 srec.app.connectionImportance = 0;
1860 }
Dianne Hackborna631d562018-11-20 15:58:15 -08001861 } else {
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08001862 if (group > 0) {
1863 srec.pendingConnectionGroup = group;
1864 srec.pendingConnectionImportance = importance;
1865 } else {
1866 srec.pendingConnectionGroup = 0;
1867 srec.pendingConnectionImportance = 0;
1868 }
Dianne Hackborna631d562018-11-20 15:58:15 -08001869 }
1870 }
1871 }
1872 }
1873
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001874 boolean unbindServiceLocked(IServiceConnection connection) {
1875 IBinder binder = connection.asBinder();
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001876 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001877 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1878 if (clist == null) {
1879 Slog.w(TAG, "Unbind failed: could not find connection for "
1880 + connection.asBinder());
1881 return false;
1882 }
1883
1884 final long origId = Binder.clearCallingIdentity();
1885 try {
1886 while (clist.size() > 0) {
1887 ConnectionRecord r = clist.get(0);
1888 removeConnectionLocked(r, null, null);
Dianne Hackborn25e1eca2014-09-23 10:13:13 -07001889 if (clist.size() > 0 && clist.get(0) == r) {
1890 // In case it didn't get removed above, do it now.
1891 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
1892 clist.remove(0);
1893 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001894
1895 if (r.binding.service.app != null) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001896 if (r.binding.service.app.whitelistManager) {
Felipe Lemea7778b02016-06-28 10:38:59 -07001897 updateWhitelistManagerLocked(r.binding.service.app);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001898 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001899 // This could have made the service less important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001900 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1901 r.binding.service.app.treatLikeActivity = true;
1902 mAm.updateLruProcessLocked(r.binding.service.app,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001903 r.binding.service.app.hasClientActivities()
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001904 || r.binding.service.app.treatLikeActivity, null);
1905 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001906 mAm.updateOomAdjLocked(r.binding.service.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001907 }
1908 }
Amith Yamasanib2926b12017-05-11 11:13:52 -07001909
1910 mAm.updateOomAdjLocked();
1911
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001912 } finally {
1913 Binder.restoreCallingIdentity(origId);
1914 }
1915
1916 return true;
1917 }
1918
1919 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
1920 final long origId = Binder.clearCallingIdentity();
1921 try {
1922 if (r != null) {
1923 Intent.FilterComparison filter
1924 = new Intent.FilterComparison(intent);
1925 IntentBindRecord b = r.bindings.get(filter);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001926 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001927 + " at " + b + ": apps="
1928 + (b != null ? b.apps.size() : 0));
1929
Dianne Hackborn164371f2013-10-01 19:10:13 -07001930 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001931 if (b != null) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001932 if (b.apps.size() > 0 && !inDestroying) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001933 // Applications have already bound since the last
1934 // unbind, so just rebind right here.
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001935 boolean inFg = false;
1936 for (int i=b.apps.size()-1; i>=0; i--) {
1937 ProcessRecord client = b.apps.valueAt(i).client;
1938 if (client != null && client.setSchedGroup
Dianne Hackborna49ad092016-03-03 13:39:10 -08001939 != ProcessList.SCHED_GROUP_BACKGROUND) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001940 inFg = true;
1941 break;
1942 }
1943 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001944 try {
1945 requestServiceBindingLocked(r, b, inFg, true);
1946 } catch (TransactionTooLargeException e) {
1947 // Don't pass this back to ActivityThread, it's unrelated.
1948 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001949 } else {
1950 // Note to tell the service the next time there is
1951 // a new client.
1952 b.doRebind = true;
1953 }
1954 }
1955
Dianne Hackborn164371f2013-10-01 19:10:13 -07001956 serviceDoneExecutingLocked(r, inDestroying, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001957 }
1958 } finally {
1959 Binder.restoreCallingIdentity(origId);
1960 }
1961 }
1962
1963 private final ServiceRecord findServiceLocked(ComponentName name,
Dianne Hackborn41203752012-08-31 14:05:51 -07001964 IBinder token, int userId) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07001965 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001966 return r == token ? r : null;
1967 }
1968
1969 private final class ServiceLookupResult {
1970 final ServiceRecord record;
1971 final String permission;
1972
1973 ServiceLookupResult(ServiceRecord _record, String _permission) {
1974 record = _record;
1975 permission = _permission;
1976 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001977 }
1978
1979 private class ServiceRestarter implements Runnable {
1980 private ServiceRecord mService;
1981
1982 void setService(ServiceRecord service) {
1983 mService = service;
1984 }
1985
1986 public void run() {
1987 synchronized(mAm) {
1988 performServiceRestartLocked(mService);
1989 }
1990 }
1991 }
1992
1993 private ServiceLookupResult retrieveServiceLocked(Intent service,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001994 String instanceName, String resolvedType, String callingPackage,
1995 int callingPid, int callingUid, int userId,
Svet Ganovd223db32017-12-22 09:43:48 -08001996 boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
1997 boolean allowInstant) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001998 ServiceRecord r = null;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001999 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002000 + " type=" + resolvedType + " callingUid=" + callingUid);
2001
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07002002 userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
jovanaka6763a32018-12-03 17:23:20 -08002003 ActivityManagerInternal.ALLOW_NON_FULL_IN_PROFILE, "service",
2004 callingPackage);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002005
Dianne Hackbornad51be92016-08-16 16:27:36 -07002006 ServiceMap smap = getServiceMapLocked(userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002007 final ComponentName comp;
2008 if (instanceName == null) {
2009 comp = service.getComponent();
2010 } else {
2011 final ComponentName realComp = service.getComponent();
2012 if (realComp == null) {
2013 throw new IllegalArgumentException("Can't use custom instance name '" + instanceName
2014 + "' without expicit component in Intent");
2015 }
2016 comp = new ComponentName(realComp.getPackageName(),
2017 realComp.getClassName() + ":" + instanceName);
2018 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002019 if (comp != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002020 r = smap.mServicesByInstanceName.get(comp);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002021 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002022 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002023 if (r == null && !isBindExternal && instanceName == null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002024 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002025 r = smap.mServicesByIntent.get(filter);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002026 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002027 }
Robert Sesekb9a86662015-12-09 16:22:45 -05002028 if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
2029 && !callingPackage.equals(r.packageName)) {
2030 // If an external service is running within its own package, other packages
2031 // should not bind to that instance.
2032 r = null;
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002033 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Whoops, can't use existing external service");
Robert Sesekb9a86662015-12-09 16:22:45 -05002034 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002035 if (r == null) {
2036 try {
Svet Ganovd223db32017-12-22 09:43:48 -08002037 int flags = ActivityManagerService.STOCK_PM_FLAGS
2038 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
2039 if (allowInstant) {
2040 flags |= PackageManager.MATCH_INSTANT;
2041 }
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002042 // TODO: come back and remove this assumption to triage all services
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002043 ResolveInfo rInfo = mAm.getPackageManagerInternalLocked().resolveService(service,
Svet Ganovd223db32017-12-22 09:43:48 -08002044 resolvedType, flags, userId, callingUid);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002045 ServiceInfo sInfo = rInfo != null ? rInfo.serviceInfo : null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002046 if (sInfo == null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002047 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002048 ": not found");
2049 return null;
2050 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002051 if (instanceName != null
2052 && (sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
2053 throw new IllegalArgumentException("Can't use instance name '" + instanceName
2054 + "' with non-isolated service '" + sInfo.name + "'");
2055 }
2056 ComponentName className = new ComponentName(
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002057 sInfo.applicationInfo.packageName, sInfo.name);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002058 ComponentName name = comp != null ? comp : className;
Dianne Hackborn769b2e72018-12-05 08:51:20 -08002059 if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid,
2060 name.getPackageName(), sInfo.applicationInfo.uid)) {
2061 String msg = "association not allowed between packages "
Amith Yamasani9f96c2b2018-12-19 18:32:44 -08002062 + callingPackage + " and " + name.getPackageName();
Dianne Hackborn769b2e72018-12-05 08:51:20 -08002063 Slog.w(TAG, "Service lookup failed: " + msg);
2064 return new ServiceLookupResult(null, msg);
2065 }
Robert Sesekb9a86662015-12-09 16:22:45 -05002066 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
2067 if (isBindExternal) {
2068 if (!sInfo.exported) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002069 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
2070 + className + " is not exported");
Robert Sesekb9a86662015-12-09 16:22:45 -05002071 }
2072 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002073 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
2074 + className + " is not an isolatedProcess");
Robert Sesekb9a86662015-12-09 16:22:45 -05002075 }
2076 // Run the service under the calling package's application.
2077 ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
2078 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
2079 if (aInfo == null) {
2080 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
2081 "could not resolve client package " + callingPackage);
2082 }
2083 sInfo = new ServiceInfo(sInfo);
2084 sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
2085 sInfo.applicationInfo.packageName = aInfo.packageName;
2086 sInfo.applicationInfo.uid = aInfo.uid;
2087 name = new ComponentName(aInfo.packageName, name.getClassName());
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002088 className = new ComponentName(aInfo.packageName,
2089 instanceName == null ? className.getClassName()
2090 : (className.getClassName() + ":" + instanceName));
Robert Sesekb9a86662015-12-09 16:22:45 -05002091 service.setComponent(name);
2092 } else {
2093 throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
2094 name);
2095 }
2096 } else if (isBindExternal) {
2097 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
2098 " is not an externalService");
2099 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002100 if (userId > 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07002101 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
Amith Yamasani4b9d79c2014-05-21 19:14:21 -07002102 sInfo.name, sInfo.flags)
2103 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002104 userId = 0;
Dianne Hackbornad51be92016-08-16 16:27:36 -07002105 smap = getServiceMapLocked(0);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002106 }
2107 sInfo = new ServiceInfo(sInfo);
2108 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
2109 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002110 r = smap.mServicesByInstanceName.get(name);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002111 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE,
2112 "Retrieved via pm by intent: " + r);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002113 if (r == null && createIfNeeded) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002114 final Intent.FilterComparison filter
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002115 = new Intent.FilterComparison(service.cloneFilter());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002116 final ServiceRestarter res = new ServiceRestarter();
2117 final BatteryStatsImpl.Uid.Pkg.Serv ss;
2118 final BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002119 synchronized (stats) {
2120 ss = stats.getServiceStatsLocked(
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002121 sInfo.applicationInfo.uid, name.getPackageName(),
2122 name.getClassName());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002123 }
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08002124 r = new ServiceRecord(mAm, ss, className, name, filter, sInfo,
2125 callingFromFg, res);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002126 res.setService(r);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002127 smap.mServicesByInstanceName.put(name, r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002128 smap.mServicesByIntent.put(filter, r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002129
2130 // Make sure this component isn't in the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002131 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002132 final ServiceRecord pr = mPendingServices.get(i);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002133 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002134 && pr.instanceName.equals(name)) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002135 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002136 mPendingServices.remove(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002137 }
2138 }
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002139 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002140 }
2141 } catch (RemoteException ex) {
2142 // pm is in same process, this will never happen.
2143 }
2144 }
2145 if (r != null) {
Dianne Hackborn769b2e72018-12-05 08:51:20 -08002146 if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid, r.packageName,
2147 r.appInfo.uid)) {
2148 String msg = "association not allowed between packages "
2149 + callingPackage + " and " + r.packageName;
2150 Slog.w(TAG, "Service lookup failed: " + msg);
2151 return new ServiceLookupResult(null, msg);
2152 }
2153 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
2154 resolvedType, r.appInfo)) {
2155 return new ServiceLookupResult(null, "blocked by firewall");
2156 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002157 if (mAm.checkComponentPermission(r.permission,
Bryce Lee290e5782017-02-01 16:41:20 -08002158 callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002159 if (!r.exported) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002160 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002161 + " from pid=" + callingPid
2162 + ", uid=" + callingUid
2163 + " that is not exported from uid " + r.appInfo.uid);
2164 return new ServiceLookupResult(null, "not exported from uid "
2165 + r.appInfo.uid);
2166 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002167 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002168 + " from pid=" + callingPid
2169 + ", uid=" + callingUid
2170 + " requires " + r.permission);
2171 return new ServiceLookupResult(null, r.permission);
Svet Ganov99b60432015-06-27 13:15:22 -07002172 } else if (r.permission != null && callingPackage != null) {
2173 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
2174 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation(
2175 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002176 Slog.w(TAG, "Appop Denial: Accessing service " + r.shortInstanceName
Svet Ganov99b60432015-06-27 13:15:22 -07002177 + " from pid=" + callingPid
2178 + ", uid=" + callingUid
2179 + " requires appop " + AppOpsManager.opToName(opCode));
2180 return null;
2181 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002182 }
2183 return new ServiceLookupResult(r, null);
2184 }
2185 return null;
2186 }
2187
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002188 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002189 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002190 + why + " of " + r + " in app " + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002191 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002192 + why + " of " + r.shortInstanceName);
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002193
2194 // For b/34123235: Services within the system server won't start until SystemServer
2195 // does Looper.loop(), so we shouldn't try to start/bind to them too early in the boot
2196 // process. However, since there's a little point of showing the ANR dialog in that case,
2197 // let's suppress the timeout until PHASE_THIRD_PARTY_APPS_CAN_START.
2198 //
2199 // (Note there are multiple services start at PHASE_THIRD_PARTY_APPS_CAN_START too,
2200 // which technically could also trigger this timeout if there's a system server
2201 // that takes a long time to handle PHASE_THIRD_PARTY_APPS_CAN_START, but that shouldn't
2202 // happen.)
2203 boolean timeoutNeeded = true;
2204 if ((mAm.mBootPhase < SystemService.PHASE_THIRD_PARTY_APPS_CAN_START)
2205 && (r.app != null) && (r.app.pid == android.os.Process.myPid())) {
2206
2207 Slog.w(TAG, "Too early to start/bind service in system_server: Phase=" + mAm.mBootPhase
2208 + " " + r.getComponentName());
2209 timeoutNeeded = false;
2210 }
2211
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002212 long now = SystemClock.uptimeMillis();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002213 if (r.executeNesting == 0) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002214 r.executeFg = fg;
Joe Onorato4eb64fd2016-03-21 15:30:09 -07002215 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002216 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002217 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002218 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002219 if (r.app != null) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002220 r.app.executingServices.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002221 r.app.execServicesFg |= fg;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002222 if (timeoutNeeded && r.app.executingServices.size() == 1) {
Dianne Hackborn2be00932013-09-22 16:46:00 -07002223 scheduleServiceTimeoutLocked(r.app);
2224 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002225 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002226 } else if (r.app != null && fg && !r.app.execServicesFg) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002227 r.app.execServicesFg = true;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002228 if (timeoutNeeded) {
2229 scheduleServiceTimeoutLocked(r.app);
2230 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002231 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002232 r.executeFg |= fg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002233 r.executeNesting++;
2234 r.executingStart = now;
2235 }
2236
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002237 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
2238 boolean execInFg, boolean rebind) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002239 if (r.app == null || r.app.thread == null) {
2240 // If service is not currently running, can't yet bind.
2241 return false;
2242 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08002243 if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
2244 + " rebind=" + rebind);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002245 if ((!i.requested || rebind) && i.apps.size() > 0) {
2246 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002247 bumpServiceExecutingLocked(r, execInFg, "bind");
Dianne Hackborna413dc02013-07-12 12:02:55 -07002248 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
2249 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002250 r.app.getReportedProcState());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002251 if (!rebind) {
2252 i.requested = true;
2253 }
2254 i.hasBound = true;
2255 i.doRebind = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002256 } catch (TransactionTooLargeException e) {
2257 // Keep the executeNesting count accurate.
2258 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
2259 final boolean inDestroying = mDestroyingServices.contains(r);
2260 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2261 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002262 } catch (RemoteException e) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002263 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002264 // Keep the executeNesting count accurate.
2265 final boolean inDestroying = mDestroyingServices.contains(r);
2266 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002267 return false;
2268 }
2269 }
2270 return true;
2271 }
2272
Dianne Hackbornad51be92016-08-16 16:27:36 -07002273 private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002274 boolean canceled = false;
2275
Wale Ogunwalef6733932018-06-27 05:14:34 -07002276 if (mAm.mAtmInternal.isShuttingDown()) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002277 Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortInstanceName
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07002278 + " - system is shutting down");
2279 return false;
2280 }
2281
Dianne Hackbornad51be92016-08-16 16:27:36 -07002282 ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002283 if (smap.mServicesByInstanceName.get(r.instanceName) != r) {
2284 ServiceRecord cur = smap.mServicesByInstanceName.get(r.instanceName);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002285 Slog.wtf(TAG, "Attempting to schedule restart of " + r
2286 + " when found in map: " + cur);
2287 return false;
2288 }
2289
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002290 final long now = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002291
2292 if ((r.serviceInfo.applicationInfo.flags
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002293 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002294 long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION;
2295 long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002296
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002297 // Any delivered but not yet finished starts should be put back
2298 // on the pending list.
2299 final int N = r.deliveredStarts.size();
2300 if (N > 0) {
2301 for (int i=N-1; i>=0; i--) {
2302 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
2303 si.removeUriPermissionsLocked();
2304 if (si.intent == null) {
2305 // We'll generate this again if needed.
2306 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
2307 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
2308 r.pendingStarts.add(0, si);
2309 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
2310 dur *= 2;
2311 if (minDuration < dur) minDuration = dur;
2312 if (resetTime < dur) resetTime = dur;
2313 } else {
2314 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002315 + r.shortInstanceName);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002316 canceled = true;
2317 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002318 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002319 r.deliveredStarts.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002320 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002321
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002322 r.totalRestartCount++;
2323 if (r.restartDelay == 0) {
2324 r.restartCount++;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002325 r.restartDelay = minDuration;
Amith Yamasanib0c8a882017-08-28 09:36:42 -07002326 } else if (r.crashCount > 1) {
2327 r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
2328 * (r.crashCount - 1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002329 } else {
Varun Shah4311f212019-01-23 05:59:31 +00002330 // If it has been a "reasonably long time" since the service
2331 // was started, then reset our restart duration back to
2332 // the beginning, so we don't infinitely increase the duration
2333 // on a service that just occasionally gets killed (which is
2334 // a normal case, due to process being killed to reclaim memory).
2335 if (now > (r.restartTime+resetTime)) {
2336 r.restartCount = 1;
2337 r.restartDelay = minDuration;
Varun Shah16522412018-12-28 15:46:01 -08002338 } else {
Varun Shah4311f212019-01-23 05:59:31 +00002339 r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
2340 if (r.restartDelay < minDuration) {
2341 r.restartDelay = minDuration;
Varun Shah16522412018-12-28 15:46:01 -08002342 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002343 }
2344 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002345
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002346 r.nextRestartTime = now + r.restartDelay;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002347
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002348 // Make sure that we don't end up restarting a bunch of services
2349 // all at the same time.
Varun Shah4311f212019-01-23 05:59:31 +00002350 boolean repeat;
2351 do {
2352 repeat = false;
2353 final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
2354 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2355 ServiceRecord r2 = mRestartingServices.get(i);
2356 if (r2 != r && r.nextRestartTime >= (r2.nextRestartTime-restartTimeBetween)
2357 && r.nextRestartTime < (r2.nextRestartTime+restartTimeBetween)) {
2358 r.nextRestartTime = r2.nextRestartTime + restartTimeBetween;
2359 r.restartDelay = r.nextRestartTime - now;
2360 repeat = true;
2361 break;
2362 }
2363 }
2364 } while (repeat);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002365
2366 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07002367 // Persistent processes are immediately restarted, so there is no
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002368 // reason to hold of on restarting their services.
2369 r.totalRestartCount++;
2370 r.restartCount = 0;
2371 r.restartDelay = 0;
2372 r.nextRestartTime = now;
2373 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002374
2375 if (!mRestartingServices.contains(r)) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002376 r.createdFromFg = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002377 mRestartingServices.add(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002378 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002379 }
2380
Christopher Tate08992ac2017-03-21 11:37:06 -07002381 cancelForegroundNotificationLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002382
2383 mAm.mHandler.removeCallbacks(r.restarter);
2384 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
2385 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
2386 Slog.w(TAG, "Scheduling restart of crashed service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002387 + r.shortInstanceName + " in " + r.restartDelay + "ms");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002388 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002389 r.userId, r.shortInstanceName, r.restartDelay);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002390
2391 return canceled;
2392 }
2393
2394 final void performServiceRestartLocked(ServiceRecord r) {
2395 if (!mRestartingServices.contains(r)) {
2396 return;
2397 }
Dianne Hackbornad51be92016-08-16 16:27:36 -07002398 if (!isServiceNeededLocked(r, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002399 // Paranoia: is this service actually needed? In theory a service that is not
2400 // needed should never remain on the restart list. In practice... well, there
2401 // have been bugs where this happens, and bad things happen because the process
2402 // ends up just being cached, so quickly killed, then restarted again and again.
2403 // Let's not let that happen.
2404 Slog.wtf(TAG, "Restarting service that is not needed: " + r);
2405 return;
2406 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002407 try {
Svet Ganov9c165d72015-12-01 19:52:26 -08002408 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002409 } catch (TransactionTooLargeException e) {
2410 // Ignore, it's been logged and nothing upstack cares.
2411 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002412 }
2413
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002414 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
2415 boolean force) {
2416 if (!force && r.restartDelay == 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002417 return false;
2418 }
Dianne Hackborn7b492722013-11-01 09:58:45 -07002419 // Remove from the restarting list; if the service is currently on the
2420 // restarting list, or the call is coming from another app, then this
2421 // service has become of much more interest so we reset the restart interval.
2422 boolean removed = mRestartingServices.remove(r);
2423 if (removed || callingUid != r.appInfo.uid) {
2424 r.resetRestartCounter();
2425 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002426 if (removed) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002427 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002428 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002429 mAm.mHandler.removeCallbacks(r.restarter);
2430 return true;
2431 }
2432
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002433 private void clearRestartingIfNeededLocked(ServiceRecord r) {
2434 if (r.restartTracker != null) {
2435 // If this is the last restarting record with this tracker, then clear
2436 // the tracker's restarting state.
2437 boolean stillTracking = false;
2438 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2439 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
2440 stillTracking = true;
2441 break;
2442 }
2443 }
2444 if (!stillTracking) {
2445 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
2446 SystemClock.uptimeMillis());
2447 r.restartTracker = null;
2448 }
2449 }
2450 }
2451
Svet Ganov9c165d72015-12-01 19:52:26 -08002452 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
2453 boolean whileRestarting, boolean permissionsReviewRequired)
2454 throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002455 //Slog.i(TAG, "Bring up service:");
2456 //r.dump(" ");
2457
2458 if (r.app != null && r.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002459 sendServiceArgsLocked(r, execInFg, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002460 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002461 }
2462
Sudheer Shanka03d0f812017-04-20 16:57:50 -07002463 if (!whileRestarting && mRestartingServices.contains(r)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002464 // If waiting for a restart, then do nothing.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002465 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002466 }
2467
Christopher Tate08992ac2017-03-21 11:37:06 -07002468 if (DEBUG_SERVICE) {
2469 Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
2470 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002471
2472 // We are now bringing the service up, so no longer in the
2473 // restarting state.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002474 if (mRestartingServices.remove(r)) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002475 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002476 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002477
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002478 // Make sure this service is no longer considered delayed, we are starting it now.
2479 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002480 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002481 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002482 r.delayed = false;
2483 }
2484
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002485 // Make sure that the user who owns this service is started. If not,
2486 // we don't want to allow it to run.
Fyodor Kupolov610acda2015-10-19 18:44:07 -07002487 if (!mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002488 String msg = "Unable to launch app "
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002489 + r.appInfo.packageName + "/"
2490 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002491 + r.intent.getIntent() + ": user " + r.userId + " is stopped";
2492 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002493 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002494 return msg;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002495 }
2496
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002497 // Service is now being launched, its package can't be stopped.
2498 try {
2499 AppGlobals.getPackageManager().setPackageStoppedState(
2500 r.packageName, false, r.userId);
2501 } catch (RemoteException e) {
2502 } catch (IllegalArgumentException e) {
2503 Slog.w(TAG, "Failed trying to unstop package "
2504 + r.packageName + ": " + e);
2505 }
2506
2507 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
2508 final String procName = r.processName;
Robert Sesekc5f86642016-11-04 10:20:38 -04002509 String hostingType = "service";
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002510 ProcessRecord app;
2511
2512 if (!isolated) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07002513 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
2514 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
2515 + " app=" + app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002516 if (app != null && app.thread != null) {
2517 try {
Patrick Baumannc2def582018-04-04 12:14:15 -07002518 app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode, mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002519 realStartServiceLocked(r, app, execInFg);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002520 return null;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002521 } catch (TransactionTooLargeException e) {
2522 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002523 } catch (RemoteException e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002524 Slog.w(TAG, "Exception when starting service " + r.shortInstanceName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002525 }
2526
2527 // If a dead object exception was thrown -- fall through to
2528 // restart the application.
2529 }
2530 } else {
2531 // If this service runs in an isolated process, then each time
2532 // we call startProcessLocked() we will get a new isolated
2533 // process, starting another process if we are currently waiting
2534 // for a previous process to come up. To deal with this, we store
2535 // in the service any current isolated process it is running in or
2536 // waiting to have come up.
2537 app = r.isolatedProc;
Robert Sesekc5f86642016-11-04 10:20:38 -04002538 if (WebViewZygote.isMultiprocessEnabled()
2539 && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
2540 hostingType = "webview_service";
2541 }
Martijn Coenen7e6fa672018-11-05 11:45:26 +01002542 if ((r.serviceInfo.flags & ServiceInfo.FLAG_USE_APP_ZYGOTE) != 0) {
2543 hostingType = "app_zygote";
2544 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002545 }
2546
2547 // Not running -- get it started, and enqueue this service record
2548 // to be executed when the app comes up.
Svet Ganov9c165d72015-12-01 19:52:26 -08002549 if (app == null && !permissionsReviewRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002550 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002551 hostingType, r.instanceName, false, isolated, false)) == null) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002552 String msg = "Unable to launch app "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002553 + r.appInfo.packageName + "/"
2554 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002555 + r.intent.getIntent() + ": process is bad";
2556 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002557 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002558 return msg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002559 }
2560 if (isolated) {
2561 r.isolatedProc = app;
2562 }
2563 }
2564
Christopher Tate1536cc22017-09-18 16:43:30 -07002565 if (r.fgRequired) {
2566 if (DEBUG_FOREGROUND_SERVICE) {
2567 Slog.v(TAG, "Whitelisting " + UserHandle.formatUid(r.appInfo.uid)
2568 + " for fg-service launch");
2569 }
2570 mAm.tempWhitelistUidLocked(r.appInfo.uid,
2571 SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch");
2572 }
2573
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002574 if (!mPendingServices.contains(r)) {
2575 mPendingServices.add(r);
2576 }
2577
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002578 if (r.delayedStop) {
2579 // Oh and hey we've already been asked to stop!
2580 r.delayedStop = false;
2581 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002582 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2583 "Applying delayed stop (in bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002584 stopServiceLocked(r);
2585 }
2586 }
2587
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002588 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002589 }
2590
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002591 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
2592 throws TransactionTooLargeException {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002593 for (int i=r.bindings.size()-1; i>=0; i--) {
2594 IntentBindRecord ibr = r.bindings.valueAt(i);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002595 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002596 break;
2597 }
2598 }
2599 }
2600
2601 private final void realStartServiceLocked(ServiceRecord r,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002602 ProcessRecord app, boolean execInFg) throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002603 if (app.thread == null) {
2604 throw new RemoteException();
2605 }
2606 if (DEBUG_MU)
2607 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
2608 + ", ProcessRecord.uid = " + app.uid);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002609 r.setProcess(app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002610 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
2611
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002612 final boolean newService = app.services.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002613 bumpServiceExecutingLocked(r, execInFg, "create");
Dianne Hackborndb926082013-10-31 16:32:44 -07002614 mAm.updateLruProcessLocked(app, false, null);
Makoto Onuki0f421292017-04-28 15:03:33 -07002615 updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
2616 mAm.updateOomAdjLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002617
2618 boolean created = false;
2619 try {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002620 if (LOG_SERVICE_START_STOP) {
Dianne Hackbornab2df062015-01-07 13:43:13 -08002621 String nameTerm;
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002622 int lastPeriod = r.shortInstanceName.lastIndexOf('.');
2623 nameTerm = lastPeriod >= 0 ? r.shortInstanceName.substring(lastPeriod)
2624 : r.shortInstanceName;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002625 EventLogTags.writeAmCreateService(
2626 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
2627 }
Chenjie Yu75b3c492018-10-06 21:45:19 -07002628 StatsLog.write(StatsLog.SERVICE_LAUNCH_REPORTED, r.appInfo.uid, r.name.getPackageName(),
2629 r.name.getClassName());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002630 synchronized (r.stats.getBatteryStats()) {
2631 r.stats.startLaunchedLocked();
2632 }
Brian Carlstromca82e612016-04-19 23:16:08 -07002633 mAm.notifyPackageUse(r.serviceInfo.packageName,
2634 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
Dianne Hackborna413dc02013-07-12 12:02:55 -07002635 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002636 app.thread.scheduleCreateService(r, r.serviceInfo,
Wale Ogunwale53783742018-09-16 10:21:51 -07002637 mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002638 app.getReportedProcState());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002639 r.postNotification();
2640 created = true;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -07002641 } catch (DeadObjectException e) {
2642 Slog.w(TAG, "Application dead when creating service " + r);
2643 mAm.appDiedLocked(app);
Wale Ogunwalebfac4682015-04-08 14:33:21 -07002644 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002645 } finally {
2646 if (!created) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002647 // Keep the executeNesting count accurate.
2648 final boolean inDestroying = mDestroyingServices.contains(r);
2649 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2650
2651 // Cleanup.
2652 if (newService) {
2653 app.services.remove(r);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002654 r.setProcess(null);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002655 }
2656
2657 // Retry.
2658 if (!inDestroying) {
2659 scheduleServiceRestartLocked(r, false);
2660 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002661 }
2662 }
2663
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002664 if (r.whitelistManager) {
2665 app.whitelistManager = true;
2666 }
2667
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002668 requestServiceBindingsLocked(r, execInFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002669
Dianne Hackborn465fa392014-09-14 14:21:18 -07002670 updateServiceClientActivitiesLocked(app, null, true);
2671
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002672 // If the service is in the started state, and there are no
2673 // pending arguments, then fake up one so its onStartCommand() will
2674 // be called.
2675 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
2676 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002677 null, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002678 }
2679
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002680 sendServiceArgsLocked(r, execInFg, true);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002681
2682 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002683 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002684 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002685 r.delayed = false;
2686 }
2687
2688 if (r.delayedStop) {
2689 // Oh and hey we've already been asked to stop!
2690 r.delayedStop = false;
2691 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002692 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2693 "Applying delayed stop (from start): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002694 stopServiceLocked(r);
2695 }
2696 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002697 }
2698
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002699 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002700 boolean oomAdjusted) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002701 final int N = r.pendingStarts.size();
2702 if (N == 0) {
2703 return;
2704 }
2705
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002706 ArrayList<ServiceStartArgs> args = new ArrayList<>();
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002707
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002708 while (r.pendingStarts.size() > 0) {
2709 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
2710 if (DEBUG_SERVICE) {
2711 Slog.v(TAG_SERVICE, "Sending arguments to: "
2712 + r + " " + r.intent + " args=" + si.intent);
2713 }
2714 if (si.intent == null && N > 1) {
2715 // If somehow we got a dummy null intent in the middle,
2716 // then skip it. DO NOT skip a null intent when it is
2717 // the only one in the list -- this is to support the
2718 // onStartCommand(null) case.
2719 continue;
2720 }
2721 si.deliveredTime = SystemClock.uptimeMillis();
2722 r.deliveredStarts.add(si);
2723 si.deliveryCount++;
2724 if (si.neededGrants != null) {
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07002725 mAm.mUgmInternal.grantUriPermissionUncheckedFromIntent(si.neededGrants,
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002726 si.getUriPermissionsLocked());
2727 }
Hai Zhangbb23d532018-08-27 16:00:35 -07002728 mAm.grantEphemeralAccessLocked(r.userId, si.intent, UserHandle.getAppId(r.appInfo.uid),
2729 UserHandle.getAppId(si.callingId));
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002730 bumpServiceExecutingLocked(r, execInFg, "start");
2731 if (!oomAdjusted) {
2732 oomAdjusted = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002733 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002734 }
2735 if (r.fgRequired && !r.fgWaiting) {
2736 if (!r.isForeground) {
2737 if (DEBUG_BACKGROUND_CHECK) {
2738 Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r);
2739 }
2740 scheduleServiceForegroundTransitionTimeoutLocked(r);
2741 } else {
2742 if (DEBUG_BACKGROUND_CHECK) {
2743 Slog.i(TAG, "Service already foreground; no new timeout: " + r);
2744 }
2745 r.fgRequired = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002746 }
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002747 }
2748 int flags = 0;
2749 if (si.deliveryCount > 1) {
2750 flags |= Service.START_FLAG_RETRY;
2751 }
2752 if (si.doneExecutingCount > 0) {
2753 flags |= Service.START_FLAG_REDELIVERY;
2754 }
2755 args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
2756 }
2757
2758 ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
2759 slice.setInlineCountLimit(4);
2760 Exception caughtException = null;
2761 try {
2762 r.app.thread.scheduleServiceArgs(r, slice);
2763 } catch (TransactionTooLargeException e) {
2764 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
2765 + " args, first: " + args.get(0).args);
2766 Slog.w(TAG, "Failed delivering service starts", e);
2767 caughtException = e;
2768 } catch (RemoteException e) {
2769 // Remote process gone... we'll let the normal cleanup take care of this.
2770 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
2771 Slog.w(TAG, "Failed delivering service starts", e);
2772 caughtException = e;
2773 } catch (Exception e) {
2774 Slog.w(TAG, "Unexpected exception", e);
2775 caughtException = e;
2776 }
2777
2778 if (caughtException != null) {
2779 // Keep nesting count correct
2780 final boolean inDestroying = mDestroyingServices.contains(r);
2781 for (int i = 0; i < args.size(); i++) {
2782 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2783 }
2784 if (caughtException instanceof TransactionTooLargeException) {
2785 throw (TransactionTooLargeException)caughtException;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002786 }
2787 }
2788 }
2789
Dianne Hackbornad51be92016-08-16 16:27:36 -07002790 private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn,
2791 boolean hasConn) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002792 // Are we still explicitly being asked to run?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002793 if (r.startRequested) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002794 return true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002795 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002796
Dianne Hackborncb015632017-06-14 17:30:15 -07002797 // Is someone still bound to us keeping us running?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002798 if (!knowConn) {
2799 hasConn = r.hasAutoCreateConnections();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002800 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002801 if (hasConn) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002802 return true;
2803 }
2804
2805 return false;
2806 }
2807
2808 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
2809 boolean hasConn) {
2810 //Slog.i(TAG, "Bring down service:");
2811 //r.dump(" ");
2812
Dianne Hackbornad51be92016-08-16 16:27:36 -07002813 if (isServiceNeededLocked(r, knowConn, hasConn)) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002814 return;
2815 }
2816
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002817 // Are we in the process of launching?
2818 if (mPendingServices.contains(r)) {
2819 return;
2820 }
2821
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002822 bringDownServiceLocked(r);
2823 }
2824
2825 private final void bringDownServiceLocked(ServiceRecord r) {
2826 //Slog.i(TAG, "Bring down service:");
2827 //r.dump(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002828
Dianne Hackborn390517b2013-05-30 15:03:32 -07002829 // Report to all of the connections that the service is no longer
2830 // available.
2831 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2832 ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
2833 for (int i=0; i<c.size(); i++) {
2834 ConnectionRecord cr = c.get(i);
2835 // There is still a connection to the service that is
2836 // being brought down. Mark it as dead.
2837 cr.serviceDead = true;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002838 cr.stopAssociation();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002839 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07002840 cr.conn.connected(r.name, null, true);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002841 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002842 Slog.w(TAG, "Failure disconnecting service " + r.shortInstanceName
2843 + " to connection " + c.get(i).conn.asBinder()
2844 + " (in " + c.get(i).binding.client.processName + ")", e);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002845 }
2846 }
2847 }
2848
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002849 // Tell the service that it has been unbound.
Dianne Hackborn390517b2013-05-30 15:03:32 -07002850 if (r.app != null && r.app.thread != null) {
2851 for (int i=r.bindings.size()-1; i>=0; i--) {
2852 IntentBindRecord ibr = r.bindings.valueAt(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002853 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002854 + ": hasBound=" + ibr.hasBound);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002855 if (ibr.hasBound) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002856 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002857 bumpServiceExecutingLocked(r, false, "bring down unbind");
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002858 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002859 ibr.hasBound = false;
Dianne Hackborn85e35642017-01-12 15:10:57 -08002860 ibr.requested = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002861 r.app.thread.scheduleUnbindService(r,
2862 ibr.intent.getIntent());
2863 } catch (Exception e) {
2864 Slog.w(TAG, "Exception when unbinding service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002865 + r.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002866 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002867 }
2868 }
2869 }
2870 }
2871
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002872 // Check to see if the service had been started as foreground, but being
2873 // brought down before actually showing a notification. That is not allowed.
2874 if (r.fgRequired) {
2875 Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
2876 + r);
2877 r.fgRequired = false;
2878 r.fgWaiting = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002879 ServiceState stracker = r.getTracker();
2880 if (stracker != null) {
2881 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
2882 r.lastActivity);
2883 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07002884 mAm.mAppOpsService.finishOperation(AppOpsManager.getToken(mAm.mAppOpsService),
2885 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002886 mAm.mHandler.removeMessages(
2887 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
2888 if (r.app != null) {
2889 Message msg = mAm.mHandler.obtainMessage(
2890 ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
2891 msg.obj = r.app;
Kodlee Yin7e951262018-04-05 12:59:56 -07002892 msg.getData().putCharSequence(
2893 ActivityManagerService.SERVICE_RECORD_KEY, r.toString());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002894 mAm.mHandler.sendMessage(msg);
2895 }
2896 }
2897
2898 if (DEBUG_SERVICE) {
2899 RuntimeException here = new RuntimeException();
2900 here.fillInStackTrace();
2901 Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here);
2902 }
Craig Mautner66c4a822015-01-16 12:48:16 -08002903 r.destroyTime = SystemClock.uptimeMillis();
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002904 if (LOG_SERVICE_START_STOP) {
2905 EventLogTags.writeAmDestroyService(
2906 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
2907 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002908
Dianne Hackbornad51be92016-08-16 16:27:36 -07002909 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002910 ServiceRecord found = smap.mServicesByInstanceName.remove(r.instanceName);
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002911
2912 // Note when this method is called by bringUpServiceLocked(), the service is not found
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002913 // in mServicesByInstanceName and found will be null.
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002914 if (found != null && found != r) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002915 // This is not actually the service we think is running... this should not happen,
2916 // but if it does, fail hard.
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002917 smap.mServicesByInstanceName.put(r.instanceName, found);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002918 throw new IllegalStateException("Bringing down " + r + " but actually running "
2919 + found);
2920 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002921 smap.mServicesByIntent.remove(r.intent);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002922 r.totalRestartCount = 0;
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002923 unscheduleServiceRestartLocked(r, 0, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002924
2925 // Also make sure it is not on the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002926 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002927 if (mPendingServices.get(i) == r) {
2928 mPendingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002929 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002930 }
2931 }
2932
Christopher Tate08992ac2017-03-21 11:37:06 -07002933 cancelForegroundNotificationLocked(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002934 if (r.isForeground) {
2935 decActiveForegroundAppLocked(smap, r);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002936 ServiceState stracker = r.getTracker();
2937 if (stracker != null) {
2938 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
2939 r.lastActivity);
2940 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07002941 mAm.mAppOpsService.finishOperation(
2942 AppOpsManager.getToken(mAm.mAppOpsService),
2943 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002944 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED, r.appInfo.uid,
2945 r.shortInstanceName, StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Hui Yue361a232018-10-04 15:05:21 -07002946 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002947 }
Chenjie Yuccfe6452018-01-30 11:33:21 -08002948
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002949 r.isForeground = false;
2950 r.foregroundId = 0;
2951 r.foregroundNoti = null;
2952
2953 // Clear start entries.
2954 r.clearDeliveredStartsLocked();
2955 r.pendingStarts.clear();
2956
2957 if (r.app != null) {
2958 synchronized (r.stats.getBatteryStats()) {
2959 r.stats.stopLaunchedLocked();
2960 }
2961 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002962 if (r.whitelistManager) {
2963 updateWhitelistManagerLocked(r.app);
2964 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002965 if (r.app.thread != null) {
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002966 updateServiceForegroundLocked(r.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002967 try {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002968 bumpServiceExecutingLocked(r, false, "destroy");
2969 mDestroyingServices.add(r);
Dianne Hackborn455625e2015-01-21 09:55:13 -08002970 r.destroying = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002971 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002972 r.app.thread.scheduleStopService(r);
2973 } catch (Exception e) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002974 Slog.w(TAG, "Exception when destroying service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002975 + r.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002976 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002977 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002978 } else {
2979 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002980 TAG_SERVICE, "Removed service that has no process: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002981 }
2982 } else {
2983 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002984 TAG_SERVICE, "Removed service that is not running: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002985 }
2986
2987 if (r.bindings.size() > 0) {
2988 r.bindings.clear();
2989 }
2990
2991 if (r.restarter instanceof ServiceRestarter) {
2992 ((ServiceRestarter)r.restarter).setService(null);
2993 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002994
Dianne Hackbornd2932242013-08-05 18:18:42 -07002995 int memFactor = mAm.mProcessStats.getMemFactorLocked();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002996 long now = SystemClock.uptimeMillis();
2997 if (r.tracker != null) {
2998 r.tracker.setStarted(false, memFactor, now);
2999 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003000 if (r.executeNesting == 0) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07003001 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003002 r.tracker = null;
3003 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003004 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003005
Dianne Hackbornad51be92016-08-16 16:27:36 -07003006 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003007 }
3008
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07003009 void removeConnectionLocked(ConnectionRecord c, ProcessRecord skipApp,
3010 ActivityServiceConnectionsHolder skipAct) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003011 IBinder binder = c.conn.asBinder();
3012 AppBindRecord b = c.binding;
3013 ServiceRecord s = b.service;
3014 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
3015 if (clist != null) {
3016 clist.remove(c);
3017 if (clist.size() == 0) {
3018 s.connections.remove(binder);
3019 }
3020 }
3021 b.connections.remove(c);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003022 c.stopAssociation();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003023 if (c.activity != null && c.activity != skipAct) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07003024 c.activity.removeConnection(c);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003025 }
3026 if (b.client != skipApp) {
3027 b.client.connections.remove(c);
3028 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
3029 b.client.updateHasAboveClientLocked();
3030 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003031 // If this connection requested whitelist management, see if we should
3032 // now clear that state.
3033 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
3034 s.updateWhitelistManager();
3035 if (!s.whitelistManager && s.app != null) {
3036 updateWhitelistManagerLocked(s.app);
3037 }
3038 }
Dianne Hackborndb926082013-10-31 16:32:44 -07003039 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07003040 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07003041 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003042 }
3043 clist = mServiceConnections.get(binder);
3044 if (clist != null) {
3045 clist.remove(c);
3046 if (clist.size() == 0) {
3047 mServiceConnections.remove(binder);
3048 }
3049 }
3050
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003051 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003052 s.appInfo.longVersionCode, s.instanceName, s.processName);
Dianne Hackbornab2df062015-01-07 13:43:13 -08003053
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003054 if (b.connections.size() == 0) {
3055 b.intent.apps.remove(b.client);
3056 }
3057
3058 if (!c.serviceDead) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003059 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003060 + ": shouldUnbind=" + b.intent.hasBound);
3061 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
3062 && b.intent.hasBound) {
3063 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003064 bumpServiceExecutingLocked(s, false, "unbind");
Dianne Hackborndb926082013-10-31 16:32:44 -07003065 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
Dianne Hackbornf097d422017-12-15 16:32:19 -08003066 && s.app.setProcState <= ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
Dianne Hackborndb926082013-10-31 16:32:44 -07003067 // If this service's process is not already in the cached list,
3068 // then update it in the LRU list here because this may be causing
3069 // it to go down there and we want it to start out near the top.
3070 mAm.updateLruProcessLocked(s.app, false, null);
3071 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07003072 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003073 b.intent.hasBound = false;
3074 // Assume the client doesn't want to know about a rebind;
3075 // we will deal with that later if it asks for one.
3076 b.intent.doRebind = false;
3077 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
3078 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003079 Slog.w(TAG, "Exception when unbinding service " + s.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07003080 serviceProcessGoneLocked(s);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003081 }
3082 }
3083
Svet Ganov9c165d72015-12-01 19:52:26 -08003084 // If unbound while waiting to start, remove the pending service
3085 mPendingServices.remove(s);
3086
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003087 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003088 boolean hasAutoCreate = s.hasAutoCreateConnections();
3089 if (!hasAutoCreate) {
3090 if (s.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003091 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003092 SystemClock.uptimeMillis());
3093 }
3094 }
3095 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003096 }
3097 }
3098 }
3099
3100 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003101 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003102 if (r != null) {
Dianne Hackborn455625e2015-01-21 09:55:13 -08003103 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003104 // This is a call from a service start... take care of
3105 // book-keeping.
3106 r.callStart = true;
3107 switch (res) {
3108 case Service.START_STICKY_COMPATIBILITY:
3109 case Service.START_STICKY: {
3110 // We are done with the associated start arguments.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003111 r.findDeliveredStart(startId, false, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003112 // Don't stop if killed.
3113 r.stopIfKilled = false;
3114 break;
3115 }
3116 case Service.START_NOT_STICKY: {
3117 // We are done with the associated start arguments.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003118 r.findDeliveredStart(startId, false, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003119 if (r.getLastStartId() == startId) {
3120 // There is no more work, and this service
3121 // doesn't want to hang around if killed.
3122 r.stopIfKilled = true;
3123 }
3124 break;
3125 }
3126 case Service.START_REDELIVER_INTENT: {
3127 // We'll keep this item until they explicitly
3128 // call stop for it, but keep track of the fact
3129 // that it was delivered.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003130 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003131 if (si != null) {
3132 si.deliveryCount = 0;
3133 si.doneExecutingCount++;
3134 // Don't stop if killed.
3135 r.stopIfKilled = true;
3136 }
3137 break;
3138 }
3139 case Service.START_TASK_REMOVED_COMPLETE: {
3140 // Special processing for onTaskRemoved(). Don't
3141 // impact normal onStartCommand() processing.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003142 r.findDeliveredStart(startId, true, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003143 break;
3144 }
3145 default:
3146 throw new IllegalArgumentException(
3147 "Unknown service start result: " + res);
3148 }
3149 if (res == Service.START_STICKY_COMPATIBILITY) {
3150 r.callStart = false;
3151 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08003152 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
3153 // This is the final call from destroying the service... we should
3154 // actually be getting rid of the service at this point. Do some
3155 // validation of its state, and ensure it will be fully removed.
3156 if (!inDestroying) {
3157 // Not sure what else to do with this... if it is not actually in the
3158 // destroying list, we don't need to make sure to remove it from it.
Amith Yamasanid0418222016-05-10 15:49:51 -07003159 // If the app is null, then it was probably removed because the process died,
3160 // otherwise wtf
3161 if (r.app != null) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07003162 Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
Amith Yamasanid0418222016-05-10 15:49:51 -07003163 + r + ", app=" + r.app);
3164 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08003165 } else if (r.executeNesting != 1) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07003166 Slog.w(TAG, "Service done with onDestroy, but executeNesting="
Dianne Hackborn455625e2015-01-21 09:55:13 -08003167 + r.executeNesting + ": " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003168 // Fake it to keep from ANR due to orphaned entry.
Dianne Hackborn455625e2015-01-21 09:55:13 -08003169 r.executeNesting = 1;
3170 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003171 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003172 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn164371f2013-10-01 19:10:13 -07003173 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003174 Binder.restoreCallingIdentity(origId);
3175 } else {
3176 Slog.w(TAG, "Done executing unknown service from pid "
3177 + Binder.getCallingPid());
3178 }
3179 }
3180
Dianne Hackborn878deb32013-10-14 16:55:09 -07003181 private void serviceProcessGoneLocked(ServiceRecord r) {
3182 if (r.tracker != null) {
3183 int memFactor = mAm.mProcessStats.getMemFactorLocked();
3184 long now = SystemClock.uptimeMillis();
3185 r.tracker.setExecuting(false, memFactor, now);
3186 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbc72dce2013-11-11 10:43:38 -08003187 r.tracker.setStarted(false, memFactor, now);
Dianne Hackborn878deb32013-10-14 16:55:09 -07003188 }
3189 serviceDoneExecutingLocked(r, true, true);
3190 }
3191
Dianne Hackborn164371f2013-10-01 19:10:13 -07003192 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
3193 boolean finishing) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003194 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003195 + ": nesting=" + r.executeNesting
Dianne Hackborn164371f2013-10-01 19:10:13 -07003196 + ", inDestroying=" + inDestroying + ", app=" + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003197 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003198 "<<< DONE EXECUTING " + r.shortInstanceName);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003199 r.executeNesting--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003200 if (r.executeNesting <= 0) {
3201 if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003202 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003203 "Nesting at 0 of " + r.shortInstanceName);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003204 r.app.execServicesFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003205 r.app.executingServices.remove(r);
3206 if (r.app.executingServices.size() == 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003207 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003208 "No more executingServices of " + r.shortInstanceName);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003209 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003210 } else if (r.executeFg) {
3211 // Need to re-evaluate whether the app still needs to be in the foreground.
3212 for (int i=r.app.executingServices.size()-1; i>=0; i--) {
3213 if (r.app.executingServices.valueAt(i).executeFg) {
3214 r.app.execServicesFg = true;
3215 break;
3216 }
3217 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003218 }
Dianne Hackborn164371f2013-10-01 19:10:13 -07003219 if (inDestroying) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003220 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn164371f2013-10-01 19:10:13 -07003221 "doneExecuting remove destroying " + r);
3222 mDestroyingServices.remove(r);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003223 r.bindings.clear();
3224 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07003225 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003226 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003227 r.executeFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003228 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003229 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003230 SystemClock.uptimeMillis());
Dianne Hackborn164371f2013-10-01 19:10:13 -07003231 if (finishing) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07003232 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003233 r.tracker = null;
3234 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003235 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003236 if (finishing) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003237 if (r.app != null && !r.app.isPersistent()) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003238 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003239 if (r.whitelistManager) {
3240 updateWhitelistManagerLocked(r.app);
3241 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003242 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003243 r.setProcess(null);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003244 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003245 }
3246 }
3247
Dianne Hackbornff072722014-09-24 10:56:28 -07003248 boolean attachApplicationLocked(ProcessRecord proc, String processName)
3249 throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003250 boolean didSomething = false;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003251 // Collect any services that are waiting for this process to come up.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003252 if (mPendingServices.size() > 0) {
3253 ServiceRecord sr = null;
3254 try {
3255 for (int i=0; i<mPendingServices.size(); i++) {
3256 sr = mPendingServices.get(i);
3257 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3258 || !processName.equals(sr.processName))) {
3259 continue;
3260 }
3261
3262 mPendingServices.remove(i);
3263 i--;
Patrick Baumannc2def582018-04-04 12:14:15 -07003264 proc.addPackage(sr.appInfo.packageName, sr.appInfo.longVersionCode,
Dianne Hackbornf7097a52014-05-13 09:56:14 -07003265 mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003266 realStartServiceLocked(sr, proc, sr.createdFromFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003267 didSomething = true;
Dianne Hackbornad51be92016-08-16 16:27:36 -07003268 if (!isServiceNeededLocked(sr, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003269 // We were waiting for this service to start, but it is actually no
3270 // longer needed. This could happen because bringDownServiceIfNeeded
3271 // won't bring down a service that is pending... so now the pending
3272 // is done, so let's drop it.
3273 bringDownServiceLocked(sr);
3274 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003275 }
Dianne Hackbornff072722014-09-24 10:56:28 -07003276 } catch (RemoteException e) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003277 Slog.w(TAG, "Exception in new application when starting service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003278 + sr.shortInstanceName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003279 throw e;
3280 }
3281 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003282 // Also, if there are any services that are waiting to restart and
3283 // would run in this process, now is a good time to start them. It would
3284 // be weird to bring up the process but arbitrarily not let the services
3285 // run at this point just because their restart time hasn't come up.
3286 if (mRestartingServices.size() > 0) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003287 ServiceRecord sr;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003288 for (int i=0; i<mRestartingServices.size(); i++) {
3289 sr = mRestartingServices.get(i);
3290 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3291 || !processName.equals(sr.processName))) {
3292 continue;
3293 }
3294 mAm.mHandler.removeCallbacks(sr.restarter);
3295 mAm.mHandler.post(sr.restarter);
3296 }
3297 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003298 return didSomething;
3299 }
3300
3301 void processStartTimedOutLocked(ProcessRecord proc) {
3302 for (int i=0; i<mPendingServices.size(); i++) {
3303 ServiceRecord sr = mPendingServices.get(i);
3304 if ((proc.uid == sr.appInfo.uid
3305 && proc.processName.equals(sr.processName))
3306 || sr.isolatedProc == proc) {
3307 Slog.w(TAG, "Forcing bringing down service: " + sr);
3308 sr.isolatedProc = null;
3309 mPendingServices.remove(i);
3310 i--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003311 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003312 }
3313 }
3314 }
3315
Wale Ogunwale540e1232015-05-01 15:35:39 -07003316 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003317 boolean evenPersistent, boolean doit, boolean killProcess,
3318 ArrayMap<ComponentName, ServiceRecord> services) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003319 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003320 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003321 ServiceRecord service = services.valueAt(i);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003322 final boolean sameComponent = packageName == null
3323 || (service.packageName.equals(packageName)
3324 && (filterByClasses == null
3325 || filterByClasses.contains(service.name.getClassName())));
3326 if (sameComponent
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003327 && (service.app == null || evenPersistent || !service.app.isPersistent())) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003328 if (!doit) {
3329 return true;
3330 }
3331 didSomething = true;
3332 Slog.i(TAG, " Force stopping service " + service);
3333 if (service.app != null) {
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003334 service.app.removed = killProcess;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003335 if (!service.app.isPersistent()) {
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08003336 service.app.services.remove(service);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003337 if (service.whitelistManager) {
3338 updateWhitelistManagerLocked(service.app);
3339 }
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,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003354 int userId, boolean evenPersistent, boolean killProcess, 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,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003364 evenPersistent, doit, killProcess,
3365 mServiceMap.valueAt(i).mServicesByInstanceName);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003366 if (!doit && didSomething) {
3367 return true;
3368 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003369 if (doit && filterByClasses == null) {
3370 forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId);
3371 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003372 }
3373 } else {
Amith Yamasani540b6592013-10-01 13:02:52 -07003374 ServiceMap smap = mServiceMap.get(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003375 if (smap != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003376 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByInstanceName;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003377 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003378 evenPersistent, doit, killProcess, items);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003379 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003380 if (doit && filterByClasses == null) {
3381 forceStopPackageLocked(packageName, userId);
3382 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003383 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003384
Wale Ogunwale540e1232015-05-01 15:35:39 -07003385 if (mTmpCollectionResults != null) {
3386 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
3387 bringDownServiceLocked(mTmpCollectionResults.get(i));
3388 }
3389 mTmpCollectionResults.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003390 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003391
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003392 return didSomething;
3393 }
3394
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003395 void forceStopPackageLocked(String packageName, int userId) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003396 ServiceMap smap = mServiceMap.get(userId);
3397 if (smap != null && smap.mActiveForegroundApps.size() > 0) {
Dianne Hackbornaf597682017-05-01 10:54:07 -07003398 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003399 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
3400 if (aa.mPackageName.equals(packageName)) {
3401 smap.mActiveForegroundApps.removeAt(i);
3402 smap.mActiveForegroundAppsChanged = true;
3403 }
3404 }
3405 if (smap.mActiveForegroundAppsChanged) {
3406 requestUpdateActiveForegroundAppsLocked(smap, 0);
3407 }
3408 }
3409 }
3410
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003411 void cleanUpServices(int userId, ComponentName component, Intent baseIntent) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003412 ArrayList<ServiceRecord> services = new ArrayList<>();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003413 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003414 for (int i = alls.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003415 ServiceRecord sr = alls.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003416 if (sr.packageName.equals(component.getPackageName())) {
3417 services.add(sr);
3418 }
3419 }
3420
3421 // Take care of any running services associated with the app.
Wale Ogunwale540e1232015-05-01 15:35:39 -07003422 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003423 ServiceRecord sr = services.get(i);
3424 if (sr.startRequested) {
3425 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003426 Slog.i(TAG, "Stopping service " + sr.shortInstanceName + ": remove task");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003427 stopServiceLocked(sr);
3428 } else {
3429 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003430 sr.getLastStartId(), baseIntent, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003431 if (sr.app != null && sr.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003432 // We always run in the foreground, since this is called as
3433 // part of the "remove task" UI operation.
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003434 try {
3435 sendServiceArgsLocked(sr, true, false);
3436 } catch (TransactionTooLargeException e) {
3437 // Ignore, keep going.
3438 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003439 }
3440 }
3441 }
3442 }
3443 }
3444
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003445 final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003446 // Report disconnected services.
3447 if (false) {
3448 // XXX we are letting the client link to the service for
3449 // death notifications.
3450 if (app.services.size() > 0) {
3451 Iterator<ServiceRecord> it = app.services.iterator();
3452 while (it.hasNext()) {
3453 ServiceRecord r = it.next();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003454 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3455 ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
3456 for (int i=0; i<cl.size(); i++) {
3457 ConnectionRecord c = cl.get(i);
3458 if (c.binding.client != app) {
3459 try {
3460 //c.conn.connected(r.className, null);
3461 } catch (Exception e) {
3462 // todo: this should be asynchronous!
3463 Slog.w(TAG, "Exception thrown disconnected servce "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003464 + r.shortInstanceName
Dianne Hackborn390517b2013-05-30 15:03:32 -07003465 + " from app " + app.processName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003466 }
3467 }
3468 }
3469 }
3470 }
3471 }
3472 }
3473
louis_chang40e259c2015-03-26 13:31:14 +08003474 // Clean up any connections this application has to other services.
3475 for (int i = app.connections.size() - 1; i >= 0; i--) {
3476 ConnectionRecord r = app.connections.valueAt(i);
3477 removeConnectionLocked(r, app, null);
3478 }
3479 updateServiceConnectionActivitiesLocked(app);
3480 app.connections.clear();
3481
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003482 app.whitelistManager = false;
3483
louis_chang40e259c2015-03-26 13:31:14 +08003484 // Clear app state from services.
3485 for (int i = app.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003486 ServiceRecord sr = app.services.valueAt(i);
3487 synchronized (sr.stats.getBatteryStats()) {
3488 sr.stats.stopLaunchedLocked();
3489 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003490 if (sr.app != app && sr.app != null && !sr.app.isPersistent()) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003491 sr.app.services.remove(sr);
3492 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003493 sr.setProcess(null);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003494 sr.isolatedProc = null;
3495 sr.executeNesting = 0;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003496 sr.forceClearTracker();
3497 if (mDestroyingServices.remove(sr)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003498 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003499 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003500
Dianne Hackbornc8230512013-07-13 21:32:12 -07003501 final int numClients = sr.bindings.size();
3502 for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
3503 IntentBindRecord b = sr.bindings.valueAt(bindingi);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003504 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
Dianne Hackbornc8230512013-07-13 21:32:12 -07003505 + ": shouldUnbind=" + b.hasBound);
3506 b.binder = null;
3507 b.requested = b.received = b.hasBound = false;
Dianne Hackborn465fa392014-09-14 14:21:18 -07003508 // If this binding is coming from a cached process and is asking to keep
3509 // the service created, then we'll kill the cached process as well -- we
3510 // don't want to be thrashing around restarting processes that are only
3511 // there to be cached.
3512 for (int appi=b.apps.size()-1; appi>=0; appi--) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003513 final ProcessRecord proc = b.apps.keyAt(appi);
3514 // If the process is already gone, skip it.
3515 if (proc.killedByAm || proc.thread == null) {
3516 continue;
3517 }
3518 // Only do this for processes that have an auto-create binding;
3519 // otherwise the binding can be left, because it won't cause the
3520 // service to restart.
3521 final AppBindRecord abind = b.apps.valueAt(appi);
3522 boolean hasCreate = false;
3523 for (int conni=abind.connections.size()-1; conni>=0; conni--) {
3524 ConnectionRecord conn = abind.connections.valueAt(conni);
Dianne Hackborn0fe3c252014-09-19 15:09:39 -07003525 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
3526 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003527 hasCreate = true;
3528 break;
3529 }
3530 }
3531 if (!hasCreate) {
3532 continue;
3533 }
Dianne Hackborncd97c962014-09-25 18:34:02 -07003534 // XXX turned off for now until we have more time to get a better policy.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003535 if (false && proc != null && !proc.isPersistent() && proc.thread != null
Dianne Hackborn465fa392014-09-14 14:21:18 -07003536 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
3537 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003538 proc.kill("bound to service " + sr.shortInstanceName
Dianne Hackborn465fa392014-09-14 14:21:18 -07003539 + " in dying proc " + (app != null ? app.processName : "??"), true);
3540 }
3541 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003542 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003543 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003544
Dianne Hackbornad51be92016-08-16 16:27:36 -07003545 ServiceMap smap = getServiceMapLocked(app.userId);
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003546
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003547 // Now do remaining service cleanup.
3548 for (int i=app.services.size()-1; i>=0; i--) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003549 ServiceRecord sr = app.services.valueAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003550
3551 // Unless the process is persistent, this process record is going away,
3552 // so make sure the service is cleaned out of it.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003553 if (!app.isPersistent()) {
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003554 app.services.removeAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003555 }
3556
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003557 // Sanity check: if the service listed for the app is not one
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003558 // we actually are maintaining, just let it drop.
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003559 final ServiceRecord curRec = smap.mServicesByInstanceName.get(sr.instanceName);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003560 if (curRec != sr) {
3561 if (curRec != null) {
3562 Slog.wtf(TAG, "Service " + sr + " in process " + app
3563 + " not same as in map: " + curRec);
3564 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003565 continue;
3566 }
3567
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003568 // Any services running in the application may need to be placed
3569 // back in the pending list.
Amith Yamasanib0c8a882017-08-28 09:36:42 -07003570 if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
3571 && (sr.serviceInfo.applicationInfo.flags
3572 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003573 Slog.w(TAG, "Service crashed " + sr.crashCount
3574 + " times, stopping: " + sr);
3575 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003576 sr.userId, sr.crashCount, sr.shortInstanceName, app.pid);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003577 bringDownServiceLocked(sr);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003578 } else if (!allowRestart
Fyodor Kupolov1b3edac2017-09-19 15:48:06 -07003579 || !mAm.mUserController.isUserRunning(sr.userId, 0)) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003580 bringDownServiceLocked(sr);
3581 } else {
3582 boolean canceled = scheduleServiceRestartLocked(sr, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003583
Dianne Hackbornc8230512013-07-13 21:32:12 -07003584 // Should the service remain running? Note that in the
3585 // extreme case of so many attempts to deliver a command
3586 // that it failed we also will stop it here.
3587 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
3588 if (sr.pendingStarts.size() == 0) {
3589 sr.startRequested = false;
3590 if (sr.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003591 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackbornc8230512013-07-13 21:32:12 -07003592 SystemClock.uptimeMillis());
3593 }
3594 if (!sr.hasAutoCreateConnections()) {
3595 // Whoops, no reason to restart!
3596 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003597 }
3598 }
3599 }
3600 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003601 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003602
Dianne Hackbornc8230512013-07-13 21:32:12 -07003603 if (!allowRestart) {
3604 app.services.clear();
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003605
3606 // Make sure there are no more restarting services for this process.
3607 for (int i=mRestartingServices.size()-1; i>=0; i--) {
3608 ServiceRecord r = mRestartingServices.get(i);
3609 if (r.processName.equals(app.processName) &&
3610 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3611 mRestartingServices.remove(i);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08003612 clearRestartingIfNeededLocked(r);
3613 }
3614 }
3615 for (int i=mPendingServices.size()-1; i>=0; i--) {
3616 ServiceRecord r = mPendingServices.get(i);
3617 if (r.processName.equals(app.processName) &&
3618 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3619 mPendingServices.remove(i);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003620 }
3621 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003622 }
3623
3624 // Make sure we have no more records on the stopping list.
Dianne Hackborn164371f2013-10-01 19:10:13 -07003625 int i = mDestroyingServices.size();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003626 while (i > 0) {
3627 i--;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003628 ServiceRecord sr = mDestroyingServices.get(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003629 if (sr.app == app) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003630 sr.forceClearTracker();
3631 mDestroyingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003632 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003633 }
3634 }
3635
3636 app.executingServices.clear();
3637 }
3638
3639 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
3640 ActivityManager.RunningServiceInfo info =
3641 new ActivityManager.RunningServiceInfo();
3642 info.service = r.name;
3643 if (r.app != null) {
3644 info.pid = r.app.pid;
3645 }
3646 info.uid = r.appInfo.uid;
3647 info.process = r.processName;
3648 info.foreground = r.isForeground;
Yi Jin6b514142017-10-30 14:54:12 -07003649 info.activeSince = r.createRealTime;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003650 info.started = r.startRequested;
3651 info.clientCount = r.connections.size();
3652 info.crashCount = r.crashCount;
3653 info.lastActivityTime = r.lastActivity;
3654 if (r.isForeground) {
3655 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
3656 }
3657 if (r.startRequested) {
3658 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
3659 }
3660 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
3661 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
3662 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003663 if (r.app != null && r.app.isPersistent()) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003664 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
3665 }
3666
Dianne Hackborn390517b2013-05-30 15:03:32 -07003667 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3668 ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003669 for (int i=0; i<connl.size(); i++) {
3670 ConnectionRecord conn = connl.get(i);
3671 if (conn.clientLabel != 0) {
3672 info.clientPackage = conn.binding.client.info.packageName;
3673 info.clientLabel = conn.clientLabel;
3674 return info;
3675 }
3676 }
3677 }
3678 return info;
3679 }
3680
Bryce Lee290e5782017-02-01 16:41:20 -08003681 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags,
Shunta Sato55af6c52016-10-19 15:58:52 +09003682 int callingUid, boolean allowed, boolean canInteractAcrossUsers) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003683 ArrayList<ActivityManager.RunningServiceInfo> res
3684 = new ArrayList<ActivityManager.RunningServiceInfo>();
3685
Dianne Hackborn0c380492012-08-20 17:23:30 -07003686 final long ident = Binder.clearCallingIdentity();
3687 try {
Shunta Sato55af6c52016-10-19 15:58:52 +09003688 if (canInteractAcrossUsers) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003689 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003690 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003691 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003692 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3693 ServiceRecord sr = alls.valueAt(i);
3694 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07003695 }
3696 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003697
Dianne Hackborn0c380492012-08-20 17:23:30 -07003698 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3699 ServiceRecord r = mRestartingServices.get(i);
3700 ActivityManager.RunningServiceInfo info =
3701 makeRunningServiceInfoLocked(r);
3702 info.restarting = r.nextRestartTime;
3703 res.add(info);
3704 }
3705 } else {
Bryce Lee290e5782017-02-01 16:41:20 -08003706 int userId = UserHandle.getUserId(callingUid);
Dianne Hackbornad51be92016-08-16 16:27:36 -07003707 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003708 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3709 ServiceRecord sr = alls.valueAt(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003710
3711 if (allowed || (sr.app != null && sr.app.uid == callingUid)) {
3712 res.add(makeRunningServiceInfoLocked(sr));
3713 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07003714 }
3715
3716 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3717 ServiceRecord r = mRestartingServices.get(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003718 if (r.userId == userId
3719 && (allowed || (r.app != null && r.app.uid == callingUid))) {
Dianne Hackborn0c380492012-08-20 17:23:30 -07003720 ActivityManager.RunningServiceInfo info =
3721 makeRunningServiceInfoLocked(r);
3722 info.restarting = r.nextRestartTime;
3723 res.add(info);
3724 }
3725 }
3726 }
3727 } finally {
3728 Binder.restoreCallingIdentity(ident);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003729 }
3730
3731 return res;
3732 }
3733
3734 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003735 int userId = UserHandle.getUserId(Binder.getCallingUid());
Dianne Hackbornad51be92016-08-16 16:27:36 -07003736 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003737 if (r != null) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003738 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3739 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003740 for (int i=0; i<conn.size(); i++) {
3741 if (conn.get(i).clientIntent != null) {
3742 return conn.get(i).clientIntent;
3743 }
3744 }
3745 }
3746 }
3747 return null;
3748 }
3749
3750 void serviceTimeout(ProcessRecord proc) {
3751 String anrMessage = null;
3752
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003753 synchronized(mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003754 if (proc.executingServices.size() == 0 || proc.thread == null) {
3755 return;
3756 }
Dianne Hackbornab2df062015-01-07 13:43:13 -08003757 final long now = SystemClock.uptimeMillis();
3758 final long maxTime = now -
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003759 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003760 ServiceRecord timeout = null;
3761 long nextTime = 0;
Dianne Hackbornc8230512013-07-13 21:32:12 -07003762 for (int i=proc.executingServices.size()-1; i>=0; i--) {
3763 ServiceRecord sr = proc.executingServices.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003764 if (sr.executingStart < maxTime) {
3765 timeout = sr;
3766 break;
3767 }
3768 if (sr.executingStart > nextTime) {
3769 nextTime = sr.executingStart;
3770 }
3771 }
Amith Yamasani98a00922018-08-21 12:50:30 -04003772 if (timeout != null && mAm.mProcessList.mLruProcesses.contains(proc)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003773 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08003774 StringWriter sw = new StringWriter();
3775 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
3776 pw.println(timeout);
3777 timeout.dump(pw, " ");
3778 pw.close();
3779 mLastAnrDump = sw.toString();
3780 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
3781 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003782 anrMessage = "executing service " + timeout.shortInstanceName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003783 } else {
3784 Message msg = mAm.mHandler.obtainMessage(
3785 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3786 msg.obj = proc;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003787 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
Dianne Hackborn2be00932013-09-22 16:46:00 -07003788 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003789 }
3790 }
3791
3792 if (anrMessage != null) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07003793 proc.appNotResponding(null, null, null, null, false, anrMessage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003794 }
3795 }
3796
Christopher Tate08992ac2017-03-21 11:37:06 -07003797 void serviceForegroundTimeout(ServiceRecord r) {
3798 ProcessRecord app;
3799 synchronized (mAm) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003800 if (!r.fgRequired || r.destroying) {
Christopher Tate08992ac2017-03-21 11:37:06 -07003801 return;
3802 }
3803
Christopher Tate54f51b02018-02-16 11:07:12 -08003804 app = r.app;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07003805 if (app != null && app.isDebugging()) {
Christopher Tate54f51b02018-02-16 11:07:12 -08003806 // The app's being debugged; let it ride
3807 return;
3808 }
3809
Christopher Tate08992ac2017-03-21 11:37:06 -07003810 if (DEBUG_BACKGROUND_CHECK) {
3811 Slog.i(TAG, "Service foreground-required timeout for " + r);
3812 }
Christopher Tate08992ac2017-03-21 11:37:06 -07003813 r.fgWaiting = false;
3814 stopServiceLocked(r);
3815 }
3816
3817 if (app != null) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07003818 app.appNotResponding(null, null, null, null, false,
Kodlee Yin7e951262018-04-05 12:59:56 -07003819 "Context.startForegroundService() did not then call Service.startForeground(): "
3820 + r);
Christopher Tate08992ac2017-03-21 11:37:06 -07003821 }
3822 }
3823
Fyodor Kupolovcc269d92018-05-14 14:20:29 -07003824 public void updateServiceApplicationInfoLocked(ApplicationInfo applicationInfo) {
3825 final int userId = UserHandle.getUserId(applicationInfo.uid);
3826 ServiceMap serviceMap = mServiceMap.get(userId);
3827 if (serviceMap != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003828 ArrayMap<ComponentName, ServiceRecord> servicesByName
3829 = serviceMap.mServicesByInstanceName;
Fyodor Kupolovcc269d92018-05-14 14:20:29 -07003830 for (int j = servicesByName.size() - 1; j >= 0; j--) {
3831 ServiceRecord serviceRecord = servicesByName.valueAt(j);
3832 if (applicationInfo.packageName.equals(serviceRecord.appInfo.packageName)) {
3833 serviceRecord.appInfo = applicationInfo;
3834 serviceRecord.serviceInfo.applicationInfo = applicationInfo;
3835 }
3836 }
3837 }
3838 }
3839
Kodlee Yin7e951262018-04-05 12:59:56 -07003840 void serviceForegroundCrash(ProcessRecord app, CharSequence serviceRecord) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003841 mAm.crashApplication(app.uid, app.pid, app.info.packageName, app.userId,
Kodlee Yin7e951262018-04-05 12:59:56 -07003842 "Context.startForegroundService() did not then call Service.startForeground(): "
3843 + serviceRecord);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003844 }
3845
Dianne Hackborn2be00932013-09-22 16:46:00 -07003846 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
3847 if (proc.executingServices.size() == 0 || proc.thread == null) {
3848 return;
3849 }
Dianne Hackborn2be00932013-09-22 16:46:00 -07003850 Message msg = mAm.mHandler.obtainMessage(
3851 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3852 msg.obj = proc;
Christopher Tate08992ac2017-03-21 11:37:06 -07003853 mAm.mHandler.sendMessageDelayed(msg,
3854 proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
3855 }
3856
3857 void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
3858 if (r.app.executingServices.size() == 0 || r.app.thread == null) {
3859 return;
3860 }
3861 Message msg = mAm.mHandler.obtainMessage(
3862 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG);
3863 msg.obj = r;
3864 r.fgWaiting = true;
3865 mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT);
Dianne Hackborn2be00932013-09-22 16:46:00 -07003866 }
3867
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003868 final class ServiceDumper {
3869 private final FileDescriptor fd;
3870 private final PrintWriter pw;
3871 private final String[] args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003872 private final boolean dumpAll;
3873 private final String dumpPackage;
3874 private final ItemMatcher matcher;
3875 private final ArrayList<ServiceRecord> services = new ArrayList<>();
3876
3877 private final long nowReal = SystemClock.elapsedRealtime();
3878
3879 private boolean needSep = false;
3880 private boolean printedAnything = false;
3881 private boolean printed = false;
3882
3883 /**
3884 * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
3885 * must be called with the lock held).
3886 */
3887 ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
3888 int opti, boolean dumpAll, String dumpPackage) {
3889 this.fd = fd;
3890 this.pw = pw;
3891 this.args = args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003892 this.dumpAll = dumpAll;
3893 this.dumpPackage = dumpPackage;
3894 matcher = new ItemMatcher();
3895 matcher.build(args, opti);
3896
3897 final int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003898 for (int user : users) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003899 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003900 if (smap.mServicesByInstanceName.size() > 0) {
3901 for (int si=0; si<smap.mServicesByInstanceName.size(); si++) {
3902 ServiceRecord r = smap.mServicesByInstanceName.valueAt(si);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003903 if (!matcher.match(r, r.name)) {
3904 continue;
3905 }
3906 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3907 continue;
3908 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003909 services.add(r);
3910 }
3911 }
3912 }
3913 }
3914
3915 private void dumpHeaderLocked() {
3916 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
3917 if (mLastAnrDump != null) {
3918 pw.println(" Last ANR service:");
3919 pw.print(mLastAnrDump);
3920 pw.println();
3921 }
3922 }
3923
3924 void dumpLocked() {
3925 dumpHeaderLocked();
3926
3927 try {
3928 int[] users = mAm.mUserController.getUsers();
3929 for (int user : users) {
3930 // Find the first service for this user.
3931 int serviceIdx = 0;
3932 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3933 serviceIdx++;
3934 }
3935 printed = false;
3936 if (serviceIdx < services.size()) {
3937 needSep = false;
3938 while (serviceIdx < services.size()) {
3939 ServiceRecord r = services.get(serviceIdx);
3940 serviceIdx++;
3941 if (r.userId != user) {
3942 break;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003943 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003944 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003945 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003946 needSep |= printed;
3947 }
3948
3949 dumpUserRemainsLocked(user);
3950 }
3951 } catch (Exception e) {
3952 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3953 }
3954
3955 dumpRemainsLocked();
3956 }
3957
3958 void dumpWithClient() {
3959 synchronized(mAm) {
3960 dumpHeaderLocked();
3961 }
3962
3963 try {
3964 int[] users = mAm.mUserController.getUsers();
3965 for (int user : users) {
3966 // Find the first service for this user.
3967 int serviceIdx = 0;
3968 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3969 serviceIdx++;
3970 }
3971 printed = false;
3972 if (serviceIdx < services.size()) {
3973 needSep = false;
3974 while (serviceIdx < services.size()) {
3975 ServiceRecord r = services.get(serviceIdx);
3976 serviceIdx++;
3977 if (r.userId != user) {
3978 break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003979 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003980 synchronized(mAm) {
3981 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003982 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003983 dumpServiceClient(r);
3984 }
3985 needSep |= printed;
3986 }
3987
3988 synchronized(mAm) {
3989 dumpUserRemainsLocked(user);
3990 }
3991 }
3992 } catch (Exception e) {
3993 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3994 }
3995
3996 synchronized(mAm) {
3997 dumpRemainsLocked();
3998 }
3999 }
4000
4001 private void dumpUserHeaderLocked(int user) {
4002 if (!printed) {
4003 if (printedAnything) {
4004 pw.println();
4005 }
4006 pw.println(" User " + user + " active services:");
4007 printed = true;
4008 }
4009 printedAnything = true;
4010 if (needSep) {
4011 pw.println();
4012 }
4013 }
4014
4015 private void dumpServiceLocalLocked(ServiceRecord r) {
4016 dumpUserHeaderLocked(r.userId);
4017 pw.print(" * ");
4018 pw.println(r);
4019 if (dumpAll) {
4020 r.dump(pw, " ");
4021 needSep = true;
4022 } else {
4023 pw.print(" app=");
4024 pw.println(r.app);
4025 pw.print(" created=");
Yi Jin6b514142017-10-30 14:54:12 -07004026 TimeUtils.formatDuration(r.createRealTime, nowReal, pw);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004027 pw.print(" started=");
4028 pw.print(r.startRequested);
4029 pw.print(" connections=");
4030 pw.println(r.connections.size());
4031 if (r.connections.size() > 0) {
4032 pw.println(" Connections:");
4033 for (int conni=0; conni<r.connections.size(); conni++) {
4034 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
4035 for (int i = 0; i < clist.size(); i++) {
4036 ConnectionRecord conn = clist.get(i);
4037 pw.print(" ");
4038 pw.print(conn.binding.intent.intent.getIntent()
4039 .toShortString(false, false, false, false));
4040 pw.print(" -> ");
4041 ProcessRecord proc = conn.binding.client;
4042 pw.println(proc != null ? proc.toShortString() : "null");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004043 }
4044 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004045 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004046 }
4047 }
4048
4049 private void dumpServiceClient(ServiceRecord r) {
4050 final ProcessRecord proc = r.app;
4051 if (proc == null) {
4052 return;
4053 }
4054 final IApplicationThread thread = proc.thread;
4055 if (thread == null) {
4056 return;
4057 }
4058 pw.println(" Client:");
4059 pw.flush();
4060 try {
4061 TransferPipe tp = new TransferPipe();
4062 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004063 thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004064 tp.setBufferPrefix(" ");
4065 // Short timeout, since blocking here can
4066 // deadlock with the application.
4067 tp.go(fd, 2000);
4068 } finally {
4069 tp.kill();
4070 }
4071 } catch (IOException e) {
4072 pw.println(" Failure while dumping the service: " + e);
4073 } catch (RemoteException e) {
4074 pw.println(" Got a RemoteException while dumping the service");
4075 }
4076 needSep = true;
4077 }
4078
4079 private void dumpUserRemainsLocked(int user) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07004080 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004081 printed = false;
4082 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
4083 ServiceRecord r = smap.mDelayedStartList.get(si);
4084 if (!matcher.match(r, r.name)) {
4085 continue;
4086 }
4087 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4088 continue;
4089 }
4090 if (!printed) {
4091 if (printedAnything) {
4092 pw.println();
4093 }
4094 pw.println(" User " + user + " delayed start services:");
4095 printed = true;
4096 }
4097 printedAnything = true;
4098 pw.print(" * Delayed start "); pw.println(r);
4099 }
4100 printed = false;
4101 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
4102 ServiceRecord r = smap.mStartingBackground.get(si);
4103 if (!matcher.match(r, r.name)) {
4104 continue;
4105 }
4106 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4107 continue;
4108 }
4109 if (!printed) {
4110 if (printedAnything) {
4111 pw.println();
4112 }
4113 pw.println(" User " + user + " starting in background:");
4114 printed = true;
4115 }
4116 printedAnything = true;
4117 pw.print(" * Starting bg "); pw.println(r);
4118 }
4119 }
4120
4121 private void dumpRemainsLocked() {
4122 if (mPendingServices.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004123 printed = false;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004124 for (int i=0; i<mPendingServices.size(); i++) {
4125 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004126 if (!matcher.match(r, r.name)) {
4127 continue;
4128 }
4129 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4130 continue;
4131 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004132 printedAnything = true;
4133 if (!printed) {
4134 if (needSep) pw.println();
4135 needSep = true;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004136 pw.println(" Pending services:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004137 printed = true;
4138 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004139 pw.print(" * Pending "); pw.println(r);
4140 r.dump(pw, " ");
4141 }
4142 needSep = true;
4143 }
4144
4145 if (mRestartingServices.size() > 0) {
4146 printed = false;
4147 for (int i=0; i<mRestartingServices.size(); i++) {
4148 ServiceRecord r = mRestartingServices.get(i);
4149 if (!matcher.match(r, r.name)) {
4150 continue;
4151 }
4152 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4153 continue;
4154 }
4155 printedAnything = true;
4156 if (!printed) {
4157 if (needSep) pw.println();
4158 needSep = true;
4159 pw.println(" Restarting services:");
4160 printed = true;
4161 }
4162 pw.print(" * Restarting "); pw.println(r);
4163 r.dump(pw, " ");
4164 }
4165 needSep = true;
4166 }
4167
4168 if (mDestroyingServices.size() > 0) {
4169 printed = false;
4170 for (int i=0; i< mDestroyingServices.size(); i++) {
4171 ServiceRecord r = mDestroyingServices.get(i);
4172 if (!matcher.match(r, r.name)) {
4173 continue;
4174 }
4175 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4176 continue;
4177 }
4178 printedAnything = true;
4179 if (!printed) {
4180 if (needSep) pw.println();
4181 needSep = true;
4182 pw.println(" Destroying services:");
4183 printed = true;
4184 }
4185 pw.print(" * Destroy "); pw.println(r);
4186 r.dump(pw, " ");
4187 }
4188 needSep = true;
4189 }
4190
4191 if (dumpAll) {
4192 printed = false;
4193 for (int ic=0; ic<mServiceConnections.size(); ic++) {
4194 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
4195 for (int i=0; i<r.size(); i++) {
4196 ConnectionRecord cr = r.get(i);
4197 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
4198 continue;
4199 }
4200 if (dumpPackage != null && (cr.binding.client == null
4201 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
4202 continue;
4203 }
4204 printedAnything = true;
4205 if (!printed) {
4206 if (needSep) pw.println();
4207 needSep = true;
4208 pw.println(" Connection bindings to services:");
4209 printed = true;
4210 }
4211 pw.print(" * "); pw.println(cr);
4212 cr.dump(pw, " ");
4213 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004214 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004215 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004216
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004217 if (matcher.all) {
4218 final long nowElapsed = SystemClock.elapsedRealtime();
4219 final int[] users = mAm.mUserController.getUsers();
4220 for (int user : users) {
4221 boolean printedUser = false;
4222 ServiceMap smap = mServiceMap.get(user);
4223 if (smap == null) {
4224 continue;
4225 }
4226 for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) {
4227 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
4228 if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) {
4229 continue;
4230 }
4231 if (!printedUser) {
4232 printedUser = true;
4233 printedAnything = true;
4234 if (needSep) pw.println();
4235 needSep = true;
4236 pw.print("Active foreground apps - user ");
4237 pw.print(user);
4238 pw.println(":");
4239 }
4240 pw.print(" #");
4241 pw.print(i);
4242 pw.print(": ");
4243 pw.println(aa.mPackageName);
4244 if (aa.mLabel != null) {
4245 pw.print(" mLabel=");
4246 pw.println(aa.mLabel);
4247 }
4248 pw.print(" mNumActive=");
4249 pw.print(aa.mNumActive);
Dianne Hackbornbe68d492017-05-03 18:04:05 -07004250 pw.print(" mAppOnTop=");
4251 pw.print(aa.mAppOnTop);
4252 pw.print(" mShownWhileTop=");
4253 pw.print(aa.mShownWhileTop);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004254 pw.print(" mShownWhileScreenOn=");
4255 pw.println(aa.mShownWhileScreenOn);
4256 pw.print(" mStartTime=");
4257 TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw);
4258 pw.print(" mStartVisibleTime=");
4259 TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw);
4260 pw.println();
4261 if (aa.mEndTime != 0) {
4262 pw.print(" mEndTime=");
4263 TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw);
4264 pw.println();
4265 }
4266 }
Dianne Hackborncb015632017-06-14 17:30:15 -07004267 if (smap.hasMessagesOrCallbacks()) {
4268 if (needSep) {
4269 pw.println();
4270 }
4271 printedAnything = true;
4272 needSep = true;
4273 pw.print(" Handler - user ");
4274 pw.print(user);
4275 pw.println(":");
4276 smap.dumpMine(new PrintWriterPrinter(pw), " ");
4277 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004278 }
4279 }
4280
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004281 if (!printedAnything) {
4282 pw.println(" (nothing)");
4283 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07004284 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004285 }
4286
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004287 ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4288 int opti, boolean dumpAll, String dumpPackage) {
4289 return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
4290 }
4291
Yi Jin2b30f322018-02-20 15:41:47 -08004292 protected void writeToProto(ProtoOutputStream proto, long fieldId) {
Yi Jin6b514142017-10-30 14:54:12 -07004293 synchronized (mAm) {
Yi Jin2b30f322018-02-20 15:41:47 -08004294 final long outterToken = proto.start(fieldId);
Yi Jin6b514142017-10-30 14:54:12 -07004295 int[] users = mAm.mUserController.getUsers();
4296 for (int user : users) {
4297 ServiceMap smap = mServiceMap.get(user);
4298 if (smap == null) {
4299 continue;
4300 }
4301 long token = proto.start(ActiveServicesProto.SERVICES_BY_USERS);
4302 proto.write(ActiveServicesProto.ServicesByUser.USER_ID, user);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004303 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
Yi Jin6b514142017-10-30 14:54:12 -07004304 for (int i=0; i<alls.size(); i++) {
4305 alls.valueAt(i).writeToProto(proto,
4306 ActiveServicesProto.ServicesByUser.SERVICE_RECORDS);
4307 }
4308 proto.end(token);
4309 }
Yi Jin2b30f322018-02-20 15:41:47 -08004310 proto.end(outterToken);
Yi Jin6b514142017-10-30 14:54:12 -07004311 }
4312 }
4313
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004314 /**
4315 * There are three ways to call this:
4316 * - no service specified: dump all the services
4317 * - a flattened component name that matched an existing service was specified as the
4318 * first arg: dump that one service
4319 * - the first arg isn't the flattened component name of an existing service:
4320 * dump all services whose component contains the first arg as a substring
4321 */
Makoto Onuki0b575a32018-04-16 14:33:59 -07004322 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, final String name,
4323 String[] args, int opti, boolean dumpAll) {
4324 final ArrayList<ServiceRecord> services = new ArrayList<>();
4325
4326 final Predicate<ServiceRecord> filter = DumpUtils.filterRecord(name);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004327
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004328 synchronized (mAm) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07004329 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004330
Makoto Onuki0b575a32018-04-16 14:33:59 -07004331 for (int user : users) {
4332 ServiceMap smap = mServiceMap.get(user);
4333 if (smap == null) {
4334 continue;
4335 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004336 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
Makoto Onuki0b575a32018-04-16 14:33:59 -07004337 for (int i=0; i<alls.size(); i++) {
4338 ServiceRecord r1 = alls.valueAt(i);
4339
4340 if (filter.test(r1)) {
4341 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004342 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004343 }
4344 }
4345 }
4346
4347 if (services.size() <= 0) {
4348 return false;
4349 }
4350
Makoto Onuki0b575a32018-04-16 14:33:59 -07004351 // Sort by component name.
4352 services.sort(Comparator.comparing(WithComponentName::getComponentName));
4353
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004354 boolean needSep = false;
4355 for (int i=0; i<services.size(); i++) {
4356 if (needSep) {
4357 pw.println();
4358 }
4359 needSep = true;
4360 dumpService("", fd, pw, services.get(i), args, dumpAll);
4361 }
4362 return true;
4363 }
4364
4365 /**
4366 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
4367 * there is a thread associated with the service.
4368 */
4369 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
4370 final ServiceRecord r, String[] args, boolean dumpAll) {
4371 String innerPrefix = prefix + " ";
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004372 synchronized (mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004373 pw.print(prefix); pw.print("SERVICE ");
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004374 pw.print(r.shortInstanceName); pw.print(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004375 pw.print(Integer.toHexString(System.identityHashCode(r)));
4376 pw.print(" pid=");
4377 if (r.app != null) pw.println(r.app.pid);
4378 else pw.println("(not running)");
4379 if (dumpAll) {
4380 r.dump(pw, innerPrefix);
4381 }
4382 }
4383 if (r.app != null && r.app.thread != null) {
4384 pw.print(prefix); pw.println(" Client:");
4385 pw.flush();
4386 try {
4387 TransferPipe tp = new TransferPipe();
4388 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004389 r.app.thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004390 tp.setBufferPrefix(prefix + " ");
4391 tp.go(fd);
4392 } finally {
4393 tp.kill();
4394 }
4395 } catch (IOException e) {
4396 pw.println(prefix + " Failure while dumping the service: " + e);
4397 } catch (RemoteException e) {
4398 pw.println(prefix + " Got a RemoteException while dumping the service");
4399 }
4400 }
4401 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004402}