blob: b1cb2fe70a6eccfb79d1a9ca1f3b8e35e124f46c [file] [log] [blame]
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Bryce Lee290e5782017-02-01 16:41:20 -080019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwaled57969f2014-11-15 19:37:29 -080020import static com.android.server.am.ActivityManagerDebugConfig.*;
21
Dianne Hackborn599db5c2012-08-03 19:28:48 -070022import java.io.FileDescriptor;
23import java.io.IOException;
24import java.io.PrintWriter;
Dianne Hackborncff1bbf2015-01-20 13:43:32 -080025import java.io.StringWriter;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070026import java.util.ArrayList;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070027import java.util.HashSet;
28import java.util.Iterator;
29import java.util.List;
Wale Ogunwale540e1232015-05-01 15:35:39 -070030import java.util.Set;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070031
Dianne Hackborn455625e2015-01-21 09:55:13 -080032import android.app.ActivityThread;
Svet Ganov99b60432015-06-27 13:15:22 -070033import android.app.AppOpsManager;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070034import android.app.NotificationManager;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070035import android.app.ServiceStartArgs;
Svet Ganov9c165d72015-12-01 19:52:26 -080036import android.content.IIntentSender;
37import android.content.IntentSender;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070038import android.content.pm.ParceledListSlice;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070039import android.net.Uri;
Christoph Studer365e4c32014-09-18 20:35:36 +020040import android.os.Build;
Svet Ganov9c165d72015-12-01 19:52:26 -080041import android.os.Bundle;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -070042import android.os.DeadObjectException;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070043import android.os.Handler;
Dianne Hackborn13c590d2013-10-07 14:32:00 -070044import android.os.Looper;
Svet Ganov9c165d72015-12-01 19:52:26 -080045import android.os.RemoteCallback;
Dianne Hackborn23037412013-11-04 18:11:29 -080046import android.os.SystemProperties;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -070047import android.os.TransactionTooLargeException;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070048import android.provider.Settings;
Dianne Hackborn9210bc82013-09-05 12:31:16 -070049import android.util.ArrayMap;
Dianne Hackborn465fa392014-09-14 14:21:18 -070050import android.util.ArraySet;
Wale Ogunwaled57969f2014-11-15 19:37:29 -080051
Dianne Hackborn83b40f62017-04-26 13:59:47 -070052import com.android.internal.R;
Joe Onorato4eb64fd2016-03-21 15:30:09 -070053import com.android.internal.app.procstats.ServiceState;
Dianne Hackborn83b40f62017-04-26 13:59:47 -070054import com.android.internal.messages.nano.SystemMessageProto;
55import com.android.internal.notification.SystemNotificationChannels;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070056import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborncbfd23e2013-06-11 14:26:53 -070057import com.android.internal.os.TransferPipe;
Dianne Hackborncff1bbf2015-01-20 13:43:32 -080058import com.android.internal.util.FastPrintWriter;
Christopher Tatec7933ac2018-03-12 17:57:09 -070059import com.android.server.AppStateTracker;
60import com.android.server.LocalServices;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070061import com.android.server.am.ActivityManagerService.ItemMatcher;
62import com.android.server.am.ActivityManagerService.NeededUriGrants;
63
64import android.app.ActivityManager;
65import android.app.AppGlobals;
66import android.app.IApplicationThread;
67import android.app.IServiceConnection;
68import android.app.Notification;
69import android.app.PendingIntent;
70import android.app.Service;
71import android.content.ComponentName;
72import android.content.Context;
73import android.content.Intent;
74import android.content.pm.ApplicationInfo;
75import android.content.pm.PackageManager;
76import android.content.pm.ResolveInfo;
77import android.content.pm.ServiceInfo;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070078import android.os.Binder;
79import android.os.IBinder;
80import android.os.Message;
81import android.os.Process;
82import android.os.RemoteException;
83import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070084import android.os.UserHandle;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070085import android.util.EventLog;
Dianne Hackborncb015632017-06-14 17:30:15 -070086import android.util.PrintWriterPrinter;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070087import android.util.Slog;
Chenjie Yuccfe6452018-01-30 11:33:21 -080088import android.util.StatsLog;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070089import android.util.SparseArray;
90import android.util.TimeUtils;
Yi Jin6b514142017-10-30 14:54:12 -070091import android.util.proto.ProtoOutputStream;
Robert Sesekc5f86642016-11-04 10:20:38 -040092import android.webkit.WebViewZygote;
Dianne Hackborn599db5c2012-08-03 19:28:48 -070093
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -070094public final class ActiveServices {
Wale Ogunwaled57969f2014-11-15 19:37:29 -080095 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM;
96 private static final String TAG_MU = TAG + POSTFIX_MU;
97 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
98 private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING;
99
100 private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE;
101 private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE;
102
103 private static final boolean LOG_SERVICE_START_STOP = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700104
105 // How long we wait for a service to finish executing.
106 static final int SERVICE_TIMEOUT = 20*1000;
107
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700108 // How long we wait for a service to finish executing.
109 static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
110
Christopher Tate08992ac2017-03-21 11:37:06 -0700111 // How long the startForegroundService() grace period is to get around to
112 // calling startForeground() before we ANR + stop it.
113 static final int SERVICE_START_FOREGROUND_TIMEOUT = 5*1000;
114
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700115 final ActivityManagerService mAm;
116
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700117 // Maximum number of services that we allow to start in the background
118 // at the same time.
119 final int mMaxStartingBackground;
120
Wale Ogunwale540e1232015-05-01 15:35:39 -0700121 final SparseArray<ServiceMap> mServiceMap = new SparseArray<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700122
123 /**
124 * All currently bound service connections. Keys are the IBinder of
125 * the client's IServiceConnection.
126 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700127 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700128
129 /**
130 * List of services that we have been asked to start,
131 * but haven't yet been able to. It is used to hold start requests
132 * while waiting for their corresponding application thread to get
133 * going.
134 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700135 final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700136
137 /**
138 * List of services that are scheduled to restart following a crash.
139 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700140 final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700141
142 /**
Dianne Hackborn164371f2013-10-01 19:10:13 -0700143 * List of services that are in the process of being destroyed.
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700144 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700145 final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>();
146
147 /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */
148 private ArrayList<ServiceRecord> mTmpCollectionResults = null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700149
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700150 /**
151 * For keeping ActiveForegroundApps retaining state while the screen is off.
152 */
153 boolean mScreenOn = true;
154
Dianne Hackborncff1bbf2015-01-20 13:43:32 -0800155 /** Amount of time to allow a last ANR message to exist before freeing the memory. */
156 static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
157
158 String mLastAnrDump;
159
160 final Runnable mLastAnrDumpClearer = new Runnable() {
161 @Override public void run() {
162 synchronized (mAm) {
163 mLastAnrDump = null;
164 }
165 }
166 };
167
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700168 /**
Christopher Tatec7933ac2018-03-12 17:57:09 -0700169 * Watch for apps being put into forced app standby, so we can step their fg
170 * services down.
171 */
172 class ForcedStandbyListener extends AppStateTracker.Listener {
173 @Override
174 public void stopForegroundServicesForUidPackage(final int uid, final String packageName) {
175 synchronized (mAm) {
176 final ServiceMap smap = getServiceMapLocked(UserHandle.getUserId(uid));
177 final int N = smap.mServicesByName.size();
178 final ArrayList<ServiceRecord> toStop = new ArrayList<>(N);
179 for (int i = 0; i < N; i++) {
180 final ServiceRecord r = smap.mServicesByName.valueAt(i);
181 if (uid == r.serviceInfo.applicationInfo.uid
182 || packageName.equals(r.serviceInfo.packageName)) {
183 if (r.isForeground) {
184 toStop.add(r);
185 }
186 }
187 }
188
189 // Now stop them all
190 final int numToStop = toStop.size();
191 if (numToStop > 0 && DEBUG_FOREGROUND_SERVICE) {
192 Slog.i(TAG, "Package " + packageName + "/" + uid
193 + " entering FAS with foreground services");
194 }
195 for (int i = 0; i < numToStop; i++) {
196 final ServiceRecord r = toStop.get(i);
197 if (DEBUG_FOREGROUND_SERVICE) {
198 Slog.i(TAG, " Stopping fg for service " + r);
199 }
200 setServiceForegroundInnerLocked(r, 0, null, 0);
201 }
202 }
203 }
204 }
205
206 /**
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700207 * Information about an app that is currently running one or more foreground services.
Dan Sandler2f36ab82017-05-25 00:15:49 -0400208 * (This maps directly to the running apps we show in the notification.)
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700209 */
210 static final class ActiveForegroundApp {
211 String mPackageName;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700212 int mUid;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700213 CharSequence mLabel;
214 boolean mShownWhileScreenOn;
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700215 boolean mAppOnTop;
216 boolean mShownWhileTop;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700217 long mStartTime;
218 long mStartVisibleTime;
219 long mEndTime;
220 int mNumActive;
Dianne Hackborncb015632017-06-14 17:30:15 -0700221
222 // Temp output of foregroundAppShownEnoughLocked
223 long mHideTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700224 }
225
226 /**
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700227 * Information about services for a single user.
228 */
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700229 final class ServiceMap extends Handler {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700230 final int mUserId;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700231 final ArrayMap<ComponentName, ServiceRecord> mServicesByName = new ArrayMap<>();
232 final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700233
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700234 final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700235 /* XXX eventually I'd like to have this based on processes instead of services.
236 * That is, if we try to start two services in a row both running in the same
237 * process, this should be one entry in mStartingBackground for that one process
238 * that remains until all services in it are done.
239 final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
240 = new ArrayMap<ProcessRecord, DelayingProcess>();
241 final ArrayList<DelayingProcess> mStartingProcessList
242 = new ArrayList<DelayingProcess>();
243 */
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700244
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700245 final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700246
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700247 final ArrayMap<String, ActiveForegroundApp> mActiveForegroundApps = new ArrayMap<>();
248 boolean mActiveForegroundAppsChanged;
249
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700250 static final int MSG_BG_START_TIMEOUT = 1;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700251 static final int MSG_UPDATE_FOREGROUND_APPS = 2;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700252
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700253 ServiceMap(Looper looper, int userId) {
254 super(looper);
Dianne Hackborn6285a322013-09-18 12:09:47 -0700255 mUserId = userId;
256 }
257
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700258 @Override
259 public void handleMessage(Message msg) {
260 switch (msg.what) {
261 case MSG_BG_START_TIMEOUT: {
262 synchronized (mAm) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700263 rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700264 }
265 } break;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700266 case MSG_UPDATE_FOREGROUND_APPS: {
267 updateForegroundApps(this);
268 } break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700269 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700270 }
271
Dianne Hackbornad51be92016-08-16 16:27:36 -0700272 void ensureNotStartingBackgroundLocked(ServiceRecord r) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700273 if (mStartingBackground.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800274 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
275 "No longer background starting: " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -0700276 rescheduleDelayedStartsLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700277 }
Dianne Hackborn2e46bb52013-09-13 17:01:26 -0700278 if (mDelayedStartList.remove(r)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800279 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700280 }
281 }
282
Dianne Hackbornad51be92016-08-16 16:27:36 -0700283 void rescheduleDelayedStartsLocked() {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700284 removeMessages(MSG_BG_START_TIMEOUT);
285 final long now = SystemClock.uptimeMillis();
286 for (int i=0, N=mStartingBackground.size(); i<N; i++) {
287 ServiceRecord r = mStartingBackground.get(i);
288 if (r.startingBgTimeout <= now) {
289 Slog.i(TAG, "Waited long enough for: " + r);
290 mStartingBackground.remove(i);
291 N--;
Junu Kimfcb87362014-02-19 16:25:21 +0900292 i--;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700293 }
294 }
295 while (mDelayedStartList.size() > 0
296 && mStartingBackground.size() < mMaxStartingBackground) {
297 ServiceRecord r = mDelayedStartList.remove(0);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800298 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
299 "REM FR DELAY LIST (exec next): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700300 if (r.pendingStarts.size() <= 0) {
301 Slog.w(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
302 + " delayedStop=" + r.delayedStop);
303 }
304 if (DEBUG_DELAYED_SERVICE) {
305 if (mDelayedStartList.size() > 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800306 Slog.v(TAG_SERVICE, "Remaining delayed list:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700307 for (int i=0; i<mDelayedStartList.size(); i++) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800308 Slog.v(TAG_SERVICE, " #" + i + ": " + mDelayedStartList.get(i));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700309 }
310 }
311 }
312 r.delayed = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700313 try {
314 startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false, true);
315 } catch (TransactionTooLargeException e) {
316 // Ignore, nobody upstack cares.
317 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700318 }
319 if (mStartingBackground.size() > 0) {
320 ServiceRecord next = mStartingBackground.get(0);
321 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800322 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700323 + ", can delay others up to " + when);
324 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
325 sendMessageAtTime(msg, when);
326 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700327 if (mStartingBackground.size() < mMaxStartingBackground) {
328 mAm.backgroundServicesFinishedLocked(mUserId);
329 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700330 }
331 }
332
333 public ActiveServices(ActivityManagerService service) {
334 mAm = service;
Dianne Hackborn23037412013-11-04 18:11:29 -0800335 int maxBg = 0;
336 try {
337 maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
338 } catch(RuntimeException e) {
339 }
Dianne Hackborn20d94742014-05-29 18:35:45 -0700340 mMaxStartingBackground = maxBg > 0
341 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700342 }
343
Christopher Tatec7933ac2018-03-12 17:57:09 -0700344 void systemServicesReady() {
345 AppStateTracker ast = LocalServices.getService(AppStateTracker.class);
346 ast.addListener(new ForcedStandbyListener());
347 }
348
Dianne Hackbornad51be92016-08-16 16:27:36 -0700349 ServiceRecord getServiceByNameLocked(ComponentName name, int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700350 // TODO: Deal with global services
351 if (DEBUG_MU)
Dianne Hackbornad51be92016-08-16 16:27:36 -0700352 Slog.v(TAG_MU, "getServiceByNameLocked(" + name + "), callingUser = " + callingUser);
353 return getServiceMapLocked(callingUser).mServicesByName.get(name);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700354 }
355
Dianne Hackbornad51be92016-08-16 16:27:36 -0700356 boolean hasBackgroundServicesLocked(int callingUser) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700357 ServiceMap smap = mServiceMap.get(callingUser);
358 return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
359 }
360
Dianne Hackbornad51be92016-08-16 16:27:36 -0700361 private ServiceMap getServiceMapLocked(int callingUser) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700362 ServiceMap smap = mServiceMap.get(callingUser);
363 if (smap == null) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -0700364 smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700365 mServiceMap.put(callingUser, smap);
366 }
367 return smap;
368 }
369
Dianne Hackbornad51be92016-08-16 16:27:36 -0700370 ArrayMap<ComponentName, ServiceRecord> getServicesLocked(int callingUser) {
371 return getServiceMapLocked(callingUser).mServicesByName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700372 }
373
Christopher Tatec7933ac2018-03-12 17:57:09 -0700374 private boolean appRestrictedAnyInBackground(final int uid, final String packageName) {
375 final int mode = mAm.mAppOpsService.checkOperation(
376 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, uid, packageName);
377 return (mode != AppOpsManager.MODE_ALLOWED);
378 }
379
Svet Ganov99b60432015-06-27 13:15:22 -0700380 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
Christopher Tate242ba3e92017-04-14 15:07:06 -0700381 int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700382 throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800383 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700384 + " type=" + resolvedType + " args=" + service.getExtras());
385
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700386 final boolean callerFg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700387 if (caller != null) {
388 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
389 if (callerApp == null) {
390 throw new SecurityException(
391 "Unable to find app for caller " + caller
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700392 + " (pid=" + callingPid
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700393 + ") when starting service " + service);
394 }
Dianne Hackborna49ad092016-03-03 13:39:10 -0800395 callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -0700396 } else {
397 callerFg = true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700398 }
399
400 ServiceLookupResult res =
Svet Ganov99b60432015-06-27 13:15:22 -0700401 retrieveServiceLocked(service, resolvedType, callingPackage,
Svet Ganovd223db32017-12-22 09:43:48 -0800402 callingPid, callingUid, userId, true, callerFg, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700403 if (res == null) {
404 return null;
405 }
406 if (res.record == null) {
407 return new ComponentName("!", res.permission != null
408 ? res.permission : "private to package");
409 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700410
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700411 ServiceRecord r = res.record;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700412
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700413 if (!mAm.mUserController.exists(r.userId)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700414 Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700415 return null;
416 }
417
Christopher Tate85048282018-03-30 14:08:59 -0700418 // If we're starting indirectly (e.g. from PendingIntent), figure out whether
419 // we're launching into an app in a background state.
420 final int uidState = mAm.getUidStateLocked(r.appInfo.uid);
421 if (DEBUG_SERVICE) {
422 Slog.v(TAG_SERVICE, "Uid state " + uidState + " indirect starting " + r.shortName);
423 }
424 final boolean bgLaunch = (uidState >
425 ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
426
427 // If the app has strict background restrictions, we treat any bg service
428 // start analogously to the legacy-app forced-restrictions case, regardless
429 // of its target SDK version.
Christopher Tatec7933ac2018-03-12 17:57:09 -0700430 boolean forcedStandby = false;
Christopher Tate85048282018-03-30 14:08:59 -0700431 if (bgLaunch && appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
Christopher Tatec7933ac2018-03-12 17:57:09 -0700432 if (DEBUG_FOREGROUND_SERVICE) {
Christopher Tate85048282018-03-30 14:08:59 -0700433 Slog.d(TAG, "Forcing bg-only service start only for " + r.shortName
434 + " : bgLaunch=" + bgLaunch + " callerFg=" + callerFg);
Christopher Tatec7933ac2018-03-12 17:57:09 -0700435 }
436 forcedStandby = true;
437 }
438
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700439 // If this is a direct-to-foreground start, make sure it is allowed as per the app op.
440 boolean forceSilentAbort = false;
441 if (fgRequired) {
442 final int mode = mAm.mAppOpsService.checkOperation(
443 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
444 switch (mode) {
445 case AppOpsManager.MODE_ALLOWED:
446 case AppOpsManager.MODE_DEFAULT:
447 // All okay.
448 break;
449 case AppOpsManager.MODE_IGNORED:
450 // Not allowed, fall back to normal start service, failing siliently
451 // if background check restricts that.
452 Slog.w(TAG, "startForegroundService not allowed due to app op: service "
453 + service + " to " + r.name.flattenToShortString()
454 + " from pid=" + callingPid + " uid=" + callingUid
455 + " pkg=" + callingPackage);
456 fgRequired = false;
457 forceSilentAbort = true;
458 break;
459 default:
460 return new ComponentName("!!", "foreground not allowed as per app op");
461 }
462 }
463
Christopher Tate08992ac2017-03-21 11:37:06 -0700464 // If this isn't a direct-to-foreground start, check our ability to kick off an
465 // arbitrary service
Christopher Tatec7933ac2018-03-12 17:57:09 -0700466 if (forcedStandby || (!r.startRequested && !fgRequired)) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700467 // Before going further -- if this app is not allowed to start services in the
468 // background, then at this point we aren't going to let it period.
469 final int allowed = mAm.getAppStartModeLocked(r.appInfo.uid, r.packageName,
Christopher Tatec7933ac2018-03-12 17:57:09 -0700470 r.appInfo.targetSdkVersion, callingPid, false, false, forcedStandby);
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700471 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
472 Slog.w(TAG, "Background start not allowed: service "
473 + service + " to " + r.name.flattenToShortString()
474 + " from pid=" + callingPid + " uid=" + callingUid
475 + " pkg=" + callingPackage);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700476 if (allowed == ActivityManager.APP_START_MODE_DELAYED || forceSilentAbort) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700477 // In this case we are silently disabling the app, to disrupt as
478 // little as possible existing apps.
479 return null;
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700480 }
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700481 // This app knows it is in the new model where this operation is not
482 // allowed, so tell it what has happened.
483 UidRecord uidRec = mAm.mActiveUids.get(r.appInfo.uid);
484 return new ComponentName("?", "app is in background uid " + uidRec);
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700485 }
486 }
487
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700488 NeededUriGrants neededGrants = mAm.checkGrantUriPermissionFromIntentLocked(
Nicolas Prevotc6cf95c2014-05-29 11:30:36 +0100489 callingUid, r.packageName, service, service.getFlags(), null, r.userId);
Svet Ganov9c165d72015-12-01 19:52:26 -0800490
491 // If permissions need a review before any of the app components can run,
492 // we do not start the service and launch a review activity if the calling app
493 // is in the foreground passing it a pending intent to start the service when
494 // review is completed.
Svet Ganov77df6f32016-08-17 11:46:34 -0700495 if (mAm.mPermissionReviewRequired) {
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700496 // XXX This is not dealing with fgRequired!
Svet Ganov9c165d72015-12-01 19:52:26 -0800497 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage,
498 callingUid, service, callerFg, userId)) {
499 return null;
500 }
501 }
502
Dianne Hackbornd6f5b622013-11-11 17:25:37 -0800503 if (unscheduleServiceRestartLocked(r, callingUid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800504 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700505 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700506 r.lastActivity = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700507 r.startRequested = true;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700508 r.delayedStop = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700509 r.fgRequired = fgRequired;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700510 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -0700511 service, neededGrants, callingUid));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700512
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700513 if (fgRequired) {
514 // We are now effectively running a foreground service.
515 mAm.mAppOpsService.startOperation(AppOpsManager.getToken(mAm.mAppOpsService),
516 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, true);
517 }
518
Dianne Hackbornad51be92016-08-16 16:27:36 -0700519 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700520 boolean addToStarting = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700521 if (!callerFg && !fgRequired && r.app == null
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700522 && mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700523 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700524 if (proc == null || proc.curProcState > ActivityManager.PROCESS_STATE_RECEIVER) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700525 // If this is not coming from a foreground caller, then we may want
526 // to delay the start if there are already other background services
527 // that are starting. This is to avoid process start spam when lots
528 // of applications are all handling things like connectivity broadcasts.
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700529 // We only do this for cached processes, because otherwise an application
530 // can have assumptions about calling startService() for a service to run
531 // in its own process, and for that process to not be killed before the
532 // service is started. This is especially the case for receivers, which
533 // may start a service in onReceive() to do some additional work and have
534 // initialized some global state as part of that.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800535 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
536 + r + " in " + proc);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700537 if (r.delayed) {
538 // This service is already scheduled for a delayed start; just leave
539 // it still waiting.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800540 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700541 return r.name;
542 }
543 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
544 // Something else is starting, delay!
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800545 Slog.i(TAG_SERVICE, "Delaying start of: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700546 smap.mDelayedStartList.add(r);
547 r.delayed = true;
548 return r.name;
549 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800550 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700551 addToStarting = true;
552 } else if (proc.curProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
553 // We slightly loosen when we will enqueue this new service as a background
554 // starting service we are waiting for, to also include processes that are
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700555 // currently running other services or receivers.
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700556 addToStarting = true;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800557 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
558 "Not delaying, but counting as bg: " + r);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800559 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn8e692572013-09-10 19:06:15 -0700560 StringBuilder sb = new StringBuilder(128);
561 sb.append("Not potential delay (state=").append(proc.curProcState)
562 .append(' ').append(proc.adjType);
563 String reason = proc.makeAdjReason();
564 if (reason != null) {
565 sb.append(' ');
566 sb.append(reason);
567 }
568 sb.append("): ");
569 sb.append(r.toString());
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800570 Slog.v(TAG_SERVICE, sb.toString());
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700571 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800572 } else if (DEBUG_DELAYED_STARTS) {
Christopher Tate08992ac2017-03-21 11:37:06 -0700573 if (callerFg || fgRequired) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800574 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
Christopher Tate08992ac2017-03-21 11:37:06 -0700575 + callingUid + " pid=" + callingPid + " fgRequired=" + fgRequired + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700576 } else if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800577 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700578 } else {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800579 Slog.v(TAG_SERVICE,
580 "Not potential delay (user " + r.userId + " not started): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700581 }
582 }
583
Christopher Tate42a386b2016-11-07 12:21:21 -0800584 ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
Christopher Tate42a386b2016-11-07 12:21:21 -0800585 return cmp;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700586 }
587
Svet Ganov9c165d72015-12-01 19:52:26 -0800588 private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
589 String callingPackage, int callingUid, Intent service, boolean callerFg,
590 final int userId) {
591 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
592 r.packageName, r.userId)) {
593
594 // Show a permission review UI only for starting from a foreground app
595 if (!callerFg) {
596 Slog.w(TAG, "u" + r.userId + " Starting a service in package"
597 + r.packageName + " requires a permissions review");
598 return false;
599 }
600
601 IIntentSender target = mAm.getIntentSenderLocked(
602 ActivityManager.INTENT_SENDER_SERVICE, callingPackage,
603 callingUid, userId, null, null, 0, new Intent[]{service},
604 new String[]{service.resolveType(mAm.mContext.getContentResolver())},
605 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
606 | PendingIntent.FLAG_IMMUTABLE, null);
607
608 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
609 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
610 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
611 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
612 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
613
614 if (DEBUG_PERMISSIONS_REVIEW) {
615 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
616 + r.packageName);
617 }
618
619 mAm.mHandler.post(new Runnable() {
620 @Override
621 public void run() {
622 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
623 }
624 });
625
626 return false;
627 }
628
629 return true;
630 }
631
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700632 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
633 boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
Joe Onorato4eb64fd2016-03-21 15:30:09 -0700634 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700635 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700636 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700637 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700638 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700639 synchronized (r.stats.getBatteryStats()) {
640 r.stats.startRunningLocked();
641 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800642 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700643 if (error != null) {
644 return new ComponentName("!!", error);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700645 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700646
647 if (r.startRequested && addToStarting) {
648 boolean first = smap.mStartingBackground.size() == 0;
649 smap.mStartingBackground.add(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700650 r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700651 if (DEBUG_DELAYED_SERVICE) {
652 RuntimeException here = new RuntimeException("here");
653 here.fillInStackTrace();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800654 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800655 } else if (DEBUG_DELAYED_STARTS) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800656 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700657 }
658 if (first) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700659 smap.rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700660 }
Christopher Tate08992ac2017-03-21 11:37:06 -0700661 } else if (callerFg || r.fgRequired) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700662 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700663 }
664
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700665 return r.name;
666 }
667
668 private void stopServiceLocked(ServiceRecord service) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700669 if (service.delayed) {
670 // If service isn't actually running, but is is being held in the
671 // delayed list, then we need to keep it started but note that it
672 // should be stopped once no longer delayed.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800673 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700674 service.delayedStop = true;
675 return;
676 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700677 synchronized (service.stats.getBatteryStats()) {
678 service.stats.stopRunningLocked();
679 }
680 service.startRequested = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700681 if (service.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700682 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700683 SystemClock.uptimeMillis());
684 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700685 service.callStart = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700686 bringDownServiceIfNeededLocked(service, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700687 }
688
689 int stopServiceLocked(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700690 String resolvedType, int userId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800691 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700692 + " type=" + resolvedType);
693
694 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
695 if (caller != null && callerApp == null) {
696 throw new SecurityException(
697 "Unable to find app for caller " + caller
698 + " (pid=" + Binder.getCallingPid()
699 + ") when stopping service " + service);
700 }
701
702 // If this service is active, make sure it is stopped.
Svet Ganov99b60432015-06-27 13:15:22 -0700703 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, null,
Svet Ganovd223db32017-12-22 09:43:48 -0800704 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700705 if (r != null) {
706 if (r.record != null) {
707 final long origId = Binder.clearCallingIdentity();
708 try {
709 stopServiceLocked(r.record);
710 } finally {
711 Binder.restoreCallingIdentity(origId);
712 }
713 return 1;
714 }
715 return -1;
716 }
717
718 return 0;
719 }
720
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700721 void stopInBackgroundLocked(int uid) {
722 // Stop all services associated with this uid due to it going to the background
723 // stopped state.
724 ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
725 ArrayList<ServiceRecord> stopping = null;
726 if (services != null) {
727 for (int i=services.mServicesByName.size()-1; i>=0; i--) {
728 ServiceRecord service = services.mServicesByName.valueAt(i);
729 if (service.appInfo.uid == uid && service.startRequested) {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800730 if (mAm.getAppStartModeLocked(service.appInfo.uid, service.packageName,
Christopher Tatec7933ac2018-03-12 17:57:09 -0700731 service.appInfo.targetSdkVersion, -1, false, false, false)
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800732 != ActivityManager.APP_START_MODE_NORMAL) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700733 if (stopping == null) {
734 stopping = new ArrayList<>();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700735 }
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700736 String compName = service.name.flattenToShortString();
737 EventLogTags.writeAmStopIdleService(service.appInfo.uid, compName);
738 StringBuilder sb = new StringBuilder(64);
739 sb.append("Stopping service due to app idle: ");
740 UserHandle.formatUid(sb, service.appInfo.uid);
741 sb.append(" ");
Yi Jin6b514142017-10-30 14:54:12 -0700742 TimeUtils.formatDuration(service.createRealTime
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700743 - SystemClock.elapsedRealtime(), sb);
744 sb.append(" ");
745 sb.append(compName);
746 Slog.w(TAG, sb.toString());
747 stopping.add(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700748 }
749 }
750 }
751 if (stopping != null) {
752 for (int i=stopping.size()-1; i>=0; i--) {
753 ServiceRecord service = stopping.get(i);
754 service.delayed = false;
Dianne Hackbornad51be92016-08-16 16:27:36 -0700755 services.ensureNotStartingBackgroundLocked(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700756 stopServiceLocked(service);
757 }
758 }
759 }
760 }
761
Svet Ganov99b60432015-06-27 13:15:22 -0700762 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
763 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, callingPackage,
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -0700764 Binder.getCallingPid(), Binder.getCallingUid(),
Svet Ganovd223db32017-12-22 09:43:48 -0800765 UserHandle.getCallingUserId(), false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700766
767 IBinder ret = null;
768 if (r != null) {
769 // r.record is null if findServiceLocked() failed the caller permission check
770 if (r.record == null) {
771 throw new SecurityException(
Christopher Desjardins5862c5f2015-05-19 11:25:40 +0000772 "Permission Denial: Accessing service"
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700773 + " from pid=" + Binder.getCallingPid()
774 + ", uid=" + Binder.getCallingUid()
775 + " requires " + r.permission);
776 }
777 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
778 if (ib != null) {
779 ret = ib.binder;
780 }
781 }
782
783 return ret;
784 }
785
786 boolean stopServiceTokenLocked(ComponentName className, IBinder token,
787 int startId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800788 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700789 + " " + token + " startId=" + startId);
Dianne Hackborn41203752012-08-31 14:05:51 -0700790 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700791 if (r != null) {
792 if (startId >= 0) {
793 // Asked to only stop if done with all work. Note that
794 // to avoid leaks, we will take this as dropping all
795 // start items up to and including this one.
796 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
797 if (si != null) {
798 while (r.deliveredStarts.size() > 0) {
799 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
800 cur.removeUriPermissionsLocked();
801 if (cur == si) {
802 break;
803 }
804 }
805 }
806
807 if (r.getLastStartId() != startId) {
808 return false;
809 }
810
811 if (r.deliveredStarts.size() > 0) {
812 Slog.w(TAG, "stopServiceToken startId " + startId
813 + " is last, but have " + r.deliveredStarts.size()
814 + " remaining args");
815 }
816 }
817
818 synchronized (r.stats.getBatteryStats()) {
819 r.stats.stopRunningLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700820 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700821 r.startRequested = false;
822 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700823 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700824 SystemClock.uptimeMillis());
825 }
826 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700827 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700828 bringDownServiceIfNeededLocked(r, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700829 Binder.restoreCallingIdentity(origId);
830 return true;
831 }
832 return false;
833 }
834
Sudheer Shankac9d94072017-02-22 22:13:55 +0000835 public void setServiceForegroundLocked(ComponentName className, IBinder token,
Dianne Hackborn67324c92016-04-18 13:55:25 -0700836 int id, Notification notification, int flags) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700837 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700838 final long origId = Binder.clearCallingIdentity();
839 try {
Dianne Hackborn41203752012-08-31 14:05:51 -0700840 ServiceRecord r = findServiceLocked(className, token, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700841 if (r != null) {
Sudheer Shankac9d94072017-02-22 22:13:55 +0000842 setServiceForegroundInnerLocked(r, id, notification, flags);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700843 }
844 } finally {
845 Binder.restoreCallingIdentity(origId);
846 }
847 }
848
Dianne Hackborncb015632017-06-14 17:30:15 -0700849 boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) {
850 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid="
851 + aa.mUid);
852 boolean canRemove = false;
853 aa.mHideTime = Long.MAX_VALUE;
854 if (aa.mShownWhileTop) {
855 // If the app was ever at the top of the screen while the foreground
856 // service was running, then we can always just immediately remove it.
857 canRemove = true;
858 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown while on top");
859 } else if (mScreenOn || aa.mShownWhileScreenOn) {
860 final long minTime = aa.mStartVisibleTime
861 + (aa.mStartTime != aa.mStartVisibleTime
862 ? mAm.mConstants.FGSERVICE_SCREEN_ON_AFTER_TIME
863 : mAm.mConstants.FGSERVICE_MIN_SHOWN_TIME);
864 if (nowElapsed >= minTime) {
865 // If shown while the screen is on, and it has been shown for
866 // at least the minimum show time, then we can now remove it.
867 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown long enough with screen on");
868 canRemove = true;
869 } else {
870 // This is when we will be okay to stop telling the user.
871 long reportTime = nowElapsed + mAm.mConstants.FGSERVICE_MIN_REPORT_TIME;
872 aa.mHideTime = reportTime > minTime ? reportTime : minTime;
873 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
874 + " with screen on");
875 }
876 } else {
877 final long minTime = aa.mEndTime
878 + mAm.mConstants.FGSERVICE_SCREEN_ON_BEFORE_TIME;
879 if (nowElapsed >= minTime) {
880 // If the foreground service has only run while the screen is
881 // off, but it has been gone now for long enough that we won't
882 // care to tell the user about it when the screen comes back on,
883 // then we can remove it now.
884 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - gone long enough with screen off");
885 canRemove = true;
886 } else {
887 // This is when we won't care about this old fg service.
888 aa.mHideTime = minTime;
889 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
890 + " with screen off");
891 }
892 }
893 return canRemove;
894 }
895
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700896 void updateForegroundApps(ServiceMap smap) {
897 // This is called from the handler without the lock held.
898 ArrayList<ActiveForegroundApp> active = null;
899 synchronized (mAm) {
900 final long now = SystemClock.elapsedRealtime();
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700901 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700902 if (smap != null) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700903 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Updating foreground apps for user "
904 + smap.mUserId);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700905 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
906 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -0700907 if (aa.mEndTime != 0) {
908 boolean canRemove = foregroundAppShownEnoughLocked(aa, now);
909 if (canRemove) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700910 // This was up for longer than the timeout, so just remove immediately.
911 smap.mActiveForegroundApps.removeAt(i);
912 smap.mActiveForegroundAppsChanged = true;
913 continue;
914 }
Dianne Hackborncb015632017-06-14 17:30:15 -0700915 if (aa.mHideTime < nextUpdateTime) {
916 nextUpdateTime = aa.mHideTime;
917 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700918 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700919 if (!aa.mAppOnTop) {
920 if (active == null) {
921 active = new ArrayList<>();
922 }
Dianne Hackborncb015632017-06-14 17:30:15 -0700923 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
924 + aa.mPackageName + ", uid=" + aa.mUid);
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700925 active.add(aa);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700926 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700927 }
928 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
929 if (nextUpdateTime < Long.MAX_VALUE) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700930 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Next update time in: "
931 + (nextUpdateTime-now));
932 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700933 smap.sendMessageAtTime(msg, nextUpdateTime
934 + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700935 }
936 }
937 if (!smap.mActiveForegroundAppsChanged) {
938 return;
939 }
940 smap.mActiveForegroundAppsChanged = false;
941 }
942
943 final NotificationManager nm = (NotificationManager) mAm.mContext.getSystemService(
944 Context.NOTIFICATION_SERVICE);
945 final Context context = mAm.mContext;
946
947 if (active != null) {
948 for (int i = 0; i < active.size(); i++) {
949 ActiveForegroundApp aa = active.get(i);
950 if (aa.mLabel == null) {
951 PackageManager pm = context.getPackageManager();
952 try {
953 ApplicationInfo ai = pm.getApplicationInfoAsUser(aa.mPackageName,
954 PackageManager.MATCH_KNOWN_PACKAGES, smap.mUserId);
955 aa.mLabel = ai.loadLabel(pm);
956 } catch (PackageManager.NameNotFoundException e) {
957 aa.mLabel = aa.mPackageName;
958 }
959 }
960 }
961
962 Intent intent;
963 String title;
964 String msg;
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700965 String[] pkgs;
Dan Sandler886e0162017-06-06 14:23:43 -0400966 final long nowElapsed = SystemClock.elapsedRealtime();
967 long oldestStartTime = nowElapsed;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700968 if (active.size() == 1) {
969 intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
970 intent.setData(Uri.fromParts("package", active.get(0).mPackageName, null));
971 title = context.getString(
972 R.string.foreground_service_app_in_background, active.get(0).mLabel);
973 msg = context.getString(R.string.foreground_service_tap_for_details);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700974 pkgs = new String[] { active.get(0).mPackageName };
Dan Sandler2f36ab82017-05-25 00:15:49 -0400975 oldestStartTime = active.get(0).mStartTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700976 } else {
977 intent = new Intent(Settings.ACTION_FOREGROUND_SERVICES_SETTINGS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700978 pkgs = new String[active.size()];
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700979 for (int i = 0; i < active.size(); i++) {
980 pkgs[i] = active.get(i).mPackageName;
Dan Sandler2f36ab82017-05-25 00:15:49 -0400981 oldestStartTime = Math.min(oldestStartTime, active.get(i).mStartTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700982 }
983 intent.putExtra("packages", pkgs);
984 title = context.getString(
985 R.string.foreground_service_apps_in_background, active.size());
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700986 msg = active.get(0).mLabel.toString();
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700987 for (int i = 1; i < active.size(); i++) {
988 msg = context.getString(R.string.foreground_service_multiple_separator,
989 msg, active.get(i).mLabel);
990 }
991 }
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700992 Bundle notificationBundle = new Bundle();
993 notificationBundle.putStringArray(Notification.EXTRA_FOREGROUND_APPS, pkgs);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700994 Notification.Builder n =
995 new Notification.Builder(context,
996 SystemNotificationChannels.FOREGROUND_SERVICE)
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700997 .addExtras(notificationBundle)
Dan Sandler2f36ab82017-05-25 00:15:49 -0400998 .setSmallIcon(R.drawable.stat_sys_vitals)
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700999 .setOngoing(true)
Dan Sandler886e0162017-06-06 14:23:43 -04001000 .setShowWhen(oldestStartTime < nowElapsed)
1001 .setWhen(System.currentTimeMillis() - (nowElapsed - oldestStartTime))
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001002 .setColor(context.getColor(
1003 com.android.internal.R.color.system_notification_accent_color))
1004 .setContentTitle(title)
1005 .setContentText(msg)
1006 .setContentIntent(
1007 PendingIntent.getActivityAsUser(context, 0, intent,
1008 PendingIntent.FLAG_UPDATE_CURRENT,
1009 null, new UserHandle(smap.mUserId)));
1010 nm.notifyAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1011 n.build(), new UserHandle(smap.mUserId));
1012 } else {
1013 nm.cancelAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1014 new UserHandle(smap.mUserId));
1015 }
1016 }
1017
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001018 private void requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001019 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001020 if (timeElapsed != 0) {
1021 smap.sendMessageAtTime(msg,
1022 timeElapsed + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001023 } else {
1024 smap.mActiveForegroundAppsChanged = true;
1025 smap.sendMessage(msg);
1026 }
1027 }
1028
1029 private void decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r) {
1030 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1031 if (active != null) {
1032 active.mNumActive--;
1033 if (active.mNumActive <= 0) {
1034 active.mEndTime = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001035 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Ended running of service");
1036 if (foregroundAppShownEnoughLocked(active, active.mEndTime)) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001037 // Have been active for long enough that we will remove it immediately.
1038 smap.mActiveForegroundApps.remove(r.packageName);
1039 smap.mActiveForegroundAppsChanged = true;
1040 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001041 } else if (active.mHideTime < Long.MAX_VALUE){
1042 requestUpdateActiveForegroundAppsLocked(smap, active.mHideTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001043 }
1044 }
1045 }
1046 }
1047
1048 void updateScreenStateLocked(boolean screenOn) {
1049 if (mScreenOn != screenOn) {
1050 mScreenOn = screenOn;
1051
1052 // If screen is turning on, then we now reset the start time of any foreground
1053 // services that were started while the screen was off.
1054 if (screenOn) {
1055 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001056 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Screen turned on");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001057 for (int i = mServiceMap.size()-1; i >= 0; i--) {
1058 ServiceMap smap = mServiceMap.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -07001059 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001060 boolean changed = false;
1061 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1062 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
Dianne Hackborncb015632017-06-14 17:30:15 -07001063 if (active.mEndTime == 0) {
1064 if (!active.mShownWhileScreenOn) {
1065 active.mShownWhileScreenOn = true;
1066 active.mStartVisibleTime = nowElapsed;
1067 }
1068 } else {
1069 if (!active.mShownWhileScreenOn
1070 && active.mStartVisibleTime == active.mStartTime) {
1071 // If this was never shown while the screen was on, then we will
1072 // count the time it started being visible as now, to tell the user
1073 // about it now that they have a screen to look at.
1074 active.mEndTime = active.mStartVisibleTime = nowElapsed;
1075 }
1076 if (foregroundAppShownEnoughLocked(active, nowElapsed)) {
1077 // Have been active for long enough that we will remove it
1078 // immediately.
1079 smap.mActiveForegroundApps.remove(active.mPackageName);
1080 smap.mActiveForegroundAppsChanged = true;
1081 changed = true;
1082 } else {
1083 if (active.mHideTime < nextUpdateTime) {
1084 nextUpdateTime = active.mHideTime;
1085 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001086 }
1087 }
1088 }
1089 if (changed) {
Dianne Hackborncb015632017-06-14 17:30:15 -07001090 // Need to immediately update.
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001091 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001092 } else if (nextUpdateTime < Long.MAX_VALUE) {
1093 requestUpdateActiveForegroundAppsLocked(smap, nextUpdateTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001094 }
1095 }
1096 }
1097 }
1098 }
1099
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001100 void foregroundServiceProcStateChangedLocked(UidRecord uidRec) {
1101 ServiceMap smap = mServiceMap.get(UserHandle.getUserId(uidRec.uid));
1102 if (smap != null) {
1103 boolean changed = false;
1104 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1105 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
1106 if (active.mUid == uidRec.uid) {
1107 if (uidRec.curProcState <= ActivityManager.PROCESS_STATE_TOP) {
1108 if (!active.mAppOnTop) {
1109 active.mAppOnTop = true;
1110 changed = true;
1111 }
1112 active.mShownWhileTop = true;
1113 } else if (active.mAppOnTop) {
1114 active.mAppOnTop = false;
1115 changed = true;
1116 }
1117 }
1118 }
1119 if (changed) {
1120 requestUpdateActiveForegroundAppsLocked(smap, 0);
1121 }
1122 }
1123 }
1124
Christopher Tatec7933ac2018-03-12 17:57:09 -07001125 /**
1126 * @param id Notification ID. Zero === exit foreground state for the given service.
1127 */
1128 private void setServiceForegroundInnerLocked(final ServiceRecord r, int id,
Christopher Tate42a386b2016-11-07 12:21:21 -08001129 Notification notification, int flags) {
1130 if (id != 0) {
1131 if (notification == null) {
1132 throw new IllegalArgumentException("null notification");
1133 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001134 // Instant apps need permission to create foreground services.
1135 if (r.appInfo.isInstantApp()) {
1136 final int mode = mAm.mAppOpsService.checkOperation(
1137 AppOpsManager.OP_INSTANT_APP_START_FOREGROUND,
1138 r.appInfo.uid,
1139 r.appInfo.packageName);
1140 switch (mode) {
1141 case AppOpsManager.MODE_ALLOWED:
1142 break;
1143 case AppOpsManager.MODE_IGNORED:
1144 Slog.w(TAG, "Instant app " + r.appInfo.packageName
1145 + " does not have permission to create foreground services"
1146 + ", ignoring.");
Sudheer Shankac9d94072017-02-22 22:13:55 +00001147 return;
Chad Brubaker97b383f2017-02-02 15:04:35 -08001148 case AppOpsManager.MODE_ERRORED:
1149 throw new SecurityException("Instant app " + r.appInfo.packageName
1150 + " does not have permission to create foreground services");
1151 default:
Dianne Hackborndd027b32018-01-19 17:44:46 -08001152 mAm.enforcePermission(
1153 android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
1154 r.app.pid, r.appInfo.uid, "startForeground");
Chad Brubaker97b383f2017-02-02 15:04:35 -08001155 }
Dianne Hackborndd027b32018-01-19 17:44:46 -08001156 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
1157 mAm.enforcePermission(
1158 android.Manifest.permission.FOREGROUND_SERVICE,
1159 r.app.pid, r.appInfo.uid, "startForeground");
Chad Brubaker97b383f2017-02-02 15:04:35 -08001160 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001161 boolean alreadyStartedOp = false;
Christopher Tate08992ac2017-03-21 11:37:06 -07001162 if (r.fgRequired) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001163 if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001164 Slog.i(TAG, "Service called startForeground() as required: " + r);
1165 }
1166 r.fgRequired = false;
1167 r.fgWaiting = false;
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001168 alreadyStartedOp = true;
Christopher Tate08992ac2017-03-21 11:37:06 -07001169 mAm.mHandler.removeMessages(
1170 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
1171 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001172
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001173 try {
1174 boolean ignoreForeground = false;
1175 final int mode = mAm.mAppOpsService.checkOperation(
1176 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
1177 switch (mode) {
1178 case AppOpsManager.MODE_ALLOWED:
1179 case AppOpsManager.MODE_DEFAULT:
1180 // All okay.
1181 break;
1182 case AppOpsManager.MODE_IGNORED:
1183 // Whoops, silently ignore this.
1184 Slog.w(TAG, "Service.startForeground() not allowed due to app op: service "
1185 + r.shortName);
1186 ignoreForeground = true;
1187 break;
1188 default:
1189 throw new SecurityException("Foreground not allowed as per app op");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001190 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001191
1192 if (!ignoreForeground &&
1193 appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
1194 ignoreForeground = true;
1195 Slog.w(TAG,
1196 "Service.startForeground() not allowed due to bg restriction: service "
1197 + r.shortName);
1198 }
1199
1200 // Apps under strict background restrictions simply don't get to have foreground
1201 // services, so now that we've enforced the startForegroundService() contract
1202 // we only do the machinery of making the service foreground when the app
1203 // is not restricted.
1204 if (!ignoreForeground) {
1205 if (r.foregroundId != id) {
1206 cancelForegroundNotificationLocked(r);
1207 r.foregroundId = id;
Christopher Tatec7933ac2018-03-12 17:57:09 -07001208 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001209 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
1210 r.foregroundNoti = notification;
1211 if (!r.isForeground) {
1212 final ServiceMap smap = getServiceMapLocked(r.userId);
1213 if (smap != null) {
1214 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1215 if (active == null) {
1216 active = new ActiveForegroundApp();
1217 active.mPackageName = r.packageName;
1218 active.mUid = r.appInfo.uid;
1219 active.mShownWhileScreenOn = mScreenOn;
1220 if (r.app != null) {
1221 active.mAppOnTop = active.mShownWhileTop =
1222 r.app.uidRecord.curProcState
1223 <= ActivityManager.PROCESS_STATE_TOP;
1224 }
1225 active.mStartTime = active.mStartVisibleTime
1226 = SystemClock.elapsedRealtime();
1227 smap.mActiveForegroundApps.put(r.packageName, active);
1228 requestUpdateActiveForegroundAppsLocked(smap, 0);
1229 }
1230 active.mNumActive++;
1231 }
1232 r.isForeground = true;
1233 mAm.mAppOpsService.startOperation(
1234 AppOpsManager.getToken(mAm.mAppOpsService),
1235 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName,
1236 true);
1237 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
1238 r.appInfo.uid, r.shortName,
1239 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER);
1240 }
1241 r.postNotification();
1242 if (r.app != null) {
1243 updateServiceForegroundLocked(r.app, true);
1244 }
1245 getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
1246 mAm.notifyPackageUse(r.serviceInfo.packageName,
1247 PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
1248 } else {
1249 if (DEBUG_FOREGROUND_SERVICE) {
1250 Slog.d(TAG, "Suppressing startForeground() for FAS " + r);
1251 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001252 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001253 } finally {
1254 if (alreadyStartedOp) {
1255 // If we had previously done a start op for direct foreground start,
1256 // we have cleared the flag so can now drop it.
1257 mAm.mAppOpsService.finishOperation(
1258 AppOpsManager.getToken(mAm.mAppOpsService),
1259 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001260 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001261 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001262 } else {
1263 if (r.isForeground) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001264 final ServiceMap smap = getServiceMapLocked(r.userId);
1265 if (smap != null) {
1266 decActiveForegroundAppLocked(smap, r);
1267 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001268 r.isForeground = false;
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001269 mAm.mAppOpsService.finishOperation(
1270 AppOpsManager.getToken(mAm.mAppOpsService),
1271 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001272 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
1273 r.appInfo.uid, r.shortName,
Chenjie Yuccfe6452018-01-30 11:33:21 -08001274 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Christopher Tate42a386b2016-11-07 12:21:21 -08001275 if (r.app != null) {
1276 mAm.updateLruProcessLocked(r.app, false, null);
1277 updateServiceForegroundLocked(r.app, true);
1278 }
1279 }
1280 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001281 cancelForegroundNotificationLocked(r);
Christopher Tate42a386b2016-11-07 12:21:21 -08001282 r.foregroundId = 0;
1283 r.foregroundNoti = null;
1284 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1285 r.stripForegroundServiceFlagFromNotification();
1286 if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
1287 r.foregroundId = 0;
1288 r.foregroundNoti = null;
1289 }
1290 }
1291 }
1292 }
1293
Christopher Tate08992ac2017-03-21 11:37:06 -07001294 private void cancelForegroundNotificationLocked(ServiceRecord r) {
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001295 if (r.foregroundId != 0) {
1296 // First check to see if this app has any other active foreground services
1297 // with the same notification ID. If so, we shouldn't actually cancel it,
1298 // because that would wipe away the notification that still needs to be shown
1299 // due the other service.
Dianne Hackbornad51be92016-08-16 16:27:36 -07001300 ServiceMap sm = getServiceMapLocked(r.userId);
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001301 if (sm != null) {
1302 for (int i = sm.mServicesByName.size()-1; i >= 0; i--) {
1303 ServiceRecord other = sm.mServicesByName.valueAt(i);
Dianne Hackborn569a4582016-08-04 14:00:22 -07001304 if (other != r && other.foregroundId == r.foregroundId
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001305 && other.packageName.equals(r.packageName)) {
1306 // Found one! Abort the cancel.
1307 return;
1308 }
1309 }
1310 }
1311 r.cancelNotification();
1312 }
1313 }
1314
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001315 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
1316 boolean anyForeground = false;
Dianne Hackbornc8230512013-07-13 21:32:12 -07001317 for (int i=proc.services.size()-1; i>=0; i--) {
1318 ServiceRecord sr = proc.services.valueAt(i);
Christopher Tatee23fa2b2017-04-20 14:48:13 -07001319 if (sr.isForeground || sr.fgRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001320 anyForeground = true;
1321 break;
1322 }
1323 }
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08001324 mAm.updateProcessForegroundLocked(proc, anyForeground, oomAdj);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001325 }
1326
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001327 private void updateWhitelistManagerLocked(ProcessRecord proc) {
1328 proc.whitelistManager = false;
1329 for (int i=proc.services.size()-1; i>=0; i--) {
1330 ServiceRecord sr = proc.services.valueAt(i);
1331 if (sr.whitelistManager) {
1332 proc.whitelistManager = true;
1333 break;
1334 }
1335 }
1336 }
1337
Dianne Hackborn465fa392014-09-14 14:21:18 -07001338 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
1339 ArraySet<ProcessRecord> updatedProcesses = null;
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001340 for (int i = 0; i < clientProc.connections.size(); i++) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001341 final ConnectionRecord conn = clientProc.connections.valueAt(i);
1342 final ProcessRecord proc = conn.binding.service.app;
1343 if (proc == null || proc == clientProc) {
1344 continue;
1345 } else if (updatedProcesses == null) {
1346 updatedProcesses = new ArraySet<>();
1347 } else if (updatedProcesses.contains(proc)) {
1348 continue;
1349 }
1350 updatedProcesses.add(proc);
1351 updateServiceClientActivitiesLocked(proc, null, false);
1352 }
1353 }
1354
Dianne Hackborndb926082013-10-31 16:32:44 -07001355 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
Dianne Hackborn465fa392014-09-14 14:21:18 -07001356 ConnectionRecord modCr, boolean updateLru) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001357 if (modCr != null && modCr.binding.client != null) {
1358 if (modCr.binding.client.activities.size() <= 0) {
1359 // This connection is from a client without activities, so adding
1360 // and removing is not interesting.
1361 return false;
1362 }
1363 }
1364
1365 boolean anyClientActivities = false;
1366 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
1367 ServiceRecord sr = proc.services.valueAt(i);
1368 for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) {
1369 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni);
1370 for (int cri=clist.size()-1; cri>=0; cri--) {
1371 ConnectionRecord cr = clist.get(cri);
1372 if (cr.binding.client == null || cr.binding.client == proc) {
1373 // Binding to ourself is not interesting.
1374 continue;
1375 }
1376 if (cr.binding.client.activities.size() > 0) {
1377 anyClientActivities = true;
1378 break;
1379 }
1380 }
1381 }
1382 }
1383 if (anyClientActivities != proc.hasClientActivities) {
1384 proc.hasClientActivities = anyClientActivities;
Dianne Hackborn465fa392014-09-14 14:21:18 -07001385 if (updateLru) {
1386 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
1387 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001388 return true;
1389 }
1390 return false;
1391 }
1392
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001393 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
Svet Ganov9c165d72015-12-01 19:52:26 -08001394 String resolvedType, final IServiceConnection connection, int flags,
1395 String callingPackage, final int userId) throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001396 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001397 + " type=" + resolvedType + " conn=" + connection.asBinder()
1398 + " flags=0x" + Integer.toHexString(flags));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001399 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
1400 if (callerApp == null) {
1401 throw new SecurityException(
1402 "Unable to find app for caller " + caller
1403 + " (pid=" + Binder.getCallingPid()
1404 + ") when binding service " + service);
1405 }
1406
1407 ActivityRecord activity = null;
1408 if (token != null) {
Craig Mautnerd2328952013-03-05 12:46:26 -08001409 activity = ActivityRecord.isInStackLocked(token);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001410 if (activity == null) {
1411 Slog.w(TAG, "Binding with unknown activity: " + token);
1412 return 0;
1413 }
1414 }
1415
1416 int clientLabel = 0;
1417 PendingIntent clientIntent = null;
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001418 final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001419
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001420 if (isCallerSystem) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001421 // Hacky kind of thing -- allow system stuff to tell us
1422 // what they are, so we can report this elsewhere for
1423 // others to know why certain services are running.
Jeff Sharkeyf0ec2e02016-03-21 12:37:54 -06001424 service.setDefusable(true);
1425 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001426 if (clientIntent != null) {
1427 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
1428 if (clientLabel != 0) {
1429 // There are no useful extras in the intent, trash them.
1430 // System code calling with this stuff just needs to know
1431 // this will happen.
1432 service = service.cloneFilter();
1433 }
1434 }
1435 }
1436
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001437 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1438 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
1439 "BIND_TREAT_LIKE_ACTIVITY");
1440 }
1441
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001442 if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
1443 throw new SecurityException(
1444 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1445 + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
1446 }
1447
Svet Ganovd223db32017-12-22 09:43:48 -08001448 if ((flags & Context.BIND_ALLOW_INSTANT) != 0 && !isCallerSystem) {
1449 throw new SecurityException(
1450 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1451 + ") set BIND_ALLOW_INSTANT when binding service " + service);
1452 }
1453
Dianne Hackborna49ad092016-03-03 13:39:10 -08001454 final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Robert Sesekb9a86662015-12-09 16:22:45 -05001455 final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
Svet Ganovd223db32017-12-22 09:43:48 -08001456 final boolean allowInstant = (flags & Context.BIND_ALLOW_INSTANT) != 0;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001457
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001458 ServiceLookupResult res =
Robert Sesekb9a86662015-12-09 16:22:45 -05001459 retrieveServiceLocked(service, resolvedType, callingPackage, Binder.getCallingPid(),
Svet Ganovd223db32017-12-22 09:43:48 -08001460 Binder.getCallingUid(), userId, true, callerFg, isBindExternal, allowInstant);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001461 if (res == null) {
1462 return 0;
1463 }
1464 if (res.record == null) {
1465 return -1;
1466 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001467 ServiceRecord s = res.record;
1468
Svet Ganov9c165d72015-12-01 19:52:26 -08001469 boolean permissionsReviewRequired = false;
1470
1471 // If permissions need a review before any of the app components can run,
1472 // we schedule binding to the service but do not start its process, then
1473 // we launch a review activity to which is passed a callback to invoke
1474 // when done to start the bound service's process to completing the binding.
Svet Ganov77df6f32016-08-17 11:46:34 -07001475 if (mAm.mPermissionReviewRequired) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001476 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
1477 s.packageName, s.userId)) {
1478
1479 permissionsReviewRequired = true;
1480
1481 // Show a permission review UI only for binding from a foreground app
1482 if (!callerFg) {
1483 Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
1484 + s.packageName + " requires a permissions review");
1485 return 0;
1486 }
1487
1488 final ServiceRecord serviceRecord = s;
1489 final Intent serviceIntent = service;
1490
1491 RemoteCallback callback = new RemoteCallback(
1492 new RemoteCallback.OnResultListener() {
1493 @Override
1494 public void onResult(Bundle result) {
1495 synchronized(mAm) {
1496 final long identity = Binder.clearCallingIdentity();
1497 try {
1498 if (!mPendingServices.contains(serviceRecord)) {
1499 return;
1500 }
1501 // If there is still a pending record, then the service
1502 // binding request is still valid, so hook them up. We
1503 // proceed only if the caller cleared the review requirement
1504 // otherwise we unbind because the user didn't approve.
1505 if (!mAm.getPackageManagerInternalLocked()
1506 .isPermissionsReviewRequired(
1507 serviceRecord.packageName,
1508 serviceRecord.userId)) {
1509 try {
1510 bringUpServiceLocked(serviceRecord,
1511 serviceIntent.getFlags(),
1512 callerFg, false, false);
1513 } catch (RemoteException e) {
1514 /* ignore - local call */
1515 }
1516 } else {
1517 unbindServiceLocked(connection);
1518 }
1519 } finally {
1520 Binder.restoreCallingIdentity(identity);
1521 }
1522 }
1523 }
1524 });
1525
1526 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
1527 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1528 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1529 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
1530 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
1531
1532 if (DEBUG_PERMISSIONS_REVIEW) {
1533 Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
1534 + s.packageName);
1535 }
1536
1537 mAm.mHandler.post(new Runnable() {
1538 @Override
1539 public void run() {
1540 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
1541 }
1542 });
1543 }
1544 }
1545
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001546 final long origId = Binder.clearCallingIdentity();
1547
1548 try {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001549 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001550 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001551 + s);
1552 }
1553
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001554 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1555 s.lastActivity = SystemClock.uptimeMillis();
1556 if (!s.hasAutoCreateConnections()) {
1557 // This is the first binding, let the tracker know.
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001558 ServiceState stracker = s.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001559 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001560 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001561 s.lastActivity);
1562 }
1563 }
1564 }
1565
Joe Onorato05c9ecc2016-03-30 15:13:46 -07001566 mAm.startAssociationLocked(callerApp.uid, callerApp.processName, callerApp.curProcState,
Dianne Hackbornab2df062015-01-07 13:43:13 -08001567 s.appInfo.uid, s.name, s.processName);
Jesse Evans02af3ea2017-05-03 09:57:16 -07001568 // Once the apps have become associated, if one of them is caller is ephemeral
1569 // the target app should now be able to see the calling app
1570 mAm.grantEphemeralAccessLocked(callerApp.userId, service,
1571 s.appInfo.uid, UserHandle.getAppId(callerApp.uid));
Dianne Hackbornab2df062015-01-07 13:43:13 -08001572
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001573 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
1574 ConnectionRecord c = new ConnectionRecord(b, activity,
1575 connection, flags, clientLabel, clientIntent);
1576
1577 IBinder binder = connection.asBinder();
1578 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
1579 if (clist == null) {
1580 clist = new ArrayList<ConnectionRecord>();
1581 s.connections.put(binder, clist);
1582 }
1583 clist.add(c);
1584 b.connections.add(c);
1585 if (activity != null) {
1586 if (activity.connections == null) {
1587 activity.connections = new HashSet<ConnectionRecord>();
1588 }
1589 activity.connections.add(c);
1590 }
1591 b.client.connections.add(c);
1592 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
1593 b.client.hasAboveClient = true;
1594 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001595 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
1596 s.whitelistManager = true;
1597 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001598 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001599 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07001600 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001601 clist = mServiceConnections.get(binder);
1602 if (clist == null) {
1603 clist = new ArrayList<ConnectionRecord>();
1604 mServiceConnections.put(binder, clist);
1605 }
1606 clist.add(c);
1607
1608 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1609 s.lastActivity = SystemClock.uptimeMillis();
Svet Ganov9c165d72015-12-01 19:52:26 -08001610 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
1611 permissionsReviewRequired) != null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001612 return 0;
1613 }
1614 }
1615
1616 if (s.app != null) {
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001617 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1618 s.app.treatLikeActivity = true;
1619 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001620 if (s.whitelistManager) {
1621 s.app.whitelistManager = true;
1622 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001623 // This could have made the service more important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001624 mAm.updateLruProcessLocked(s.app, s.app.hasClientActivities
1625 || s.app.treatLikeActivity, b.client);
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001626 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001627 }
1628
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001629 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001630 + ": received=" + b.intent.received
1631 + " apps=" + b.intent.apps.size()
1632 + " doRebind=" + b.intent.doRebind);
1633
1634 if (s.app != null && b.intent.received) {
1635 // Service is already running, so we can immediately
1636 // publish the connection.
1637 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001638 c.conn.connected(s.name, b.intent.binder, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001639 } catch (Exception e) {
1640 Slog.w(TAG, "Failure sending service " + s.shortName
1641 + " to connection " + c.conn.asBinder()
1642 + " (in " + c.binding.client.processName + ")", e);
1643 }
1644
1645 // If this is the first app connected back to this binding,
1646 // and the service had previously asked to be told when
1647 // rebound, then do so.
1648 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001649 requestServiceBindingLocked(s, b.intent, callerFg, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001650 }
1651 } else if (!b.intent.requested) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001652 requestServiceBindingLocked(s, b.intent, callerFg, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001653 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001654
Dianne Hackbornad51be92016-08-16 16:27:36 -07001655 getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001656
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001657 } finally {
1658 Binder.restoreCallingIdentity(origId);
1659 }
1660
1661 return 1;
1662 }
1663
1664 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
1665 final long origId = Binder.clearCallingIdentity();
1666 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001667 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001668 + " " + intent + ": " + service);
1669 if (r != null) {
1670 Intent.FilterComparison filter
1671 = new Intent.FilterComparison(intent);
1672 IntentBindRecord b = r.bindings.get(filter);
1673 if (b != null && !b.received) {
1674 b.binder = service;
1675 b.requested = true;
1676 b.received = true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07001677 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1678 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
1679 for (int i=0; i<clist.size(); i++) {
1680 ConnectionRecord c = clist.get(i);
1681 if (!filter.equals(c.binding.intent.intent)) {
1682 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001683 TAG_SERVICE, "Not publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001684 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001685 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001686 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001687 TAG_SERVICE, "Published intent: " + intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001688 continue;
1689 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001690 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001691 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001692 c.conn.connected(r.name, service, false);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001693 } catch (Exception e) {
1694 Slog.w(TAG, "Failure sending service " + r.name +
1695 " to connection " + c.conn.asBinder() +
1696 " (in " + c.binding.client.processName + ")", e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001697 }
1698 }
1699 }
1700 }
1701
Dianne Hackborn164371f2013-10-01 19:10:13 -07001702 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001703 }
1704 } finally {
1705 Binder.restoreCallingIdentity(origId);
1706 }
1707 }
1708
1709 boolean unbindServiceLocked(IServiceConnection connection) {
1710 IBinder binder = connection.asBinder();
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001711 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001712 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1713 if (clist == null) {
1714 Slog.w(TAG, "Unbind failed: could not find connection for "
1715 + connection.asBinder());
1716 return false;
1717 }
1718
1719 final long origId = Binder.clearCallingIdentity();
1720 try {
1721 while (clist.size() > 0) {
1722 ConnectionRecord r = clist.get(0);
1723 removeConnectionLocked(r, null, null);
Dianne Hackborn25e1eca2014-09-23 10:13:13 -07001724 if (clist.size() > 0 && clist.get(0) == r) {
1725 // In case it didn't get removed above, do it now.
1726 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
1727 clist.remove(0);
1728 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001729
1730 if (r.binding.service.app != null) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001731 if (r.binding.service.app.whitelistManager) {
Felipe Lemea7778b02016-06-28 10:38:59 -07001732 updateWhitelistManagerLocked(r.binding.service.app);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001733 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001734 // This could have made the service less important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001735 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1736 r.binding.service.app.treatLikeActivity = true;
1737 mAm.updateLruProcessLocked(r.binding.service.app,
1738 r.binding.service.app.hasClientActivities
1739 || r.binding.service.app.treatLikeActivity, null);
1740 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001741 mAm.updateOomAdjLocked(r.binding.service.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001742 }
1743 }
Amith Yamasanib2926b12017-05-11 11:13:52 -07001744
1745 mAm.updateOomAdjLocked();
1746
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001747 } finally {
1748 Binder.restoreCallingIdentity(origId);
1749 }
1750
1751 return true;
1752 }
1753
1754 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
1755 final long origId = Binder.clearCallingIdentity();
1756 try {
1757 if (r != null) {
1758 Intent.FilterComparison filter
1759 = new Intent.FilterComparison(intent);
1760 IntentBindRecord b = r.bindings.get(filter);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001761 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001762 + " at " + b + ": apps="
1763 + (b != null ? b.apps.size() : 0));
1764
Dianne Hackborn164371f2013-10-01 19:10:13 -07001765 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001766 if (b != null) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001767 if (b.apps.size() > 0 && !inDestroying) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001768 // Applications have already bound since the last
1769 // unbind, so just rebind right here.
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001770 boolean inFg = false;
1771 for (int i=b.apps.size()-1; i>=0; i--) {
1772 ProcessRecord client = b.apps.valueAt(i).client;
1773 if (client != null && client.setSchedGroup
Dianne Hackborna49ad092016-03-03 13:39:10 -08001774 != ProcessList.SCHED_GROUP_BACKGROUND) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001775 inFg = true;
1776 break;
1777 }
1778 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001779 try {
1780 requestServiceBindingLocked(r, b, inFg, true);
1781 } catch (TransactionTooLargeException e) {
1782 // Don't pass this back to ActivityThread, it's unrelated.
1783 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001784 } else {
1785 // Note to tell the service the next time there is
1786 // a new client.
1787 b.doRebind = true;
1788 }
1789 }
1790
Dianne Hackborn164371f2013-10-01 19:10:13 -07001791 serviceDoneExecutingLocked(r, inDestroying, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001792 }
1793 } finally {
1794 Binder.restoreCallingIdentity(origId);
1795 }
1796 }
1797
1798 private final ServiceRecord findServiceLocked(ComponentName name,
Dianne Hackborn41203752012-08-31 14:05:51 -07001799 IBinder token, int userId) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07001800 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001801 return r == token ? r : null;
1802 }
1803
1804 private final class ServiceLookupResult {
1805 final ServiceRecord record;
1806 final String permission;
1807
1808 ServiceLookupResult(ServiceRecord _record, String _permission) {
1809 record = _record;
1810 permission = _permission;
1811 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001812 }
1813
1814 private class ServiceRestarter implements Runnable {
1815 private ServiceRecord mService;
1816
1817 void setService(ServiceRecord service) {
1818 mService = service;
1819 }
1820
1821 public void run() {
1822 synchronized(mAm) {
1823 performServiceRestartLocked(mService);
1824 }
1825 }
1826 }
1827
1828 private ServiceLookupResult retrieveServiceLocked(Intent service,
Svet Ganov99b60432015-06-27 13:15:22 -07001829 String resolvedType, String callingPackage, int callingPid, int callingUid, int userId,
Svet Ganovd223db32017-12-22 09:43:48 -08001830 boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
1831 boolean allowInstant) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001832 ServiceRecord r = null;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001833 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001834 + " type=" + resolvedType + " callingUid=" + callingUid);
1835
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001836 userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
1837 ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE, "service", null);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001838
Dianne Hackbornad51be92016-08-16 16:27:36 -07001839 ServiceMap smap = getServiceMapLocked(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001840 final ComponentName comp = service.getComponent();
1841 if (comp != null) {
1842 r = smap.mServicesByName.get(comp);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001843 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001844 }
Robert Sesekb9a86662015-12-09 16:22:45 -05001845 if (r == null && !isBindExternal) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001846 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001847 r = smap.mServicesByIntent.get(filter);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001848 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001849 }
Robert Sesekb9a86662015-12-09 16:22:45 -05001850 if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
1851 && !callingPackage.equals(r.packageName)) {
1852 // If an external service is running within its own package, other packages
1853 // should not bind to that instance.
1854 r = null;
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001855 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Whoops, can't use existing external service");
Robert Sesekb9a86662015-12-09 16:22:45 -05001856 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001857 if (r == null) {
1858 try {
Svet Ganovd223db32017-12-22 09:43:48 -08001859 int flags = ActivityManagerService.STOCK_PM_FLAGS
1860 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
1861 if (allowInstant) {
1862 flags |= PackageManager.MATCH_INSTANT;
1863 }
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001864 // TODO: come back and remove this assumption to triage all services
Todd Kennedy51b3aac2017-03-30 17:50:42 -07001865 ResolveInfo rInfo = mAm.getPackageManagerInternalLocked().resolveService(service,
Svet Ganovd223db32017-12-22 09:43:48 -08001866 resolvedType, flags, userId, callingUid);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001867 ServiceInfo sInfo =
1868 rInfo != null ? rInfo.serviceInfo : null;
1869 if (sInfo == null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001870 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001871 ": not found");
1872 return null;
1873 }
1874 ComponentName name = new ComponentName(
1875 sInfo.applicationInfo.packageName, sInfo.name);
Robert Sesekb9a86662015-12-09 16:22:45 -05001876 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
1877 if (isBindExternal) {
1878 if (!sInfo.exported) {
1879 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1880 " is not exported");
1881 }
1882 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
1883 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1884 " is not an isolatedProcess");
1885 }
1886 // Run the service under the calling package's application.
1887 ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
1888 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
1889 if (aInfo == null) {
1890 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
1891 "could not resolve client package " + callingPackage);
1892 }
1893 sInfo = new ServiceInfo(sInfo);
1894 sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
1895 sInfo.applicationInfo.packageName = aInfo.packageName;
1896 sInfo.applicationInfo.uid = aInfo.uid;
1897 name = new ComponentName(aInfo.packageName, name.getClassName());
1898 service.setComponent(name);
1899 } else {
1900 throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
1901 name);
1902 }
1903 } else if (isBindExternal) {
1904 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1905 " is not an externalService");
1906 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001907 if (userId > 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001908 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
Amith Yamasani4b9d79c2014-05-21 19:14:21 -07001909 sInfo.name, sInfo.flags)
1910 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001911 userId = 0;
Dianne Hackbornad51be92016-08-16 16:27:36 -07001912 smap = getServiceMapLocked(0);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001913 }
1914 sInfo = new ServiceInfo(sInfo);
1915 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
1916 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001917 r = smap.mServicesByName.get(name);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001918 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE,
1919 "Retrieved via pm by intent: " + r);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001920 if (r == null && createIfNeeded) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001921 final Intent.FilterComparison filter
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001922 = new Intent.FilterComparison(service.cloneFilter());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001923 final ServiceRestarter res = new ServiceRestarter();
1924 final BatteryStatsImpl.Uid.Pkg.Serv ss;
1925 final BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001926 synchronized (stats) {
1927 ss = stats.getServiceStatsLocked(
1928 sInfo.applicationInfo.uid, sInfo.packageName,
1929 sInfo.name);
1930 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001931 r = new ServiceRecord(mAm, ss, name, filter, sInfo, callingFromFg, res);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001932 res.setService(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001933 smap.mServicesByName.put(name, r);
1934 smap.mServicesByIntent.put(filter, r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001935
1936 // Make sure this component isn't in the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001937 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001938 final ServiceRecord pr = mPendingServices.get(i);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001939 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
1940 && pr.name.equals(name)) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001941 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001942 mPendingServices.remove(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001943 }
1944 }
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001945 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001946 }
1947 } catch (RemoteException ex) {
1948 // pm is in same process, this will never happen.
1949 }
1950 }
1951 if (r != null) {
1952 if (mAm.checkComponentPermission(r.permission,
Bryce Lee290e5782017-02-01 16:41:20 -08001953 callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001954 if (!r.exported) {
1955 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1956 + " from pid=" + callingPid
1957 + ", uid=" + callingUid
1958 + " that is not exported from uid " + r.appInfo.uid);
1959 return new ServiceLookupResult(null, "not exported from uid "
1960 + r.appInfo.uid);
1961 }
1962 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1963 + " from pid=" + callingPid
1964 + ", uid=" + callingUid
1965 + " requires " + r.permission);
1966 return new ServiceLookupResult(null, r.permission);
Svet Ganov99b60432015-06-27 13:15:22 -07001967 } else if (r.permission != null && callingPackage != null) {
1968 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
1969 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation(
1970 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
1971 Slog.w(TAG, "Appop Denial: Accessing service " + r.name
1972 + " from pid=" + callingPid
1973 + ", uid=" + callingUid
1974 + " requires appop " + AppOpsManager.opToName(opCode));
1975 return null;
1976 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001977 }
Svet Ganov99b60432015-06-27 13:15:22 -07001978
Ben Gruverf5323fe2013-07-31 15:09:51 -07001979 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
1980 resolvedType, r.appInfo)) {
Ben Gruverb6223792013-07-29 16:35:40 -07001981 return null;
1982 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001983 return new ServiceLookupResult(r, null);
1984 }
1985 return null;
1986 }
1987
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001988 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001989 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001990 + why + " of " + r + " in app " + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001991 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001992 + why + " of " + r.shortName);
1993 long now = SystemClock.uptimeMillis();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001994 if (r.executeNesting == 0) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001995 r.executeFg = fg;
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001996 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001997 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001998 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001999 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002000 if (r.app != null) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002001 r.app.executingServices.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002002 r.app.execServicesFg |= fg;
Dianne Hackborn2be00932013-09-22 16:46:00 -07002003 if (r.app.executingServices.size() == 1) {
2004 scheduleServiceTimeoutLocked(r.app);
2005 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002006 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002007 } else if (r.app != null && fg && !r.app.execServicesFg) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002008 r.app.execServicesFg = true;
Dianne Hackborn2be00932013-09-22 16:46:00 -07002009 scheduleServiceTimeoutLocked(r.app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002010 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002011 r.executeFg |= fg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002012 r.executeNesting++;
2013 r.executingStart = now;
2014 }
2015
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002016 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
2017 boolean execInFg, boolean rebind) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002018 if (r.app == null || r.app.thread == null) {
2019 // If service is not currently running, can't yet bind.
2020 return false;
2021 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08002022 if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
2023 + " rebind=" + rebind);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002024 if ((!i.requested || rebind) && i.apps.size() > 0) {
2025 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002026 bumpServiceExecutingLocked(r, execInFg, "bind");
Dianne Hackborna413dc02013-07-12 12:02:55 -07002027 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
2028 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
2029 r.app.repProcState);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002030 if (!rebind) {
2031 i.requested = true;
2032 }
2033 i.hasBound = true;
2034 i.doRebind = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002035 } catch (TransactionTooLargeException e) {
2036 // Keep the executeNesting count accurate.
2037 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
2038 final boolean inDestroying = mDestroyingServices.contains(r);
2039 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2040 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002041 } catch (RemoteException e) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002042 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002043 // Keep the executeNesting count accurate.
2044 final boolean inDestroying = mDestroyingServices.contains(r);
2045 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002046 return false;
2047 }
2048 }
2049 return true;
2050 }
2051
Dianne Hackbornad51be92016-08-16 16:27:36 -07002052 private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002053 boolean canceled = false;
2054
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07002055 if (mAm.isShuttingDownLocked()) {
2056 Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortName
2057 + " - system is shutting down");
2058 return false;
2059 }
2060
Dianne Hackbornad51be92016-08-16 16:27:36 -07002061 ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002062 if (smap.mServicesByName.get(r.name) != r) {
2063 ServiceRecord cur = smap.mServicesByName.get(r.name);
2064 Slog.wtf(TAG, "Attempting to schedule restart of " + r
2065 + " when found in map: " + cur);
2066 return false;
2067 }
2068
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002069 final long now = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002070
2071 if ((r.serviceInfo.applicationInfo.flags
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002072 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002073 long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION;
2074 long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002075
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002076 // Any delivered but not yet finished starts should be put back
2077 // on the pending list.
2078 final int N = r.deliveredStarts.size();
2079 if (N > 0) {
2080 for (int i=N-1; i>=0; i--) {
2081 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
2082 si.removeUriPermissionsLocked();
2083 if (si.intent == null) {
2084 // We'll generate this again if needed.
2085 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
2086 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
2087 r.pendingStarts.add(0, si);
2088 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
2089 dur *= 2;
2090 if (minDuration < dur) minDuration = dur;
2091 if (resetTime < dur) resetTime = dur;
2092 } else {
2093 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
2094 + r.name);
2095 canceled = true;
2096 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002097 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002098 r.deliveredStarts.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002099 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002100
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002101 r.totalRestartCount++;
2102 if (r.restartDelay == 0) {
2103 r.restartCount++;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002104 r.restartDelay = minDuration;
Amith Yamasanib0c8a882017-08-28 09:36:42 -07002105 } else if (r.crashCount > 1) {
2106 r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
2107 * (r.crashCount - 1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002108 } else {
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002109 // If it has been a "reasonably long time" since the service
2110 // was started, then reset our restart duration back to
2111 // the beginning, so we don't infinitely increase the duration
2112 // on a service that just occasionally gets killed (which is
2113 // a normal case, due to process being killed to reclaim memory).
2114 if (now > (r.restartTime+resetTime)) {
2115 r.restartCount = 1;
2116 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002117 } else {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002118 r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
Dianne Hackborn7b492722013-11-01 09:58:45 -07002119 if (r.restartDelay < minDuration) {
2120 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002121 }
2122 }
2123 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002124
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002125 r.nextRestartTime = now + r.restartDelay;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002126
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002127 // Make sure that we don't end up restarting a bunch of services
2128 // all at the same time.
2129 boolean repeat;
2130 do {
2131 repeat = false;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002132 final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002133 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2134 ServiceRecord r2 = mRestartingServices.get(i);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002135 if (r2 != r && r.nextRestartTime >= (r2.nextRestartTime-restartTimeBetween)
2136 && r.nextRestartTime < (r2.nextRestartTime+restartTimeBetween)) {
2137 r.nextRestartTime = r2.nextRestartTime + restartTimeBetween;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002138 r.restartDelay = r.nextRestartTime - now;
2139 repeat = true;
2140 break;
2141 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002142 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002143 } while (repeat);
2144
2145 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07002146 // Persistent processes are immediately restarted, so there is no
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002147 // reason to hold of on restarting their services.
2148 r.totalRestartCount++;
2149 r.restartCount = 0;
2150 r.restartDelay = 0;
2151 r.nextRestartTime = now;
2152 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002153
2154 if (!mRestartingServices.contains(r)) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002155 r.createdFromFg = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002156 mRestartingServices.add(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002157 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002158 }
2159
Christopher Tate08992ac2017-03-21 11:37:06 -07002160 cancelForegroundNotificationLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002161
2162 mAm.mHandler.removeCallbacks(r.restarter);
2163 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
2164 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
2165 Slog.w(TAG, "Scheduling restart of crashed service "
2166 + r.shortName + " in " + r.restartDelay + "ms");
2167 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002168 r.userId, r.shortName, r.restartDelay);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002169
2170 return canceled;
2171 }
2172
2173 final void performServiceRestartLocked(ServiceRecord r) {
2174 if (!mRestartingServices.contains(r)) {
2175 return;
2176 }
Dianne Hackbornad51be92016-08-16 16:27:36 -07002177 if (!isServiceNeededLocked(r, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002178 // Paranoia: is this service actually needed? In theory a service that is not
2179 // needed should never remain on the restart list. In practice... well, there
2180 // have been bugs where this happens, and bad things happen because the process
2181 // ends up just being cached, so quickly killed, then restarted again and again.
2182 // Let's not let that happen.
2183 Slog.wtf(TAG, "Restarting service that is not needed: " + r);
2184 return;
2185 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002186 try {
Svet Ganov9c165d72015-12-01 19:52:26 -08002187 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002188 } catch (TransactionTooLargeException e) {
2189 // Ignore, it's been logged and nothing upstack cares.
2190 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002191 }
2192
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002193 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
2194 boolean force) {
2195 if (!force && r.restartDelay == 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002196 return false;
2197 }
Dianne Hackborn7b492722013-11-01 09:58:45 -07002198 // Remove from the restarting list; if the service is currently on the
2199 // restarting list, or the call is coming from another app, then this
2200 // service has become of much more interest so we reset the restart interval.
2201 boolean removed = mRestartingServices.remove(r);
2202 if (removed || callingUid != r.appInfo.uid) {
2203 r.resetRestartCounter();
2204 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002205 if (removed) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002206 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002207 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002208 mAm.mHandler.removeCallbacks(r.restarter);
2209 return true;
2210 }
2211
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002212 private void clearRestartingIfNeededLocked(ServiceRecord r) {
2213 if (r.restartTracker != null) {
2214 // If this is the last restarting record with this tracker, then clear
2215 // the tracker's restarting state.
2216 boolean stillTracking = false;
2217 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2218 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
2219 stillTracking = true;
2220 break;
2221 }
2222 }
2223 if (!stillTracking) {
2224 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
2225 SystemClock.uptimeMillis());
2226 r.restartTracker = null;
2227 }
2228 }
2229 }
2230
Svet Ganov9c165d72015-12-01 19:52:26 -08002231 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
2232 boolean whileRestarting, boolean permissionsReviewRequired)
2233 throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002234 //Slog.i(TAG, "Bring up service:");
2235 //r.dump(" ");
2236
2237 if (r.app != null && r.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002238 sendServiceArgsLocked(r, execInFg, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002239 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002240 }
2241
Sudheer Shanka03d0f812017-04-20 16:57:50 -07002242 if (!whileRestarting && mRestartingServices.contains(r)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002243 // If waiting for a restart, then do nothing.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002244 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002245 }
2246
Christopher Tate08992ac2017-03-21 11:37:06 -07002247 if (DEBUG_SERVICE) {
2248 Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
2249 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002250
2251 // We are now bringing the service up, so no longer in the
2252 // restarting state.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002253 if (mRestartingServices.remove(r)) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002254 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002255 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002256
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002257 // Make sure this service is no longer considered delayed, we are starting it now.
2258 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002259 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002260 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002261 r.delayed = false;
2262 }
2263
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002264 // Make sure that the user who owns this service is started. If not,
2265 // we don't want to allow it to run.
Fyodor Kupolov610acda2015-10-19 18:44:07 -07002266 if (!mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002267 String msg = "Unable to launch app "
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002268 + r.appInfo.packageName + "/"
2269 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002270 + r.intent.getIntent() + ": user " + r.userId + " is stopped";
2271 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002272 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002273 return msg;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002274 }
2275
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002276 // Service is now being launched, its package can't be stopped.
2277 try {
2278 AppGlobals.getPackageManager().setPackageStoppedState(
2279 r.packageName, false, r.userId);
2280 } catch (RemoteException e) {
2281 } catch (IllegalArgumentException e) {
2282 Slog.w(TAG, "Failed trying to unstop package "
2283 + r.packageName + ": " + e);
2284 }
2285
2286 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
2287 final String procName = r.processName;
Robert Sesekc5f86642016-11-04 10:20:38 -04002288 String hostingType = "service";
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002289 ProcessRecord app;
2290
2291 if (!isolated) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07002292 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
2293 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
2294 + " app=" + app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002295 if (app != null && app.thread != null) {
2296 try {
Patrick Baumannc2def582018-04-04 12:14:15 -07002297 app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode, mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002298 realStartServiceLocked(r, app, execInFg);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002299 return null;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002300 } catch (TransactionTooLargeException e) {
2301 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002302 } catch (RemoteException e) {
2303 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
2304 }
2305
2306 // If a dead object exception was thrown -- fall through to
2307 // restart the application.
2308 }
2309 } else {
2310 // If this service runs in an isolated process, then each time
2311 // we call startProcessLocked() we will get a new isolated
2312 // process, starting another process if we are currently waiting
2313 // for a previous process to come up. To deal with this, we store
2314 // in the service any current isolated process it is running in or
2315 // waiting to have come up.
2316 app = r.isolatedProc;
Robert Sesekc5f86642016-11-04 10:20:38 -04002317 if (WebViewZygote.isMultiprocessEnabled()
2318 && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
2319 hostingType = "webview_service";
2320 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002321 }
2322
2323 // Not running -- get it started, and enqueue this service record
2324 // to be executed when the app comes up.
Svet Ganov9c165d72015-12-01 19:52:26 -08002325 if (app == null && !permissionsReviewRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002326 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
Robert Sesekc5f86642016-11-04 10:20:38 -04002327 hostingType, r.name, false, isolated, false)) == null) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002328 String msg = "Unable to launch app "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002329 + r.appInfo.packageName + "/"
2330 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002331 + r.intent.getIntent() + ": process is bad";
2332 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002333 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002334 return msg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002335 }
2336 if (isolated) {
2337 r.isolatedProc = app;
2338 }
2339 }
2340
Christopher Tate1536cc22017-09-18 16:43:30 -07002341 if (r.fgRequired) {
2342 if (DEBUG_FOREGROUND_SERVICE) {
2343 Slog.v(TAG, "Whitelisting " + UserHandle.formatUid(r.appInfo.uid)
2344 + " for fg-service launch");
2345 }
2346 mAm.tempWhitelistUidLocked(r.appInfo.uid,
2347 SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch");
2348 }
2349
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002350 if (!mPendingServices.contains(r)) {
2351 mPendingServices.add(r);
2352 }
2353
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002354 if (r.delayedStop) {
2355 // Oh and hey we've already been asked to stop!
2356 r.delayedStop = false;
2357 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002358 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2359 "Applying delayed stop (in bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002360 stopServiceLocked(r);
2361 }
2362 }
2363
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002364 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002365 }
2366
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002367 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
2368 throws TransactionTooLargeException {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002369 for (int i=r.bindings.size()-1; i>=0; i--) {
2370 IntentBindRecord ibr = r.bindings.valueAt(i);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002371 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002372 break;
2373 }
2374 }
2375 }
2376
2377 private final void realStartServiceLocked(ServiceRecord r,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002378 ProcessRecord app, boolean execInFg) throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002379 if (app.thread == null) {
2380 throw new RemoteException();
2381 }
2382 if (DEBUG_MU)
2383 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
2384 + ", ProcessRecord.uid = " + app.uid);
2385 r.app = app;
2386 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
2387
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002388 final boolean newService = app.services.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002389 bumpServiceExecutingLocked(r, execInFg, "create");
Dianne Hackborndb926082013-10-31 16:32:44 -07002390 mAm.updateLruProcessLocked(app, false, null);
Makoto Onuki0f421292017-04-28 15:03:33 -07002391 updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
2392 mAm.updateOomAdjLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002393
2394 boolean created = false;
2395 try {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002396 if (LOG_SERVICE_START_STOP) {
Dianne Hackbornab2df062015-01-07 13:43:13 -08002397 String nameTerm;
2398 int lastPeriod = r.shortName.lastIndexOf('.');
2399 nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002400 EventLogTags.writeAmCreateService(
2401 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
2402 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002403 synchronized (r.stats.getBatteryStats()) {
2404 r.stats.startLaunchedLocked();
2405 }
Brian Carlstromca82e612016-04-19 23:16:08 -07002406 mAm.notifyPackageUse(r.serviceInfo.packageName,
2407 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
Dianne Hackborna413dc02013-07-12 12:02:55 -07002408 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002409 app.thread.scheduleCreateService(r, r.serviceInfo,
Dianne Hackborna413dc02013-07-12 12:02:55 -07002410 mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
2411 app.repProcState);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002412 r.postNotification();
2413 created = true;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -07002414 } catch (DeadObjectException e) {
2415 Slog.w(TAG, "Application dead when creating service " + r);
2416 mAm.appDiedLocked(app);
Wale Ogunwalebfac4682015-04-08 14:33:21 -07002417 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002418 } finally {
2419 if (!created) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002420 // Keep the executeNesting count accurate.
2421 final boolean inDestroying = mDestroyingServices.contains(r);
2422 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2423
2424 // Cleanup.
2425 if (newService) {
2426 app.services.remove(r);
2427 r.app = null;
2428 }
2429
2430 // Retry.
2431 if (!inDestroying) {
2432 scheduleServiceRestartLocked(r, false);
2433 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002434 }
2435 }
2436
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002437 if (r.whitelistManager) {
2438 app.whitelistManager = true;
2439 }
2440
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002441 requestServiceBindingsLocked(r, execInFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002442
Dianne Hackborn465fa392014-09-14 14:21:18 -07002443 updateServiceClientActivitiesLocked(app, null, true);
2444
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002445 // If the service is in the started state, and there are no
2446 // pending arguments, then fake up one so its onStartCommand() will
2447 // be called.
2448 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
2449 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002450 null, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002451 }
2452
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002453 sendServiceArgsLocked(r, execInFg, true);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002454
2455 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002456 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002457 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002458 r.delayed = false;
2459 }
2460
2461 if (r.delayedStop) {
2462 // Oh and hey we've already been asked to stop!
2463 r.delayedStop = false;
2464 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002465 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2466 "Applying delayed stop (from start): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002467 stopServiceLocked(r);
2468 }
2469 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002470 }
2471
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002472 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002473 boolean oomAdjusted) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002474 final int N = r.pendingStarts.size();
2475 if (N == 0) {
2476 return;
2477 }
2478
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002479 ArrayList<ServiceStartArgs> args = new ArrayList<>();
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002480
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002481 while (r.pendingStarts.size() > 0) {
2482 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
2483 if (DEBUG_SERVICE) {
2484 Slog.v(TAG_SERVICE, "Sending arguments to: "
2485 + r + " " + r.intent + " args=" + si.intent);
2486 }
2487 if (si.intent == null && N > 1) {
2488 // If somehow we got a dummy null intent in the middle,
2489 // then skip it. DO NOT skip a null intent when it is
2490 // the only one in the list -- this is to support the
2491 // onStartCommand(null) case.
2492 continue;
2493 }
2494 si.deliveredTime = SystemClock.uptimeMillis();
2495 r.deliveredStarts.add(si);
2496 si.deliveryCount++;
2497 if (si.neededGrants != null) {
2498 mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
2499 si.getUriPermissionsLocked());
2500 }
2501 mAm.grantEphemeralAccessLocked(r.userId, si.intent,
2502 r.appInfo.uid, UserHandle.getAppId(si.callingId));
2503 bumpServiceExecutingLocked(r, execInFg, "start");
2504 if (!oomAdjusted) {
2505 oomAdjusted = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002506 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002507 }
2508 if (r.fgRequired && !r.fgWaiting) {
2509 if (!r.isForeground) {
2510 if (DEBUG_BACKGROUND_CHECK) {
2511 Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r);
2512 }
2513 scheduleServiceForegroundTransitionTimeoutLocked(r);
2514 } else {
2515 if (DEBUG_BACKGROUND_CHECK) {
2516 Slog.i(TAG, "Service already foreground; no new timeout: " + r);
2517 }
2518 r.fgRequired = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002519 }
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002520 }
2521 int flags = 0;
2522 if (si.deliveryCount > 1) {
2523 flags |= Service.START_FLAG_RETRY;
2524 }
2525 if (si.doneExecutingCount > 0) {
2526 flags |= Service.START_FLAG_REDELIVERY;
2527 }
2528 args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
2529 }
2530
2531 ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
2532 slice.setInlineCountLimit(4);
2533 Exception caughtException = null;
2534 try {
2535 r.app.thread.scheduleServiceArgs(r, slice);
2536 } catch (TransactionTooLargeException e) {
2537 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
2538 + " args, first: " + args.get(0).args);
2539 Slog.w(TAG, "Failed delivering service starts", e);
2540 caughtException = e;
2541 } catch (RemoteException e) {
2542 // Remote process gone... we'll let the normal cleanup take care of this.
2543 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
2544 Slog.w(TAG, "Failed delivering service starts", e);
2545 caughtException = e;
2546 } catch (Exception e) {
2547 Slog.w(TAG, "Unexpected exception", e);
2548 caughtException = e;
2549 }
2550
2551 if (caughtException != null) {
2552 // Keep nesting count correct
2553 final boolean inDestroying = mDestroyingServices.contains(r);
2554 for (int i = 0; i < args.size(); i++) {
2555 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2556 }
2557 if (caughtException instanceof TransactionTooLargeException) {
2558 throw (TransactionTooLargeException)caughtException;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002559 }
2560 }
2561 }
2562
Dianne Hackbornad51be92016-08-16 16:27:36 -07002563 private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn,
2564 boolean hasConn) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002565 // Are we still explicitly being asked to run?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002566 if (r.startRequested) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002567 return true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002568 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002569
Dianne Hackborncb015632017-06-14 17:30:15 -07002570 // Is someone still bound to us keeping us running?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002571 if (!knowConn) {
2572 hasConn = r.hasAutoCreateConnections();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002573 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002574 if (hasConn) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002575 return true;
2576 }
2577
2578 return false;
2579 }
2580
2581 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
2582 boolean hasConn) {
2583 //Slog.i(TAG, "Bring down service:");
2584 //r.dump(" ");
2585
Dianne Hackbornad51be92016-08-16 16:27:36 -07002586 if (isServiceNeededLocked(r, knowConn, hasConn)) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002587 return;
2588 }
2589
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002590 // Are we in the process of launching?
2591 if (mPendingServices.contains(r)) {
2592 return;
2593 }
2594
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002595 bringDownServiceLocked(r);
2596 }
2597
2598 private final void bringDownServiceLocked(ServiceRecord r) {
2599 //Slog.i(TAG, "Bring down service:");
2600 //r.dump(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002601
Dianne Hackborn390517b2013-05-30 15:03:32 -07002602 // Report to all of the connections that the service is no longer
2603 // available.
2604 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2605 ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
2606 for (int i=0; i<c.size(); i++) {
2607 ConnectionRecord cr = c.get(i);
2608 // There is still a connection to the service that is
2609 // being brought down. Mark it as dead.
2610 cr.serviceDead = true;
2611 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07002612 cr.conn.connected(r.name, null, true);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002613 } catch (Exception e) {
2614 Slog.w(TAG, "Failure disconnecting service " + r.name +
2615 " to connection " + c.get(i).conn.asBinder() +
2616 " (in " + c.get(i).binding.client.processName + ")", e);
2617 }
2618 }
2619 }
2620
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002621 // Tell the service that it has been unbound.
Dianne Hackborn390517b2013-05-30 15:03:32 -07002622 if (r.app != null && r.app.thread != null) {
2623 for (int i=r.bindings.size()-1; i>=0; i--) {
2624 IntentBindRecord ibr = r.bindings.valueAt(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002625 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002626 + ": hasBound=" + ibr.hasBound);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002627 if (ibr.hasBound) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002628 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002629 bumpServiceExecutingLocked(r, false, "bring down unbind");
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002630 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002631 ibr.hasBound = false;
Dianne Hackborn85e35642017-01-12 15:10:57 -08002632 ibr.requested = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002633 r.app.thread.scheduleUnbindService(r,
2634 ibr.intent.getIntent());
2635 } catch (Exception e) {
2636 Slog.w(TAG, "Exception when unbinding service "
2637 + r.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002638 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002639 }
2640 }
2641 }
2642 }
2643
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002644 // Check to see if the service had been started as foreground, but being
2645 // brought down before actually showing a notification. That is not allowed.
2646 if (r.fgRequired) {
2647 Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
2648 + r);
2649 r.fgRequired = false;
2650 r.fgWaiting = false;
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07002651 mAm.mAppOpsService.finishOperation(AppOpsManager.getToken(mAm.mAppOpsService),
2652 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002653 mAm.mHandler.removeMessages(
2654 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
2655 if (r.app != null) {
2656 Message msg = mAm.mHandler.obtainMessage(
2657 ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
2658 msg.obj = r.app;
Kodlee Yin7e951262018-04-05 12:59:56 -07002659 msg.getData().putCharSequence(
2660 ActivityManagerService.SERVICE_RECORD_KEY, r.toString());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002661 mAm.mHandler.sendMessage(msg);
2662 }
2663 }
2664
2665 if (DEBUG_SERVICE) {
2666 RuntimeException here = new RuntimeException();
2667 here.fillInStackTrace();
2668 Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here);
2669 }
Craig Mautner66c4a822015-01-16 12:48:16 -08002670 r.destroyTime = SystemClock.uptimeMillis();
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002671 if (LOG_SERVICE_START_STOP) {
2672 EventLogTags.writeAmDestroyService(
2673 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
2674 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002675
Dianne Hackbornad51be92016-08-16 16:27:36 -07002676 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002677 ServiceRecord found = smap.mServicesByName.remove(r.name);
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002678
2679 // Note when this method is called by bringUpServiceLocked(), the service is not found
2680 // in mServicesByName and found will be null.
2681 if (found != null && found != r) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002682 // This is not actually the service we think is running... this should not happen,
2683 // but if it does, fail hard.
2684 smap.mServicesByName.put(r.name, found);
2685 throw new IllegalStateException("Bringing down " + r + " but actually running "
2686 + found);
2687 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002688 smap.mServicesByIntent.remove(r.intent);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002689 r.totalRestartCount = 0;
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002690 unscheduleServiceRestartLocked(r, 0, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002691
2692 // Also make sure it is not on the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002693 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002694 if (mPendingServices.get(i) == r) {
2695 mPendingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002696 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002697 }
2698 }
2699
Christopher Tate08992ac2017-03-21 11:37:06 -07002700 cancelForegroundNotificationLocked(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002701 if (r.isForeground) {
2702 decActiveForegroundAppLocked(smap, r);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07002703 mAm.mAppOpsService.finishOperation(
2704 AppOpsManager.getToken(mAm.mAppOpsService),
2705 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Chenjie Yu1b9b21c2018-02-13 10:21:59 -08002706 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED, r.appInfo.uid, r.shortName,
Chenjie Yuccfe6452018-01-30 11:33:21 -08002707 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002708 }
Chenjie Yuccfe6452018-01-30 11:33:21 -08002709
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002710 r.isForeground = false;
2711 r.foregroundId = 0;
2712 r.foregroundNoti = null;
2713
2714 // Clear start entries.
2715 r.clearDeliveredStartsLocked();
2716 r.pendingStarts.clear();
2717
2718 if (r.app != null) {
2719 synchronized (r.stats.getBatteryStats()) {
2720 r.stats.stopLaunchedLocked();
2721 }
2722 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002723 if (r.whitelistManager) {
2724 updateWhitelistManagerLocked(r.app);
2725 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002726 if (r.app.thread != null) {
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002727 updateServiceForegroundLocked(r.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002728 try {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002729 bumpServiceExecutingLocked(r, false, "destroy");
2730 mDestroyingServices.add(r);
Dianne Hackborn455625e2015-01-21 09:55:13 -08002731 r.destroying = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002732 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002733 r.app.thread.scheduleStopService(r);
2734 } catch (Exception e) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002735 Slog.w(TAG, "Exception when destroying service "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002736 + r.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002737 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002738 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002739 } else {
2740 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002741 TAG_SERVICE, "Removed service that has no process: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002742 }
2743 } else {
2744 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002745 TAG_SERVICE, "Removed service that is not running: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002746 }
2747
2748 if (r.bindings.size() > 0) {
2749 r.bindings.clear();
2750 }
2751
2752 if (r.restarter instanceof ServiceRestarter) {
2753 ((ServiceRestarter)r.restarter).setService(null);
2754 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002755
Dianne Hackbornd2932242013-08-05 18:18:42 -07002756 int memFactor = mAm.mProcessStats.getMemFactorLocked();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002757 long now = SystemClock.uptimeMillis();
2758 if (r.tracker != null) {
2759 r.tracker.setStarted(false, memFactor, now);
2760 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002761 if (r.executeNesting == 0) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07002762 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002763 r.tracker = null;
2764 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002765 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002766
Dianne Hackbornad51be92016-08-16 16:27:36 -07002767 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002768 }
2769
2770 void removeConnectionLocked(
2771 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
2772 IBinder binder = c.conn.asBinder();
2773 AppBindRecord b = c.binding;
2774 ServiceRecord s = b.service;
2775 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
2776 if (clist != null) {
2777 clist.remove(c);
2778 if (clist.size() == 0) {
2779 s.connections.remove(binder);
2780 }
2781 }
2782 b.connections.remove(c);
2783 if (c.activity != null && c.activity != skipAct) {
2784 if (c.activity.connections != null) {
2785 c.activity.connections.remove(c);
2786 }
2787 }
2788 if (b.client != skipApp) {
2789 b.client.connections.remove(c);
2790 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
2791 b.client.updateHasAboveClientLocked();
2792 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002793 // If this connection requested whitelist management, see if we should
2794 // now clear that state.
2795 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
2796 s.updateWhitelistManager();
2797 if (!s.whitelistManager && s.app != null) {
2798 updateWhitelistManagerLocked(s.app);
2799 }
2800 }
Dianne Hackborndb926082013-10-31 16:32:44 -07002801 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07002802 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07002803 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002804 }
2805 clist = mServiceConnections.get(binder);
2806 if (clist != null) {
2807 clist.remove(c);
2808 if (clist.size() == 0) {
2809 mServiceConnections.remove(binder);
2810 }
2811 }
2812
Dianne Hackbornab2df062015-01-07 13:43:13 -08002813 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid, s.name);
2814
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002815 if (b.connections.size() == 0) {
2816 b.intent.apps.remove(b.client);
2817 }
2818
2819 if (!c.serviceDead) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002820 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002821 + ": shouldUnbind=" + b.intent.hasBound);
2822 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
2823 && b.intent.hasBound) {
2824 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002825 bumpServiceExecutingLocked(s, false, "unbind");
Dianne Hackborndb926082013-10-31 16:32:44 -07002826 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
Dianne Hackbornf097d422017-12-15 16:32:19 -08002827 && s.app.setProcState <= ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
Dianne Hackborndb926082013-10-31 16:32:44 -07002828 // If this service's process is not already in the cached list,
2829 // then update it in the LRU list here because this may be causing
2830 // it to go down there and we want it to start out near the top.
2831 mAm.updateLruProcessLocked(s.app, false, null);
2832 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002833 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002834 b.intent.hasBound = false;
2835 // Assume the client doesn't want to know about a rebind;
2836 // we will deal with that later if it asks for one.
2837 b.intent.doRebind = false;
2838 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
2839 } catch (Exception e) {
2840 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002841 serviceProcessGoneLocked(s);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002842 }
2843 }
2844
Svet Ganov9c165d72015-12-01 19:52:26 -08002845 // If unbound while waiting to start, remove the pending service
2846 mPendingServices.remove(s);
2847
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002848 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002849 boolean hasAutoCreate = s.hasAutoCreateConnections();
2850 if (!hasAutoCreate) {
2851 if (s.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002852 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002853 SystemClock.uptimeMillis());
2854 }
2855 }
2856 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002857 }
2858 }
2859 }
2860
2861 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002862 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002863 if (r != null) {
Dianne Hackborn455625e2015-01-21 09:55:13 -08002864 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002865 // This is a call from a service start... take care of
2866 // book-keeping.
2867 r.callStart = true;
2868 switch (res) {
2869 case Service.START_STICKY_COMPATIBILITY:
2870 case Service.START_STICKY: {
2871 // We are done with the associated start arguments.
2872 r.findDeliveredStart(startId, true);
2873 // Don't stop if killed.
2874 r.stopIfKilled = false;
2875 break;
2876 }
2877 case Service.START_NOT_STICKY: {
2878 // We are done with the associated start arguments.
2879 r.findDeliveredStart(startId, true);
2880 if (r.getLastStartId() == startId) {
2881 // There is no more work, and this service
2882 // doesn't want to hang around if killed.
2883 r.stopIfKilled = true;
2884 }
2885 break;
2886 }
2887 case Service.START_REDELIVER_INTENT: {
2888 // We'll keep this item until they explicitly
2889 // call stop for it, but keep track of the fact
2890 // that it was delivered.
2891 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
2892 if (si != null) {
2893 si.deliveryCount = 0;
2894 si.doneExecutingCount++;
2895 // Don't stop if killed.
2896 r.stopIfKilled = true;
2897 }
2898 break;
2899 }
2900 case Service.START_TASK_REMOVED_COMPLETE: {
2901 // Special processing for onTaskRemoved(). Don't
2902 // impact normal onStartCommand() processing.
2903 r.findDeliveredStart(startId, true);
2904 break;
2905 }
2906 default:
2907 throw new IllegalArgumentException(
2908 "Unknown service start result: " + res);
2909 }
2910 if (res == Service.START_STICKY_COMPATIBILITY) {
2911 r.callStart = false;
2912 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08002913 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
2914 // This is the final call from destroying the service... we should
2915 // actually be getting rid of the service at this point. Do some
2916 // validation of its state, and ensure it will be fully removed.
2917 if (!inDestroying) {
2918 // Not sure what else to do with this... if it is not actually in the
2919 // destroying list, we don't need to make sure to remove it from it.
Amith Yamasanid0418222016-05-10 15:49:51 -07002920 // If the app is null, then it was probably removed because the process died,
2921 // otherwise wtf
2922 if (r.app != null) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07002923 Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
Amith Yamasanid0418222016-05-10 15:49:51 -07002924 + r + ", app=" + r.app);
2925 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08002926 } else if (r.executeNesting != 1) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07002927 Slog.w(TAG, "Service done with onDestroy, but executeNesting="
Dianne Hackborn455625e2015-01-21 09:55:13 -08002928 + r.executeNesting + ": " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002929 // Fake it to keep from ANR due to orphaned entry.
Dianne Hackborn455625e2015-01-21 09:55:13 -08002930 r.executeNesting = 1;
2931 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002932 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002933 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn164371f2013-10-01 19:10:13 -07002934 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002935 Binder.restoreCallingIdentity(origId);
2936 } else {
2937 Slog.w(TAG, "Done executing unknown service from pid "
2938 + Binder.getCallingPid());
2939 }
2940 }
2941
Dianne Hackborn878deb32013-10-14 16:55:09 -07002942 private void serviceProcessGoneLocked(ServiceRecord r) {
2943 if (r.tracker != null) {
2944 int memFactor = mAm.mProcessStats.getMemFactorLocked();
2945 long now = SystemClock.uptimeMillis();
2946 r.tracker.setExecuting(false, memFactor, now);
2947 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbc72dce2013-11-11 10:43:38 -08002948 r.tracker.setStarted(false, memFactor, now);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002949 }
2950 serviceDoneExecutingLocked(r, true, true);
2951 }
2952
Dianne Hackborn164371f2013-10-01 19:10:13 -07002953 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
2954 boolean finishing) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002955 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002956 + ": nesting=" + r.executeNesting
Dianne Hackborn164371f2013-10-01 19:10:13 -07002957 + ", inDestroying=" + inDestroying + ", app=" + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002958 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
2959 "<<< DONE EXECUTING " + r.shortName);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002960 r.executeNesting--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002961 if (r.executeNesting <= 0) {
2962 if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002963 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002964 "Nesting at 0 of " + r.shortName);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002965 r.app.execServicesFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002966 r.app.executingServices.remove(r);
2967 if (r.app.executingServices.size() == 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002968 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002969 "No more executingServices of " + r.shortName);
2970 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002971 } else if (r.executeFg) {
2972 // Need to re-evaluate whether the app still needs to be in the foreground.
2973 for (int i=r.app.executingServices.size()-1; i>=0; i--) {
2974 if (r.app.executingServices.valueAt(i).executeFg) {
2975 r.app.execServicesFg = true;
2976 break;
2977 }
2978 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002979 }
Dianne Hackborn164371f2013-10-01 19:10:13 -07002980 if (inDestroying) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002981 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn164371f2013-10-01 19:10:13 -07002982 "doneExecuting remove destroying " + r);
2983 mDestroyingServices.remove(r);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002984 r.bindings.clear();
2985 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002986 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002987 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002988 r.executeFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002989 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002990 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002991 SystemClock.uptimeMillis());
Dianne Hackborn164371f2013-10-01 19:10:13 -07002992 if (finishing) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07002993 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002994 r.tracker = null;
2995 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002996 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002997 if (finishing) {
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08002998 if (r.app != null && !r.app.persistent) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002999 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003000 if (r.whitelistManager) {
3001 updateWhitelistManagerLocked(r.app);
3002 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003003 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003004 r.app = null;
3005 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003006 }
3007 }
3008
Dianne Hackbornff072722014-09-24 10:56:28 -07003009 boolean attachApplicationLocked(ProcessRecord proc, String processName)
3010 throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003011 boolean didSomething = false;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003012 // Collect any services that are waiting for this process to come up.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003013 if (mPendingServices.size() > 0) {
3014 ServiceRecord sr = null;
3015 try {
3016 for (int i=0; i<mPendingServices.size(); i++) {
3017 sr = mPendingServices.get(i);
3018 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3019 || !processName.equals(sr.processName))) {
3020 continue;
3021 }
3022
3023 mPendingServices.remove(i);
3024 i--;
Patrick Baumannc2def582018-04-04 12:14:15 -07003025 proc.addPackage(sr.appInfo.packageName, sr.appInfo.longVersionCode,
Dianne Hackbornf7097a52014-05-13 09:56:14 -07003026 mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003027 realStartServiceLocked(sr, proc, sr.createdFromFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003028 didSomething = true;
Dianne Hackbornad51be92016-08-16 16:27:36 -07003029 if (!isServiceNeededLocked(sr, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003030 // We were waiting for this service to start, but it is actually no
3031 // longer needed. This could happen because bringDownServiceIfNeeded
3032 // won't bring down a service that is pending... so now the pending
3033 // is done, so let's drop it.
3034 bringDownServiceLocked(sr);
3035 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003036 }
Dianne Hackbornff072722014-09-24 10:56:28 -07003037 } catch (RemoteException e) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003038 Slog.w(TAG, "Exception in new application when starting service "
3039 + sr.shortName, e);
3040 throw e;
3041 }
3042 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003043 // Also, if there are any services that are waiting to restart and
3044 // would run in this process, now is a good time to start them. It would
3045 // be weird to bring up the process but arbitrarily not let the services
3046 // run at this point just because their restart time hasn't come up.
3047 if (mRestartingServices.size() > 0) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003048 ServiceRecord sr;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003049 for (int i=0; i<mRestartingServices.size(); i++) {
3050 sr = mRestartingServices.get(i);
3051 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3052 || !processName.equals(sr.processName))) {
3053 continue;
3054 }
3055 mAm.mHandler.removeCallbacks(sr.restarter);
3056 mAm.mHandler.post(sr.restarter);
3057 }
3058 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003059 return didSomething;
3060 }
3061
3062 void processStartTimedOutLocked(ProcessRecord proc) {
3063 for (int i=0; i<mPendingServices.size(); i++) {
3064 ServiceRecord sr = mPendingServices.get(i);
3065 if ((proc.uid == sr.appInfo.uid
3066 && proc.processName.equals(sr.processName))
3067 || sr.isolatedProc == proc) {
3068 Slog.w(TAG, "Forcing bringing down service: " + sr);
3069 sr.isolatedProc = null;
3070 mPendingServices.remove(i);
3071 i--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003072 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003073 }
3074 }
3075 }
3076
Wale Ogunwale540e1232015-05-01 15:35:39 -07003077 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003078 boolean evenPersistent, boolean doit, boolean killProcess,
3079 ArrayMap<ComponentName, ServiceRecord> services) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003080 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003081 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003082 ServiceRecord service = services.valueAt(i);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003083 final boolean sameComponent = packageName == null
3084 || (service.packageName.equals(packageName)
3085 && (filterByClasses == null
3086 || filterByClasses.contains(service.name.getClassName())));
3087 if (sameComponent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003088 && (service.app == null || evenPersistent || !service.app.persistent)) {
3089 if (!doit) {
3090 return true;
3091 }
3092 didSomething = true;
3093 Slog.i(TAG, " Force stopping service " + service);
3094 if (service.app != null) {
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003095 service.app.removed = killProcess;
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08003096 if (!service.app.persistent) {
3097 service.app.services.remove(service);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003098 if (service.whitelistManager) {
3099 updateWhitelistManagerLocked(service.app);
3100 }
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08003101 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003102 }
3103 service.app = null;
3104 service.isolatedProc = null;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003105 if (mTmpCollectionResults == null) {
3106 mTmpCollectionResults = new ArrayList<>();
3107 }
3108 mTmpCollectionResults.add(service);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003109 }
3110 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003111 return didSomething;
3112 }
3113
Wale Ogunwale540e1232015-05-01 15:35:39 -07003114 boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003115 int userId, boolean evenPersistent, boolean killProcess, boolean doit) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003116 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003117
3118 if (mTmpCollectionResults != null) {
3119 mTmpCollectionResults.clear();
3120 }
3121
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003122 if (userId == UserHandle.USER_ALL) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003123 for (int i = mServiceMap.size() - 1; i >= 0; i--) {
3124 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003125 evenPersistent, doit, killProcess, mServiceMap.valueAt(i).mServicesByName);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003126 if (!doit && didSomething) {
3127 return true;
3128 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003129 if (doit && filterByClasses == null) {
3130 forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId);
3131 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003132 }
3133 } else {
Amith Yamasani540b6592013-10-01 13:02:52 -07003134 ServiceMap smap = mServiceMap.get(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003135 if (smap != null) {
3136 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByName;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003137 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003138 evenPersistent, doit, killProcess, items);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003139 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003140 if (doit && filterByClasses == null) {
3141 forceStopPackageLocked(packageName, userId);
3142 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003143 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003144
Wale Ogunwale540e1232015-05-01 15:35:39 -07003145 if (mTmpCollectionResults != null) {
3146 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
3147 bringDownServiceLocked(mTmpCollectionResults.get(i));
3148 }
3149 mTmpCollectionResults.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003150 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003151
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003152 return didSomething;
3153 }
3154
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003155 void forceStopPackageLocked(String packageName, int userId) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003156 ServiceMap smap = mServiceMap.get(userId);
3157 if (smap != null && smap.mActiveForegroundApps.size() > 0) {
Dianne Hackbornaf597682017-05-01 10:54:07 -07003158 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003159 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
3160 if (aa.mPackageName.equals(packageName)) {
3161 smap.mActiveForegroundApps.removeAt(i);
3162 smap.mActiveForegroundAppsChanged = true;
3163 }
3164 }
3165 if (smap.mActiveForegroundAppsChanged) {
3166 requestUpdateActiveForegroundAppsLocked(smap, 0);
3167 }
3168 }
3169 }
3170
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003171 void cleanUpRemovedTaskLocked(TaskRecord tr, ComponentName component, Intent baseIntent) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003172 ArrayList<ServiceRecord> services = new ArrayList<>();
Dianne Hackbornad51be92016-08-16 16:27:36 -07003173 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(tr.userId);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003174 for (int i = alls.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003175 ServiceRecord sr = alls.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003176 if (sr.packageName.equals(component.getPackageName())) {
3177 services.add(sr);
3178 }
3179 }
3180
3181 // Take care of any running services associated with the app.
Wale Ogunwale540e1232015-05-01 15:35:39 -07003182 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003183 ServiceRecord sr = services.get(i);
3184 if (sr.startRequested) {
3185 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
3186 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
3187 stopServiceLocked(sr);
3188 } else {
3189 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Todd Kennedy51b3aac2017-03-30 17:50:42 -07003190 sr.makeNextStartId(), baseIntent, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003191 if (sr.app != null && sr.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003192 // We always run in the foreground, since this is called as
3193 // part of the "remove task" UI operation.
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003194 try {
3195 sendServiceArgsLocked(sr, true, false);
3196 } catch (TransactionTooLargeException e) {
3197 // Ignore, keep going.
3198 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003199 }
3200 }
3201 }
3202 }
3203 }
3204
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003205 final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003206 // Report disconnected services.
3207 if (false) {
3208 // XXX we are letting the client link to the service for
3209 // death notifications.
3210 if (app.services.size() > 0) {
3211 Iterator<ServiceRecord> it = app.services.iterator();
3212 while (it.hasNext()) {
3213 ServiceRecord r = it.next();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003214 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3215 ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
3216 for (int i=0; i<cl.size(); i++) {
3217 ConnectionRecord c = cl.get(i);
3218 if (c.binding.client != app) {
3219 try {
3220 //c.conn.connected(r.className, null);
3221 } catch (Exception e) {
3222 // todo: this should be asynchronous!
3223 Slog.w(TAG, "Exception thrown disconnected servce "
3224 + r.shortName
3225 + " from app " + app.processName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003226 }
3227 }
3228 }
3229 }
3230 }
3231 }
3232 }
3233
louis_chang40e259c2015-03-26 13:31:14 +08003234 // Clean up any connections this application has to other services.
3235 for (int i = app.connections.size() - 1; i >= 0; i--) {
3236 ConnectionRecord r = app.connections.valueAt(i);
3237 removeConnectionLocked(r, app, null);
3238 }
3239 updateServiceConnectionActivitiesLocked(app);
3240 app.connections.clear();
3241
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003242 app.whitelistManager = false;
3243
louis_chang40e259c2015-03-26 13:31:14 +08003244 // Clear app state from services.
3245 for (int i = app.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003246 ServiceRecord sr = app.services.valueAt(i);
3247 synchronized (sr.stats.getBatteryStats()) {
3248 sr.stats.stopLaunchedLocked();
3249 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003250 if (sr.app != app && sr.app != null && !sr.app.persistent) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003251 sr.app.services.remove(sr);
3252 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003253 sr.app = null;
3254 sr.isolatedProc = null;
3255 sr.executeNesting = 0;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003256 sr.forceClearTracker();
3257 if (mDestroyingServices.remove(sr)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003258 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003259 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003260
Dianne Hackbornc8230512013-07-13 21:32:12 -07003261 final int numClients = sr.bindings.size();
3262 for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
3263 IntentBindRecord b = sr.bindings.valueAt(bindingi);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003264 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
Dianne Hackbornc8230512013-07-13 21:32:12 -07003265 + ": shouldUnbind=" + b.hasBound);
3266 b.binder = null;
3267 b.requested = b.received = b.hasBound = false;
Dianne Hackborn465fa392014-09-14 14:21:18 -07003268 // If this binding is coming from a cached process and is asking to keep
3269 // the service created, then we'll kill the cached process as well -- we
3270 // don't want to be thrashing around restarting processes that are only
3271 // there to be cached.
3272 for (int appi=b.apps.size()-1; appi>=0; appi--) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003273 final ProcessRecord proc = b.apps.keyAt(appi);
3274 // If the process is already gone, skip it.
3275 if (proc.killedByAm || proc.thread == null) {
3276 continue;
3277 }
3278 // Only do this for processes that have an auto-create binding;
3279 // otherwise the binding can be left, because it won't cause the
3280 // service to restart.
3281 final AppBindRecord abind = b.apps.valueAt(appi);
3282 boolean hasCreate = false;
3283 for (int conni=abind.connections.size()-1; conni>=0; conni--) {
3284 ConnectionRecord conn = abind.connections.valueAt(conni);
Dianne Hackborn0fe3c252014-09-19 15:09:39 -07003285 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
3286 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003287 hasCreate = true;
3288 break;
3289 }
3290 }
3291 if (!hasCreate) {
3292 continue;
3293 }
Dianne Hackborncd97c962014-09-25 18:34:02 -07003294 // XXX turned off for now until we have more time to get a better policy.
3295 if (false && proc != null && !proc.persistent && proc.thread != null
Dianne Hackborn465fa392014-09-14 14:21:18 -07003296 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
3297 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
3298 proc.kill("bound to service " + sr.name.flattenToShortString()
3299 + " in dying proc " + (app != null ? app.processName : "??"), true);
3300 }
3301 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003302 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003303 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003304
Dianne Hackbornad51be92016-08-16 16:27:36 -07003305 ServiceMap smap = getServiceMapLocked(app.userId);
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003306
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003307 // Now do remaining service cleanup.
3308 for (int i=app.services.size()-1; i>=0; i--) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003309 ServiceRecord sr = app.services.valueAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003310
3311 // Unless the process is persistent, this process record is going away,
3312 // so make sure the service is cleaned out of it.
3313 if (!app.persistent) {
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003314 app.services.removeAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003315 }
3316
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003317 // Sanity check: if the service listed for the app is not one
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003318 // we actually are maintaining, just let it drop.
Dianne Hackborn40c87252014-03-19 16:55:40 -07003319 final ServiceRecord curRec = smap.mServicesByName.get(sr.name);
3320 if (curRec != sr) {
3321 if (curRec != null) {
3322 Slog.wtf(TAG, "Service " + sr + " in process " + app
3323 + " not same as in map: " + curRec);
3324 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003325 continue;
3326 }
3327
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003328 // Any services running in the application may need to be placed
3329 // back in the pending list.
Amith Yamasanib0c8a882017-08-28 09:36:42 -07003330 if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
3331 && (sr.serviceInfo.applicationInfo.flags
3332 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003333 Slog.w(TAG, "Service crashed " + sr.crashCount
3334 + " times, stopping: " + sr);
3335 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
3336 sr.userId, sr.crashCount, sr.shortName, app.pid);
3337 bringDownServiceLocked(sr);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003338 } else if (!allowRestart
Fyodor Kupolov1b3edac2017-09-19 15:48:06 -07003339 || !mAm.mUserController.isUserRunning(sr.userId, 0)) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003340 bringDownServiceLocked(sr);
3341 } else {
3342 boolean canceled = scheduleServiceRestartLocked(sr, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003343
Dianne Hackbornc8230512013-07-13 21:32:12 -07003344 // Should the service remain running? Note that in the
3345 // extreme case of so many attempts to deliver a command
3346 // that it failed we also will stop it here.
3347 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
3348 if (sr.pendingStarts.size() == 0) {
3349 sr.startRequested = false;
3350 if (sr.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003351 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackbornc8230512013-07-13 21:32:12 -07003352 SystemClock.uptimeMillis());
3353 }
3354 if (!sr.hasAutoCreateConnections()) {
3355 // Whoops, no reason to restart!
3356 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003357 }
3358 }
3359 }
3360 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003361 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003362
Dianne Hackbornc8230512013-07-13 21:32:12 -07003363 if (!allowRestart) {
3364 app.services.clear();
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003365
3366 // Make sure there are no more restarting services for this process.
3367 for (int i=mRestartingServices.size()-1; i>=0; i--) {
3368 ServiceRecord r = mRestartingServices.get(i);
3369 if (r.processName.equals(app.processName) &&
3370 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3371 mRestartingServices.remove(i);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08003372 clearRestartingIfNeededLocked(r);
3373 }
3374 }
3375 for (int i=mPendingServices.size()-1; i>=0; i--) {
3376 ServiceRecord r = mPendingServices.get(i);
3377 if (r.processName.equals(app.processName) &&
3378 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3379 mPendingServices.remove(i);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003380 }
3381 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003382 }
3383
3384 // Make sure we have no more records on the stopping list.
Dianne Hackborn164371f2013-10-01 19:10:13 -07003385 int i = mDestroyingServices.size();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003386 while (i > 0) {
3387 i--;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003388 ServiceRecord sr = mDestroyingServices.get(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003389 if (sr.app == app) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003390 sr.forceClearTracker();
3391 mDestroyingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003392 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003393 }
3394 }
3395
3396 app.executingServices.clear();
3397 }
3398
3399 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
3400 ActivityManager.RunningServiceInfo info =
3401 new ActivityManager.RunningServiceInfo();
3402 info.service = r.name;
3403 if (r.app != null) {
3404 info.pid = r.app.pid;
3405 }
3406 info.uid = r.appInfo.uid;
3407 info.process = r.processName;
3408 info.foreground = r.isForeground;
Yi Jin6b514142017-10-30 14:54:12 -07003409 info.activeSince = r.createRealTime;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003410 info.started = r.startRequested;
3411 info.clientCount = r.connections.size();
3412 info.crashCount = r.crashCount;
3413 info.lastActivityTime = r.lastActivity;
3414 if (r.isForeground) {
3415 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
3416 }
3417 if (r.startRequested) {
3418 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
3419 }
3420 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
3421 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
3422 }
3423 if (r.app != null && r.app.persistent) {
3424 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
3425 }
3426
Dianne Hackborn390517b2013-05-30 15:03:32 -07003427 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3428 ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003429 for (int i=0; i<connl.size(); i++) {
3430 ConnectionRecord conn = connl.get(i);
3431 if (conn.clientLabel != 0) {
3432 info.clientPackage = conn.binding.client.info.packageName;
3433 info.clientLabel = conn.clientLabel;
3434 return info;
3435 }
3436 }
3437 }
3438 return info;
3439 }
3440
Bryce Lee290e5782017-02-01 16:41:20 -08003441 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags,
Shunta Sato55af6c52016-10-19 15:58:52 +09003442 int callingUid, boolean allowed, boolean canInteractAcrossUsers) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003443 ArrayList<ActivityManager.RunningServiceInfo> res
3444 = new ArrayList<ActivityManager.RunningServiceInfo>();
3445
Dianne Hackborn0c380492012-08-20 17:23:30 -07003446 final long ident = Binder.clearCallingIdentity();
3447 try {
Shunta Sato55af6c52016-10-19 15:58:52 +09003448 if (canInteractAcrossUsers) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003449 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003450 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003451 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003452 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3453 ServiceRecord sr = alls.valueAt(i);
3454 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07003455 }
3456 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003457
Dianne Hackborn0c380492012-08-20 17:23:30 -07003458 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3459 ServiceRecord r = mRestartingServices.get(i);
3460 ActivityManager.RunningServiceInfo info =
3461 makeRunningServiceInfoLocked(r);
3462 info.restarting = r.nextRestartTime;
3463 res.add(info);
3464 }
3465 } else {
Bryce Lee290e5782017-02-01 16:41:20 -08003466 int userId = UserHandle.getUserId(callingUid);
Dianne Hackbornad51be92016-08-16 16:27:36 -07003467 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003468 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3469 ServiceRecord sr = alls.valueAt(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003470
3471 if (allowed || (sr.app != null && sr.app.uid == callingUid)) {
3472 res.add(makeRunningServiceInfoLocked(sr));
3473 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07003474 }
3475
3476 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3477 ServiceRecord r = mRestartingServices.get(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003478 if (r.userId == userId
3479 && (allowed || (r.app != null && r.app.uid == callingUid))) {
Dianne Hackborn0c380492012-08-20 17:23:30 -07003480 ActivityManager.RunningServiceInfo info =
3481 makeRunningServiceInfoLocked(r);
3482 info.restarting = r.nextRestartTime;
3483 res.add(info);
3484 }
3485 }
3486 }
3487 } finally {
3488 Binder.restoreCallingIdentity(ident);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003489 }
3490
3491 return res;
3492 }
3493
3494 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003495 int userId = UserHandle.getUserId(Binder.getCallingUid());
Dianne Hackbornad51be92016-08-16 16:27:36 -07003496 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003497 if (r != null) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003498 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3499 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003500 for (int i=0; i<conn.size(); i++) {
3501 if (conn.get(i).clientIntent != null) {
3502 return conn.get(i).clientIntent;
3503 }
3504 }
3505 }
3506 }
3507 return null;
3508 }
3509
3510 void serviceTimeout(ProcessRecord proc) {
3511 String anrMessage = null;
3512
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003513 synchronized(mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003514 if (proc.executingServices.size() == 0 || proc.thread == null) {
3515 return;
3516 }
Dianne Hackbornab2df062015-01-07 13:43:13 -08003517 final long now = SystemClock.uptimeMillis();
3518 final long maxTime = now -
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003519 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003520 ServiceRecord timeout = null;
3521 long nextTime = 0;
Dianne Hackbornc8230512013-07-13 21:32:12 -07003522 for (int i=proc.executingServices.size()-1; i>=0; i--) {
3523 ServiceRecord sr = proc.executingServices.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003524 if (sr.executingStart < maxTime) {
3525 timeout = sr;
3526 break;
3527 }
3528 if (sr.executingStart > nextTime) {
3529 nextTime = sr.executingStart;
3530 }
3531 }
3532 if (timeout != null && mAm.mLruProcesses.contains(proc)) {
3533 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08003534 StringWriter sw = new StringWriter();
3535 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
3536 pw.println(timeout);
3537 timeout.dump(pw, " ");
3538 pw.close();
3539 mLastAnrDump = sw.toString();
3540 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
3541 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
3542 anrMessage = "executing service " + timeout.shortName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003543 } else {
3544 Message msg = mAm.mHandler.obtainMessage(
3545 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3546 msg.obj = proc;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003547 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
Dianne Hackborn2be00932013-09-22 16:46:00 -07003548 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003549 }
3550 }
3551
3552 if (anrMessage != null) {
Adrian Roos20d7df32016-01-12 18:59:43 +01003553 mAm.mAppErrors.appNotResponding(proc, null, null, false, anrMessage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003554 }
3555 }
3556
Christopher Tate08992ac2017-03-21 11:37:06 -07003557 void serviceForegroundTimeout(ServiceRecord r) {
3558 ProcessRecord app;
3559 synchronized (mAm) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003560 if (!r.fgRequired || r.destroying) {
Christopher Tate08992ac2017-03-21 11:37:06 -07003561 return;
3562 }
3563
Christopher Tate54f51b02018-02-16 11:07:12 -08003564 app = r.app;
3565 if (app != null && app.debugging) {
3566 // The app's being debugged; let it ride
3567 return;
3568 }
3569
Christopher Tate08992ac2017-03-21 11:37:06 -07003570 if (DEBUG_BACKGROUND_CHECK) {
3571 Slog.i(TAG, "Service foreground-required timeout for " + r);
3572 }
Christopher Tate08992ac2017-03-21 11:37:06 -07003573 r.fgWaiting = false;
3574 stopServiceLocked(r);
3575 }
3576
3577 if (app != null) {
3578 mAm.mAppErrors.appNotResponding(app, null, null, false,
Kodlee Yin7e951262018-04-05 12:59:56 -07003579 "Context.startForegroundService() did not then call Service.startForeground(): "
3580 + r);
Christopher Tate08992ac2017-03-21 11:37:06 -07003581 }
3582 }
3583
Kodlee Yin7e951262018-04-05 12:59:56 -07003584 void serviceForegroundCrash(ProcessRecord app, CharSequence serviceRecord) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003585 mAm.crashApplication(app.uid, app.pid, app.info.packageName, app.userId,
Kodlee Yin7e951262018-04-05 12:59:56 -07003586 "Context.startForegroundService() did not then call Service.startForeground(): "
3587 + serviceRecord);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003588 }
3589
Dianne Hackborn2be00932013-09-22 16:46:00 -07003590 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
3591 if (proc.executingServices.size() == 0 || proc.thread == null) {
3592 return;
3593 }
Dianne Hackborn2be00932013-09-22 16:46:00 -07003594 Message msg = mAm.mHandler.obtainMessage(
3595 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3596 msg.obj = proc;
Christopher Tate08992ac2017-03-21 11:37:06 -07003597 mAm.mHandler.sendMessageDelayed(msg,
3598 proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
3599 }
3600
3601 void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
3602 if (r.app.executingServices.size() == 0 || r.app.thread == null) {
3603 return;
3604 }
3605 Message msg = mAm.mHandler.obtainMessage(
3606 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG);
3607 msg.obj = r;
3608 r.fgWaiting = true;
3609 mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT);
Dianne Hackborn2be00932013-09-22 16:46:00 -07003610 }
3611
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003612 final class ServiceDumper {
3613 private final FileDescriptor fd;
3614 private final PrintWriter pw;
3615 private final String[] args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003616 private final boolean dumpAll;
3617 private final String dumpPackage;
3618 private final ItemMatcher matcher;
3619 private final ArrayList<ServiceRecord> services = new ArrayList<>();
3620
3621 private final long nowReal = SystemClock.elapsedRealtime();
3622
3623 private boolean needSep = false;
3624 private boolean printedAnything = false;
3625 private boolean printed = false;
3626
3627 /**
3628 * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
3629 * must be called with the lock held).
3630 */
3631 ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
3632 int opti, boolean dumpAll, String dumpPackage) {
3633 this.fd = fd;
3634 this.pw = pw;
3635 this.args = args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003636 this.dumpAll = dumpAll;
3637 this.dumpPackage = dumpPackage;
3638 matcher = new ItemMatcher();
3639 matcher.build(args, opti);
3640
3641 final int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003642 for (int user : users) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003643 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003644 if (smap.mServicesByName.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003645 for (int si=0; si<smap.mServicesByName.size(); si++) {
3646 ServiceRecord r = smap.mServicesByName.valueAt(si);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003647 if (!matcher.match(r, r.name)) {
3648 continue;
3649 }
3650 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3651 continue;
3652 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003653 services.add(r);
3654 }
3655 }
3656 }
3657 }
3658
3659 private void dumpHeaderLocked() {
3660 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
3661 if (mLastAnrDump != null) {
3662 pw.println(" Last ANR service:");
3663 pw.print(mLastAnrDump);
3664 pw.println();
3665 }
3666 }
3667
3668 void dumpLocked() {
3669 dumpHeaderLocked();
3670
3671 try {
3672 int[] users = mAm.mUserController.getUsers();
3673 for (int user : users) {
3674 // Find the first service for this user.
3675 int serviceIdx = 0;
3676 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3677 serviceIdx++;
3678 }
3679 printed = false;
3680 if (serviceIdx < services.size()) {
3681 needSep = false;
3682 while (serviceIdx < services.size()) {
3683 ServiceRecord r = services.get(serviceIdx);
3684 serviceIdx++;
3685 if (r.userId != user) {
3686 break;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003687 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003688 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003689 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003690 needSep |= printed;
3691 }
3692
3693 dumpUserRemainsLocked(user);
3694 }
3695 } catch (Exception e) {
3696 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3697 }
3698
3699 dumpRemainsLocked();
3700 }
3701
3702 void dumpWithClient() {
3703 synchronized(mAm) {
3704 dumpHeaderLocked();
3705 }
3706
3707 try {
3708 int[] users = mAm.mUserController.getUsers();
3709 for (int user : users) {
3710 // Find the first service for this user.
3711 int serviceIdx = 0;
3712 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3713 serviceIdx++;
3714 }
3715 printed = false;
3716 if (serviceIdx < services.size()) {
3717 needSep = false;
3718 while (serviceIdx < services.size()) {
3719 ServiceRecord r = services.get(serviceIdx);
3720 serviceIdx++;
3721 if (r.userId != user) {
3722 break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003723 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003724 synchronized(mAm) {
3725 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003726 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003727 dumpServiceClient(r);
3728 }
3729 needSep |= printed;
3730 }
3731
3732 synchronized(mAm) {
3733 dumpUserRemainsLocked(user);
3734 }
3735 }
3736 } catch (Exception e) {
3737 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3738 }
3739
3740 synchronized(mAm) {
3741 dumpRemainsLocked();
3742 }
3743 }
3744
3745 private void dumpUserHeaderLocked(int user) {
3746 if (!printed) {
3747 if (printedAnything) {
3748 pw.println();
3749 }
3750 pw.println(" User " + user + " active services:");
3751 printed = true;
3752 }
3753 printedAnything = true;
3754 if (needSep) {
3755 pw.println();
3756 }
3757 }
3758
3759 private void dumpServiceLocalLocked(ServiceRecord r) {
3760 dumpUserHeaderLocked(r.userId);
3761 pw.print(" * ");
3762 pw.println(r);
3763 if (dumpAll) {
3764 r.dump(pw, " ");
3765 needSep = true;
3766 } else {
3767 pw.print(" app=");
3768 pw.println(r.app);
3769 pw.print(" created=");
Yi Jin6b514142017-10-30 14:54:12 -07003770 TimeUtils.formatDuration(r.createRealTime, nowReal, pw);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003771 pw.print(" started=");
3772 pw.print(r.startRequested);
3773 pw.print(" connections=");
3774 pw.println(r.connections.size());
3775 if (r.connections.size() > 0) {
3776 pw.println(" Connections:");
3777 for (int conni=0; conni<r.connections.size(); conni++) {
3778 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
3779 for (int i = 0; i < clist.size(); i++) {
3780 ConnectionRecord conn = clist.get(i);
3781 pw.print(" ");
3782 pw.print(conn.binding.intent.intent.getIntent()
3783 .toShortString(false, false, false, false));
3784 pw.print(" -> ");
3785 ProcessRecord proc = conn.binding.client;
3786 pw.println(proc != null ? proc.toShortString() : "null");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003787 }
3788 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003789 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003790 }
3791 }
3792
3793 private void dumpServiceClient(ServiceRecord r) {
3794 final ProcessRecord proc = r.app;
3795 if (proc == null) {
3796 return;
3797 }
3798 final IApplicationThread thread = proc.thread;
3799 if (thread == null) {
3800 return;
3801 }
3802 pw.println(" Client:");
3803 pw.flush();
3804 try {
3805 TransferPipe tp = new TransferPipe();
3806 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003807 thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003808 tp.setBufferPrefix(" ");
3809 // Short timeout, since blocking here can
3810 // deadlock with the application.
3811 tp.go(fd, 2000);
3812 } finally {
3813 tp.kill();
3814 }
3815 } catch (IOException e) {
3816 pw.println(" Failure while dumping the service: " + e);
3817 } catch (RemoteException e) {
3818 pw.println(" Got a RemoteException while dumping the service");
3819 }
3820 needSep = true;
3821 }
3822
3823 private void dumpUserRemainsLocked(int user) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003824 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003825 printed = false;
3826 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
3827 ServiceRecord r = smap.mDelayedStartList.get(si);
3828 if (!matcher.match(r, r.name)) {
3829 continue;
3830 }
3831 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3832 continue;
3833 }
3834 if (!printed) {
3835 if (printedAnything) {
3836 pw.println();
3837 }
3838 pw.println(" User " + user + " delayed start services:");
3839 printed = true;
3840 }
3841 printedAnything = true;
3842 pw.print(" * Delayed start "); pw.println(r);
3843 }
3844 printed = false;
3845 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
3846 ServiceRecord r = smap.mStartingBackground.get(si);
3847 if (!matcher.match(r, r.name)) {
3848 continue;
3849 }
3850 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3851 continue;
3852 }
3853 if (!printed) {
3854 if (printedAnything) {
3855 pw.println();
3856 }
3857 pw.println(" User " + user + " starting in background:");
3858 printed = true;
3859 }
3860 printedAnything = true;
3861 pw.print(" * Starting bg "); pw.println(r);
3862 }
3863 }
3864
3865 private void dumpRemainsLocked() {
3866 if (mPendingServices.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003867 printed = false;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003868 for (int i=0; i<mPendingServices.size(); i++) {
3869 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003870 if (!matcher.match(r, r.name)) {
3871 continue;
3872 }
3873 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3874 continue;
3875 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003876 printedAnything = true;
3877 if (!printed) {
3878 if (needSep) pw.println();
3879 needSep = true;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003880 pw.println(" Pending services:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003881 printed = true;
3882 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003883 pw.print(" * Pending "); pw.println(r);
3884 r.dump(pw, " ");
3885 }
3886 needSep = true;
3887 }
3888
3889 if (mRestartingServices.size() > 0) {
3890 printed = false;
3891 for (int i=0; i<mRestartingServices.size(); i++) {
3892 ServiceRecord r = mRestartingServices.get(i);
3893 if (!matcher.match(r, r.name)) {
3894 continue;
3895 }
3896 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3897 continue;
3898 }
3899 printedAnything = true;
3900 if (!printed) {
3901 if (needSep) pw.println();
3902 needSep = true;
3903 pw.println(" Restarting services:");
3904 printed = true;
3905 }
3906 pw.print(" * Restarting "); pw.println(r);
3907 r.dump(pw, " ");
3908 }
3909 needSep = true;
3910 }
3911
3912 if (mDestroyingServices.size() > 0) {
3913 printed = false;
3914 for (int i=0; i< mDestroyingServices.size(); i++) {
3915 ServiceRecord r = mDestroyingServices.get(i);
3916 if (!matcher.match(r, r.name)) {
3917 continue;
3918 }
3919 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3920 continue;
3921 }
3922 printedAnything = true;
3923 if (!printed) {
3924 if (needSep) pw.println();
3925 needSep = true;
3926 pw.println(" Destroying services:");
3927 printed = true;
3928 }
3929 pw.print(" * Destroy "); pw.println(r);
3930 r.dump(pw, " ");
3931 }
3932 needSep = true;
3933 }
3934
3935 if (dumpAll) {
3936 printed = false;
3937 for (int ic=0; ic<mServiceConnections.size(); ic++) {
3938 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
3939 for (int i=0; i<r.size(); i++) {
3940 ConnectionRecord cr = r.get(i);
3941 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
3942 continue;
3943 }
3944 if (dumpPackage != null && (cr.binding.client == null
3945 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
3946 continue;
3947 }
3948 printedAnything = true;
3949 if (!printed) {
3950 if (needSep) pw.println();
3951 needSep = true;
3952 pw.println(" Connection bindings to services:");
3953 printed = true;
3954 }
3955 pw.print(" * "); pw.println(cr);
3956 cr.dump(pw, " ");
3957 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003958 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003959 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003960
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003961 if (matcher.all) {
3962 final long nowElapsed = SystemClock.elapsedRealtime();
3963 final int[] users = mAm.mUserController.getUsers();
3964 for (int user : users) {
3965 boolean printedUser = false;
3966 ServiceMap smap = mServiceMap.get(user);
3967 if (smap == null) {
3968 continue;
3969 }
3970 for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) {
3971 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
3972 if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) {
3973 continue;
3974 }
3975 if (!printedUser) {
3976 printedUser = true;
3977 printedAnything = true;
3978 if (needSep) pw.println();
3979 needSep = true;
3980 pw.print("Active foreground apps - user ");
3981 pw.print(user);
3982 pw.println(":");
3983 }
3984 pw.print(" #");
3985 pw.print(i);
3986 pw.print(": ");
3987 pw.println(aa.mPackageName);
3988 if (aa.mLabel != null) {
3989 pw.print(" mLabel=");
3990 pw.println(aa.mLabel);
3991 }
3992 pw.print(" mNumActive=");
3993 pw.print(aa.mNumActive);
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003994 pw.print(" mAppOnTop=");
3995 pw.print(aa.mAppOnTop);
3996 pw.print(" mShownWhileTop=");
3997 pw.print(aa.mShownWhileTop);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003998 pw.print(" mShownWhileScreenOn=");
3999 pw.println(aa.mShownWhileScreenOn);
4000 pw.print(" mStartTime=");
4001 TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw);
4002 pw.print(" mStartVisibleTime=");
4003 TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw);
4004 pw.println();
4005 if (aa.mEndTime != 0) {
4006 pw.print(" mEndTime=");
4007 TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw);
4008 pw.println();
4009 }
4010 }
Dianne Hackborncb015632017-06-14 17:30:15 -07004011 if (smap.hasMessagesOrCallbacks()) {
4012 if (needSep) {
4013 pw.println();
4014 }
4015 printedAnything = true;
4016 needSep = true;
4017 pw.print(" Handler - user ");
4018 pw.print(user);
4019 pw.println(":");
4020 smap.dumpMine(new PrintWriterPrinter(pw), " ");
4021 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004022 }
4023 }
4024
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004025 if (!printedAnything) {
4026 pw.println(" (nothing)");
4027 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07004028 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004029 }
4030
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004031 ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4032 int opti, boolean dumpAll, String dumpPackage) {
4033 return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
4034 }
4035
Yi Jin2b30f322018-02-20 15:41:47 -08004036 protected void writeToProto(ProtoOutputStream proto, long fieldId) {
Yi Jin6b514142017-10-30 14:54:12 -07004037 synchronized (mAm) {
Yi Jin2b30f322018-02-20 15:41:47 -08004038 final long outterToken = proto.start(fieldId);
Yi Jin6b514142017-10-30 14:54:12 -07004039 int[] users = mAm.mUserController.getUsers();
4040 for (int user : users) {
4041 ServiceMap smap = mServiceMap.get(user);
4042 if (smap == null) {
4043 continue;
4044 }
4045 long token = proto.start(ActiveServicesProto.SERVICES_BY_USERS);
4046 proto.write(ActiveServicesProto.ServicesByUser.USER_ID, user);
4047 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
4048 for (int i=0; i<alls.size(); i++) {
4049 alls.valueAt(i).writeToProto(proto,
4050 ActiveServicesProto.ServicesByUser.SERVICE_RECORDS);
4051 }
4052 proto.end(token);
4053 }
Yi Jin2b30f322018-02-20 15:41:47 -08004054 proto.end(outterToken);
Yi Jin6b514142017-10-30 14:54:12 -07004055 }
4056 }
4057
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004058 /**
4059 * There are three ways to call this:
4060 * - no service specified: dump all the services
4061 * - a flattened component name that matched an existing service was specified as the
4062 * first arg: dump that one service
4063 * - the first arg isn't the flattened component name of an existing service:
4064 * dump all services whose component contains the first arg as a substring
4065 */
4066 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4067 int opti, boolean dumpAll) {
4068 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
4069
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004070 synchronized (mAm) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07004071 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07004072 if ("all".equals(name)) {
4073 for (int user : users) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -07004074 ServiceMap smap = mServiceMap.get(user);
4075 if (smap == null) {
4076 continue;
4077 }
4078 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004079 for (int i=0; i<alls.size(); i++) {
4080 ServiceRecord r1 = alls.valueAt(i);
Amith Yamasani258848d2012-08-10 17:06:33 -07004081 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004082 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004083 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07004084 } else {
4085 ComponentName componentName = name != null
4086 ? ComponentName.unflattenFromString(name) : null;
4087 int objectId = 0;
4088 if (componentName == null) {
4089 // Not a '/' separated full component name; maybe an object ID?
4090 try {
4091 objectId = Integer.parseInt(name, 16);
4092 name = null;
4093 componentName = null;
4094 } catch (RuntimeException e) {
4095 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004096 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004097
Dianne Hackborn1676c852012-09-10 14:52:30 -07004098 for (int user : users) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -07004099 ServiceMap smap = mServiceMap.get(user);
4100 if (smap == null) {
4101 continue;
4102 }
4103 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004104 for (int i=0; i<alls.size(); i++) {
4105 ServiceRecord r1 = alls.valueAt(i);
Amith Yamasani258848d2012-08-10 17:06:33 -07004106 if (componentName != null) {
4107 if (r1.name.equals(componentName)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004108 services.add(r1);
4109 }
Amith Yamasani258848d2012-08-10 17:06:33 -07004110 } else if (name != null) {
4111 if (r1.name.flattenToString().contains(name)) {
4112 services.add(r1);
4113 }
4114 } else if (System.identityHashCode(r1) == objectId) {
4115 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004116 }
4117 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004118 }
4119 }
4120 }
4121
4122 if (services.size() <= 0) {
4123 return false;
4124 }
4125
4126 boolean needSep = false;
4127 for (int i=0; i<services.size(); i++) {
4128 if (needSep) {
4129 pw.println();
4130 }
4131 needSep = true;
4132 dumpService("", fd, pw, services.get(i), args, dumpAll);
4133 }
4134 return true;
4135 }
4136
4137 /**
4138 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
4139 * there is a thread associated with the service.
4140 */
4141 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
4142 final ServiceRecord r, String[] args, boolean dumpAll) {
4143 String innerPrefix = prefix + " ";
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004144 synchronized (mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004145 pw.print(prefix); pw.print("SERVICE ");
4146 pw.print(r.shortName); pw.print(" ");
4147 pw.print(Integer.toHexString(System.identityHashCode(r)));
4148 pw.print(" pid=");
4149 if (r.app != null) pw.println(r.app.pid);
4150 else pw.println("(not running)");
4151 if (dumpAll) {
4152 r.dump(pw, innerPrefix);
4153 }
4154 }
4155 if (r.app != null && r.app.thread != null) {
4156 pw.print(prefix); pw.println(" Client:");
4157 pw.flush();
4158 try {
4159 TransferPipe tp = new TransferPipe();
4160 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004161 r.app.thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004162 tp.setBufferPrefix(prefix + " ");
4163 tp.go(fd);
4164 } finally {
4165 tp.kill();
4166 }
4167 } catch (IOException e) {
4168 pw.println(prefix + " Failure while dumping the service: " + e);
4169 } catch (RemoteException e) {
4170 pw.println(prefix + " Got a RemoteException while dumping the service");
4171 }
4172 }
4173 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004174}