blob: fb541e00f5889e47efc38a51a85779ed166b1f9b [file] [log] [blame]
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Bryce Lee290e5782017-02-01 16:41:20 -080019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Hui Yu2d4207f2019-01-22 15:32:20 -080020import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST;
Wale Ogunwaled57969f2014-11-15 19:37:29 -080021
Hui Yue361a232018-10-04 15:05:21 -070022import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK;
23import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOREGROUND_SERVICE;
24import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
25import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
26import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE;
27import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE_EXECUTING;
28import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
29import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE;
30import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE_EXECUTING;
31import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
32import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070033
Hui Yue361a232018-10-04 15:05:21 -070034import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070035import android.app.ActivityManagerInternal;
Dianne Hackborn455625e2015-01-21 09:55:13 -080036import android.app.ActivityThread;
Hui Yue361a232018-10-04 15:05:21 -070037import android.app.AppGlobals;
Svet Ganov99b60432015-06-27 13:15:22 -070038import android.app.AppOpsManager;
Hui Yue361a232018-10-04 15:05:21 -070039import android.app.IApplicationThread;
40import android.app.IServiceConnection;
41import android.app.Notification;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070042import android.app.NotificationManager;
Hui Yue361a232018-10-04 15:05:21 -070043import android.app.PendingIntent;
44import android.app.Service;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070045import android.app.ServiceStartArgs;
Hui Yue361a232018-10-04 15:05:21 -070046import android.content.ComponentName;
Makoto Onuki0b575a32018-04-16 14:33:59 -070047import android.content.ComponentName.WithComponentName;
Hui Yue361a232018-10-04 15:05:21 -070048import android.content.Context;
Svet Ganov9c165d72015-12-01 19:52:26 -080049import android.content.IIntentSender;
Hui Yue361a232018-10-04 15:05:21 -070050import android.content.Intent;
Svet Ganov9c165d72015-12-01 19:52:26 -080051import android.content.IntentSender;
Hui Yue361a232018-10-04 15:05:21 -070052import android.content.pm.ApplicationInfo;
53import android.content.pm.PackageManager;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070054import android.content.pm.ParceledListSlice;
Hui Yue361a232018-10-04 15:05:21 -070055import android.content.pm.ResolveInfo;
56import android.content.pm.ServiceInfo;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070057import android.net.Uri;
Hui Yue361a232018-10-04 15:05:21 -070058import android.os.Binder;
Christoph Studer365e4c32014-09-18 20:35:36 +020059import android.os.Build;
Svet Ganov9c165d72015-12-01 19:52:26 -080060import android.os.Bundle;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -070061import android.os.DeadObjectException;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070062import android.os.Handler;
Hui Yue361a232018-10-04 15:05:21 -070063import android.os.IBinder;
Dianne Hackborn13c590d2013-10-07 14:32:00 -070064import android.os.Looper;
Hui Yue361a232018-10-04 15:05:21 -070065import android.os.Message;
66import android.os.Process;
Svet Ganov9c165d72015-12-01 19:52:26 -080067import android.os.RemoteCallback;
Hui Yue361a232018-10-04 15:05:21 -070068import android.os.RemoteException;
69import android.os.SystemClock;
Dianne Hackborn23037412013-11-04 18:11:29 -080070import android.os.SystemProperties;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -070071import android.os.TransactionTooLargeException;
Hui Yue361a232018-10-04 15:05:21 -070072import android.os.UserHandle;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070073import android.provider.Settings;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070074import android.util.ArrayMap;
Dianne Hackborn465fa392014-09-14 14:21:18 -070075import android.util.ArraySet;
Hui Yue361a232018-10-04 15:05:21 -070076import android.util.EventLog;
77import android.util.PrintWriterPrinter;
78import android.util.Slog;
79import android.util.SparseArray;
80import android.util.StatsLog;
81import android.util.TimeUtils;
82import android.util.proto.ProtoOutputStream;
83import android.webkit.WebViewZygote;
Wale Ogunwaled57969f2014-11-15 19:37:29 -080084
Dianne Hackborn83b40f62017-04-26 13:59:47 -070085import com.android.internal.R;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070086import com.android.internal.app.procstats.ServiceState;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070087import com.android.internal.messages.nano.SystemMessageProto;
88import com.android.internal.notification.SystemNotificationChannels;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070089import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborncbfd23e2013-06-11 14:26:53 -070090import com.android.internal.os.TransferPipe;
Makoto Onuki0b575a32018-04-16 14:33:59 -070091import com.android.internal.util.DumpUtils;
Dianne Hackborncff1bbf2015-01-20 13:43:32 -080092import com.android.internal.util.FastPrintWriter;
Christopher Tatec7933ac2018-03-12 17:57:09 -070093import com.android.server.AppStateTracker;
94import com.android.server.LocalServices;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -070095import com.android.server.SystemService;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070096import com.android.server.am.ActivityManagerService.ItemMatcher;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -070097import com.android.server.uri.NeededUriGrants;
Wale Ogunwale59507092018-10-29 09:00:30 -070098import com.android.server.wm.ActivityServiceConnectionsHolder;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070099
Hui Yue361a232018-10-04 15:05:21 -0700100import java.io.FileDescriptor;
101import java.io.IOException;
102import java.io.PrintWriter;
103import java.io.StringWriter;
104import java.util.ArrayList;
105import java.util.Comparator;
106import java.util.Iterator;
107import java.util.List;
108import java.util.Set;
109import java.util.function.Predicate;
110
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -0700111public final class ActiveServices {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800112 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM;
113 private static final String TAG_MU = TAG + POSTFIX_MU;
114 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
115 private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING;
116
117 private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE;
118 private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE;
119
120 private static final boolean LOG_SERVICE_START_STOP = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700121
Dianne Hackborn070d1422018-05-02 13:48:30 -0700122 private static final boolean SHOW_DUNGEON_NOTIFICATION = false;
123
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700124 // How long we wait for a service to finish executing.
125 static final int SERVICE_TIMEOUT = 20*1000;
126
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700127 // How long we wait for a service to finish executing.
128 static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
129
Christopher Tate08992ac2017-03-21 11:37:06 -0700130 // How long the startForegroundService() grace period is to get around to
131 // calling startForeground() before we ANR + stop it.
Christopher Tate5e5c3452018-05-25 13:12:12 -0700132 static final int SERVICE_START_FOREGROUND_TIMEOUT = 10*1000;
Christopher Tate08992ac2017-03-21 11:37:06 -0700133
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000134 // For how long after a whitelisted service's start its process can start a background activity
135 private static final int SERVICE_BG_ACTIVITY_START_TIMEOUT_MS = 10*1000;
136
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700137 final ActivityManagerService mAm;
138
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700139 // Maximum number of services that we allow to start in the background
140 // at the same time.
141 final int mMaxStartingBackground;
142
Wale Ogunwale540e1232015-05-01 15:35:39 -0700143 final SparseArray<ServiceMap> mServiceMap = new SparseArray<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700144
145 /**
146 * All currently bound service connections. Keys are the IBinder of
147 * the client's IServiceConnection.
148 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700149 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700150
151 /**
152 * List of services that we have been asked to start,
153 * but haven't yet been able to. It is used to hold start requests
154 * while waiting for their corresponding application thread to get
155 * going.
156 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700157 final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700158
159 /**
160 * List of services that are scheduled to restart following a crash.
161 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700162 final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700163
164 /**
Dianne Hackborn164371f2013-10-01 19:10:13 -0700165 * List of services that are in the process of being destroyed.
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700166 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700167 final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>();
168
169 /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */
170 private ArrayList<ServiceRecord> mTmpCollectionResults = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700171
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700172 /**
173 * For keeping ActiveForegroundApps retaining state while the screen is off.
174 */
175 boolean mScreenOn = true;
176
Dianne Hackborncff1bbf2015-01-20 13:43:32 -0800177 /** Amount of time to allow a last ANR message to exist before freeing the memory. */
178 static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
179
180 String mLastAnrDump;
181
182 final Runnable mLastAnrDumpClearer = new Runnable() {
183 @Override public void run() {
184 synchronized (mAm) {
185 mLastAnrDump = null;
186 }
187 }
188 };
189
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700190 /**
Christopher Tatec7933ac2018-03-12 17:57:09 -0700191 * Watch for apps being put into forced app standby, so we can step their fg
192 * services down.
193 */
194 class ForcedStandbyListener extends AppStateTracker.Listener {
195 @Override
196 public void stopForegroundServicesForUidPackage(final int uid, final String packageName) {
197 synchronized (mAm) {
198 final ServiceMap smap = getServiceMapLocked(UserHandle.getUserId(uid));
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800199 final int N = smap.mServicesByInstanceName.size();
Christopher Tatec7933ac2018-03-12 17:57:09 -0700200 final ArrayList<ServiceRecord> toStop = new ArrayList<>(N);
201 for (int i = 0; i < N; i++) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800202 final ServiceRecord r = smap.mServicesByInstanceName.valueAt(i);
Christopher Tatec7933ac2018-03-12 17:57:09 -0700203 if (uid == r.serviceInfo.applicationInfo.uid
204 || packageName.equals(r.serviceInfo.packageName)) {
205 if (r.isForeground) {
206 toStop.add(r);
207 }
208 }
209 }
210
211 // Now stop them all
212 final int numToStop = toStop.size();
213 if (numToStop > 0 && DEBUG_FOREGROUND_SERVICE) {
214 Slog.i(TAG, "Package " + packageName + "/" + uid
215 + " entering FAS with foreground services");
216 }
217 for (int i = 0; i < numToStop; i++) {
218 final ServiceRecord r = toStop.get(i);
219 if (DEBUG_FOREGROUND_SERVICE) {
220 Slog.i(TAG, " Stopping fg for service " + r);
221 }
Hui Yu2d4207f2019-01-22 15:32:20 -0800222 setServiceForegroundInnerLocked(r, 0, null, 0, 0);
Christopher Tatec7933ac2018-03-12 17:57:09 -0700223 }
224 }
225 }
226 }
227
228 /**
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700229 * Information about an app that is currently running one or more foreground services.
Dan Sandler2f36ab82017-05-25 00:15:49 -0400230 * (This maps directly to the running apps we show in the notification.)
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700231 */
232 static final class ActiveForegroundApp {
233 String mPackageName;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700234 int mUid;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700235 CharSequence mLabel;
236 boolean mShownWhileScreenOn;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700237 boolean mAppOnTop;
238 boolean mShownWhileTop;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700239 long mStartTime;
240 long mStartVisibleTime;
241 long mEndTime;
242 int mNumActive;
Dianne Hackborncb015632017-06-14 17:30:15 -0700243
244 // Temp output of foregroundAppShownEnoughLocked
245 long mHideTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700246 }
247
248 /**
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700249 * Information about services for a single user.
250 */
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700251 final class ServiceMap extends Handler {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700252 final int mUserId;
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800253 final ArrayMap<ComponentName, ServiceRecord> mServicesByInstanceName = new ArrayMap<>();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700254 final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700255
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700256 final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700257 /* XXX eventually I'd like to have this based on processes instead of services.
258 * That is, if we try to start two services in a row both running in the same
259 * process, this should be one entry in mStartingBackground for that one process
260 * that remains until all services in it are done.
261 final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
262 = new ArrayMap<ProcessRecord, DelayingProcess>();
263 final ArrayList<DelayingProcess> mStartingProcessList
264 = new ArrayList<DelayingProcess>();
265 */
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700266
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700267 final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700268
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700269 final ArrayMap<String, ActiveForegroundApp> mActiveForegroundApps = new ArrayMap<>();
270 boolean mActiveForegroundAppsChanged;
271
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700272 static final int MSG_BG_START_TIMEOUT = 1;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700273 static final int MSG_UPDATE_FOREGROUND_APPS = 2;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700274
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700275 ServiceMap(Looper looper, int userId) {
276 super(looper);
Dianne Hackborn6285a322013-09-18 12:09:47 -0700277 mUserId = userId;
278 }
279
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700280 @Override
281 public void handleMessage(Message msg) {
282 switch (msg.what) {
283 case MSG_BG_START_TIMEOUT: {
284 synchronized (mAm) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700285 rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700286 }
287 } break;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700288 case MSG_UPDATE_FOREGROUND_APPS: {
289 updateForegroundApps(this);
290 } break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700291 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700292 }
293
Dianne Hackbornad51be92016-08-16 16:27:36 -0700294 void ensureNotStartingBackgroundLocked(ServiceRecord r) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700295 if (mStartingBackground.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800296 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
297 "No longer background starting: " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -0700298 rescheduleDelayedStartsLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700299 }
Dianne Hackborn2e46bb52013-09-13 17:01:26 -0700300 if (mDelayedStartList.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800301 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700302 }
303 }
304
Dianne Hackbornad51be92016-08-16 16:27:36 -0700305 void rescheduleDelayedStartsLocked() {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700306 removeMessages(MSG_BG_START_TIMEOUT);
307 final long now = SystemClock.uptimeMillis();
308 for (int i=0, N=mStartingBackground.size(); i<N; i++) {
309 ServiceRecord r = mStartingBackground.get(i);
310 if (r.startingBgTimeout <= now) {
311 Slog.i(TAG, "Waited long enough for: " + r);
312 mStartingBackground.remove(i);
313 N--;
Junu Kimfcb87362014-02-19 16:25:21 +0900314 i--;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700315 }
316 }
317 while (mDelayedStartList.size() > 0
318 && mStartingBackground.size() < mMaxStartingBackground) {
319 ServiceRecord r = mDelayedStartList.remove(0);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800320 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
321 "REM FR DELAY LIST (exec next): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700322 if (DEBUG_DELAYED_SERVICE) {
323 if (mDelayedStartList.size() > 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800324 Slog.v(TAG_SERVICE, "Remaining delayed list:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700325 for (int i=0; i<mDelayedStartList.size(); i++) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800326 Slog.v(TAG_SERVICE, " #" + i + ": " + mDelayedStartList.get(i));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700327 }
328 }
329 }
330 r.delayed = false;
Christopher Tate752bc2a2019-02-15 16:48:22 -0800331 if (r.pendingStarts.size() <= 0) {
332 Slog.wtf(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
333 + " delayedStop=" + r.delayedStop);
334 } else {
335 try {
336 startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false, true,
337 false);
338 } catch (TransactionTooLargeException e) {
339 // Ignore, nobody upstack cares.
340 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700341 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700342 }
343 if (mStartingBackground.size() > 0) {
344 ServiceRecord next = mStartingBackground.get(0);
345 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800346 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700347 + ", can delay others up to " + when);
348 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
349 sendMessageAtTime(msg, when);
350 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700351 if (mStartingBackground.size() < mMaxStartingBackground) {
352 mAm.backgroundServicesFinishedLocked(mUserId);
353 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700354 }
355 }
356
357 public ActiveServices(ActivityManagerService service) {
358 mAm = service;
Dianne Hackborn23037412013-11-04 18:11:29 -0800359 int maxBg = 0;
360 try {
361 maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
362 } catch(RuntimeException e) {
363 }
Dianne Hackborn20d94742014-05-29 18:35:45 -0700364 mMaxStartingBackground = maxBg > 0
365 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700366 }
367
Christopher Tatec7933ac2018-03-12 17:57:09 -0700368 void systemServicesReady() {
369 AppStateTracker ast = LocalServices.getService(AppStateTracker.class);
370 ast.addListener(new ForcedStandbyListener());
371 }
372
Dianne Hackbornad51be92016-08-16 16:27:36 -0700373 ServiceRecord getServiceByNameLocked(ComponentName name, int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700374 // TODO: Deal with global services
375 if (DEBUG_MU)
Dianne Hackbornad51be92016-08-16 16:27:36 -0700376 Slog.v(TAG_MU, "getServiceByNameLocked(" + name + "), callingUser = " + callingUser);
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800377 return getServiceMapLocked(callingUser).mServicesByInstanceName.get(name);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700378 }
379
Dianne Hackbornad51be92016-08-16 16:27:36 -0700380 boolean hasBackgroundServicesLocked(int callingUser) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700381 ServiceMap smap = mServiceMap.get(callingUser);
382 return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
383 }
384
Dianne Hackbornad51be92016-08-16 16:27:36 -0700385 private ServiceMap getServiceMapLocked(int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700386 ServiceMap smap = mServiceMap.get(callingUser);
387 if (smap == null) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700388 smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700389 mServiceMap.put(callingUser, smap);
390 }
391 return smap;
392 }
393
Dianne Hackbornad51be92016-08-16 16:27:36 -0700394 ArrayMap<ComponentName, ServiceRecord> getServicesLocked(int callingUser) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800395 return getServiceMapLocked(callingUser).mServicesByInstanceName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700396 }
397
Christopher Tatec7933ac2018-03-12 17:57:09 -0700398 private boolean appRestrictedAnyInBackground(final int uid, final String packageName) {
399 final int mode = mAm.mAppOpsService.checkOperation(
400 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, uid, packageName);
401 return (mode != AppOpsManager.MODE_ALLOWED);
402 }
403
Svet Ganov99b60432015-06-27 13:15:22 -0700404 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
Christopher Tate242ba3e92017-04-14 15:07:06 -0700405 int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700406 throws TransactionTooLargeException {
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000407 return startServiceLocked(caller, service, resolvedType, callingPid, callingUid, fgRequired,
408 callingPackage, userId, false);
409 }
410
411 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
412 int callingPid, int callingUid, boolean fgRequired, String callingPackage,
413 final int userId, boolean allowBackgroundActivityStarts)
414 throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800415 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700416 + " type=" + resolvedType + " args=" + service.getExtras());
417
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700418 final boolean callerFg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700419 if (caller != null) {
420 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
421 if (callerApp == null) {
422 throw new SecurityException(
423 "Unable to find app for caller " + caller
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700424 + " (pid=" + callingPid
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700425 + ") when starting service " + service);
426 }
Dianne Hackborna49ad092016-03-03 13:39:10 -0800427 callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700428 } else {
429 callerFg = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700430 }
431
432 ServiceLookupResult res =
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800433 retrieveServiceLocked(service, null, resolvedType, callingPackage,
Svet Ganovd223db32017-12-22 09:43:48 -0800434 callingPid, callingUid, userId, true, callerFg, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700435 if (res == null) {
436 return null;
437 }
438 if (res.record == null) {
439 return new ComponentName("!", res.permission != null
440 ? res.permission : "private to package");
441 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700442
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700443 ServiceRecord r = res.record;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700444
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700445 if (!mAm.mUserController.exists(r.userId)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700446 Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700447 return null;
448 }
449
Christopher Tate85048282018-03-30 14:08:59 -0700450 // If we're starting indirectly (e.g. from PendingIntent), figure out whether
Christopher Tate45f06c792018-04-25 10:47:23 -0700451 // we're launching into an app in a background state. This keys off of the same
452 // idleness state tracking as e.g. O+ background service start policy.
453 final boolean bgLaunch = !mAm.isUidActiveLocked(r.appInfo.uid);
Christopher Tate85048282018-03-30 14:08:59 -0700454
455 // If the app has strict background restrictions, we treat any bg service
456 // start analogously to the legacy-app forced-restrictions case, regardless
457 // of its target SDK version.
Christopher Tatec7933ac2018-03-12 17:57:09 -0700458 boolean forcedStandby = false;
Christopher Tate85048282018-03-30 14:08:59 -0700459 if (bgLaunch && appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
Christopher Tatec7933ac2018-03-12 17:57:09 -0700460 if (DEBUG_FOREGROUND_SERVICE) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800461 Slog.d(TAG, "Forcing bg-only service start only for " + r.shortInstanceName
Christopher Tate85048282018-03-30 14:08:59 -0700462 + " : bgLaunch=" + bgLaunch + " callerFg=" + callerFg);
Christopher Tatec7933ac2018-03-12 17:57:09 -0700463 }
464 forcedStandby = true;
465 }
466
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700467 // If this is a direct-to-foreground start, make sure it is allowed as per the app op.
468 boolean forceSilentAbort = false;
469 if (fgRequired) {
470 final int mode = mAm.mAppOpsService.checkOperation(
471 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
472 switch (mode) {
473 case AppOpsManager.MODE_ALLOWED:
474 case AppOpsManager.MODE_DEFAULT:
475 // All okay.
476 break;
477 case AppOpsManager.MODE_IGNORED:
478 // Not allowed, fall back to normal start service, failing siliently
479 // if background check restricts that.
480 Slog.w(TAG, "startForegroundService not allowed due to app op: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800481 + service + " to " + r.shortInstanceName
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700482 + " from pid=" + callingPid + " uid=" + callingUid
483 + " pkg=" + callingPackage);
484 fgRequired = false;
485 forceSilentAbort = true;
486 break;
487 default:
488 return new ComponentName("!!", "foreground not allowed as per app op");
489 }
490 }
491
Christopher Tate08992ac2017-03-21 11:37:06 -0700492 // If this isn't a direct-to-foreground start, check our ability to kick off an
493 // arbitrary service
Christopher Tatec7933ac2018-03-12 17:57:09 -0700494 if (forcedStandby || (!r.startRequested && !fgRequired)) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700495 // Before going further -- if this app is not allowed to start services in the
496 // background, then at this point we aren't going to let it period.
497 final int allowed = mAm.getAppStartModeLocked(r.appInfo.uid, r.packageName,
Christopher Tatec7933ac2018-03-12 17:57:09 -0700498 r.appInfo.targetSdkVersion, callingPid, false, false, forcedStandby);
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700499 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
500 Slog.w(TAG, "Background start not allowed: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800501 + service + " to " + r.shortInstanceName
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700502 + " from pid=" + callingPid + " uid=" + callingUid
Christopher Tatee84ffd92018-05-16 12:59:43 -0700503 + " pkg=" + callingPackage + " startFg?=" + fgRequired);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700504 if (allowed == ActivityManager.APP_START_MODE_DELAYED || forceSilentAbort) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700505 // In this case we are silently disabling the app, to disrupt as
506 // little as possible existing apps.
507 return null;
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700508 }
Christopher Tatee84ffd92018-05-16 12:59:43 -0700509 if (forcedStandby) {
510 // This is an O+ app, but we might be here because the user has placed
511 // it under strict background restrictions. Don't punish the app if it's
512 // trying to do the right thing but we're denying it for that reason.
513 if (fgRequired) {
514 if (DEBUG_BACKGROUND_CHECK) {
515 Slog.v(TAG, "Silently dropping foreground service launch due to FAS");
516 }
517 return null;
518 }
519 }
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700520 // This app knows it is in the new model where this operation is not
521 // allowed, so tell it what has happened.
Amith Yamasaniaa746442019-01-10 10:09:12 -0800522 UidRecord uidRec = mAm.mProcessList.getUidRecordLocked(r.appInfo.uid);
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700523 return new ComponentName("?", "app is in background uid " + uidRec);
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700524 }
525 }
526
Christopher Tate0a826902018-05-25 15:15:44 -0700527 // At this point we've applied allowed-to-start policy based on whether this was
528 // an ordinary startService() or a startForegroundService(). Now, only require that
529 // the app follow through on the startForegroundService() -> startForeground()
530 // contract if it actually targets O+.
531 if (r.appInfo.targetSdkVersion < Build.VERSION_CODES.O && fgRequired) {
532 if (DEBUG_BACKGROUND_CHECK || DEBUG_FOREGROUND_SERVICE) {
533 Slog.i(TAG, "startForegroundService() but host targets "
534 + r.appInfo.targetSdkVersion + " - not requiring startForeground()");
535 }
536 fgRequired = false;
537 }
538
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700539 NeededUriGrants neededGrants = mAm.mUgmInternal.checkGrantUriPermissionFromIntent(
Nicolas Prevotc6cf95c2014-05-29 11:30:36 +0100540 callingUid, r.packageName, service, service.getFlags(), null, r.userId);
Svet Ganov9c165d72015-12-01 19:52:26 -0800541
542 // If permissions need a review before any of the app components can run,
543 // we do not start the service and launch a review activity if the calling app
544 // is in the foreground passing it a pending intent to start the service when
545 // review is completed.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700546
547 // XXX This is not dealing with fgRequired!
548 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage,
549 callingUid, service, callerFg, userId)) {
550 return null;
Svet Ganov9c165d72015-12-01 19:52:26 -0800551 }
552
Dianne Hackbornd6f5b622013-11-11 17:25:37 -0800553 if (unscheduleServiceRestartLocked(r, callingUid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800554 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700555 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700556 r.lastActivity = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700557 r.startRequested = true;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700558 r.delayedStop = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700559 r.fgRequired = fgRequired;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700560 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -0700561 service, neededGrants, callingUid));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700562
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700563 if (fgRequired) {
564 // We are now effectively running a foreground service.
Dianne Hackborn2aec55a2018-06-26 10:35:35 -0700565 ServiceState stracker = r.getTracker();
566 if (stracker != null) {
567 stracker.setForeground(true, mAm.mProcessStats.getMemFactorLocked(),
568 r.lastActivity);
569 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700570 mAm.mAppOpsService.startOperation(AppOpsManager.getToken(mAm.mAppOpsService),
571 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, true);
572 }
573
Dianne Hackbornad51be92016-08-16 16:27:36 -0700574 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700575 boolean addToStarting = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700576 if (!callerFg && !fgRequired && r.app == null
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700577 && mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700578 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700579 if (proc == null || proc.getCurProcState() > ActivityManager.PROCESS_STATE_RECEIVER) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700580 // If this is not coming from a foreground caller, then we may want
581 // to delay the start if there are already other background services
582 // that are starting. This is to avoid process start spam when lots
583 // of applications are all handling things like connectivity broadcasts.
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700584 // We only do this for cached processes, because otherwise an application
585 // can have assumptions about calling startService() for a service to run
586 // in its own process, and for that process to not be killed before the
587 // service is started. This is especially the case for receivers, which
588 // may start a service in onReceive() to do some additional work and have
589 // initialized some global state as part of that.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800590 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
591 + r + " in " + proc);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700592 if (r.delayed) {
593 // This service is already scheduled for a delayed start; just leave
594 // it still waiting.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800595 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700596 return r.name;
597 }
598 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
599 // Something else is starting, delay!
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800600 Slog.i(TAG_SERVICE, "Delaying start of: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700601 smap.mDelayedStartList.add(r);
602 r.delayed = true;
603 return r.name;
604 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800605 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700606 addToStarting = true;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700607 } else if (proc.getCurProcState() >= ActivityManager.PROCESS_STATE_SERVICE) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700608 // We slightly loosen when we will enqueue this new service as a background
609 // starting service we are waiting for, to also include processes that are
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700610 // currently running other services or receivers.
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700611 addToStarting = true;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800612 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
613 "Not delaying, but counting as bg: " + r);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800614 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn8e692572013-09-10 19:06:15 -0700615 StringBuilder sb = new StringBuilder(128);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700616 sb.append("Not potential delay (state=").append(proc.getCurProcState())
Dianne Hackborn8e692572013-09-10 19:06:15 -0700617 .append(' ').append(proc.adjType);
618 String reason = proc.makeAdjReason();
619 if (reason != null) {
620 sb.append(' ');
621 sb.append(reason);
622 }
623 sb.append("): ");
624 sb.append(r.toString());
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800625 Slog.v(TAG_SERVICE, sb.toString());
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700626 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800627 } else if (DEBUG_DELAYED_STARTS) {
Christopher Tate08992ac2017-03-21 11:37:06 -0700628 if (callerFg || fgRequired) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800629 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
Christopher Tate08992ac2017-03-21 11:37:06 -0700630 + callingUid + " pid=" + callingPid + " fgRequired=" + fgRequired + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700631 } else if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800632 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700633 } else {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800634 Slog.v(TAG_SERVICE,
635 "Not potential delay (user " + r.userId + " not started): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700636 }
637 }
638
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000639 if (allowBackgroundActivityStarts) {
640 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
641 if (proc != null) {
642 proc.addAllowBackgroundActivityStartsToken(r);
643 // schedule removal of the whitelisting token after the timeout
644 removeAllowBackgroundActivityStartsServiceToken(proc, r,
645 SERVICE_BG_ACTIVITY_START_TIMEOUT_MS);
646 }
647 }
Michal Karpinski9cbb20b2019-02-05 17:31:50 +0000648 ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting,
649 allowBackgroundActivityStarts);
Christopher Tate42a386b2016-11-07 12:21:21 -0800650 return cmp;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700651 }
652
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000653 private void removeAllowBackgroundActivityStartsServiceToken(ProcessRecord proc,
654 ServiceRecord r, int delayMillis) {
655 mAm.mHandler.postDelayed(() -> {
656 if (proc != null) {
657 proc.removeAllowBackgroundActivityStartsToken(r);
658 }
659 }, delayMillis);
660 }
661
Svet Ganov9c165d72015-12-01 19:52:26 -0800662 private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
663 String callingPackage, int callingUid, Intent service, boolean callerFg,
664 final int userId) {
665 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
666 r.packageName, r.userId)) {
667
668 // Show a permission review UI only for starting from a foreground app
669 if (!callerFg) {
670 Slog.w(TAG, "u" + r.userId + " Starting a service in package"
671 + r.packageName + " requires a permissions review");
672 return false;
673 }
674
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700675 IIntentSender target = mAm.mPendingIntentController.getIntentSender(
Svet Ganov9c165d72015-12-01 19:52:26 -0800676 ActivityManager.INTENT_SENDER_SERVICE, callingPackage,
677 callingUid, userId, null, null, 0, new Intent[]{service},
678 new String[]{service.resolveType(mAm.mContext.getContentResolver())},
679 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
680 | PendingIntent.FLAG_IMMUTABLE, null);
681
682 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
683 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
Philip P. Moltmann751e46ca2019-01-24 13:56:47 -0800684 | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
Svet Ganov9c165d72015-12-01 19:52:26 -0800685 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
686 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
687 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
688
689 if (DEBUG_PERMISSIONS_REVIEW) {
690 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
691 + r.packageName);
692 }
693
694 mAm.mHandler.post(new Runnable() {
695 @Override
696 public void run() {
697 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
698 }
699 });
700
701 return false;
702 }
703
704 return true;
705 }
706
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700707 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
Michal Karpinski9cbb20b2019-02-05 17:31:50 +0000708 boolean callerFg, boolean addToStarting, boolean allowBackgroundActivityStarts)
709 throws TransactionTooLargeException {
Joe Onorato4eb64fd2016-03-21 15:30:09 -0700710 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700711 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700712 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700713 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700714 r.callStart = false;
Chenjie Yu75b3c492018-10-06 21:45:19 -0700715 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid, r.name.getPackageName(),
716 r.name.getClassName(), StatsLog.SERVICE_STATE_CHANGED__STATE__START);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700717 synchronized (r.stats.getBatteryStats()) {
718 r.stats.startRunningLocked();
719 }
Michal Karpinski9cbb20b2019-02-05 17:31:50 +0000720 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false,
721 allowBackgroundActivityStarts);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700722 if (error != null) {
723 return new ComponentName("!!", error);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700724 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700725
726 if (r.startRequested && addToStarting) {
727 boolean first = smap.mStartingBackground.size() == 0;
728 smap.mStartingBackground.add(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700729 r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700730 if (DEBUG_DELAYED_SERVICE) {
731 RuntimeException here = new RuntimeException("here");
732 here.fillInStackTrace();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800733 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800734 } else if (DEBUG_DELAYED_STARTS) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800735 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700736 }
737 if (first) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700738 smap.rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700739 }
Christopher Tate08992ac2017-03-21 11:37:06 -0700740 } else if (callerFg || r.fgRequired) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700741 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700742 }
743
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700744 return r.name;
745 }
746
747 private void stopServiceLocked(ServiceRecord service) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700748 if (service.delayed) {
Mohammad Samiul Islame896c212019-01-10 12:14:23 +0000749 // If service isn't actually running, but is being held in the
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700750 // delayed list, then we need to keep it started but note that it
751 // should be stopped once no longer delayed.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800752 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700753 service.delayedStop = true;
754 return;
755 }
Chenjie Yu75b3c492018-10-06 21:45:19 -0700756 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, service.appInfo.uid,
757 service.name.getPackageName(), service.name.getClassName(),
758 StatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700759 synchronized (service.stats.getBatteryStats()) {
760 service.stats.stopRunningLocked();
761 }
762 service.startRequested = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700763 if (service.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700764 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700765 SystemClock.uptimeMillis());
766 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700767 service.callStart = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700768 bringDownServiceIfNeededLocked(service, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700769 }
770
771 int stopServiceLocked(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700772 String resolvedType, int userId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800773 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700774 + " type=" + resolvedType);
775
776 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
777 if (caller != null && callerApp == null) {
778 throw new SecurityException(
779 "Unable to find app for caller " + caller
780 + " (pid=" + Binder.getCallingPid()
781 + ") when stopping service " + service);
782 }
783
784 // If this service is active, make sure it is stopped.
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800785 ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, null,
Svet Ganovd223db32017-12-22 09:43:48 -0800786 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700787 if (r != null) {
788 if (r.record != null) {
789 final long origId = Binder.clearCallingIdentity();
790 try {
Michal Karpinskic8aa91b2019-01-10 16:45:59 +0000791 // immediately remove bg activity whitelisting token if there was one
792 removeAllowBackgroundActivityStartsServiceToken(callerApp, r.record,
793 0 /* delayMillis */);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700794 stopServiceLocked(r.record);
795 } finally {
796 Binder.restoreCallingIdentity(origId);
797 }
798 return 1;
799 }
800 return -1;
801 }
802
803 return 0;
804 }
805
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700806 void stopInBackgroundLocked(int uid) {
807 // Stop all services associated with this uid due to it going to the background
808 // stopped state.
809 ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
810 ArrayList<ServiceRecord> stopping = null;
811 if (services != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800812 for (int i = services.mServicesByInstanceName.size() - 1; i >= 0; i--) {
813 ServiceRecord service = services.mServicesByInstanceName.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700814 if (service.appInfo.uid == uid && service.startRequested) {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800815 if (mAm.getAppStartModeLocked(service.appInfo.uid, service.packageName,
Christopher Tatec7933ac2018-03-12 17:57:09 -0700816 service.appInfo.targetSdkVersion, -1, false, false, false)
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800817 != ActivityManager.APP_START_MODE_NORMAL) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700818 if (stopping == null) {
819 stopping = new ArrayList<>();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700820 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800821 String compName = service.shortInstanceName;
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700822 EventLogTags.writeAmStopIdleService(service.appInfo.uid, compName);
823 StringBuilder sb = new StringBuilder(64);
824 sb.append("Stopping service due to app idle: ");
825 UserHandle.formatUid(sb, service.appInfo.uid);
826 sb.append(" ");
Yi Jin6b514142017-10-30 14:54:12 -0700827 TimeUtils.formatDuration(service.createRealTime
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700828 - SystemClock.elapsedRealtime(), sb);
829 sb.append(" ");
830 sb.append(compName);
831 Slog.w(TAG, sb.toString());
832 stopping.add(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700833 }
834 }
835 }
836 if (stopping != null) {
837 for (int i=stopping.size()-1; i>=0; i--) {
838 ServiceRecord service = stopping.get(i);
839 service.delayed = false;
Dianne Hackbornad51be92016-08-16 16:27:36 -0700840 services.ensureNotStartingBackgroundLocked(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700841 stopServiceLocked(service);
842 }
843 }
844 }
845 }
846
Svet Ganov99b60432015-06-27 13:15:22 -0700847 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800848 ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, callingPackage,
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -0700849 Binder.getCallingPid(), Binder.getCallingUid(),
Svet Ganovd223db32017-12-22 09:43:48 -0800850 UserHandle.getCallingUserId(), false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700851
852 IBinder ret = null;
853 if (r != null) {
854 // r.record is null if findServiceLocked() failed the caller permission check
855 if (r.record == null) {
856 throw new SecurityException(
Christopher Desjardins5862c5f2015-05-19 11:25:40 +0000857 "Permission Denial: Accessing service"
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700858 + " from pid=" + Binder.getCallingPid()
859 + ", uid=" + Binder.getCallingUid()
860 + " requires " + r.permission);
861 }
862 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
863 if (ib != null) {
864 ret = ib.binder;
865 }
866 }
867
868 return ret;
869 }
870
871 boolean stopServiceTokenLocked(ComponentName className, IBinder token,
872 int startId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800873 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700874 + " " + token + " startId=" + startId);
Dianne Hackborn41203752012-08-31 14:05:51 -0700875 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700876 if (r != null) {
877 if (startId >= 0) {
878 // Asked to only stop if done with all work. Note that
879 // to avoid leaks, we will take this as dropping all
880 // start items up to and including this one.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -0700881 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700882 if (si != null) {
883 while (r.deliveredStarts.size() > 0) {
884 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
885 cur.removeUriPermissionsLocked();
886 if (cur == si) {
887 break;
888 }
889 }
890 }
891
892 if (r.getLastStartId() != startId) {
893 return false;
894 }
895
896 if (r.deliveredStarts.size() > 0) {
897 Slog.w(TAG, "stopServiceToken startId " + startId
898 + " is last, but have " + r.deliveredStarts.size()
899 + " remaining args");
900 }
901 }
902
Chenjie Yu75b3c492018-10-06 21:45:19 -0700903 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid, r.name.getPackageName(),
904 r.name.getClassName(), StatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700905 synchronized (r.stats.getBatteryStats()) {
906 r.stats.stopRunningLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700907 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700908 r.startRequested = false;
909 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700910 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700911 SystemClock.uptimeMillis());
912 }
913 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700914 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700915 bringDownServiceIfNeededLocked(r, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700916 Binder.restoreCallingIdentity(origId);
917 return true;
918 }
919 return false;
920 }
921
Sudheer Shankac9d94072017-02-22 22:13:55 +0000922 public void setServiceForegroundLocked(ComponentName className, IBinder token,
Hui Yu2d4207f2019-01-22 15:32:20 -0800923 int id, Notification notification, int flags, int foregroundServiceType) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700924 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700925 final long origId = Binder.clearCallingIdentity();
926 try {
Dianne Hackborn41203752012-08-31 14:05:51 -0700927 ServiceRecord r = findServiceLocked(className, token, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700928 if (r != null) {
Hui Yu2d4207f2019-01-22 15:32:20 -0800929 setServiceForegroundInnerLocked(r, id, notification, flags, foregroundServiceType);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700930 }
931 } finally {
932 Binder.restoreCallingIdentity(origId);
933 }
934 }
935
Dianne Hackborncb015632017-06-14 17:30:15 -0700936 boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) {
937 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid="
938 + aa.mUid);
939 boolean canRemove = false;
940 aa.mHideTime = Long.MAX_VALUE;
941 if (aa.mShownWhileTop) {
942 // If the app was ever at the top of the screen while the foreground
943 // service was running, then we can always just immediately remove it.
944 canRemove = true;
945 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown while on top");
946 } else if (mScreenOn || aa.mShownWhileScreenOn) {
947 final long minTime = aa.mStartVisibleTime
948 + (aa.mStartTime != aa.mStartVisibleTime
949 ? mAm.mConstants.FGSERVICE_SCREEN_ON_AFTER_TIME
950 : mAm.mConstants.FGSERVICE_MIN_SHOWN_TIME);
951 if (nowElapsed >= minTime) {
952 // If shown while the screen is on, and it has been shown for
953 // at least the minimum show time, then we can now remove it.
954 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown long enough with screen on");
955 canRemove = true;
956 } else {
957 // This is when we will be okay to stop telling the user.
958 long reportTime = nowElapsed + mAm.mConstants.FGSERVICE_MIN_REPORT_TIME;
959 aa.mHideTime = reportTime > minTime ? reportTime : minTime;
960 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
961 + " with screen on");
962 }
963 } else {
964 final long minTime = aa.mEndTime
965 + mAm.mConstants.FGSERVICE_SCREEN_ON_BEFORE_TIME;
966 if (nowElapsed >= minTime) {
967 // If the foreground service has only run while the screen is
968 // off, but it has been gone now for long enough that we won't
969 // care to tell the user about it when the screen comes back on,
970 // then we can remove it now.
971 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - gone long enough with screen off");
972 canRemove = true;
973 } else {
974 // This is when we won't care about this old fg service.
975 aa.mHideTime = minTime;
976 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
977 + " with screen off");
978 }
979 }
980 return canRemove;
981 }
982
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700983 void updateForegroundApps(ServiceMap smap) {
984 // This is called from the handler without the lock held.
985 ArrayList<ActiveForegroundApp> active = null;
986 synchronized (mAm) {
987 final long now = SystemClock.elapsedRealtime();
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700988 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700989 if (smap != null) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700990 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Updating foreground apps for user "
991 + smap.mUserId);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700992 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
993 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -0700994 if (aa.mEndTime != 0) {
995 boolean canRemove = foregroundAppShownEnoughLocked(aa, now);
996 if (canRemove) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700997 // This was up for longer than the timeout, so just remove immediately.
998 smap.mActiveForegroundApps.removeAt(i);
999 smap.mActiveForegroundAppsChanged = true;
1000 continue;
1001 }
Dianne Hackborncb015632017-06-14 17:30:15 -07001002 if (aa.mHideTime < nextUpdateTime) {
1003 nextUpdateTime = aa.mHideTime;
1004 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001005 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001006 if (!aa.mAppOnTop) {
1007 if (active == null) {
1008 active = new ArrayList<>();
1009 }
Dianne Hackborncb015632017-06-14 17:30:15 -07001010 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
1011 + aa.mPackageName + ", uid=" + aa.mUid);
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001012 active.add(aa);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001013 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001014 }
1015 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
1016 if (nextUpdateTime < Long.MAX_VALUE) {
Dianne Hackborncb015632017-06-14 17:30:15 -07001017 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Next update time in: "
1018 + (nextUpdateTime-now));
1019 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001020 smap.sendMessageAtTime(msg, nextUpdateTime
1021 + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001022 }
1023 }
1024 if (!smap.mActiveForegroundAppsChanged) {
1025 return;
1026 }
1027 smap.mActiveForegroundAppsChanged = false;
1028 }
1029
Dianne Hackborn070d1422018-05-02 13:48:30 -07001030 if (!SHOW_DUNGEON_NOTIFICATION) {
1031 return;
1032 }
1033
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001034 final NotificationManager nm = (NotificationManager) mAm.mContext.getSystemService(
1035 Context.NOTIFICATION_SERVICE);
1036 final Context context = mAm.mContext;
1037
1038 if (active != null) {
1039 for (int i = 0; i < active.size(); i++) {
1040 ActiveForegroundApp aa = active.get(i);
1041 if (aa.mLabel == null) {
1042 PackageManager pm = context.getPackageManager();
1043 try {
1044 ApplicationInfo ai = pm.getApplicationInfoAsUser(aa.mPackageName,
1045 PackageManager.MATCH_KNOWN_PACKAGES, smap.mUserId);
1046 aa.mLabel = ai.loadLabel(pm);
1047 } catch (PackageManager.NameNotFoundException e) {
1048 aa.mLabel = aa.mPackageName;
1049 }
1050 }
1051 }
1052
1053 Intent intent;
1054 String title;
1055 String msg;
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001056 String[] pkgs;
Dan Sandler886e0162017-06-06 14:23:43 -04001057 final long nowElapsed = SystemClock.elapsedRealtime();
1058 long oldestStartTime = nowElapsed;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001059 if (active.size() == 1) {
1060 intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
1061 intent.setData(Uri.fromParts("package", active.get(0).mPackageName, null));
1062 title = context.getString(
1063 R.string.foreground_service_app_in_background, active.get(0).mLabel);
1064 msg = context.getString(R.string.foreground_service_tap_for_details);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001065 pkgs = new String[] { active.get(0).mPackageName };
Dan Sandler2f36ab82017-05-25 00:15:49 -04001066 oldestStartTime = active.get(0).mStartTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001067 } else {
1068 intent = new Intent(Settings.ACTION_FOREGROUND_SERVICES_SETTINGS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001069 pkgs = new String[active.size()];
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001070 for (int i = 0; i < active.size(); i++) {
1071 pkgs[i] = active.get(i).mPackageName;
Dan Sandler2f36ab82017-05-25 00:15:49 -04001072 oldestStartTime = Math.min(oldestStartTime, active.get(i).mStartTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001073 }
1074 intent.putExtra("packages", pkgs);
1075 title = context.getString(
1076 R.string.foreground_service_apps_in_background, active.size());
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001077 msg = active.get(0).mLabel.toString();
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001078 for (int i = 1; i < active.size(); i++) {
1079 msg = context.getString(R.string.foreground_service_multiple_separator,
1080 msg, active.get(i).mLabel);
1081 }
1082 }
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001083 Bundle notificationBundle = new Bundle();
1084 notificationBundle.putStringArray(Notification.EXTRA_FOREGROUND_APPS, pkgs);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001085 Notification.Builder n =
1086 new Notification.Builder(context,
1087 SystemNotificationChannels.FOREGROUND_SERVICE)
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001088 .addExtras(notificationBundle)
Dan Sandler2f36ab82017-05-25 00:15:49 -04001089 .setSmallIcon(R.drawable.stat_sys_vitals)
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001090 .setOngoing(true)
Dan Sandler886e0162017-06-06 14:23:43 -04001091 .setShowWhen(oldestStartTime < nowElapsed)
1092 .setWhen(System.currentTimeMillis() - (nowElapsed - oldestStartTime))
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001093 .setColor(context.getColor(
1094 com.android.internal.R.color.system_notification_accent_color))
1095 .setContentTitle(title)
1096 .setContentText(msg)
1097 .setContentIntent(
1098 PendingIntent.getActivityAsUser(context, 0, intent,
1099 PendingIntent.FLAG_UPDATE_CURRENT,
1100 null, new UserHandle(smap.mUserId)));
1101 nm.notifyAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1102 n.build(), new UserHandle(smap.mUserId));
1103 } else {
1104 nm.cancelAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1105 new UserHandle(smap.mUserId));
1106 }
1107 }
1108
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001109 private void requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001110 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001111 if (timeElapsed != 0) {
1112 smap.sendMessageAtTime(msg,
1113 timeElapsed + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001114 } else {
1115 smap.mActiveForegroundAppsChanged = true;
1116 smap.sendMessage(msg);
1117 }
1118 }
1119
1120 private void decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r) {
1121 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1122 if (active != null) {
1123 active.mNumActive--;
1124 if (active.mNumActive <= 0) {
1125 active.mEndTime = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001126 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Ended running of service");
1127 if (foregroundAppShownEnoughLocked(active, active.mEndTime)) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001128 // Have been active for long enough that we will remove it immediately.
1129 smap.mActiveForegroundApps.remove(r.packageName);
1130 smap.mActiveForegroundAppsChanged = true;
1131 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001132 } else if (active.mHideTime < Long.MAX_VALUE){
1133 requestUpdateActiveForegroundAppsLocked(smap, active.mHideTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001134 }
1135 }
1136 }
1137 }
1138
1139 void updateScreenStateLocked(boolean screenOn) {
1140 if (mScreenOn != screenOn) {
1141 mScreenOn = screenOn;
1142
1143 // If screen is turning on, then we now reset the start time of any foreground
1144 // services that were started while the screen was off.
1145 if (screenOn) {
1146 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001147 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Screen turned on");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001148 for (int i = mServiceMap.size()-1; i >= 0; i--) {
1149 ServiceMap smap = mServiceMap.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -07001150 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001151 boolean changed = false;
1152 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1153 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
Dianne Hackborncb015632017-06-14 17:30:15 -07001154 if (active.mEndTime == 0) {
1155 if (!active.mShownWhileScreenOn) {
1156 active.mShownWhileScreenOn = true;
1157 active.mStartVisibleTime = nowElapsed;
1158 }
1159 } else {
1160 if (!active.mShownWhileScreenOn
1161 && active.mStartVisibleTime == active.mStartTime) {
1162 // If this was never shown while the screen was on, then we will
1163 // count the time it started being visible as now, to tell the user
1164 // about it now that they have a screen to look at.
1165 active.mEndTime = active.mStartVisibleTime = nowElapsed;
1166 }
1167 if (foregroundAppShownEnoughLocked(active, nowElapsed)) {
1168 // Have been active for long enough that we will remove it
1169 // immediately.
1170 smap.mActiveForegroundApps.remove(active.mPackageName);
1171 smap.mActiveForegroundAppsChanged = true;
1172 changed = true;
1173 } else {
1174 if (active.mHideTime < nextUpdateTime) {
1175 nextUpdateTime = active.mHideTime;
1176 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001177 }
1178 }
1179 }
1180 if (changed) {
Dianne Hackborncb015632017-06-14 17:30:15 -07001181 // Need to immediately update.
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001182 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001183 } else if (nextUpdateTime < Long.MAX_VALUE) {
1184 requestUpdateActiveForegroundAppsLocked(smap, nextUpdateTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001185 }
1186 }
1187 }
1188 }
1189 }
1190
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001191 void foregroundServiceProcStateChangedLocked(UidRecord uidRec) {
1192 ServiceMap smap = mServiceMap.get(UserHandle.getUserId(uidRec.uid));
1193 if (smap != null) {
1194 boolean changed = false;
1195 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1196 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
1197 if (active.mUid == uidRec.uid) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07001198 if (uidRec.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001199 if (!active.mAppOnTop) {
1200 active.mAppOnTop = true;
1201 changed = true;
1202 }
1203 active.mShownWhileTop = true;
1204 } else if (active.mAppOnTop) {
1205 active.mAppOnTop = false;
1206 changed = true;
1207 }
1208 }
1209 }
1210 if (changed) {
1211 requestUpdateActiveForegroundAppsLocked(smap, 0);
1212 }
1213 }
1214 }
1215
Christopher Tatec7933ac2018-03-12 17:57:09 -07001216 /**
1217 * @param id Notification ID. Zero === exit foreground state for the given service.
1218 */
1219 private void setServiceForegroundInnerLocked(final ServiceRecord r, int id,
Hui Yu2d4207f2019-01-22 15:32:20 -08001220 Notification notification, int flags, int foregroundServiceType) {
Christopher Tate42a386b2016-11-07 12:21:21 -08001221 if (id != 0) {
1222 if (notification == null) {
1223 throw new IllegalArgumentException("null notification");
1224 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001225 // Instant apps need permission to create foreground services.
1226 if (r.appInfo.isInstantApp()) {
1227 final int mode = mAm.mAppOpsService.checkOperation(
1228 AppOpsManager.OP_INSTANT_APP_START_FOREGROUND,
1229 r.appInfo.uid,
1230 r.appInfo.packageName);
1231 switch (mode) {
1232 case AppOpsManager.MODE_ALLOWED:
1233 break;
1234 case AppOpsManager.MODE_IGNORED:
1235 Slog.w(TAG, "Instant app " + r.appInfo.packageName
1236 + " does not have permission to create foreground services"
1237 + ", ignoring.");
Sudheer Shankac9d94072017-02-22 22:13:55 +00001238 return;
Chad Brubaker97b383f2017-02-02 15:04:35 -08001239 case AppOpsManager.MODE_ERRORED:
1240 throw new SecurityException("Instant app " + r.appInfo.packageName
1241 + " does not have permission to create foreground services");
1242 default:
Dianne Hackborndd027b32018-01-19 17:44:46 -08001243 mAm.enforcePermission(
1244 android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
1245 r.app.pid, r.appInfo.uid, "startForeground");
Chad Brubaker97b383f2017-02-02 15:04:35 -08001246 }
Hui Yu1ea85522018-12-06 16:59:18 -08001247 } else {
1248 if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
1249 mAm.enforcePermission(
1250 android.Manifest.permission.FOREGROUND_SERVICE,
1251 r.app.pid, r.appInfo.uid, "startForeground");
1252 }
Hui Yu2d4207f2019-01-22 15:32:20 -08001253
1254 int manifestType = r.serviceInfo.getForegroundServiceType();
1255 // If passed in foreground service type is FOREGROUND_SERVICE_TYPE_MANIFEST,
1256 // consider it is the same as manifest foreground service type.
1257 if (foregroundServiceType == FOREGROUND_SERVICE_TYPE_MANIFEST) {
1258 foregroundServiceType = manifestType;
1259 }
1260 // Check the passed in foreground service type flags is a subset of manifest
1261 // foreground service type flags.
1262 if ((foregroundServiceType & manifestType) != foregroundServiceType) {
Hui Yubaffff52019-02-20 10:34:27 -08001263 throw new IllegalArgumentException("foregroundServiceType "
1264 + String.format("0x%08X", foregroundServiceType)
1265 + " is not a subset of foregroundServiceType attribute "
1266 + String.format("0x%08X", manifestType)
1267 + " in service element of manifest file");
Hui Yu1ea85522018-12-06 16:59:18 -08001268 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001269 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001270 boolean alreadyStartedOp = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001271 boolean stopProcStatsOp = false;
Christopher Tate08992ac2017-03-21 11:37:06 -07001272 if (r.fgRequired) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001273 if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001274 Slog.i(TAG, "Service called startForeground() as required: " + r);
1275 }
1276 r.fgRequired = false;
1277 r.fgWaiting = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001278 alreadyStartedOp = stopProcStatsOp = true;
Christopher Tate08992ac2017-03-21 11:37:06 -07001279 mAm.mHandler.removeMessages(
1280 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
1281 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001282
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001283 try {
1284 boolean ignoreForeground = false;
1285 final int mode = mAm.mAppOpsService.checkOperation(
1286 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
1287 switch (mode) {
1288 case AppOpsManager.MODE_ALLOWED:
1289 case AppOpsManager.MODE_DEFAULT:
1290 // All okay.
1291 break;
1292 case AppOpsManager.MODE_IGNORED:
1293 // Whoops, silently ignore this.
1294 Slog.w(TAG, "Service.startForeground() not allowed due to app op: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001295 + r.shortInstanceName);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001296 ignoreForeground = true;
1297 break;
1298 default:
1299 throw new SecurityException("Foreground not allowed as per app op");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001300 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001301
1302 if (!ignoreForeground &&
1303 appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001304 Slog.w(TAG,
1305 "Service.startForeground() not allowed due to bg restriction: service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001306 + r.shortInstanceName);
Christopher Tate45f06c792018-04-25 10:47:23 -07001307 // Back off of any foreground expectations around this service, since we've
1308 // just turned down its fg request.
1309 updateServiceForegroundLocked(r.app, false);
1310 ignoreForeground = true;
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001311 }
1312
1313 // Apps under strict background restrictions simply don't get to have foreground
1314 // services, so now that we've enforced the startForegroundService() contract
1315 // we only do the machinery of making the service foreground when the app
1316 // is not restricted.
1317 if (!ignoreForeground) {
1318 if (r.foregroundId != id) {
1319 cancelForegroundNotificationLocked(r);
1320 r.foregroundId = id;
Christopher Tatec7933ac2018-03-12 17:57:09 -07001321 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001322 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
1323 r.foregroundNoti = notification;
Hui Yu2d4207f2019-01-22 15:32:20 -08001324 r.foregroundServiceType = foregroundServiceType;
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001325 if (!r.isForeground) {
1326 final ServiceMap smap = getServiceMapLocked(r.userId);
1327 if (smap != null) {
1328 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1329 if (active == null) {
1330 active = new ActiveForegroundApp();
1331 active.mPackageName = r.packageName;
1332 active.mUid = r.appInfo.uid;
1333 active.mShownWhileScreenOn = mScreenOn;
1334 if (r.app != null) {
1335 active.mAppOnTop = active.mShownWhileTop =
Wale Ogunwalebff2df42018-10-18 17:09:19 -07001336 r.app.uidRecord.getCurProcState()
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001337 <= ActivityManager.PROCESS_STATE_TOP;
1338 }
1339 active.mStartTime = active.mStartVisibleTime
1340 = SystemClock.elapsedRealtime();
1341 smap.mActiveForegroundApps.put(r.packageName, active);
1342 requestUpdateActiveForegroundAppsLocked(smap, 0);
1343 }
1344 active.mNumActive++;
1345 }
1346 r.isForeground = true;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001347 if (!stopProcStatsOp) {
1348 ServiceState stracker = r.getTracker();
1349 if (stracker != null) {
1350 stracker.setForeground(true,
1351 mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
1352 }
1353 } else {
1354 stopProcStatsOp = false;
1355 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001356 mAm.mAppOpsService.startOperation(
1357 AppOpsManager.getToken(mAm.mAppOpsService),
1358 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName,
1359 true);
1360 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001361 r.appInfo.uid, r.shortInstanceName,
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001362 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER);
Hui Yue361a232018-10-04 15:05:21 -07001363 mAm.updateForegroundServiceUsageStats(r.name, r.userId, true);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001364 }
1365 r.postNotification();
1366 if (r.app != null) {
1367 updateServiceForegroundLocked(r.app, true);
1368 }
1369 getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
1370 mAm.notifyPackageUse(r.serviceInfo.packageName,
1371 PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
1372 } else {
1373 if (DEBUG_FOREGROUND_SERVICE) {
1374 Slog.d(TAG, "Suppressing startForeground() for FAS " + r);
1375 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001376 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001377 } finally {
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001378 if (stopProcStatsOp) {
1379 // We got through to this point with it actively being started foreground,
1380 // and never decided we wanted to keep it like that, so drop it.
1381 ServiceState stracker = r.getTracker();
1382 if (stracker != null) {
1383 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1384 r.lastActivity);
1385 }
1386 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001387 if (alreadyStartedOp) {
1388 // If we had previously done a start op for direct foreground start,
1389 // we have cleared the flag so can now drop it.
1390 mAm.mAppOpsService.finishOperation(
1391 AppOpsManager.getToken(mAm.mAppOpsService),
1392 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001393 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001394 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001395 } else {
1396 if (r.isForeground) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001397 final ServiceMap smap = getServiceMapLocked(r.userId);
1398 if (smap != null) {
1399 decActiveForegroundAppLocked(smap, r);
1400 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001401 r.isForeground = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001402 ServiceState stracker = r.getTracker();
1403 if (stracker != null) {
1404 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1405 r.lastActivity);
1406 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001407 mAm.mAppOpsService.finishOperation(
1408 AppOpsManager.getToken(mAm.mAppOpsService),
1409 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001410 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001411 r.appInfo.uid, r.shortInstanceName,
Chenjie Yuccfe6452018-01-30 11:33:21 -08001412 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Hui Yue361a232018-10-04 15:05:21 -07001413 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
Christopher Tate42a386b2016-11-07 12:21:21 -08001414 if (r.app != null) {
1415 mAm.updateLruProcessLocked(r.app, false, null);
1416 updateServiceForegroundLocked(r.app, true);
1417 }
1418 }
1419 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001420 cancelForegroundNotificationLocked(r);
Christopher Tate42a386b2016-11-07 12:21:21 -08001421 r.foregroundId = 0;
1422 r.foregroundNoti = null;
1423 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1424 r.stripForegroundServiceFlagFromNotification();
1425 if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
1426 r.foregroundId = 0;
1427 r.foregroundNoti = null;
1428 }
1429 }
1430 }
1431 }
1432
Christopher Tate08992ac2017-03-21 11:37:06 -07001433 private void cancelForegroundNotificationLocked(ServiceRecord r) {
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001434 if (r.foregroundId != 0) {
1435 // First check to see if this app has any other active foreground services
1436 // with the same notification ID. If so, we shouldn't actually cancel it,
1437 // because that would wipe away the notification that still needs to be shown
1438 // due the other service.
Dianne Hackbornad51be92016-08-16 16:27:36 -07001439 ServiceMap sm = getServiceMapLocked(r.userId);
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001440 if (sm != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001441 for (int i = sm.mServicesByInstanceName.size() - 1; i >= 0; i--) {
1442 ServiceRecord other = sm.mServicesByInstanceName.valueAt(i);
Dianne Hackborn569a4582016-08-04 14:00:22 -07001443 if (other != r && other.foregroundId == r.foregroundId
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001444 && other.packageName.equals(r.packageName)) {
1445 // Found one! Abort the cancel.
1446 return;
1447 }
1448 }
1449 }
1450 r.cancelNotification();
1451 }
1452 }
1453
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001454 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
1455 boolean anyForeground = false;
Amith Yamasania0a30a12019-01-22 11:38:06 -08001456 int fgServiceTypes = 0;
1457 for (int i = proc.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07001458 ServiceRecord sr = proc.services.valueAt(i);
Christopher Tatee23fa2b2017-04-20 14:48:13 -07001459 if (sr.isForeground || sr.fgRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001460 anyForeground = true;
Hui Yu2d4207f2019-01-22 15:32:20 -08001461 fgServiceTypes |= sr.foregroundServiceType;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001462 break;
1463 }
1464 }
Amith Yamasania0a30a12019-01-22 11:38:06 -08001465 mAm.updateProcessForegroundLocked(proc, anyForeground, fgServiceTypes, oomAdj);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001466 }
1467
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001468 private void updateWhitelistManagerLocked(ProcessRecord proc) {
1469 proc.whitelistManager = false;
1470 for (int i=proc.services.size()-1; i>=0; i--) {
1471 ServiceRecord sr = proc.services.valueAt(i);
1472 if (sr.whitelistManager) {
1473 proc.whitelistManager = true;
1474 break;
1475 }
1476 }
1477 }
1478
Dianne Hackborn465fa392014-09-14 14:21:18 -07001479 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
1480 ArraySet<ProcessRecord> updatedProcesses = null;
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001481 for (int i = 0; i < clientProc.connections.size(); i++) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001482 final ConnectionRecord conn = clientProc.connections.valueAt(i);
1483 final ProcessRecord proc = conn.binding.service.app;
1484 if (proc == null || proc == clientProc) {
1485 continue;
1486 } else if (updatedProcesses == null) {
1487 updatedProcesses = new ArraySet<>();
1488 } else if (updatedProcesses.contains(proc)) {
1489 continue;
1490 }
1491 updatedProcesses.add(proc);
1492 updateServiceClientActivitiesLocked(proc, null, false);
1493 }
1494 }
1495
Dianne Hackborndb926082013-10-31 16:32:44 -07001496 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
Dianne Hackborn465fa392014-09-14 14:21:18 -07001497 ConnectionRecord modCr, boolean updateLru) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001498 if (modCr != null && modCr.binding.client != null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001499 if (!modCr.binding.client.hasActivities()) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001500 // This connection is from a client without activities, so adding
1501 // and removing is not interesting.
1502 return false;
1503 }
1504 }
1505
1506 boolean anyClientActivities = false;
1507 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
1508 ServiceRecord sr = proc.services.valueAt(i);
1509 for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) {
1510 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni);
1511 for (int cri=clist.size()-1; cri>=0; cri--) {
1512 ConnectionRecord cr = clist.get(cri);
1513 if (cr.binding.client == null || cr.binding.client == proc) {
1514 // Binding to ourself is not interesting.
1515 continue;
1516 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001517 if (cr.binding.client.hasActivities()) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001518 anyClientActivities = true;
1519 break;
1520 }
1521 }
1522 }
1523 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001524 if (anyClientActivities != proc.hasClientActivities()) {
1525 proc.setHasClientActivities(anyClientActivities);
Dianne Hackborn465fa392014-09-14 14:21:18 -07001526 if (updateLru) {
1527 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
1528 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001529 return true;
1530 }
1531 return false;
1532 }
1533
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001534 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
Svet Ganov9c165d72015-12-01 19:52:26 -08001535 String resolvedType, final IServiceConnection connection, int flags,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001536 String instanceName, String callingPackage, final int userId)
1537 throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001538 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001539 + " type=" + resolvedType + " conn=" + connection.asBinder()
1540 + " flags=0x" + Integer.toHexString(flags));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001541 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
1542 if (callerApp == null) {
1543 throw new SecurityException(
1544 "Unable to find app for caller " + caller
1545 + " (pid=" + Binder.getCallingPid()
1546 + ") when binding service " + service);
1547 }
1548
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001549 ActivityServiceConnectionsHolder<ConnectionRecord> activity = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001550 if (token != null) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001551 activity = mAm.mAtmInternal.getServiceConnectionsHolder(token);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001552 if (activity == null) {
1553 Slog.w(TAG, "Binding with unknown activity: " + token);
1554 return 0;
1555 }
1556 }
1557
1558 int clientLabel = 0;
1559 PendingIntent clientIntent = null;
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001560 final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001561
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001562 if (isCallerSystem) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001563 // Hacky kind of thing -- allow system stuff to tell us
1564 // what they are, so we can report this elsewhere for
1565 // others to know why certain services are running.
Jeff Sharkeyf0ec2e02016-03-21 12:37:54 -06001566 service.setDefusable(true);
1567 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001568 if (clientIntent != null) {
1569 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
1570 if (clientLabel != 0) {
1571 // There are no useful extras in the intent, trash them.
1572 // System code calling with this stuff just needs to know
1573 // this will happen.
1574 service = service.cloneFilter();
1575 }
1576 }
1577 }
1578
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001579 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1580 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
1581 "BIND_TREAT_LIKE_ACTIVITY");
1582 }
1583
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001584 if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
1585 throw new SecurityException(
1586 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1587 + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
1588 }
1589
Svet Ganovd223db32017-12-22 09:43:48 -08001590 if ((flags & Context.BIND_ALLOW_INSTANT) != 0 && !isCallerSystem) {
1591 throw new SecurityException(
1592 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1593 + ") set BIND_ALLOW_INSTANT when binding service " + service);
1594 }
1595
Dianne Hackborna49ad092016-03-03 13:39:10 -08001596 final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Robert Sesekb9a86662015-12-09 16:22:45 -05001597 final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
Svet Ganovd223db32017-12-22 09:43:48 -08001598 final boolean allowInstant = (flags & Context.BIND_ALLOW_INSTANT) != 0;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001599
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001600 ServiceLookupResult res =
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001601 retrieveServiceLocked(service, instanceName, resolvedType, callingPackage,
1602 Binder.getCallingPid(), Binder.getCallingUid(), userId, true,
1603 callerFg, isBindExternal, allowInstant);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001604 if (res == null) {
1605 return 0;
1606 }
1607 if (res.record == null) {
1608 return -1;
1609 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001610 ServiceRecord s = res.record;
1611
Svet Ganov9c165d72015-12-01 19:52:26 -08001612 boolean permissionsReviewRequired = false;
1613
1614 // If permissions need a review before any of the app components can run,
1615 // we schedule binding to the service but do not start its process, then
1616 // we launch a review activity to which is passed a callback to invoke
1617 // when done to start the bound service's process to completing the binding.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001618 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
1619 s.packageName, s.userId)) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001620
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001621 permissionsReviewRequired = true;
Svet Ganov9c165d72015-12-01 19:52:26 -08001622
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001623 // Show a permission review UI only for binding from a foreground app
1624 if (!callerFg) {
1625 Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
1626 + s.packageName + " requires a permissions review");
1627 return 0;
1628 }
Svet Ganov9c165d72015-12-01 19:52:26 -08001629
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001630 final ServiceRecord serviceRecord = s;
1631 final Intent serviceIntent = service;
Svet Ganov9c165d72015-12-01 19:52:26 -08001632
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001633 RemoteCallback callback = new RemoteCallback(
1634 new RemoteCallback.OnResultListener() {
1635 @Override
1636 public void onResult(Bundle result) {
1637 synchronized(mAm) {
1638 final long identity = Binder.clearCallingIdentity();
1639 try {
1640 if (!mPendingServices.contains(serviceRecord)) {
1641 return;
Svet Ganov9c165d72015-12-01 19:52:26 -08001642 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001643 // If there is still a pending record, then the service
1644 // binding request is still valid, so hook them up. We
1645 // proceed only if the caller cleared the review requirement
1646 // otherwise we unbind because the user didn't approve.
1647 if (!mAm.getPackageManagerInternalLocked()
1648 .isPermissionsReviewRequired(
1649 serviceRecord.packageName,
1650 serviceRecord.userId)) {
1651 try {
1652 bringUpServiceLocked(serviceRecord,
1653 serviceIntent.getFlags(),
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00001654 callerFg, false, false, false);
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001655 } catch (RemoteException e) {
1656 /* ignore - local call */
1657 }
1658 } else {
1659 unbindServiceLocked(connection);
1660 }
1661 } finally {
1662 Binder.restoreCallingIdentity(identity);
Svet Ganov9c165d72015-12-01 19:52:26 -08001663 }
1664 }
Svet Ganov9c165d72015-12-01 19:52:26 -08001665 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001666 });
Svet Ganov9c165d72015-12-01 19:52:26 -08001667
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001668 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
1669 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
Philip P. Moltmann751e46ca2019-01-24 13:56:47 -08001670 | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001671 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1672 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
1673 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
1674
1675 if (DEBUG_PERMISSIONS_REVIEW) {
1676 Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
1677 + s.packageName);
Svet Ganov9c165d72015-12-01 19:52:26 -08001678 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001679
1680 mAm.mHandler.post(new Runnable() {
1681 @Override
1682 public void run() {
1683 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
1684 }
1685 });
Svet Ganov9c165d72015-12-01 19:52:26 -08001686 }
1687
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001688 final long origId = Binder.clearCallingIdentity();
1689
1690 try {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001691 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001692 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001693 + s);
1694 }
1695
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001696 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1697 s.lastActivity = SystemClock.uptimeMillis();
1698 if (!s.hasAutoCreateConnections()) {
1699 // This is the first binding, let the tracker know.
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001700 ServiceState stracker = s.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001701 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001702 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001703 s.lastActivity);
1704 }
1705 }
1706 }
1707
Dianne Hackbornc390aa82019-01-09 16:38:22 -08001708 if ((flags & Context.BIND_RESTRICT_ASSOCIATIONS) != 0) {
1709 mAm.requireAllowedAssociationsLocked(s.appInfo.packageName);
1710 }
1711
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001712 mAm.startAssociationLocked(callerApp.uid, callerApp.processName,
1713 callerApp.getCurProcState(), s.appInfo.uid, s.appInfo.longVersionCode,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001714 s.instanceName, s.processName);
Jesse Evans02af3ea2017-05-03 09:57:16 -07001715 // Once the apps have become associated, if one of them is caller is ephemeral
1716 // the target app should now be able to see the calling app
1717 mAm.grantEphemeralAccessLocked(callerApp.userId, service,
Hai Zhangbb23d532018-08-27 16:00:35 -07001718 UserHandle.getAppId(s.appInfo.uid), UserHandle.getAppId(callerApp.uid));
Dianne Hackbornab2df062015-01-07 13:43:13 -08001719
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001720 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
1721 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001722 connection, flags, clientLabel, clientIntent,
Dianne Hackborn24bbe582018-12-17 11:58:31 -08001723 callerApp.uid, callerApp.processName, callingPackage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001724
1725 IBinder binder = connection.asBinder();
1726 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
1727 if (clist == null) {
1728 clist = new ArrayList<ConnectionRecord>();
1729 s.connections.put(binder, clist);
1730 }
1731 clist.add(c);
1732 b.connections.add(c);
1733 if (activity != null) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07001734 activity.addConnection(c);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001735 }
1736 b.client.connections.add(c);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07001737 c.startAssociationIfNeeded();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001738 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
1739 b.client.hasAboveClient = true;
1740 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001741 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
1742 s.whitelistManager = true;
1743 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001744 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001745 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07001746 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001747 clist = mServiceConnections.get(binder);
1748 if (clist == null) {
1749 clist = new ArrayList<ConnectionRecord>();
1750 mServiceConnections.put(binder, clist);
1751 }
1752 clist.add(c);
1753
1754 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1755 s.lastActivity = SystemClock.uptimeMillis();
Svet Ganov9c165d72015-12-01 19:52:26 -08001756 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00001757 permissionsReviewRequired, false) != null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001758 return 0;
1759 }
1760 }
1761
1762 if (s.app != null) {
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001763 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1764 s.app.treatLikeActivity = true;
1765 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001766 if (s.whitelistManager) {
1767 s.app.whitelistManager = true;
1768 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001769 // This could have made the service more important.
Dianne Hackborna631d562018-11-20 15:58:15 -08001770 mAm.updateLruProcessLocked(s.app,
1771 (callerApp.hasActivitiesOrRecentTasks() && s.app.hasClientActivities())
1772 || (callerApp.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP
1773 && (flags & Context.BIND_TREAT_LIKE_ACTIVITY) != 0),
1774 b.client);
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001775 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001776 }
1777
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001778 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001779 + ": received=" + b.intent.received
1780 + " apps=" + b.intent.apps.size()
1781 + " doRebind=" + b.intent.doRebind);
1782
1783 if (s.app != null && b.intent.received) {
1784 // Service is already running, so we can immediately
1785 // publish the connection.
1786 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001787 c.conn.connected(s.name, b.intent.binder, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001788 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001789 Slog.w(TAG, "Failure sending service " + s.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001790 + " to connection " + c.conn.asBinder()
1791 + " (in " + c.binding.client.processName + ")", e);
1792 }
1793
1794 // If this is the first app connected back to this binding,
1795 // and the service had previously asked to be told when
1796 // rebound, then do so.
1797 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001798 requestServiceBindingLocked(s, b.intent, callerFg, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001799 }
1800 } else if (!b.intent.requested) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001801 requestServiceBindingLocked(s, b.intent, callerFg, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001802 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001803
Dianne Hackbornad51be92016-08-16 16:27:36 -07001804 getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001805
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001806 } finally {
1807 Binder.restoreCallingIdentity(origId);
1808 }
1809
1810 return 1;
1811 }
1812
1813 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
1814 final long origId = Binder.clearCallingIdentity();
1815 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001816 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001817 + " " + intent + ": " + service);
1818 if (r != null) {
1819 Intent.FilterComparison filter
1820 = new Intent.FilterComparison(intent);
1821 IntentBindRecord b = r.bindings.get(filter);
1822 if (b != null && !b.received) {
1823 b.binder = service;
1824 b.requested = true;
1825 b.received = true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07001826 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1827 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
1828 for (int i=0; i<clist.size(); i++) {
1829 ConnectionRecord c = clist.get(i);
1830 if (!filter.equals(c.binding.intent.intent)) {
1831 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001832 TAG_SERVICE, "Not publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001833 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001834 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001835 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001836 TAG_SERVICE, "Published intent: " + intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001837 continue;
1838 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001839 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001840 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001841 c.conn.connected(r.name, service, false);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001842 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001843 Slog.w(TAG, "Failure sending service " + r.shortInstanceName
1844 + " to connection " + c.conn.asBinder()
1845 + " (in " + c.binding.client.processName + ")", e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001846 }
1847 }
1848 }
1849 }
1850
Dianne Hackborn164371f2013-10-01 19:10:13 -07001851 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001852 }
1853 } finally {
1854 Binder.restoreCallingIdentity(origId);
1855 }
1856 }
1857
Dianne Hackborna631d562018-11-20 15:58:15 -08001858 void updateServiceGroupLocked(IServiceConnection connection, int group, int importance) {
1859 final IBinder binder = connection.asBinder();
1860 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "updateServiceGroup: conn=" + binder);
1861 final ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1862 if (clist == null) {
1863 throw new IllegalArgumentException("Could not find connection for "
1864 + connection.asBinder());
1865 }
1866 for (int i = clist.size() - 1; i >= 0; i--) {
1867 final ConnectionRecord crec = clist.get(i);
1868 final ServiceRecord srec = crec.binding.service;
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08001869 if (srec != null && (srec.serviceInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) != 0) {
1870 if (srec.app != null) {
1871 if (group > 0) {
1872 srec.app.connectionService = srec;
1873 srec.app.connectionGroup = group;
1874 srec.app.connectionImportance = importance;
1875 } else {
1876 srec.app.connectionService = null;
1877 srec.app.connectionGroup = 0;
1878 srec.app.connectionImportance = 0;
1879 }
Dianne Hackborna631d562018-11-20 15:58:15 -08001880 } else {
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08001881 if (group > 0) {
1882 srec.pendingConnectionGroup = group;
1883 srec.pendingConnectionImportance = importance;
1884 } else {
1885 srec.pendingConnectionGroup = 0;
1886 srec.pendingConnectionImportance = 0;
1887 }
Dianne Hackborna631d562018-11-20 15:58:15 -08001888 }
1889 }
1890 }
1891 }
1892
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001893 boolean unbindServiceLocked(IServiceConnection connection) {
1894 IBinder binder = connection.asBinder();
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001895 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001896 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1897 if (clist == null) {
1898 Slog.w(TAG, "Unbind failed: could not find connection for "
1899 + connection.asBinder());
1900 return false;
1901 }
1902
1903 final long origId = Binder.clearCallingIdentity();
1904 try {
1905 while (clist.size() > 0) {
1906 ConnectionRecord r = clist.get(0);
1907 removeConnectionLocked(r, null, null);
Dianne Hackborn25e1eca2014-09-23 10:13:13 -07001908 if (clist.size() > 0 && clist.get(0) == r) {
1909 // In case it didn't get removed above, do it now.
1910 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
1911 clist.remove(0);
1912 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001913
1914 if (r.binding.service.app != null) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001915 if (r.binding.service.app.whitelistManager) {
Felipe Lemea7778b02016-06-28 10:38:59 -07001916 updateWhitelistManagerLocked(r.binding.service.app);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001917 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001918 // This could have made the service less important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001919 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1920 r.binding.service.app.treatLikeActivity = true;
1921 mAm.updateLruProcessLocked(r.binding.service.app,
Wale Ogunwale342fbe92018-10-09 08:44:10 -07001922 r.binding.service.app.hasClientActivities()
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001923 || r.binding.service.app.treatLikeActivity, null);
1924 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001925 mAm.updateOomAdjLocked(r.binding.service.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001926 }
1927 }
Amith Yamasanib2926b12017-05-11 11:13:52 -07001928
1929 mAm.updateOomAdjLocked();
1930
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001931 } finally {
1932 Binder.restoreCallingIdentity(origId);
1933 }
1934
1935 return true;
1936 }
1937
1938 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
1939 final long origId = Binder.clearCallingIdentity();
1940 try {
1941 if (r != null) {
1942 Intent.FilterComparison filter
1943 = new Intent.FilterComparison(intent);
1944 IntentBindRecord b = r.bindings.get(filter);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001945 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001946 + " at " + b + ": apps="
1947 + (b != null ? b.apps.size() : 0));
1948
Dianne Hackborn164371f2013-10-01 19:10:13 -07001949 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001950 if (b != null) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001951 if (b.apps.size() > 0 && !inDestroying) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001952 // Applications have already bound since the last
1953 // unbind, so just rebind right here.
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001954 boolean inFg = false;
1955 for (int i=b.apps.size()-1; i>=0; i--) {
1956 ProcessRecord client = b.apps.valueAt(i).client;
1957 if (client != null && client.setSchedGroup
Dianne Hackborna49ad092016-03-03 13:39:10 -08001958 != ProcessList.SCHED_GROUP_BACKGROUND) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001959 inFg = true;
1960 break;
1961 }
1962 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001963 try {
1964 requestServiceBindingLocked(r, b, inFg, true);
1965 } catch (TransactionTooLargeException e) {
1966 // Don't pass this back to ActivityThread, it's unrelated.
1967 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001968 } else {
1969 // Note to tell the service the next time there is
1970 // a new client.
1971 b.doRebind = true;
1972 }
1973 }
1974
Dianne Hackborn164371f2013-10-01 19:10:13 -07001975 serviceDoneExecutingLocked(r, inDestroying, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001976 }
1977 } finally {
1978 Binder.restoreCallingIdentity(origId);
1979 }
1980 }
1981
1982 private final ServiceRecord findServiceLocked(ComponentName name,
Dianne Hackborn41203752012-08-31 14:05:51 -07001983 IBinder token, int userId) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07001984 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001985 return r == token ? r : null;
1986 }
1987
1988 private final class ServiceLookupResult {
1989 final ServiceRecord record;
1990 final String permission;
1991
1992 ServiceLookupResult(ServiceRecord _record, String _permission) {
1993 record = _record;
1994 permission = _permission;
1995 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001996 }
1997
1998 private class ServiceRestarter implements Runnable {
1999 private ServiceRecord mService;
2000
2001 void setService(ServiceRecord service) {
2002 mService = service;
2003 }
2004
2005 public void run() {
2006 synchronized(mAm) {
2007 performServiceRestartLocked(mService);
2008 }
2009 }
2010 }
2011
2012 private ServiceLookupResult retrieveServiceLocked(Intent service,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002013 String instanceName, String resolvedType, String callingPackage,
2014 int callingPid, int callingUid, int userId,
Svet Ganovd223db32017-12-22 09:43:48 -08002015 boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
2016 boolean allowInstant) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002017 ServiceRecord r = null;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002018 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002019 + " type=" + resolvedType + " callingUid=" + callingUid);
2020
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07002021 userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
jovanaka6763a32018-12-03 17:23:20 -08002022 ActivityManagerInternal.ALLOW_NON_FULL_IN_PROFILE, "service",
2023 callingPackage);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002024
Dianne Hackbornad51be92016-08-16 16:27:36 -07002025 ServiceMap smap = getServiceMapLocked(userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002026 final ComponentName comp;
2027 if (instanceName == null) {
2028 comp = service.getComponent();
2029 } else {
2030 final ComponentName realComp = service.getComponent();
2031 if (realComp == null) {
2032 throw new IllegalArgumentException("Can't use custom instance name '" + instanceName
2033 + "' without expicit component in Intent");
2034 }
2035 comp = new ComponentName(realComp.getPackageName(),
2036 realComp.getClassName() + ":" + instanceName);
2037 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002038 if (comp != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002039 r = smap.mServicesByInstanceName.get(comp);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002040 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002041 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002042 if (r == null && !isBindExternal && instanceName == null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002043 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002044 r = smap.mServicesByIntent.get(filter);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002045 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002046 }
Robert Sesekb9a86662015-12-09 16:22:45 -05002047 if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
2048 && !callingPackage.equals(r.packageName)) {
2049 // If an external service is running within its own package, other packages
2050 // should not bind to that instance.
2051 r = null;
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002052 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Whoops, can't use existing external service");
Robert Sesekb9a86662015-12-09 16:22:45 -05002053 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002054 if (r == null) {
2055 try {
Svet Ganovd223db32017-12-22 09:43:48 -08002056 int flags = ActivityManagerService.STOCK_PM_FLAGS
2057 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
2058 if (allowInstant) {
2059 flags |= PackageManager.MATCH_INSTANT;
2060 }
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002061 // TODO: come back and remove this assumption to triage all services
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002062 ResolveInfo rInfo = mAm.getPackageManagerInternalLocked().resolveService(service,
Svet Ganovd223db32017-12-22 09:43:48 -08002063 resolvedType, flags, userId, callingUid);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002064 ServiceInfo sInfo = rInfo != null ? rInfo.serviceInfo : null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002065 if (sInfo == null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002066 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002067 ": not found");
2068 return null;
2069 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002070 if (instanceName != null
2071 && (sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
2072 throw new IllegalArgumentException("Can't use instance name '" + instanceName
2073 + "' with non-isolated service '" + sInfo.name + "'");
2074 }
2075 ComponentName className = new ComponentName(
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002076 sInfo.applicationInfo.packageName, sInfo.name);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002077 ComponentName name = comp != null ? comp : className;
Dianne Hackborn769b2e72018-12-05 08:51:20 -08002078 if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid,
2079 name.getPackageName(), sInfo.applicationInfo.uid)) {
2080 String msg = "association not allowed between packages "
Amith Yamasani9f96c2b2018-12-19 18:32:44 -08002081 + callingPackage + " and " + name.getPackageName();
Dianne Hackborn769b2e72018-12-05 08:51:20 -08002082 Slog.w(TAG, "Service lookup failed: " + msg);
2083 return new ServiceLookupResult(null, msg);
2084 }
Robert Sesekb9a86662015-12-09 16:22:45 -05002085 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
2086 if (isBindExternal) {
2087 if (!sInfo.exported) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002088 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
2089 + className + " is not exported");
Robert Sesekb9a86662015-12-09 16:22:45 -05002090 }
2091 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002092 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
2093 + className + " is not an isolatedProcess");
Robert Sesekb9a86662015-12-09 16:22:45 -05002094 }
2095 // Run the service under the calling package's application.
2096 ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
2097 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
2098 if (aInfo == null) {
2099 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
2100 "could not resolve client package " + callingPackage);
2101 }
2102 sInfo = new ServiceInfo(sInfo);
2103 sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
2104 sInfo.applicationInfo.packageName = aInfo.packageName;
2105 sInfo.applicationInfo.uid = aInfo.uid;
2106 name = new ComponentName(aInfo.packageName, name.getClassName());
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002107 className = new ComponentName(aInfo.packageName,
2108 instanceName == null ? className.getClassName()
2109 : (className.getClassName() + ":" + instanceName));
Robert Sesekb9a86662015-12-09 16:22:45 -05002110 service.setComponent(name);
2111 } else {
2112 throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
2113 name);
2114 }
2115 } else if (isBindExternal) {
2116 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
2117 " is not an externalService");
2118 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002119 if (userId > 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07002120 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
Amith Yamasani4b9d79c2014-05-21 19:14:21 -07002121 sInfo.name, sInfo.flags)
2122 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002123 userId = 0;
Dianne Hackbornad51be92016-08-16 16:27:36 -07002124 smap = getServiceMapLocked(0);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002125 }
2126 sInfo = new ServiceInfo(sInfo);
2127 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
2128 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002129 r = smap.mServicesByInstanceName.get(name);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002130 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE,
2131 "Retrieved via pm by intent: " + r);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002132 if (r == null && createIfNeeded) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002133 final Intent.FilterComparison filter
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002134 = new Intent.FilterComparison(service.cloneFilter());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002135 final ServiceRestarter res = new ServiceRestarter();
2136 final BatteryStatsImpl.Uid.Pkg.Serv ss;
2137 final BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002138 synchronized (stats) {
2139 ss = stats.getServiceStatsLocked(
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002140 sInfo.applicationInfo.uid, name.getPackageName(),
2141 name.getClassName());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002142 }
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08002143 r = new ServiceRecord(mAm, ss, className, name, filter, sInfo,
2144 callingFromFg, res);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002145 res.setService(r);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002146 smap.mServicesByInstanceName.put(name, r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002147 smap.mServicesByIntent.put(filter, r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002148
2149 // Make sure this component isn't in the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002150 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002151 final ServiceRecord pr = mPendingServices.get(i);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002152 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002153 && pr.instanceName.equals(name)) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002154 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002155 mPendingServices.remove(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002156 }
2157 }
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002158 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002159 }
2160 } catch (RemoteException ex) {
2161 // pm is in same process, this will never happen.
2162 }
2163 }
2164 if (r != null) {
Dianne Hackborn769b2e72018-12-05 08:51:20 -08002165 if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid, r.packageName,
2166 r.appInfo.uid)) {
2167 String msg = "association not allowed between packages "
2168 + callingPackage + " and " + r.packageName;
2169 Slog.w(TAG, "Service lookup failed: " + msg);
2170 return new ServiceLookupResult(null, msg);
2171 }
2172 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
2173 resolvedType, r.appInfo)) {
2174 return new ServiceLookupResult(null, "blocked by firewall");
2175 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002176 if (mAm.checkComponentPermission(r.permission,
Bryce Lee290e5782017-02-01 16:41:20 -08002177 callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002178 if (!r.exported) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002179 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002180 + " from pid=" + callingPid
2181 + ", uid=" + callingUid
2182 + " that is not exported from uid " + r.appInfo.uid);
2183 return new ServiceLookupResult(null, "not exported from uid "
2184 + r.appInfo.uid);
2185 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002186 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002187 + " from pid=" + callingPid
2188 + ", uid=" + callingUid
2189 + " requires " + r.permission);
2190 return new ServiceLookupResult(null, r.permission);
Svet Ganov99b60432015-06-27 13:15:22 -07002191 } else if (r.permission != null && callingPackage != null) {
2192 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
2193 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation(
2194 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002195 Slog.w(TAG, "Appop Denial: Accessing service " + r.shortInstanceName
Svet Ganov99b60432015-06-27 13:15:22 -07002196 + " from pid=" + callingPid
2197 + ", uid=" + callingUid
2198 + " requires appop " + AppOpsManager.opToName(opCode));
2199 return null;
2200 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002201 }
2202 return new ServiceLookupResult(r, null);
2203 }
2204 return null;
2205 }
2206
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002207 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002208 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002209 + why + " of " + r + " in app " + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002210 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002211 + why + " of " + r.shortInstanceName);
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002212
2213 // For b/34123235: Services within the system server won't start until SystemServer
2214 // does Looper.loop(), so we shouldn't try to start/bind to them too early in the boot
2215 // process. However, since there's a little point of showing the ANR dialog in that case,
2216 // let's suppress the timeout until PHASE_THIRD_PARTY_APPS_CAN_START.
2217 //
2218 // (Note there are multiple services start at PHASE_THIRD_PARTY_APPS_CAN_START too,
2219 // which technically could also trigger this timeout if there's a system server
2220 // that takes a long time to handle PHASE_THIRD_PARTY_APPS_CAN_START, but that shouldn't
2221 // happen.)
2222 boolean timeoutNeeded = true;
2223 if ((mAm.mBootPhase < SystemService.PHASE_THIRD_PARTY_APPS_CAN_START)
2224 && (r.app != null) && (r.app.pid == android.os.Process.myPid())) {
2225
2226 Slog.w(TAG, "Too early to start/bind service in system_server: Phase=" + mAm.mBootPhase
2227 + " " + r.getComponentName());
2228 timeoutNeeded = false;
2229 }
2230
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002231 long now = SystemClock.uptimeMillis();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002232 if (r.executeNesting == 0) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002233 r.executeFg = fg;
Joe Onorato4eb64fd2016-03-21 15:30:09 -07002234 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002235 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002236 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002237 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002238 if (r.app != null) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002239 r.app.executingServices.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002240 r.app.execServicesFg |= fg;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002241 if (timeoutNeeded && r.app.executingServices.size() == 1) {
Dianne Hackborn2be00932013-09-22 16:46:00 -07002242 scheduleServiceTimeoutLocked(r.app);
2243 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002244 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002245 } else if (r.app != null && fg && !r.app.execServicesFg) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002246 r.app.execServicesFg = true;
Makoto Onuki7ce98ac2018-05-16 12:27:04 -07002247 if (timeoutNeeded) {
2248 scheduleServiceTimeoutLocked(r.app);
2249 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002250 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002251 r.executeFg |= fg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002252 r.executeNesting++;
2253 r.executingStart = now;
2254 }
2255
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002256 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
2257 boolean execInFg, boolean rebind) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002258 if (r.app == null || r.app.thread == null) {
2259 // If service is not currently running, can't yet bind.
2260 return false;
2261 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08002262 if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
2263 + " rebind=" + rebind);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002264 if ((!i.requested || rebind) && i.apps.size() > 0) {
2265 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002266 bumpServiceExecutingLocked(r, execInFg, "bind");
Dianne Hackborna413dc02013-07-12 12:02:55 -07002267 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
2268 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002269 r.app.getReportedProcState());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002270 if (!rebind) {
2271 i.requested = true;
2272 }
2273 i.hasBound = true;
2274 i.doRebind = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002275 } catch (TransactionTooLargeException e) {
2276 // Keep the executeNesting count accurate.
2277 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
2278 final boolean inDestroying = mDestroyingServices.contains(r);
2279 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2280 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002281 } catch (RemoteException e) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002282 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002283 // Keep the executeNesting count accurate.
2284 final boolean inDestroying = mDestroyingServices.contains(r);
2285 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002286 return false;
2287 }
2288 }
2289 return true;
2290 }
2291
Dianne Hackbornad51be92016-08-16 16:27:36 -07002292 private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002293 boolean canceled = false;
2294
Wale Ogunwalef6733932018-06-27 05:14:34 -07002295 if (mAm.mAtmInternal.isShuttingDown()) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002296 Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortInstanceName
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07002297 + " - system is shutting down");
2298 return false;
2299 }
2300
Dianne Hackbornad51be92016-08-16 16:27:36 -07002301 ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002302 if (smap.mServicesByInstanceName.get(r.instanceName) != r) {
2303 ServiceRecord cur = smap.mServicesByInstanceName.get(r.instanceName);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002304 Slog.wtf(TAG, "Attempting to schedule restart of " + r
2305 + " when found in map: " + cur);
2306 return false;
2307 }
2308
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002309 final long now = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002310
2311 if ((r.serviceInfo.applicationInfo.flags
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002312 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002313 long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION;
2314 long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002315
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002316 // Any delivered but not yet finished starts should be put back
2317 // on the pending list.
2318 final int N = r.deliveredStarts.size();
2319 if (N > 0) {
2320 for (int i=N-1; i>=0; i--) {
2321 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
2322 si.removeUriPermissionsLocked();
2323 if (si.intent == null) {
2324 // We'll generate this again if needed.
2325 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
2326 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
2327 r.pendingStarts.add(0, si);
2328 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
2329 dur *= 2;
2330 if (minDuration < dur) minDuration = dur;
2331 if (resetTime < dur) resetTime = dur;
2332 } else {
2333 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002334 + r.shortInstanceName);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002335 canceled = true;
2336 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002337 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002338 r.deliveredStarts.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002339 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002340
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002341 r.totalRestartCount++;
2342 if (r.restartDelay == 0) {
2343 r.restartCount++;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002344 r.restartDelay = minDuration;
Amith Yamasanib0c8a882017-08-28 09:36:42 -07002345 } else if (r.crashCount > 1) {
2346 r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
2347 * (r.crashCount - 1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002348 } else {
Varun Shah4311f212019-01-23 05:59:31 +00002349 // If it has been a "reasonably long time" since the service
2350 // was started, then reset our restart duration back to
2351 // the beginning, so we don't infinitely increase the duration
2352 // on a service that just occasionally gets killed (which is
2353 // a normal case, due to process being killed to reclaim memory).
2354 if (now > (r.restartTime+resetTime)) {
2355 r.restartCount = 1;
2356 r.restartDelay = minDuration;
Varun Shah16522412018-12-28 15:46:01 -08002357 } else {
Varun Shah4311f212019-01-23 05:59:31 +00002358 r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
2359 if (r.restartDelay < minDuration) {
2360 r.restartDelay = minDuration;
Varun Shah16522412018-12-28 15:46:01 -08002361 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002362 }
2363 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002364
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002365 r.nextRestartTime = now + r.restartDelay;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002366
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002367 // Make sure that we don't end up restarting a bunch of services
2368 // all at the same time.
Varun Shah4311f212019-01-23 05:59:31 +00002369 boolean repeat;
2370 do {
2371 repeat = false;
2372 final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
2373 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2374 ServiceRecord r2 = mRestartingServices.get(i);
2375 if (r2 != r && r.nextRestartTime >= (r2.nextRestartTime-restartTimeBetween)
2376 && r.nextRestartTime < (r2.nextRestartTime+restartTimeBetween)) {
2377 r.nextRestartTime = r2.nextRestartTime + restartTimeBetween;
2378 r.restartDelay = r.nextRestartTime - now;
2379 repeat = true;
2380 break;
2381 }
2382 }
2383 } while (repeat);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002384
2385 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07002386 // Persistent processes are immediately restarted, so there is no
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002387 // reason to hold of on restarting their services.
2388 r.totalRestartCount++;
2389 r.restartCount = 0;
2390 r.restartDelay = 0;
2391 r.nextRestartTime = now;
2392 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002393
2394 if (!mRestartingServices.contains(r)) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002395 r.createdFromFg = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002396 mRestartingServices.add(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002397 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002398 }
2399
Christopher Tate08992ac2017-03-21 11:37:06 -07002400 cancelForegroundNotificationLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002401
2402 mAm.mHandler.removeCallbacks(r.restarter);
2403 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
2404 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
2405 Slog.w(TAG, "Scheduling restart of crashed service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002406 + r.shortInstanceName + " in " + r.restartDelay + "ms");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002407 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002408 r.userId, r.shortInstanceName, r.restartDelay);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002409
2410 return canceled;
2411 }
2412
2413 final void performServiceRestartLocked(ServiceRecord r) {
2414 if (!mRestartingServices.contains(r)) {
2415 return;
2416 }
Dianne Hackbornad51be92016-08-16 16:27:36 -07002417 if (!isServiceNeededLocked(r, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002418 // Paranoia: is this service actually needed? In theory a service that is not
2419 // needed should never remain on the restart list. In practice... well, there
2420 // have been bugs where this happens, and bad things happen because the process
2421 // ends up just being cached, so quickly killed, then restarted again and again.
2422 // Let's not let that happen.
2423 Slog.wtf(TAG, "Restarting service that is not needed: " + r);
2424 return;
2425 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002426 try {
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00002427 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false,
2428 false);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002429 } catch (TransactionTooLargeException e) {
2430 // Ignore, it's been logged and nothing upstack cares.
2431 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002432 }
2433
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002434 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
2435 boolean force) {
2436 if (!force && r.restartDelay == 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002437 return false;
2438 }
Dianne Hackborn7b492722013-11-01 09:58:45 -07002439 // Remove from the restarting list; if the service is currently on the
2440 // restarting list, or the call is coming from another app, then this
2441 // service has become of much more interest so we reset the restart interval.
2442 boolean removed = mRestartingServices.remove(r);
2443 if (removed || callingUid != r.appInfo.uid) {
2444 r.resetRestartCounter();
2445 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002446 if (removed) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002447 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002448 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002449 mAm.mHandler.removeCallbacks(r.restarter);
2450 return true;
2451 }
2452
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002453 private void clearRestartingIfNeededLocked(ServiceRecord r) {
2454 if (r.restartTracker != null) {
2455 // If this is the last restarting record with this tracker, then clear
2456 // the tracker's restarting state.
2457 boolean stillTracking = false;
2458 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2459 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
2460 stillTracking = true;
2461 break;
2462 }
2463 }
2464 if (!stillTracking) {
2465 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
2466 SystemClock.uptimeMillis());
2467 r.restartTracker = null;
2468 }
2469 }
2470 }
2471
Svet Ganov9c165d72015-12-01 19:52:26 -08002472 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00002473 boolean whileRestarting, boolean permissionsReviewRequired,
2474 boolean allowBackgroundActivityStarts) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002475 //Slog.i(TAG, "Bring up service:");
2476 //r.dump(" ");
2477
2478 if (r.app != null && r.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002479 sendServiceArgsLocked(r, execInFg, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002480 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002481 }
2482
Sudheer Shanka03d0f812017-04-20 16:57:50 -07002483 if (!whileRestarting && mRestartingServices.contains(r)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002484 // If waiting for a restart, then do nothing.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002485 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002486 }
2487
Christopher Tate08992ac2017-03-21 11:37:06 -07002488 if (DEBUG_SERVICE) {
2489 Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
2490 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002491
2492 // We are now bringing the service up, so no longer in the
2493 // restarting state.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002494 if (mRestartingServices.remove(r)) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002495 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002496 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002497
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002498 // Make sure this service is no longer considered delayed, we are starting it now.
2499 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002500 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002501 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002502 r.delayed = false;
2503 }
2504
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002505 // Make sure that the user who owns this service is started. If not,
2506 // we don't want to allow it to run.
Fyodor Kupolov610acda2015-10-19 18:44:07 -07002507 if (!mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002508 String msg = "Unable to launch app "
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002509 + r.appInfo.packageName + "/"
2510 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002511 + r.intent.getIntent() + ": user " + r.userId + " is stopped";
2512 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002513 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002514 return msg;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002515 }
2516
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002517 // Service is now being launched, its package can't be stopped.
2518 try {
2519 AppGlobals.getPackageManager().setPackageStoppedState(
2520 r.packageName, false, r.userId);
2521 } catch (RemoteException e) {
2522 } catch (IllegalArgumentException e) {
2523 Slog.w(TAG, "Failed trying to unstop package "
2524 + r.packageName + ": " + e);
2525 }
2526
2527 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
2528 final String procName = r.processName;
Robert Sesekc5f86642016-11-04 10:20:38 -04002529 String hostingType = "service";
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002530 ProcessRecord app;
2531
2532 if (!isolated) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07002533 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
2534 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
2535 + " app=" + app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002536 if (app != null && app.thread != null) {
2537 try {
Patrick Baumannc2def582018-04-04 12:14:15 -07002538 app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode, mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002539 realStartServiceLocked(r, app, execInFg);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002540 return null;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002541 } catch (TransactionTooLargeException e) {
2542 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002543 } catch (RemoteException e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002544 Slog.w(TAG, "Exception when starting service " + r.shortInstanceName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002545 }
2546
2547 // If a dead object exception was thrown -- fall through to
2548 // restart the application.
2549 }
2550 } else {
2551 // If this service runs in an isolated process, then each time
2552 // we call startProcessLocked() we will get a new isolated
2553 // process, starting another process if we are currently waiting
2554 // for a previous process to come up. To deal with this, we store
2555 // in the service any current isolated process it is running in or
2556 // waiting to have come up.
2557 app = r.isolatedProc;
Robert Sesekc5f86642016-11-04 10:20:38 -04002558 if (WebViewZygote.isMultiprocessEnabled()
2559 && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
2560 hostingType = "webview_service";
2561 }
Martijn Coenen7e6fa672018-11-05 11:45:26 +01002562 if ((r.serviceInfo.flags & ServiceInfo.FLAG_USE_APP_ZYGOTE) != 0) {
2563 hostingType = "app_zygote";
2564 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002565 }
2566
2567 // Not running -- get it started, and enqueue this service record
2568 // to be executed when the app comes up.
Svet Ganov9c165d72015-12-01 19:52:26 -08002569 if (app == null && !permissionsReviewRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002570 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002571 hostingType, r.instanceName, false, isolated, false)) == null) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002572 String msg = "Unable to launch app "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002573 + r.appInfo.packageName + "/"
2574 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002575 + r.intent.getIntent() + ": process is bad";
2576 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002577 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002578 return msg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002579 }
2580 if (isolated) {
2581 r.isolatedProc = app;
2582 }
2583 }
2584
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00002585 if (app != null && allowBackgroundActivityStarts) {
2586 app.addAllowBackgroundActivityStartsToken(r);
2587 // schedule removal of the whitelisting token after the timeout
2588 removeAllowBackgroundActivityStartsServiceToken(app, r,
2589 SERVICE_BG_ACTIVITY_START_TIMEOUT_MS);
2590 }
2591
Christopher Tate1536cc22017-09-18 16:43:30 -07002592 if (r.fgRequired) {
2593 if (DEBUG_FOREGROUND_SERVICE) {
2594 Slog.v(TAG, "Whitelisting " + UserHandle.formatUid(r.appInfo.uid)
2595 + " for fg-service launch");
2596 }
2597 mAm.tempWhitelistUidLocked(r.appInfo.uid,
2598 SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch");
2599 }
2600
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002601 if (!mPendingServices.contains(r)) {
2602 mPendingServices.add(r);
2603 }
2604
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002605 if (r.delayedStop) {
2606 // Oh and hey we've already been asked to stop!
2607 r.delayedStop = false;
2608 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002609 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2610 "Applying delayed stop (in bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002611 stopServiceLocked(r);
2612 }
2613 }
2614
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002615 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002616 }
2617
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002618 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
2619 throws TransactionTooLargeException {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002620 for (int i=r.bindings.size()-1; i>=0; i--) {
2621 IntentBindRecord ibr = r.bindings.valueAt(i);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002622 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002623 break;
2624 }
2625 }
2626 }
2627
2628 private final void realStartServiceLocked(ServiceRecord r,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002629 ProcessRecord app, boolean execInFg) throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002630 if (app.thread == null) {
2631 throw new RemoteException();
2632 }
2633 if (DEBUG_MU)
2634 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
2635 + ", ProcessRecord.uid = " + app.uid);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002636 r.setProcess(app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002637 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
2638
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002639 final boolean newService = app.services.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002640 bumpServiceExecutingLocked(r, execInFg, "create");
Dianne Hackborndb926082013-10-31 16:32:44 -07002641 mAm.updateLruProcessLocked(app, false, null);
Makoto Onuki0f421292017-04-28 15:03:33 -07002642 updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
2643 mAm.updateOomAdjLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002644
2645 boolean created = false;
2646 try {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002647 if (LOG_SERVICE_START_STOP) {
Dianne Hackbornab2df062015-01-07 13:43:13 -08002648 String nameTerm;
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002649 int lastPeriod = r.shortInstanceName.lastIndexOf('.');
2650 nameTerm = lastPeriod >= 0 ? r.shortInstanceName.substring(lastPeriod)
2651 : r.shortInstanceName;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002652 EventLogTags.writeAmCreateService(
2653 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
2654 }
Chenjie Yu75b3c492018-10-06 21:45:19 -07002655 StatsLog.write(StatsLog.SERVICE_LAUNCH_REPORTED, r.appInfo.uid, r.name.getPackageName(),
2656 r.name.getClassName());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002657 synchronized (r.stats.getBatteryStats()) {
2658 r.stats.startLaunchedLocked();
2659 }
Brian Carlstromca82e612016-04-19 23:16:08 -07002660 mAm.notifyPackageUse(r.serviceInfo.packageName,
2661 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
Dianne Hackborna413dc02013-07-12 12:02:55 -07002662 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002663 app.thread.scheduleCreateService(r, r.serviceInfo,
Wale Ogunwale53783742018-09-16 10:21:51 -07002664 mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002665 app.getReportedProcState());
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002666 r.postNotification();
2667 created = true;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -07002668 } catch (DeadObjectException e) {
2669 Slog.w(TAG, "Application dead when creating service " + r);
2670 mAm.appDiedLocked(app);
Wale Ogunwalebfac4682015-04-08 14:33:21 -07002671 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002672 } finally {
2673 if (!created) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002674 // Keep the executeNesting count accurate.
2675 final boolean inDestroying = mDestroyingServices.contains(r);
2676 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2677
2678 // Cleanup.
2679 if (newService) {
2680 app.services.remove(r);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002681 r.setProcess(null);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002682 }
2683
2684 // Retry.
2685 if (!inDestroying) {
2686 scheduleServiceRestartLocked(r, false);
2687 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002688 }
2689 }
2690
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002691 if (r.whitelistManager) {
2692 app.whitelistManager = true;
2693 }
2694
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002695 requestServiceBindingsLocked(r, execInFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002696
Dianne Hackborn465fa392014-09-14 14:21:18 -07002697 updateServiceClientActivitiesLocked(app, null, true);
2698
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002699 // If the service is in the started state, and there are no
2700 // pending arguments, then fake up one so its onStartCommand() will
2701 // be called.
2702 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
2703 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002704 null, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002705 }
2706
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002707 sendServiceArgsLocked(r, execInFg, true);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002708
2709 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002710 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002711 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002712 r.delayed = false;
2713 }
2714
2715 if (r.delayedStop) {
2716 // Oh and hey we've already been asked to stop!
2717 r.delayedStop = false;
2718 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002719 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2720 "Applying delayed stop (from start): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002721 stopServiceLocked(r);
2722 }
2723 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002724 }
2725
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002726 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002727 boolean oomAdjusted) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002728 final int N = r.pendingStarts.size();
2729 if (N == 0) {
2730 return;
2731 }
2732
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002733 ArrayList<ServiceStartArgs> args = new ArrayList<>();
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002734
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002735 while (r.pendingStarts.size() > 0) {
2736 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
2737 if (DEBUG_SERVICE) {
2738 Slog.v(TAG_SERVICE, "Sending arguments to: "
2739 + r + " " + r.intent + " args=" + si.intent);
2740 }
2741 if (si.intent == null && N > 1) {
2742 // If somehow we got a dummy null intent in the middle,
2743 // then skip it. DO NOT skip a null intent when it is
2744 // the only one in the list -- this is to support the
2745 // onStartCommand(null) case.
2746 continue;
2747 }
2748 si.deliveredTime = SystemClock.uptimeMillis();
2749 r.deliveredStarts.add(si);
2750 si.deliveryCount++;
2751 if (si.neededGrants != null) {
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07002752 mAm.mUgmInternal.grantUriPermissionUncheckedFromIntent(si.neededGrants,
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002753 si.getUriPermissionsLocked());
2754 }
Hai Zhangbb23d532018-08-27 16:00:35 -07002755 mAm.grantEphemeralAccessLocked(r.userId, si.intent, UserHandle.getAppId(r.appInfo.uid),
2756 UserHandle.getAppId(si.callingId));
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002757 bumpServiceExecutingLocked(r, execInFg, "start");
2758 if (!oomAdjusted) {
2759 oomAdjusted = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002760 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002761 }
2762 if (r.fgRequired && !r.fgWaiting) {
2763 if (!r.isForeground) {
2764 if (DEBUG_BACKGROUND_CHECK) {
2765 Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r);
2766 }
2767 scheduleServiceForegroundTransitionTimeoutLocked(r);
2768 } else {
2769 if (DEBUG_BACKGROUND_CHECK) {
2770 Slog.i(TAG, "Service already foreground; no new timeout: " + r);
2771 }
2772 r.fgRequired = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002773 }
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002774 }
2775 int flags = 0;
2776 if (si.deliveryCount > 1) {
2777 flags |= Service.START_FLAG_RETRY;
2778 }
2779 if (si.doneExecutingCount > 0) {
2780 flags |= Service.START_FLAG_REDELIVERY;
2781 }
2782 args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
2783 }
2784
2785 ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
2786 slice.setInlineCountLimit(4);
2787 Exception caughtException = null;
2788 try {
2789 r.app.thread.scheduleServiceArgs(r, slice);
2790 } catch (TransactionTooLargeException e) {
2791 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
2792 + " args, first: " + args.get(0).args);
2793 Slog.w(TAG, "Failed delivering service starts", e);
2794 caughtException = e;
2795 } catch (RemoteException e) {
2796 // Remote process gone... we'll let the normal cleanup take care of this.
2797 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
2798 Slog.w(TAG, "Failed delivering service starts", e);
2799 caughtException = e;
2800 } catch (Exception e) {
2801 Slog.w(TAG, "Unexpected exception", e);
2802 caughtException = e;
2803 }
2804
2805 if (caughtException != null) {
2806 // Keep nesting count correct
2807 final boolean inDestroying = mDestroyingServices.contains(r);
2808 for (int i = 0; i < args.size(); i++) {
2809 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2810 }
2811 if (caughtException instanceof TransactionTooLargeException) {
2812 throw (TransactionTooLargeException)caughtException;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002813 }
2814 }
2815 }
2816
Dianne Hackbornad51be92016-08-16 16:27:36 -07002817 private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn,
2818 boolean hasConn) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002819 // Are we still explicitly being asked to run?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002820 if (r.startRequested) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002821 return true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002822 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002823
Dianne Hackborncb015632017-06-14 17:30:15 -07002824 // Is someone still bound to us keeping us running?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002825 if (!knowConn) {
2826 hasConn = r.hasAutoCreateConnections();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002827 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002828 if (hasConn) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002829 return true;
2830 }
2831
2832 return false;
2833 }
2834
2835 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
2836 boolean hasConn) {
2837 //Slog.i(TAG, "Bring down service:");
2838 //r.dump(" ");
2839
Dianne Hackbornad51be92016-08-16 16:27:36 -07002840 if (isServiceNeededLocked(r, knowConn, hasConn)) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002841 return;
2842 }
2843
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002844 // Are we in the process of launching?
2845 if (mPendingServices.contains(r)) {
2846 return;
2847 }
2848
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002849 bringDownServiceLocked(r);
2850 }
2851
2852 private final void bringDownServiceLocked(ServiceRecord r) {
2853 //Slog.i(TAG, "Bring down service:");
2854 //r.dump(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002855
Dianne Hackborn390517b2013-05-30 15:03:32 -07002856 // Report to all of the connections that the service is no longer
2857 // available.
2858 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2859 ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
2860 for (int i=0; i<c.size(); i++) {
2861 ConnectionRecord cr = c.get(i);
2862 // There is still a connection to the service that is
2863 // being brought down. Mark it as dead.
2864 cr.serviceDead = true;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002865 cr.stopAssociation();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002866 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07002867 cr.conn.connected(r.name, null, true);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002868 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002869 Slog.w(TAG, "Failure disconnecting service " + r.shortInstanceName
2870 + " to connection " + c.get(i).conn.asBinder()
2871 + " (in " + c.get(i).binding.client.processName + ")", e);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002872 }
2873 }
2874 }
2875
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002876 // Tell the service that it has been unbound.
Dianne Hackborn390517b2013-05-30 15:03:32 -07002877 if (r.app != null && r.app.thread != null) {
2878 for (int i=r.bindings.size()-1; i>=0; i--) {
2879 IntentBindRecord ibr = r.bindings.valueAt(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002880 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002881 + ": hasBound=" + ibr.hasBound);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002882 if (ibr.hasBound) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002883 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002884 bumpServiceExecutingLocked(r, false, "bring down unbind");
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002885 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002886 ibr.hasBound = false;
Dianne Hackborn85e35642017-01-12 15:10:57 -08002887 ibr.requested = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002888 r.app.thread.scheduleUnbindService(r,
2889 ibr.intent.getIntent());
2890 } catch (Exception e) {
2891 Slog.w(TAG, "Exception when unbinding service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002892 + r.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002893 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002894 }
2895 }
2896 }
2897 }
2898
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002899 // Check to see if the service had been started as foreground, but being
2900 // brought down before actually showing a notification. That is not allowed.
2901 if (r.fgRequired) {
2902 Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
2903 + r);
2904 r.fgRequired = false;
2905 r.fgWaiting = false;
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002906 ServiceState stracker = r.getTracker();
2907 if (stracker != null) {
2908 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
2909 r.lastActivity);
2910 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07002911 mAm.mAppOpsService.finishOperation(AppOpsManager.getToken(mAm.mAppOpsService),
2912 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002913 mAm.mHandler.removeMessages(
2914 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
2915 if (r.app != null) {
2916 Message msg = mAm.mHandler.obtainMessage(
2917 ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
2918 msg.obj = r.app;
Kodlee Yin7e951262018-04-05 12:59:56 -07002919 msg.getData().putCharSequence(
2920 ActivityManagerService.SERVICE_RECORD_KEY, r.toString());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002921 mAm.mHandler.sendMessage(msg);
2922 }
2923 }
2924
2925 if (DEBUG_SERVICE) {
2926 RuntimeException here = new RuntimeException();
2927 here.fillInStackTrace();
2928 Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here);
2929 }
Craig Mautner66c4a822015-01-16 12:48:16 -08002930 r.destroyTime = SystemClock.uptimeMillis();
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002931 if (LOG_SERVICE_START_STOP) {
2932 EventLogTags.writeAmDestroyService(
2933 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
2934 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002935
Dianne Hackbornad51be92016-08-16 16:27:36 -07002936 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002937 ServiceRecord found = smap.mServicesByInstanceName.remove(r.instanceName);
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002938
2939 // Note when this method is called by bringUpServiceLocked(), the service is not found
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002940 // in mServicesByInstanceName and found will be null.
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002941 if (found != null && found != r) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002942 // This is not actually the service we think is running... this should not happen,
2943 // but if it does, fail hard.
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002944 smap.mServicesByInstanceName.put(r.instanceName, found);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002945 throw new IllegalStateException("Bringing down " + r + " but actually running "
2946 + found);
2947 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002948 smap.mServicesByIntent.remove(r.intent);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002949 r.totalRestartCount = 0;
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002950 unscheduleServiceRestartLocked(r, 0, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002951
2952 // Also make sure it is not on the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002953 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002954 if (mPendingServices.get(i) == r) {
2955 mPendingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002956 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002957 }
2958 }
2959
Christopher Tate08992ac2017-03-21 11:37:06 -07002960 cancelForegroundNotificationLocked(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002961 if (r.isForeground) {
2962 decActiveForegroundAppLocked(smap, r);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07002963 ServiceState stracker = r.getTracker();
2964 if (stracker != null) {
2965 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
2966 r.lastActivity);
2967 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07002968 mAm.mAppOpsService.finishOperation(
2969 AppOpsManager.getToken(mAm.mAppOpsService),
2970 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08002971 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED, r.appInfo.uid,
2972 r.shortInstanceName, StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Hui Yue361a232018-10-04 15:05:21 -07002973 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002974 }
Chenjie Yuccfe6452018-01-30 11:33:21 -08002975
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002976 r.isForeground = false;
2977 r.foregroundId = 0;
2978 r.foregroundNoti = null;
2979
2980 // Clear start entries.
2981 r.clearDeliveredStartsLocked();
2982 r.pendingStarts.clear();
Christopher Tate752bc2a2019-02-15 16:48:22 -08002983 smap.mDelayedStartList.remove(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002984
2985 if (r.app != null) {
2986 synchronized (r.stats.getBatteryStats()) {
2987 r.stats.stopLaunchedLocked();
2988 }
2989 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002990 if (r.whitelistManager) {
2991 updateWhitelistManagerLocked(r.app);
2992 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002993 if (r.app.thread != null) {
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002994 updateServiceForegroundLocked(r.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002995 try {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002996 bumpServiceExecutingLocked(r, false, "destroy");
2997 mDestroyingServices.add(r);
Dianne Hackborn455625e2015-01-21 09:55:13 -08002998 r.destroying = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002999 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003000 r.app.thread.scheduleStopService(r);
3001 } catch (Exception e) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003002 Slog.w(TAG, "Exception when destroying service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003003 + r.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07003004 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003005 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003006 } else {
3007 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003008 TAG_SERVICE, "Removed service that has no process: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003009 }
3010 } else {
3011 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003012 TAG_SERVICE, "Removed service that is not running: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003013 }
3014
3015 if (r.bindings.size() > 0) {
3016 r.bindings.clear();
3017 }
3018
3019 if (r.restarter instanceof ServiceRestarter) {
3020 ((ServiceRestarter)r.restarter).setService(null);
3021 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003022
Dianne Hackbornd2932242013-08-05 18:18:42 -07003023 int memFactor = mAm.mProcessStats.getMemFactorLocked();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003024 long now = SystemClock.uptimeMillis();
3025 if (r.tracker != null) {
3026 r.tracker.setStarted(false, memFactor, now);
3027 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003028 if (r.executeNesting == 0) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07003029 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003030 r.tracker = null;
3031 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003032 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003033
Dianne Hackbornad51be92016-08-16 16:27:36 -07003034 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003035 }
3036
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07003037 void removeConnectionLocked(ConnectionRecord c, ProcessRecord skipApp,
3038 ActivityServiceConnectionsHolder skipAct) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003039 IBinder binder = c.conn.asBinder();
3040 AppBindRecord b = c.binding;
3041 ServiceRecord s = b.service;
3042 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
3043 if (clist != null) {
3044 clist.remove(c);
3045 if (clist.size() == 0) {
3046 s.connections.remove(binder);
3047 }
3048 }
3049 b.connections.remove(c);
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003050 c.stopAssociation();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003051 if (c.activity != null && c.activity != skipAct) {
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07003052 c.activity.removeConnection(c);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003053 }
3054 if (b.client != skipApp) {
3055 b.client.connections.remove(c);
3056 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
3057 b.client.updateHasAboveClientLocked();
3058 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003059 // If this connection requested whitelist management, see if we should
3060 // now clear that state.
3061 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
3062 s.updateWhitelistManager();
3063 if (!s.whitelistManager && s.app != null) {
3064 updateWhitelistManagerLocked(s.app);
3065 }
3066 }
Dianne Hackborndb926082013-10-31 16:32:44 -07003067 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07003068 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07003069 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003070 }
3071 clist = mServiceConnections.get(binder);
3072 if (clist != null) {
3073 clist.remove(c);
3074 if (clist.size() == 0) {
3075 mServiceConnections.remove(binder);
3076 }
3077 }
3078
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003079 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003080 s.appInfo.longVersionCode, s.instanceName, s.processName);
Dianne Hackbornab2df062015-01-07 13:43:13 -08003081
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003082 if (b.connections.size() == 0) {
3083 b.intent.apps.remove(b.client);
3084 }
3085
3086 if (!c.serviceDead) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003087 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003088 + ": shouldUnbind=" + b.intent.hasBound);
3089 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
3090 && b.intent.hasBound) {
3091 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003092 bumpServiceExecutingLocked(s, false, "unbind");
Dianne Hackborndb926082013-10-31 16:32:44 -07003093 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
Dianne Hackbornf097d422017-12-15 16:32:19 -08003094 && s.app.setProcState <= ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
Dianne Hackborndb926082013-10-31 16:32:44 -07003095 // If this service's process is not already in the cached list,
3096 // then update it in the LRU list here because this may be causing
3097 // it to go down there and we want it to start out near the top.
3098 mAm.updateLruProcessLocked(s.app, false, null);
3099 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07003100 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003101 b.intent.hasBound = false;
3102 // Assume the client doesn't want to know about a rebind;
3103 // we will deal with that later if it asks for one.
3104 b.intent.doRebind = false;
3105 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
3106 } catch (Exception e) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003107 Slog.w(TAG, "Exception when unbinding service " + s.shortInstanceName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07003108 serviceProcessGoneLocked(s);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003109 }
3110 }
3111
Svet Ganov9c165d72015-12-01 19:52:26 -08003112 // If unbound while waiting to start, remove the pending service
3113 mPendingServices.remove(s);
3114
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003115 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003116 boolean hasAutoCreate = s.hasAutoCreateConnections();
3117 if (!hasAutoCreate) {
3118 if (s.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003119 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003120 SystemClock.uptimeMillis());
3121 }
3122 }
3123 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003124 }
3125 }
3126 }
3127
3128 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003129 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003130 if (r != null) {
Dianne Hackborn455625e2015-01-21 09:55:13 -08003131 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003132 // This is a call from a service start... take care of
3133 // book-keeping.
3134 r.callStart = true;
3135 switch (res) {
3136 case Service.START_STICKY_COMPATIBILITY:
3137 case Service.START_STICKY: {
3138 // We are done with the associated start arguments.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003139 r.findDeliveredStart(startId, false, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003140 // Don't stop if killed.
3141 r.stopIfKilled = false;
3142 break;
3143 }
3144 case Service.START_NOT_STICKY: {
3145 // We are done with the associated start arguments.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003146 r.findDeliveredStart(startId, false, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003147 if (r.getLastStartId() == startId) {
3148 // There is no more work, and this service
3149 // doesn't want to hang around if killed.
3150 r.stopIfKilled = true;
3151 }
3152 break;
3153 }
3154 case Service.START_REDELIVER_INTENT: {
3155 // We'll keep this item until they explicitly
3156 // call stop for it, but keep track of the fact
3157 // that it was delivered.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003158 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003159 if (si != null) {
3160 si.deliveryCount = 0;
3161 si.doneExecutingCount++;
3162 // Don't stop if killed.
3163 r.stopIfKilled = true;
3164 }
3165 break;
3166 }
3167 case Service.START_TASK_REMOVED_COMPLETE: {
3168 // Special processing for onTaskRemoved(). Don't
3169 // impact normal onStartCommand() processing.
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003170 r.findDeliveredStart(startId, true, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003171 break;
3172 }
3173 default:
3174 throw new IllegalArgumentException(
3175 "Unknown service start result: " + res);
3176 }
3177 if (res == Service.START_STICKY_COMPATIBILITY) {
3178 r.callStart = false;
3179 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08003180 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
3181 // This is the final call from destroying the service... we should
3182 // actually be getting rid of the service at this point. Do some
3183 // validation of its state, and ensure it will be fully removed.
3184 if (!inDestroying) {
3185 // Not sure what else to do with this... if it is not actually in the
3186 // destroying list, we don't need to make sure to remove it from it.
Amith Yamasanid0418222016-05-10 15:49:51 -07003187 // If the app is null, then it was probably removed because the process died,
3188 // otherwise wtf
3189 if (r.app != null) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07003190 Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
Amith Yamasanid0418222016-05-10 15:49:51 -07003191 + r + ", app=" + r.app);
3192 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08003193 } else if (r.executeNesting != 1) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07003194 Slog.w(TAG, "Service done with onDestroy, but executeNesting="
Dianne Hackborn455625e2015-01-21 09:55:13 -08003195 + r.executeNesting + ": " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003196 // Fake it to keep from ANR due to orphaned entry.
Dianne Hackborn455625e2015-01-21 09:55:13 -08003197 r.executeNesting = 1;
3198 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003199 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003200 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn164371f2013-10-01 19:10:13 -07003201 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003202 Binder.restoreCallingIdentity(origId);
3203 } else {
3204 Slog.w(TAG, "Done executing unknown service from pid "
3205 + Binder.getCallingPid());
3206 }
3207 }
3208
Dianne Hackborn878deb32013-10-14 16:55:09 -07003209 private void serviceProcessGoneLocked(ServiceRecord r) {
3210 if (r.tracker != null) {
3211 int memFactor = mAm.mProcessStats.getMemFactorLocked();
3212 long now = SystemClock.uptimeMillis();
3213 r.tracker.setExecuting(false, memFactor, now);
3214 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbc72dce2013-11-11 10:43:38 -08003215 r.tracker.setStarted(false, memFactor, now);
Dianne Hackborn878deb32013-10-14 16:55:09 -07003216 }
3217 serviceDoneExecutingLocked(r, true, true);
3218 }
3219
Dianne Hackborn164371f2013-10-01 19:10:13 -07003220 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
3221 boolean finishing) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003222 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003223 + ": nesting=" + r.executeNesting
Dianne Hackborn164371f2013-10-01 19:10:13 -07003224 + ", inDestroying=" + inDestroying + ", app=" + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003225 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003226 "<<< DONE EXECUTING " + r.shortInstanceName);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003227 r.executeNesting--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003228 if (r.executeNesting <= 0) {
3229 if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003230 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003231 "Nesting at 0 of " + r.shortInstanceName);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003232 r.app.execServicesFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003233 r.app.executingServices.remove(r);
3234 if (r.app.executingServices.size() == 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003235 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003236 "No more executingServices of " + r.shortInstanceName);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003237 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003238 } else if (r.executeFg) {
3239 // Need to re-evaluate whether the app still needs to be in the foreground.
3240 for (int i=r.app.executingServices.size()-1; i>=0; i--) {
3241 if (r.app.executingServices.valueAt(i).executeFg) {
3242 r.app.execServicesFg = true;
3243 break;
3244 }
3245 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003246 }
Dianne Hackborn164371f2013-10-01 19:10:13 -07003247 if (inDestroying) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003248 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn164371f2013-10-01 19:10:13 -07003249 "doneExecuting remove destroying " + r);
3250 mDestroyingServices.remove(r);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003251 r.bindings.clear();
3252 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07003253 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003254 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003255 r.executeFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003256 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003257 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003258 SystemClock.uptimeMillis());
Dianne Hackborn164371f2013-10-01 19:10:13 -07003259 if (finishing) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07003260 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07003261 r.tracker = null;
3262 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003263 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003264 if (finishing) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003265 if (r.app != null && !r.app.isPersistent()) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003266 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003267 if (r.whitelistManager) {
3268 updateWhitelistManagerLocked(r.app);
3269 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003270 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003271 r.setProcess(null);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003272 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003273 }
3274 }
3275
Dianne Hackbornff072722014-09-24 10:56:28 -07003276 boolean attachApplicationLocked(ProcessRecord proc, String processName)
3277 throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003278 boolean didSomething = false;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003279 // Collect any services that are waiting for this process to come up.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003280 if (mPendingServices.size() > 0) {
3281 ServiceRecord sr = null;
3282 try {
3283 for (int i=0; i<mPendingServices.size(); i++) {
3284 sr = mPendingServices.get(i);
3285 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3286 || !processName.equals(sr.processName))) {
3287 continue;
3288 }
3289
3290 mPendingServices.remove(i);
3291 i--;
Patrick Baumannc2def582018-04-04 12:14:15 -07003292 proc.addPackage(sr.appInfo.packageName, sr.appInfo.longVersionCode,
Dianne Hackbornf7097a52014-05-13 09:56:14 -07003293 mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003294 realStartServiceLocked(sr, proc, sr.createdFromFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003295 didSomething = true;
Dianne Hackbornad51be92016-08-16 16:27:36 -07003296 if (!isServiceNeededLocked(sr, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003297 // We were waiting for this service to start, but it is actually no
3298 // longer needed. This could happen because bringDownServiceIfNeeded
3299 // won't bring down a service that is pending... so now the pending
3300 // is done, so let's drop it.
3301 bringDownServiceLocked(sr);
3302 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003303 }
Dianne Hackbornff072722014-09-24 10:56:28 -07003304 } catch (RemoteException e) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003305 Slog.w(TAG, "Exception in new application when starting service "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003306 + sr.shortInstanceName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003307 throw e;
3308 }
3309 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003310 // Also, if there are any services that are waiting to restart and
3311 // would run in this process, now is a good time to start them. It would
3312 // be weird to bring up the process but arbitrarily not let the services
3313 // run at this point just because their restart time hasn't come up.
3314 if (mRestartingServices.size() > 0) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003315 ServiceRecord sr;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003316 for (int i=0; i<mRestartingServices.size(); i++) {
3317 sr = mRestartingServices.get(i);
3318 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3319 || !processName.equals(sr.processName))) {
3320 continue;
3321 }
3322 mAm.mHandler.removeCallbacks(sr.restarter);
3323 mAm.mHandler.post(sr.restarter);
3324 }
3325 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003326 return didSomething;
3327 }
3328
3329 void processStartTimedOutLocked(ProcessRecord proc) {
3330 for (int i=0; i<mPendingServices.size(); i++) {
3331 ServiceRecord sr = mPendingServices.get(i);
3332 if ((proc.uid == sr.appInfo.uid
3333 && proc.processName.equals(sr.processName))
3334 || sr.isolatedProc == proc) {
3335 Slog.w(TAG, "Forcing bringing down service: " + sr);
3336 sr.isolatedProc = null;
3337 mPendingServices.remove(i);
3338 i--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003339 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003340 }
3341 }
3342 }
3343
Wale Ogunwale540e1232015-05-01 15:35:39 -07003344 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003345 boolean evenPersistent, boolean doit, ArrayMap<ComponentName, ServiceRecord> services) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003346 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003347 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003348 ServiceRecord service = services.valueAt(i);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003349 final boolean sameComponent = packageName == null
3350 || (service.packageName.equals(packageName)
3351 && (filterByClasses == null
3352 || filterByClasses.contains(service.name.getClassName())));
3353 if (sameComponent
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003354 && (service.app == null || evenPersistent || !service.app.isPersistent())) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003355 if (!doit) {
3356 return true;
3357 }
3358 didSomething = true;
3359 Slog.i(TAG, " Force stopping service " + service);
Riddle Hsuaaef7312019-01-24 19:00:58 +08003360 if (service.app != null && !service.app.isPersistent()) {
3361 service.app.services.remove(service);
3362 if (service.whitelistManager) {
3363 updateWhitelistManagerLocked(service.app);
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08003364 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003365 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003366 service.setProcess(null);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003367 service.isolatedProc = null;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003368 if (mTmpCollectionResults == null) {
3369 mTmpCollectionResults = new ArrayList<>();
3370 }
3371 mTmpCollectionResults.add(service);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003372 }
3373 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003374 return didSomething;
3375 }
3376
Wale Ogunwale540e1232015-05-01 15:35:39 -07003377 boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003378 int userId, boolean evenPersistent, boolean doit) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003379 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003380
3381 if (mTmpCollectionResults != null) {
3382 mTmpCollectionResults.clear();
3383 }
3384
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003385 if (userId == UserHandle.USER_ALL) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003386 for (int i = mServiceMap.size() - 1; i >= 0; i--) {
3387 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003388 evenPersistent, doit, mServiceMap.valueAt(i).mServicesByInstanceName);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003389 if (!doit && didSomething) {
3390 return true;
3391 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003392 if (doit && filterByClasses == null) {
3393 forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId);
3394 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003395 }
3396 } else {
Amith Yamasani540b6592013-10-01 13:02:52 -07003397 ServiceMap smap = mServiceMap.get(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003398 if (smap != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003399 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByInstanceName;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003400 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
Riddle Hsuaaef7312019-01-24 19:00:58 +08003401 evenPersistent, doit, items);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003402 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003403 if (doit && filterByClasses == null) {
3404 forceStopPackageLocked(packageName, userId);
3405 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003406 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003407
Wale Ogunwale540e1232015-05-01 15:35:39 -07003408 if (mTmpCollectionResults != null) {
3409 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
3410 bringDownServiceLocked(mTmpCollectionResults.get(i));
3411 }
3412 mTmpCollectionResults.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003413 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003414
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003415 return didSomething;
3416 }
3417
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003418 void forceStopPackageLocked(String packageName, int userId) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003419 ServiceMap smap = mServiceMap.get(userId);
3420 if (smap != null && smap.mActiveForegroundApps.size() > 0) {
Dianne Hackbornaf597682017-05-01 10:54:07 -07003421 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003422 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
3423 if (aa.mPackageName.equals(packageName)) {
3424 smap.mActiveForegroundApps.removeAt(i);
3425 smap.mActiveForegroundAppsChanged = true;
3426 }
3427 }
3428 if (smap.mActiveForegroundAppsChanged) {
3429 requestUpdateActiveForegroundAppsLocked(smap, 0);
3430 }
3431 }
3432 }
3433
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003434 void cleanUpServices(int userId, ComponentName component, Intent baseIntent) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003435 ArrayList<ServiceRecord> services = new ArrayList<>();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003436 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003437 for (int i = alls.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003438 ServiceRecord sr = alls.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003439 if (sr.packageName.equals(component.getPackageName())) {
3440 services.add(sr);
3441 }
3442 }
3443
3444 // Take care of any running services associated with the app.
Wale Ogunwale540e1232015-05-01 15:35:39 -07003445 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003446 ServiceRecord sr = services.get(i);
3447 if (sr.startRequested) {
3448 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003449 Slog.i(TAG, "Stopping service " + sr.shortInstanceName + ": remove task");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003450 stopServiceLocked(sr);
3451 } else {
3452 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn42ecdf32018-04-16 17:47:56 -07003453 sr.getLastStartId(), baseIntent, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003454 if (sr.app != null && sr.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003455 // We always run in the foreground, since this is called as
3456 // part of the "remove task" UI operation.
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003457 try {
3458 sendServiceArgsLocked(sr, true, false);
3459 } catch (TransactionTooLargeException e) {
3460 // Ignore, keep going.
3461 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003462 }
3463 }
3464 }
3465 }
3466 }
3467
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003468 final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003469 // Report disconnected services.
3470 if (false) {
3471 // XXX we are letting the client link to the service for
3472 // death notifications.
3473 if (app.services.size() > 0) {
3474 Iterator<ServiceRecord> it = app.services.iterator();
3475 while (it.hasNext()) {
3476 ServiceRecord r = it.next();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003477 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3478 ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
3479 for (int i=0; i<cl.size(); i++) {
3480 ConnectionRecord c = cl.get(i);
3481 if (c.binding.client != app) {
3482 try {
3483 //c.conn.connected(r.className, null);
3484 } catch (Exception e) {
3485 // todo: this should be asynchronous!
3486 Slog.w(TAG, "Exception thrown disconnected servce "
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003487 + r.shortInstanceName
Dianne Hackborn390517b2013-05-30 15:03:32 -07003488 + " from app " + app.processName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003489 }
3490 }
3491 }
3492 }
3493 }
3494 }
3495 }
3496
louis_chang40e259c2015-03-26 13:31:14 +08003497 // Clean up any connections this application has to other services.
3498 for (int i = app.connections.size() - 1; i >= 0; i--) {
3499 ConnectionRecord r = app.connections.valueAt(i);
3500 removeConnectionLocked(r, app, null);
3501 }
3502 updateServiceConnectionActivitiesLocked(app);
3503 app.connections.clear();
3504
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003505 app.whitelistManager = false;
3506
louis_chang40e259c2015-03-26 13:31:14 +08003507 // Clear app state from services.
3508 for (int i = app.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003509 ServiceRecord sr = app.services.valueAt(i);
3510 synchronized (sr.stats.getBatteryStats()) {
3511 sr.stats.stopLaunchedLocked();
3512 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003513 if (sr.app != app && sr.app != null && !sr.app.isPersistent()) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003514 sr.app.services.remove(sr);
3515 }
Dianne Hackborn2aec55a2018-06-26 10:35:35 -07003516 sr.setProcess(null);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003517 sr.isolatedProc = null;
3518 sr.executeNesting = 0;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003519 sr.forceClearTracker();
3520 if (mDestroyingServices.remove(sr)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003521 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003522 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003523
Dianne Hackbornc8230512013-07-13 21:32:12 -07003524 final int numClients = sr.bindings.size();
3525 for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
3526 IntentBindRecord b = sr.bindings.valueAt(bindingi);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003527 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
Dianne Hackbornc8230512013-07-13 21:32:12 -07003528 + ": shouldUnbind=" + b.hasBound);
3529 b.binder = null;
3530 b.requested = b.received = b.hasBound = false;
Dianne Hackborn465fa392014-09-14 14:21:18 -07003531 // If this binding is coming from a cached process and is asking to keep
3532 // the service created, then we'll kill the cached process as well -- we
3533 // don't want to be thrashing around restarting processes that are only
3534 // there to be cached.
3535 for (int appi=b.apps.size()-1; appi>=0; appi--) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003536 final ProcessRecord proc = b.apps.keyAt(appi);
3537 // If the process is already gone, skip it.
3538 if (proc.killedByAm || proc.thread == null) {
3539 continue;
3540 }
3541 // Only do this for processes that have an auto-create binding;
3542 // otherwise the binding can be left, because it won't cause the
3543 // service to restart.
3544 final AppBindRecord abind = b.apps.valueAt(appi);
3545 boolean hasCreate = false;
3546 for (int conni=abind.connections.size()-1; conni>=0; conni--) {
3547 ConnectionRecord conn = abind.connections.valueAt(conni);
Dianne Hackborn0fe3c252014-09-19 15:09:39 -07003548 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
3549 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003550 hasCreate = true;
3551 break;
3552 }
3553 }
3554 if (!hasCreate) {
3555 continue;
3556 }
Dianne Hackborncd97c962014-09-25 18:34:02 -07003557 // XXX turned off for now until we have more time to get a better policy.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003558 if (false && proc != null && !proc.isPersistent() && proc.thread != null
Dianne Hackborn465fa392014-09-14 14:21:18 -07003559 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
3560 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003561 proc.kill("bound to service " + sr.shortInstanceName
Dianne Hackborn465fa392014-09-14 14:21:18 -07003562 + " in dying proc " + (app != null ? app.processName : "??"), true);
3563 }
3564 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003565 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003566 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003567
Dianne Hackbornad51be92016-08-16 16:27:36 -07003568 ServiceMap smap = getServiceMapLocked(app.userId);
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003569
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003570 // Now do remaining service cleanup.
3571 for (int i=app.services.size()-1; i>=0; i--) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003572 ServiceRecord sr = app.services.valueAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003573
3574 // Unless the process is persistent, this process record is going away,
3575 // so make sure the service is cleaned out of it.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003576 if (!app.isPersistent()) {
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003577 app.services.removeAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003578 }
3579
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003580 // Sanity check: if the service listed for the app is not one
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003581 // we actually are maintaining, just let it drop.
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003582 final ServiceRecord curRec = smap.mServicesByInstanceName.get(sr.instanceName);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003583 if (curRec != sr) {
3584 if (curRec != null) {
3585 Slog.wtf(TAG, "Service " + sr + " in process " + app
3586 + " not same as in map: " + curRec);
3587 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003588 continue;
3589 }
3590
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003591 // Any services running in the application may need to be placed
3592 // back in the pending list.
Amith Yamasanib0c8a882017-08-28 09:36:42 -07003593 if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
3594 && (sr.serviceInfo.applicationInfo.flags
3595 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003596 Slog.w(TAG, "Service crashed " + sr.crashCount
3597 + " times, stopping: " + sr);
3598 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003599 sr.userId, sr.crashCount, sr.shortInstanceName, app.pid);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003600 bringDownServiceLocked(sr);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003601 } else if (!allowRestart
Fyodor Kupolov1b3edac2017-09-19 15:48:06 -07003602 || !mAm.mUserController.isUserRunning(sr.userId, 0)) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003603 bringDownServiceLocked(sr);
3604 } else {
3605 boolean canceled = scheduleServiceRestartLocked(sr, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003606
Dianne Hackbornc8230512013-07-13 21:32:12 -07003607 // Should the service remain running? Note that in the
3608 // extreme case of so many attempts to deliver a command
3609 // that it failed we also will stop it here.
3610 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
3611 if (sr.pendingStarts.size() == 0) {
3612 sr.startRequested = false;
3613 if (sr.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003614 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackbornc8230512013-07-13 21:32:12 -07003615 SystemClock.uptimeMillis());
3616 }
3617 if (!sr.hasAutoCreateConnections()) {
3618 // Whoops, no reason to restart!
3619 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003620 }
3621 }
3622 }
3623 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003624 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003625
Dianne Hackbornc8230512013-07-13 21:32:12 -07003626 if (!allowRestart) {
3627 app.services.clear();
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003628
3629 // Make sure there are no more restarting services for this process.
3630 for (int i=mRestartingServices.size()-1; i>=0; i--) {
3631 ServiceRecord r = mRestartingServices.get(i);
3632 if (r.processName.equals(app.processName) &&
3633 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3634 mRestartingServices.remove(i);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08003635 clearRestartingIfNeededLocked(r);
3636 }
3637 }
3638 for (int i=mPendingServices.size()-1; i>=0; i--) {
3639 ServiceRecord r = mPendingServices.get(i);
3640 if (r.processName.equals(app.processName) &&
3641 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3642 mPendingServices.remove(i);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003643 }
3644 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003645 }
3646
3647 // Make sure we have no more records on the stopping list.
Dianne Hackborn164371f2013-10-01 19:10:13 -07003648 int i = mDestroyingServices.size();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003649 while (i > 0) {
3650 i--;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003651 ServiceRecord sr = mDestroyingServices.get(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003652 if (sr.app == app) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003653 sr.forceClearTracker();
3654 mDestroyingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003655 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003656 }
3657 }
3658
3659 app.executingServices.clear();
3660 }
3661
3662 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
3663 ActivityManager.RunningServiceInfo info =
3664 new ActivityManager.RunningServiceInfo();
3665 info.service = r.name;
3666 if (r.app != null) {
3667 info.pid = r.app.pid;
3668 }
3669 info.uid = r.appInfo.uid;
3670 info.process = r.processName;
3671 info.foreground = r.isForeground;
Yi Jin6b514142017-10-30 14:54:12 -07003672 info.activeSince = r.createRealTime;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003673 info.started = r.startRequested;
3674 info.clientCount = r.connections.size();
3675 info.crashCount = r.crashCount;
3676 info.lastActivityTime = r.lastActivity;
3677 if (r.isForeground) {
3678 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
3679 }
3680 if (r.startRequested) {
3681 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
3682 }
3683 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
3684 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
3685 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003686 if (r.app != null && r.app.isPersistent()) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003687 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
3688 }
3689
Dianne Hackborn390517b2013-05-30 15:03:32 -07003690 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3691 ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003692 for (int i=0; i<connl.size(); i++) {
3693 ConnectionRecord conn = connl.get(i);
3694 if (conn.clientLabel != 0) {
3695 info.clientPackage = conn.binding.client.info.packageName;
3696 info.clientLabel = conn.clientLabel;
3697 return info;
3698 }
3699 }
3700 }
3701 return info;
3702 }
3703
Bryce Lee290e5782017-02-01 16:41:20 -08003704 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags,
Shunta Sato55af6c52016-10-19 15:58:52 +09003705 int callingUid, boolean allowed, boolean canInteractAcrossUsers) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003706 ArrayList<ActivityManager.RunningServiceInfo> res
3707 = new ArrayList<ActivityManager.RunningServiceInfo>();
3708
Dianne Hackborn0c380492012-08-20 17:23:30 -07003709 final long ident = Binder.clearCallingIdentity();
3710 try {
Shunta Sato55af6c52016-10-19 15:58:52 +09003711 if (canInteractAcrossUsers) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003712 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003713 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003714 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003715 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3716 ServiceRecord sr = alls.valueAt(i);
3717 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07003718 }
3719 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003720
Dianne Hackborn0c380492012-08-20 17:23:30 -07003721 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3722 ServiceRecord r = mRestartingServices.get(i);
3723 ActivityManager.RunningServiceInfo info =
3724 makeRunningServiceInfoLocked(r);
3725 info.restarting = r.nextRestartTime;
3726 res.add(info);
3727 }
3728 } else {
Bryce Lee290e5782017-02-01 16:41:20 -08003729 int userId = UserHandle.getUserId(callingUid);
Dianne Hackbornad51be92016-08-16 16:27:36 -07003730 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003731 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3732 ServiceRecord sr = alls.valueAt(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003733
3734 if (allowed || (sr.app != null && sr.app.uid == callingUid)) {
3735 res.add(makeRunningServiceInfoLocked(sr));
3736 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07003737 }
3738
3739 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3740 ServiceRecord r = mRestartingServices.get(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003741 if (r.userId == userId
3742 && (allowed || (r.app != null && r.app.uid == callingUid))) {
Dianne Hackborn0c380492012-08-20 17:23:30 -07003743 ActivityManager.RunningServiceInfo info =
3744 makeRunningServiceInfoLocked(r);
3745 info.restarting = r.nextRestartTime;
3746 res.add(info);
3747 }
3748 }
3749 }
3750 } finally {
3751 Binder.restoreCallingIdentity(ident);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003752 }
3753
3754 return res;
3755 }
3756
3757 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003758 int userId = UserHandle.getUserId(Binder.getCallingUid());
Dianne Hackbornad51be92016-08-16 16:27:36 -07003759 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003760 if (r != null) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003761 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3762 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003763 for (int i=0; i<conn.size(); i++) {
3764 if (conn.get(i).clientIntent != null) {
3765 return conn.get(i).clientIntent;
3766 }
3767 }
3768 }
3769 }
3770 return null;
3771 }
3772
3773 void serviceTimeout(ProcessRecord proc) {
3774 String anrMessage = null;
3775
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003776 synchronized(mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003777 if (proc.executingServices.size() == 0 || proc.thread == null) {
3778 return;
3779 }
Dianne Hackbornab2df062015-01-07 13:43:13 -08003780 final long now = SystemClock.uptimeMillis();
3781 final long maxTime = now -
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003782 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003783 ServiceRecord timeout = null;
3784 long nextTime = 0;
Dianne Hackbornc8230512013-07-13 21:32:12 -07003785 for (int i=proc.executingServices.size()-1; i>=0; i--) {
3786 ServiceRecord sr = proc.executingServices.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003787 if (sr.executingStart < maxTime) {
3788 timeout = sr;
3789 break;
3790 }
3791 if (sr.executingStart > nextTime) {
3792 nextTime = sr.executingStart;
3793 }
3794 }
Amith Yamasani98a00922018-08-21 12:50:30 -04003795 if (timeout != null && mAm.mProcessList.mLruProcesses.contains(proc)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003796 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08003797 StringWriter sw = new StringWriter();
3798 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
3799 pw.println(timeout);
3800 timeout.dump(pw, " ");
3801 pw.close();
3802 mLastAnrDump = sw.toString();
3803 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
3804 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003805 anrMessage = "executing service " + timeout.shortInstanceName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003806 } else {
3807 Message msg = mAm.mHandler.obtainMessage(
3808 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3809 msg.obj = proc;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003810 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
Dianne Hackborn2be00932013-09-22 16:46:00 -07003811 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003812 }
3813 }
3814
3815 if (anrMessage != null) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07003816 proc.appNotResponding(null, null, null, null, false, anrMessage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003817 }
3818 }
3819
Christopher Tate08992ac2017-03-21 11:37:06 -07003820 void serviceForegroundTimeout(ServiceRecord r) {
3821 ProcessRecord app;
3822 synchronized (mAm) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003823 if (!r.fgRequired || r.destroying) {
Christopher Tate08992ac2017-03-21 11:37:06 -07003824 return;
3825 }
3826
Christopher Tate54f51b02018-02-16 11:07:12 -08003827 app = r.app;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07003828 if (app != null && app.isDebugging()) {
Christopher Tate54f51b02018-02-16 11:07:12 -08003829 // The app's being debugged; let it ride
3830 return;
3831 }
3832
Christopher Tate08992ac2017-03-21 11:37:06 -07003833 if (DEBUG_BACKGROUND_CHECK) {
3834 Slog.i(TAG, "Service foreground-required timeout for " + r);
3835 }
Christopher Tate08992ac2017-03-21 11:37:06 -07003836 r.fgWaiting = false;
3837 stopServiceLocked(r);
3838 }
3839
3840 if (app != null) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07003841 app.appNotResponding(null, null, null, null, false,
Kodlee Yin7e951262018-04-05 12:59:56 -07003842 "Context.startForegroundService() did not then call Service.startForeground(): "
3843 + r);
Christopher Tate08992ac2017-03-21 11:37:06 -07003844 }
3845 }
3846
Fyodor Kupolovcc269d92018-05-14 14:20:29 -07003847 public void updateServiceApplicationInfoLocked(ApplicationInfo applicationInfo) {
3848 final int userId = UserHandle.getUserId(applicationInfo.uid);
3849 ServiceMap serviceMap = mServiceMap.get(userId);
3850 if (serviceMap != null) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003851 ArrayMap<ComponentName, ServiceRecord> servicesByName
3852 = serviceMap.mServicesByInstanceName;
Fyodor Kupolovcc269d92018-05-14 14:20:29 -07003853 for (int j = servicesByName.size() - 1; j >= 0; j--) {
3854 ServiceRecord serviceRecord = servicesByName.valueAt(j);
3855 if (applicationInfo.packageName.equals(serviceRecord.appInfo.packageName)) {
3856 serviceRecord.appInfo = applicationInfo;
3857 serviceRecord.serviceInfo.applicationInfo = applicationInfo;
3858 }
3859 }
3860 }
3861 }
3862
Kodlee Yin7e951262018-04-05 12:59:56 -07003863 void serviceForegroundCrash(ProcessRecord app, CharSequence serviceRecord) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003864 mAm.crashApplication(app.uid, app.pid, app.info.packageName, app.userId,
Kodlee Yin7e951262018-04-05 12:59:56 -07003865 "Context.startForegroundService() did not then call Service.startForeground(): "
3866 + serviceRecord);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003867 }
3868
Dianne Hackborn2be00932013-09-22 16:46:00 -07003869 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
3870 if (proc.executingServices.size() == 0 || proc.thread == null) {
3871 return;
3872 }
Dianne Hackborn2be00932013-09-22 16:46:00 -07003873 Message msg = mAm.mHandler.obtainMessage(
3874 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3875 msg.obj = proc;
Christopher Tate08992ac2017-03-21 11:37:06 -07003876 mAm.mHandler.sendMessageDelayed(msg,
3877 proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
3878 }
3879
3880 void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
3881 if (r.app.executingServices.size() == 0 || r.app.thread == null) {
3882 return;
3883 }
3884 Message msg = mAm.mHandler.obtainMessage(
3885 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG);
3886 msg.obj = r;
3887 r.fgWaiting = true;
3888 mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT);
Dianne Hackborn2be00932013-09-22 16:46:00 -07003889 }
3890
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003891 final class ServiceDumper {
3892 private final FileDescriptor fd;
3893 private final PrintWriter pw;
3894 private final String[] args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003895 private final boolean dumpAll;
3896 private final String dumpPackage;
3897 private final ItemMatcher matcher;
3898 private final ArrayList<ServiceRecord> services = new ArrayList<>();
3899
3900 private final long nowReal = SystemClock.elapsedRealtime();
3901
3902 private boolean needSep = false;
3903 private boolean printedAnything = false;
3904 private boolean printed = false;
3905
3906 /**
3907 * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
3908 * must be called with the lock held).
3909 */
3910 ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
3911 int opti, boolean dumpAll, String dumpPackage) {
3912 this.fd = fd;
3913 this.pw = pw;
3914 this.args = args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003915 this.dumpAll = dumpAll;
3916 this.dumpPackage = dumpPackage;
3917 matcher = new ItemMatcher();
3918 matcher.build(args, opti);
3919
3920 final int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003921 for (int user : users) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003922 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08003923 if (smap.mServicesByInstanceName.size() > 0) {
3924 for (int si=0; si<smap.mServicesByInstanceName.size(); si++) {
3925 ServiceRecord r = smap.mServicesByInstanceName.valueAt(si);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003926 if (!matcher.match(r, r.name)) {
3927 continue;
3928 }
3929 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3930 continue;
3931 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003932 services.add(r);
3933 }
3934 }
3935 }
3936 }
3937
3938 private void dumpHeaderLocked() {
3939 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
3940 if (mLastAnrDump != null) {
3941 pw.println(" Last ANR service:");
3942 pw.print(mLastAnrDump);
3943 pw.println();
3944 }
3945 }
3946
3947 void dumpLocked() {
3948 dumpHeaderLocked();
3949
3950 try {
3951 int[] users = mAm.mUserController.getUsers();
3952 for (int user : users) {
3953 // Find the first service for this user.
3954 int serviceIdx = 0;
3955 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3956 serviceIdx++;
3957 }
3958 printed = false;
3959 if (serviceIdx < services.size()) {
3960 needSep = false;
3961 while (serviceIdx < services.size()) {
3962 ServiceRecord r = services.get(serviceIdx);
3963 serviceIdx++;
3964 if (r.userId != user) {
3965 break;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003966 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003967 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003968 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003969 needSep |= printed;
3970 }
3971
3972 dumpUserRemainsLocked(user);
3973 }
3974 } catch (Exception e) {
3975 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3976 }
3977
3978 dumpRemainsLocked();
3979 }
3980
3981 void dumpWithClient() {
3982 synchronized(mAm) {
3983 dumpHeaderLocked();
3984 }
3985
3986 try {
3987 int[] users = mAm.mUserController.getUsers();
3988 for (int user : users) {
3989 // Find the first service for this user.
3990 int serviceIdx = 0;
3991 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3992 serviceIdx++;
3993 }
3994 printed = false;
3995 if (serviceIdx < services.size()) {
3996 needSep = false;
3997 while (serviceIdx < services.size()) {
3998 ServiceRecord r = services.get(serviceIdx);
3999 serviceIdx++;
4000 if (r.userId != user) {
4001 break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004002 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004003 synchronized(mAm) {
4004 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004005 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004006 dumpServiceClient(r);
4007 }
4008 needSep |= printed;
4009 }
4010
4011 synchronized(mAm) {
4012 dumpUserRemainsLocked(user);
4013 }
4014 }
4015 } catch (Exception e) {
4016 Slog.w(TAG, "Exception in dumpServicesLocked", e);
4017 }
4018
4019 synchronized(mAm) {
4020 dumpRemainsLocked();
4021 }
4022 }
4023
4024 private void dumpUserHeaderLocked(int user) {
4025 if (!printed) {
4026 if (printedAnything) {
4027 pw.println();
4028 }
4029 pw.println(" User " + user + " active services:");
4030 printed = true;
4031 }
4032 printedAnything = true;
4033 if (needSep) {
4034 pw.println();
4035 }
4036 }
4037
4038 private void dumpServiceLocalLocked(ServiceRecord r) {
4039 dumpUserHeaderLocked(r.userId);
4040 pw.print(" * ");
4041 pw.println(r);
4042 if (dumpAll) {
4043 r.dump(pw, " ");
4044 needSep = true;
4045 } else {
4046 pw.print(" app=");
4047 pw.println(r.app);
4048 pw.print(" created=");
Yi Jin6b514142017-10-30 14:54:12 -07004049 TimeUtils.formatDuration(r.createRealTime, nowReal, pw);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004050 pw.print(" started=");
4051 pw.print(r.startRequested);
4052 pw.print(" connections=");
4053 pw.println(r.connections.size());
4054 if (r.connections.size() > 0) {
4055 pw.println(" Connections:");
4056 for (int conni=0; conni<r.connections.size(); conni++) {
4057 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
4058 for (int i = 0; i < clist.size(); i++) {
4059 ConnectionRecord conn = clist.get(i);
4060 pw.print(" ");
4061 pw.print(conn.binding.intent.intent.getIntent()
4062 .toShortString(false, false, false, false));
4063 pw.print(" -> ");
4064 ProcessRecord proc = conn.binding.client;
4065 pw.println(proc != null ? proc.toShortString() : "null");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004066 }
4067 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004068 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004069 }
4070 }
4071
4072 private void dumpServiceClient(ServiceRecord r) {
4073 final ProcessRecord proc = r.app;
4074 if (proc == null) {
4075 return;
4076 }
4077 final IApplicationThread thread = proc.thread;
4078 if (thread == null) {
4079 return;
4080 }
4081 pw.println(" Client:");
4082 pw.flush();
4083 try {
4084 TransferPipe tp = new TransferPipe();
4085 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004086 thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004087 tp.setBufferPrefix(" ");
4088 // Short timeout, since blocking here can
4089 // deadlock with the application.
4090 tp.go(fd, 2000);
4091 } finally {
4092 tp.kill();
4093 }
4094 } catch (IOException e) {
4095 pw.println(" Failure while dumping the service: " + e);
4096 } catch (RemoteException e) {
4097 pw.println(" Got a RemoteException while dumping the service");
4098 }
4099 needSep = true;
4100 }
4101
4102 private void dumpUserRemainsLocked(int user) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07004103 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004104 printed = false;
4105 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
4106 ServiceRecord r = smap.mDelayedStartList.get(si);
4107 if (!matcher.match(r, r.name)) {
4108 continue;
4109 }
4110 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4111 continue;
4112 }
4113 if (!printed) {
4114 if (printedAnything) {
4115 pw.println();
4116 }
4117 pw.println(" User " + user + " delayed start services:");
4118 printed = true;
4119 }
4120 printedAnything = true;
4121 pw.print(" * Delayed start "); pw.println(r);
4122 }
4123 printed = false;
4124 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
4125 ServiceRecord r = smap.mStartingBackground.get(si);
4126 if (!matcher.match(r, r.name)) {
4127 continue;
4128 }
4129 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4130 continue;
4131 }
4132 if (!printed) {
4133 if (printedAnything) {
4134 pw.println();
4135 }
4136 pw.println(" User " + user + " starting in background:");
4137 printed = true;
4138 }
4139 printedAnything = true;
4140 pw.print(" * Starting bg "); pw.println(r);
4141 }
4142 }
4143
4144 private void dumpRemainsLocked() {
4145 if (mPendingServices.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004146 printed = false;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004147 for (int i=0; i<mPendingServices.size(); i++) {
4148 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004149 if (!matcher.match(r, r.name)) {
4150 continue;
4151 }
4152 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4153 continue;
4154 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004155 printedAnything = true;
4156 if (!printed) {
4157 if (needSep) pw.println();
4158 needSep = true;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004159 pw.println(" Pending services:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004160 printed = true;
4161 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004162 pw.print(" * Pending "); pw.println(r);
4163 r.dump(pw, " ");
4164 }
4165 needSep = true;
4166 }
4167
4168 if (mRestartingServices.size() > 0) {
4169 printed = false;
4170 for (int i=0; i<mRestartingServices.size(); i++) {
4171 ServiceRecord r = mRestartingServices.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(" Restarting services:");
4183 printed = true;
4184 }
4185 pw.print(" * Restarting "); pw.println(r);
4186 r.dump(pw, " ");
4187 }
4188 needSep = true;
4189 }
4190
4191 if (mDestroyingServices.size() > 0) {
4192 printed = false;
4193 for (int i=0; i< mDestroyingServices.size(); i++) {
4194 ServiceRecord r = mDestroyingServices.get(i);
4195 if (!matcher.match(r, r.name)) {
4196 continue;
4197 }
4198 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
4199 continue;
4200 }
4201 printedAnything = true;
4202 if (!printed) {
4203 if (needSep) pw.println();
4204 needSep = true;
4205 pw.println(" Destroying services:");
4206 printed = true;
4207 }
4208 pw.print(" * Destroy "); pw.println(r);
4209 r.dump(pw, " ");
4210 }
4211 needSep = true;
4212 }
4213
4214 if (dumpAll) {
4215 printed = false;
4216 for (int ic=0; ic<mServiceConnections.size(); ic++) {
4217 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
4218 for (int i=0; i<r.size(); i++) {
4219 ConnectionRecord cr = r.get(i);
4220 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
4221 continue;
4222 }
4223 if (dumpPackage != null && (cr.binding.client == null
4224 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
4225 continue;
4226 }
4227 printedAnything = true;
4228 if (!printed) {
4229 if (needSep) pw.println();
4230 needSep = true;
4231 pw.println(" Connection bindings to services:");
4232 printed = true;
4233 }
4234 pw.print(" * "); pw.println(cr);
4235 cr.dump(pw, " ");
4236 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004237 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004238 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004239
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004240 if (matcher.all) {
4241 final long nowElapsed = SystemClock.elapsedRealtime();
4242 final int[] users = mAm.mUserController.getUsers();
4243 for (int user : users) {
4244 boolean printedUser = false;
4245 ServiceMap smap = mServiceMap.get(user);
4246 if (smap == null) {
4247 continue;
4248 }
4249 for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) {
4250 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
4251 if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) {
4252 continue;
4253 }
4254 if (!printedUser) {
4255 printedUser = true;
4256 printedAnything = true;
4257 if (needSep) pw.println();
4258 needSep = true;
4259 pw.print("Active foreground apps - user ");
4260 pw.print(user);
4261 pw.println(":");
4262 }
4263 pw.print(" #");
4264 pw.print(i);
4265 pw.print(": ");
4266 pw.println(aa.mPackageName);
4267 if (aa.mLabel != null) {
4268 pw.print(" mLabel=");
4269 pw.println(aa.mLabel);
4270 }
4271 pw.print(" mNumActive=");
4272 pw.print(aa.mNumActive);
Dianne Hackbornbe68d492017-05-03 18:04:05 -07004273 pw.print(" mAppOnTop=");
4274 pw.print(aa.mAppOnTop);
4275 pw.print(" mShownWhileTop=");
4276 pw.print(aa.mShownWhileTop);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004277 pw.print(" mShownWhileScreenOn=");
4278 pw.println(aa.mShownWhileScreenOn);
4279 pw.print(" mStartTime=");
4280 TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw);
4281 pw.print(" mStartVisibleTime=");
4282 TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw);
4283 pw.println();
4284 if (aa.mEndTime != 0) {
4285 pw.print(" mEndTime=");
4286 TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw);
4287 pw.println();
4288 }
4289 }
Dianne Hackborncb015632017-06-14 17:30:15 -07004290 if (smap.hasMessagesOrCallbacks()) {
4291 if (needSep) {
4292 pw.println();
4293 }
4294 printedAnything = true;
4295 needSep = true;
4296 pw.print(" Handler - user ");
4297 pw.print(user);
4298 pw.println(":");
4299 smap.dumpMine(new PrintWriterPrinter(pw), " ");
4300 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004301 }
4302 }
4303
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004304 if (!printedAnything) {
4305 pw.println(" (nothing)");
4306 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07004307 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004308 }
4309
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004310 ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4311 int opti, boolean dumpAll, String dumpPackage) {
4312 return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
4313 }
4314
Yi Jin2b30f322018-02-20 15:41:47 -08004315 protected void writeToProto(ProtoOutputStream proto, long fieldId) {
Yi Jin6b514142017-10-30 14:54:12 -07004316 synchronized (mAm) {
Yi Jin2b30f322018-02-20 15:41:47 -08004317 final long outterToken = proto.start(fieldId);
Yi Jin6b514142017-10-30 14:54:12 -07004318 int[] users = mAm.mUserController.getUsers();
4319 for (int user : users) {
4320 ServiceMap smap = mServiceMap.get(user);
4321 if (smap == null) {
4322 continue;
4323 }
4324 long token = proto.start(ActiveServicesProto.SERVICES_BY_USERS);
4325 proto.write(ActiveServicesProto.ServicesByUser.USER_ID, user);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004326 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
Yi Jin6b514142017-10-30 14:54:12 -07004327 for (int i=0; i<alls.size(); i++) {
4328 alls.valueAt(i).writeToProto(proto,
4329 ActiveServicesProto.ServicesByUser.SERVICE_RECORDS);
4330 }
4331 proto.end(token);
4332 }
Yi Jin2b30f322018-02-20 15:41:47 -08004333 proto.end(outterToken);
Yi Jin6b514142017-10-30 14:54:12 -07004334 }
4335 }
4336
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004337 /**
4338 * There are three ways to call this:
4339 * - no service specified: dump all the services
4340 * - a flattened component name that matched an existing service was specified as the
4341 * first arg: dump that one service
4342 * - the first arg isn't the flattened component name of an existing service:
4343 * dump all services whose component contains the first arg as a substring
4344 */
Makoto Onuki0b575a32018-04-16 14:33:59 -07004345 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, final String name,
4346 String[] args, int opti, boolean dumpAll) {
4347 final ArrayList<ServiceRecord> services = new ArrayList<>();
4348
4349 final Predicate<ServiceRecord> filter = DumpUtils.filterRecord(name);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004350
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004351 synchronized (mAm) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07004352 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004353
Makoto Onuki0b575a32018-04-16 14:33:59 -07004354 for (int user : users) {
4355 ServiceMap smap = mServiceMap.get(user);
4356 if (smap == null) {
4357 continue;
4358 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004359 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
Makoto Onuki0b575a32018-04-16 14:33:59 -07004360 for (int i=0; i<alls.size(); i++) {
4361 ServiceRecord r1 = alls.valueAt(i);
4362
4363 if (filter.test(r1)) {
4364 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004365 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004366 }
4367 }
4368 }
4369
4370 if (services.size() <= 0) {
4371 return false;
4372 }
4373
Makoto Onuki0b575a32018-04-16 14:33:59 -07004374 // Sort by component name.
4375 services.sort(Comparator.comparing(WithComponentName::getComponentName));
4376
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004377 boolean needSep = false;
4378 for (int i=0; i<services.size(); i++) {
4379 if (needSep) {
4380 pw.println();
4381 }
4382 needSep = true;
4383 dumpService("", fd, pw, services.get(i), args, dumpAll);
4384 }
4385 return true;
4386 }
4387
4388 /**
4389 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
4390 * there is a thread associated with the service.
4391 */
4392 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
4393 final ServiceRecord r, String[] args, boolean dumpAll) {
4394 String innerPrefix = prefix + " ";
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004395 synchronized (mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004396 pw.print(prefix); pw.print("SERVICE ");
Dianne Hackborn27b4d942018-11-12 15:01:40 -08004397 pw.print(r.shortInstanceName); pw.print(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004398 pw.print(Integer.toHexString(System.identityHashCode(r)));
4399 pw.print(" pid=");
4400 if (r.app != null) pw.println(r.app.pid);
4401 else pw.println("(not running)");
4402 if (dumpAll) {
4403 r.dump(pw, innerPrefix);
4404 }
4405 }
4406 if (r.app != null && r.app.thread != null) {
4407 pw.print(prefix); pw.println(" Client:");
4408 pw.flush();
4409 try {
4410 TransferPipe tp = new TransferPipe();
4411 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004412 r.app.thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004413 tp.setBufferPrefix(prefix + " ");
4414 tp.go(fd);
4415 } finally {
4416 tp.kill();
4417 }
4418 } catch (IOException e) {
4419 pw.println(prefix + " Failure while dumping the service: " + e);
4420 } catch (RemoteException e) {
4421 pw.println(prefix + " Got a RemoteException while dumping the service");
4422 }
4423 }
4424 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004425}