blob: 067566dcc1774143578643064a5d005fa44ea539 [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 Tatec7933ac2018-03-12 17:57:09 -0700418 // If the app has strict background restrictions, we treat any service
419 // start analogously to the legacy-app forced-restrictions case.
420 boolean forcedStandby = false;
421 if (appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
422 if (DEBUG_FOREGROUND_SERVICE) {
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700423 Slog.d(TAG, "Forcing bg-only service start only for " + r.shortName);
Christopher Tatec7933ac2018-03-12 17:57:09 -0700424 }
425 forcedStandby = true;
426 }
427
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700428 // If this is a direct-to-foreground start, make sure it is allowed as per the app op.
429 boolean forceSilentAbort = false;
430 if (fgRequired) {
431 final int mode = mAm.mAppOpsService.checkOperation(
432 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
433 switch (mode) {
434 case AppOpsManager.MODE_ALLOWED:
435 case AppOpsManager.MODE_DEFAULT:
436 // All okay.
437 break;
438 case AppOpsManager.MODE_IGNORED:
439 // Not allowed, fall back to normal start service, failing siliently
440 // if background check restricts that.
441 Slog.w(TAG, "startForegroundService not allowed due to app op: service "
442 + service + " to " + r.name.flattenToShortString()
443 + " from pid=" + callingPid + " uid=" + callingUid
444 + " pkg=" + callingPackage);
445 fgRequired = false;
446 forceSilentAbort = true;
447 break;
448 default:
449 return new ComponentName("!!", "foreground not allowed as per app op");
450 }
451 }
452
Christopher Tate08992ac2017-03-21 11:37:06 -0700453 // If this isn't a direct-to-foreground start, check our ability to kick off an
454 // arbitrary service
Christopher Tatec7933ac2018-03-12 17:57:09 -0700455 if (forcedStandby || (!r.startRequested && !fgRequired)) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700456 // Before going further -- if this app is not allowed to start services in the
457 // background, then at this point we aren't going to let it period.
458 final int allowed = mAm.getAppStartModeLocked(r.appInfo.uid, r.packageName,
Christopher Tatec7933ac2018-03-12 17:57:09 -0700459 r.appInfo.targetSdkVersion, callingPid, false, false, forcedStandby);
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700460 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
461 Slog.w(TAG, "Background start not allowed: service "
462 + service + " to " + r.name.flattenToShortString()
463 + " from pid=" + callingPid + " uid=" + callingUid
464 + " pkg=" + callingPackage);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700465 if (allowed == ActivityManager.APP_START_MODE_DELAYED || forceSilentAbort) {
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700466 // In this case we are silently disabling the app, to disrupt as
467 // little as possible existing apps.
468 return null;
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700469 }
Dianne Hackbornc75587e2017-04-11 15:37:03 -0700470 // This app knows it is in the new model where this operation is not
471 // allowed, so tell it what has happened.
472 UidRecord uidRec = mAm.mActiveUids.get(r.appInfo.uid);
473 return new ComponentName("?", "app is in background uid " + uidRec);
Dianne Hackborn4fb9c4a2016-04-04 13:31:18 -0700474 }
475 }
476
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700477 NeededUriGrants neededGrants = mAm.checkGrantUriPermissionFromIntentLocked(
Nicolas Prevotc6cf95c2014-05-29 11:30:36 +0100478 callingUid, r.packageName, service, service.getFlags(), null, r.userId);
Svet Ganov9c165d72015-12-01 19:52:26 -0800479
480 // If permissions need a review before any of the app components can run,
481 // we do not start the service and launch a review activity if the calling app
482 // is in the foreground passing it a pending intent to start the service when
483 // review is completed.
Svet Ganov77df6f32016-08-17 11:46:34 -0700484 if (mAm.mPermissionReviewRequired) {
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700485 // XXX This is not dealing with fgRequired!
Svet Ganov9c165d72015-12-01 19:52:26 -0800486 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage,
487 callingUid, service, callerFg, userId)) {
488 return null;
489 }
490 }
491
Dianne Hackbornd6f5b622013-11-11 17:25:37 -0800492 if (unscheduleServiceRestartLocked(r, callingUid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800493 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700494 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700495 r.lastActivity = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700496 r.startRequested = true;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700497 r.delayedStop = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700498 r.fgRequired = fgRequired;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700499 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -0700500 service, neededGrants, callingUid));
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700501
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -0700502 if (fgRequired) {
503 // We are now effectively running a foreground service.
504 mAm.mAppOpsService.startOperation(AppOpsManager.getToken(mAm.mAppOpsService),
505 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, true);
506 }
507
Dianne Hackbornad51be92016-08-16 16:27:36 -0700508 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700509 boolean addToStarting = false;
Christopher Tate08992ac2017-03-21 11:37:06 -0700510 if (!callerFg && !fgRequired && r.app == null
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700511 && mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700512 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700513 if (proc == null || proc.curProcState > ActivityManager.PROCESS_STATE_RECEIVER) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700514 // If this is not coming from a foreground caller, then we may want
515 // to delay the start if there are already other background services
516 // that are starting. This is to avoid process start spam when lots
517 // of applications are all handling things like connectivity broadcasts.
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700518 // We only do this for cached processes, because otherwise an application
519 // can have assumptions about calling startService() for a service to run
520 // in its own process, and for that process to not be killed before the
521 // service is started. This is especially the case for receivers, which
522 // may start a service in onReceive() to do some additional work and have
523 // initialized some global state as part of that.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800524 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
525 + r + " in " + proc);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700526 if (r.delayed) {
527 // This service is already scheduled for a delayed start; just leave
528 // it still waiting.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800529 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700530 return r.name;
531 }
532 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
533 // Something else is starting, delay!
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800534 Slog.i(TAG_SERVICE, "Delaying start of: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700535 smap.mDelayedStartList.add(r);
536 r.delayed = true;
537 return r.name;
538 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800539 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700540 addToStarting = true;
541 } else if (proc.curProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
542 // We slightly loosen when we will enqueue this new service as a background
543 // starting service we are waiting for, to also include processes that are
Dianne Hackborn0d97cd12013-09-16 19:02:52 -0700544 // currently running other services or receivers.
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700545 addToStarting = true;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800546 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
547 "Not delaying, but counting as bg: " + r);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800548 } else if (DEBUG_DELAYED_STARTS) {
Dianne Hackborn8e692572013-09-10 19:06:15 -0700549 StringBuilder sb = new StringBuilder(128);
550 sb.append("Not potential delay (state=").append(proc.curProcState)
551 .append(' ').append(proc.adjType);
552 String reason = proc.makeAdjReason();
553 if (reason != null) {
554 sb.append(' ');
555 sb.append(reason);
556 }
557 sb.append("): ");
558 sb.append(r.toString());
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800559 Slog.v(TAG_SERVICE, sb.toString());
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700560 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800561 } else if (DEBUG_DELAYED_STARTS) {
Christopher Tate08992ac2017-03-21 11:37:06 -0700562 if (callerFg || fgRequired) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800563 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
Christopher Tate08992ac2017-03-21 11:37:06 -0700564 + callingUid + " pid=" + callingPid + " fgRequired=" + fgRequired + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700565 } else if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800566 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700567 } else {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800568 Slog.v(TAG_SERVICE,
569 "Not potential delay (user " + r.userId + " not started): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700570 }
571 }
572
Christopher Tate42a386b2016-11-07 12:21:21 -0800573 ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
Christopher Tate42a386b2016-11-07 12:21:21 -0800574 return cmp;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700575 }
576
Svet Ganov9c165d72015-12-01 19:52:26 -0800577 private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
578 String callingPackage, int callingUid, Intent service, boolean callerFg,
579 final int userId) {
580 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
581 r.packageName, r.userId)) {
582
583 // Show a permission review UI only for starting from a foreground app
584 if (!callerFg) {
585 Slog.w(TAG, "u" + r.userId + " Starting a service in package"
586 + r.packageName + " requires a permissions review");
587 return false;
588 }
589
590 IIntentSender target = mAm.getIntentSenderLocked(
591 ActivityManager.INTENT_SENDER_SERVICE, callingPackage,
592 callingUid, userId, null, null, 0, new Intent[]{service},
593 new String[]{service.resolveType(mAm.mContext.getContentResolver())},
594 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
595 | PendingIntent.FLAG_IMMUTABLE, null);
596
597 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
598 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
599 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
600 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
601 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
602
603 if (DEBUG_PERMISSIONS_REVIEW) {
604 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
605 + r.packageName);
606 }
607
608 mAm.mHandler.post(new Runnable() {
609 @Override
610 public void run() {
611 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
612 }
613 });
614
615 return false;
616 }
617
618 return true;
619 }
620
Craig Mautner5f2bb4c2015-03-12 16:10:27 -0700621 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
622 boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
Joe Onorato4eb64fd2016-03-21 15:30:09 -0700623 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -0700624 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700625 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700626 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700627 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700628 synchronized (r.stats.getBatteryStats()) {
629 r.stats.startRunningLocked();
630 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800631 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700632 if (error != null) {
633 return new ComponentName("!!", error);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700634 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700635
636 if (r.startRequested && addToStarting) {
637 boolean first = smap.mStartingBackground.size() == 0;
638 smap.mStartingBackground.add(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700639 r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700640 if (DEBUG_DELAYED_SERVICE) {
641 RuntimeException here = new RuntimeException("here");
642 here.fillInStackTrace();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800643 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -0800644 } else if (DEBUG_DELAYED_STARTS) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800645 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700646 }
647 if (first) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700648 smap.rescheduleDelayedStartsLocked();
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700649 }
Christopher Tate08992ac2017-03-21 11:37:06 -0700650 } else if (callerFg || r.fgRequired) {
Dianne Hackbornad51be92016-08-16 16:27:36 -0700651 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700652 }
653
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700654 return r.name;
655 }
656
657 private void stopServiceLocked(ServiceRecord service) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700658 if (service.delayed) {
659 // If service isn't actually running, but is is being held in the
660 // delayed list, then we need to keep it started but note that it
661 // should be stopped once no longer delayed.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800662 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -0700663 service.delayedStop = true;
664 return;
665 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700666 synchronized (service.stats.getBatteryStats()) {
667 service.stats.stopRunningLocked();
668 }
669 service.startRequested = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700670 if (service.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700671 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700672 SystemClock.uptimeMillis());
673 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700674 service.callStart = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700675 bringDownServiceIfNeededLocked(service, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700676 }
677
678 int stopServiceLocked(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700679 String resolvedType, int userId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800680 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700681 + " type=" + resolvedType);
682
683 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
684 if (caller != null && callerApp == null) {
685 throw new SecurityException(
686 "Unable to find app for caller " + caller
687 + " (pid=" + Binder.getCallingPid()
688 + ") when stopping service " + service);
689 }
690
691 // If this service is active, make sure it is stopped.
Svet Ganov99b60432015-06-27 13:15:22 -0700692 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, null,
Svet Ganovd223db32017-12-22 09:43:48 -0800693 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700694 if (r != null) {
695 if (r.record != null) {
696 final long origId = Binder.clearCallingIdentity();
697 try {
698 stopServiceLocked(r.record);
699 } finally {
700 Binder.restoreCallingIdentity(origId);
701 }
702 return 1;
703 }
704 return -1;
705 }
706
707 return 0;
708 }
709
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700710 void stopInBackgroundLocked(int uid) {
711 // Stop all services associated with this uid due to it going to the background
712 // stopped state.
713 ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
714 ArrayList<ServiceRecord> stopping = null;
715 if (services != null) {
716 for (int i=services.mServicesByName.size()-1; i>=0; i--) {
717 ServiceRecord service = services.mServicesByName.valueAt(i);
718 if (service.appInfo.uid == uid && service.startRequested) {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800719 if (mAm.getAppStartModeLocked(service.appInfo.uid, service.packageName,
Christopher Tatec7933ac2018-03-12 17:57:09 -0700720 service.appInfo.targetSdkVersion, -1, false, false, false)
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800721 != ActivityManager.APP_START_MODE_NORMAL) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700722 if (stopping == null) {
723 stopping = new ArrayList<>();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700724 }
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700725 String compName = service.name.flattenToShortString();
726 EventLogTags.writeAmStopIdleService(service.appInfo.uid, compName);
727 StringBuilder sb = new StringBuilder(64);
728 sb.append("Stopping service due to app idle: ");
729 UserHandle.formatUid(sb, service.appInfo.uid);
730 sb.append(" ");
Yi Jin6b514142017-10-30 14:54:12 -0700731 TimeUtils.formatDuration(service.createRealTime
Dianne Hackborna33f1a22017-06-15 14:33:16 -0700732 - SystemClock.elapsedRealtime(), sb);
733 sb.append(" ");
734 sb.append(compName);
735 Slog.w(TAG, sb.toString());
736 stopping.add(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700737 }
738 }
739 }
740 if (stopping != null) {
741 for (int i=stopping.size()-1; i>=0; i--) {
742 ServiceRecord service = stopping.get(i);
743 service.delayed = false;
Dianne Hackbornad51be92016-08-16 16:27:36 -0700744 services.ensureNotStartingBackgroundLocked(service);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700745 stopServiceLocked(service);
746 }
747 }
748 }
749 }
750
Svet Ganov99b60432015-06-27 13:15:22 -0700751 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
752 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, callingPackage,
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -0700753 Binder.getCallingPid(), Binder.getCallingUid(),
Svet Ganovd223db32017-12-22 09:43:48 -0800754 UserHandle.getCallingUserId(), false, false, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700755
756 IBinder ret = null;
757 if (r != null) {
758 // r.record is null if findServiceLocked() failed the caller permission check
759 if (r.record == null) {
760 throw new SecurityException(
Christopher Desjardins5862c5f2015-05-19 11:25:40 +0000761 "Permission Denial: Accessing service"
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700762 + " from pid=" + Binder.getCallingPid()
763 + ", uid=" + Binder.getCallingUid()
764 + " requires " + r.permission);
765 }
766 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
767 if (ib != null) {
768 ret = ib.binder;
769 }
770 }
771
772 return ret;
773 }
774
775 boolean stopServiceTokenLocked(ComponentName className, IBinder token,
776 int startId) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800777 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700778 + " " + token + " startId=" + startId);
Dianne Hackborn41203752012-08-31 14:05:51 -0700779 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700780 if (r != null) {
781 if (startId >= 0) {
782 // Asked to only stop if done with all work. Note that
783 // to avoid leaks, we will take this as dropping all
784 // start items up to and including this one.
785 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
786 if (si != null) {
787 while (r.deliveredStarts.size() > 0) {
788 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
789 cur.removeUriPermissionsLocked();
790 if (cur == si) {
791 break;
792 }
793 }
794 }
795
796 if (r.getLastStartId() != startId) {
797 return false;
798 }
799
800 if (r.deliveredStarts.size() > 0) {
801 Slog.w(TAG, "stopServiceToken startId " + startId
802 + " is last, but have " + r.deliveredStarts.size()
803 + " remaining args");
804 }
805 }
806
807 synchronized (r.stats.getBatteryStats()) {
808 r.stats.stopRunningLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700809 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700810 r.startRequested = false;
811 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -0700812 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700813 SystemClock.uptimeMillis());
814 }
815 r.callStart = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700816 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700817 bringDownServiceIfNeededLocked(r, false, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700818 Binder.restoreCallingIdentity(origId);
819 return true;
820 }
821 return false;
822 }
823
Sudheer Shankac9d94072017-02-22 22:13:55 +0000824 public void setServiceForegroundLocked(ComponentName className, IBinder token,
Dianne Hackborn67324c92016-04-18 13:55:25 -0700825 int id, Notification notification, int flags) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700826 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700827 final long origId = Binder.clearCallingIdentity();
828 try {
Dianne Hackborn41203752012-08-31 14:05:51 -0700829 ServiceRecord r = findServiceLocked(className, token, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700830 if (r != null) {
Sudheer Shankac9d94072017-02-22 22:13:55 +0000831 setServiceForegroundInnerLocked(r, id, notification, flags);
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700832 }
833 } finally {
834 Binder.restoreCallingIdentity(origId);
835 }
836 }
837
Dianne Hackborncb015632017-06-14 17:30:15 -0700838 boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) {
839 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid="
840 + aa.mUid);
841 boolean canRemove = false;
842 aa.mHideTime = Long.MAX_VALUE;
843 if (aa.mShownWhileTop) {
844 // If the app was ever at the top of the screen while the foreground
845 // service was running, then we can always just immediately remove it.
846 canRemove = true;
847 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown while on top");
848 } else if (mScreenOn || aa.mShownWhileScreenOn) {
849 final long minTime = aa.mStartVisibleTime
850 + (aa.mStartTime != aa.mStartVisibleTime
851 ? mAm.mConstants.FGSERVICE_SCREEN_ON_AFTER_TIME
852 : mAm.mConstants.FGSERVICE_MIN_SHOWN_TIME);
853 if (nowElapsed >= minTime) {
854 // If shown while the screen is on, and it has been shown for
855 // at least the minimum show time, then we can now remove it.
856 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown long enough with screen on");
857 canRemove = true;
858 } else {
859 // This is when we will be okay to stop telling the user.
860 long reportTime = nowElapsed + mAm.mConstants.FGSERVICE_MIN_REPORT_TIME;
861 aa.mHideTime = reportTime > minTime ? reportTime : minTime;
862 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
863 + " with screen on");
864 }
865 } else {
866 final long minTime = aa.mEndTime
867 + mAm.mConstants.FGSERVICE_SCREEN_ON_BEFORE_TIME;
868 if (nowElapsed >= minTime) {
869 // If the foreground service has only run while the screen is
870 // off, but it has been gone now for long enough that we won't
871 // care to tell the user about it when the screen comes back on,
872 // then we can remove it now.
873 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - gone long enough with screen off");
874 canRemove = true;
875 } else {
876 // This is when we won't care about this old fg service.
877 aa.mHideTime = minTime;
878 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
879 + " with screen off");
880 }
881 }
882 return canRemove;
883 }
884
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700885 void updateForegroundApps(ServiceMap smap) {
886 // This is called from the handler without the lock held.
887 ArrayList<ActiveForegroundApp> active = null;
888 synchronized (mAm) {
889 final long now = SystemClock.elapsedRealtime();
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700890 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700891 if (smap != null) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700892 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Updating foreground apps for user "
893 + smap.mUserId);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700894 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
895 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -0700896 if (aa.mEndTime != 0) {
897 boolean canRemove = foregroundAppShownEnoughLocked(aa, now);
898 if (canRemove) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700899 // This was up for longer than the timeout, so just remove immediately.
900 smap.mActiveForegroundApps.removeAt(i);
901 smap.mActiveForegroundAppsChanged = true;
902 continue;
903 }
Dianne Hackborncb015632017-06-14 17:30:15 -0700904 if (aa.mHideTime < nextUpdateTime) {
905 nextUpdateTime = aa.mHideTime;
906 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700907 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700908 if (!aa.mAppOnTop) {
909 if (active == null) {
910 active = new ArrayList<>();
911 }
Dianne Hackborncb015632017-06-14 17:30:15 -0700912 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
913 + aa.mPackageName + ", uid=" + aa.mUid);
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700914 active.add(aa);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700915 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -0700916 }
917 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
918 if (nextUpdateTime < Long.MAX_VALUE) {
Dianne Hackborncb015632017-06-14 17:30:15 -0700919 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Next update time in: "
920 + (nextUpdateTime-now));
921 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700922 smap.sendMessageAtTime(msg, nextUpdateTime
923 + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700924 }
925 }
926 if (!smap.mActiveForegroundAppsChanged) {
927 return;
928 }
929 smap.mActiveForegroundAppsChanged = false;
930 }
931
932 final NotificationManager nm = (NotificationManager) mAm.mContext.getSystemService(
933 Context.NOTIFICATION_SERVICE);
934 final Context context = mAm.mContext;
935
936 if (active != null) {
937 for (int i = 0; i < active.size(); i++) {
938 ActiveForegroundApp aa = active.get(i);
939 if (aa.mLabel == null) {
940 PackageManager pm = context.getPackageManager();
941 try {
942 ApplicationInfo ai = pm.getApplicationInfoAsUser(aa.mPackageName,
943 PackageManager.MATCH_KNOWN_PACKAGES, smap.mUserId);
944 aa.mLabel = ai.loadLabel(pm);
945 } catch (PackageManager.NameNotFoundException e) {
946 aa.mLabel = aa.mPackageName;
947 }
948 }
949 }
950
951 Intent intent;
952 String title;
953 String msg;
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700954 String[] pkgs;
Dan Sandler886e0162017-06-06 14:23:43 -0400955 final long nowElapsed = SystemClock.elapsedRealtime();
956 long oldestStartTime = nowElapsed;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700957 if (active.size() == 1) {
958 intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
959 intent.setData(Uri.fromParts("package", active.get(0).mPackageName, null));
960 title = context.getString(
961 R.string.foreground_service_app_in_background, active.get(0).mLabel);
962 msg = context.getString(R.string.foreground_service_tap_for_details);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700963 pkgs = new String[] { active.get(0).mPackageName };
Dan Sandler2f36ab82017-05-25 00:15:49 -0400964 oldestStartTime = active.get(0).mStartTime;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700965 } else {
966 intent = new Intent(Settings.ACTION_FOREGROUND_SERVICES_SETTINGS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700967 pkgs = new String[active.size()];
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700968 for (int i = 0; i < active.size(); i++) {
969 pkgs[i] = active.get(i).mPackageName;
Dan Sandler2f36ab82017-05-25 00:15:49 -0400970 oldestStartTime = Math.min(oldestStartTime, active.get(i).mStartTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700971 }
972 intent.putExtra("packages", pkgs);
973 title = context.getString(
974 R.string.foreground_service_apps_in_background, active.size());
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700975 msg = active.get(0).mLabel.toString();
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700976 for (int i = 1; i < active.size(); i++) {
977 msg = context.getString(R.string.foreground_service_multiple_separator,
978 msg, active.get(i).mLabel);
979 }
980 }
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700981 Bundle notificationBundle = new Bundle();
982 notificationBundle.putStringArray(Notification.EXTRA_FOREGROUND_APPS, pkgs);
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700983 Notification.Builder n =
984 new Notification.Builder(context,
985 SystemNotificationChannels.FOREGROUND_SERVICE)
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -0700986 .addExtras(notificationBundle)
Dan Sandler2f36ab82017-05-25 00:15:49 -0400987 .setSmallIcon(R.drawable.stat_sys_vitals)
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700988 .setOngoing(true)
Dan Sandler886e0162017-06-06 14:23:43 -0400989 .setShowWhen(oldestStartTime < nowElapsed)
990 .setWhen(System.currentTimeMillis() - (nowElapsed - oldestStartTime))
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700991 .setColor(context.getColor(
992 com.android.internal.R.color.system_notification_accent_color))
993 .setContentTitle(title)
994 .setContentText(msg)
995 .setContentIntent(
996 PendingIntent.getActivityAsUser(context, 0, intent,
997 PendingIntent.FLAG_UPDATE_CURRENT,
998 null, new UserHandle(smap.mUserId)));
999 nm.notifyAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1000 n.build(), new UserHandle(smap.mUserId));
1001 } else {
1002 nm.cancelAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1003 new UserHandle(smap.mUserId));
1004 }
1005 }
1006
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001007 private void requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001008 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001009 if (timeElapsed != 0) {
1010 smap.sendMessageAtTime(msg,
1011 timeElapsed + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001012 } else {
1013 smap.mActiveForegroundAppsChanged = true;
1014 smap.sendMessage(msg);
1015 }
1016 }
1017
1018 private void decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r) {
1019 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1020 if (active != null) {
1021 active.mNumActive--;
1022 if (active.mNumActive <= 0) {
1023 active.mEndTime = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001024 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Ended running of service");
1025 if (foregroundAppShownEnoughLocked(active, active.mEndTime)) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001026 // Have been active for long enough that we will remove it immediately.
1027 smap.mActiveForegroundApps.remove(r.packageName);
1028 smap.mActiveForegroundAppsChanged = true;
1029 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001030 } else if (active.mHideTime < Long.MAX_VALUE){
1031 requestUpdateActiveForegroundAppsLocked(smap, active.mHideTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001032 }
1033 }
1034 }
1035 }
1036
1037 void updateScreenStateLocked(boolean screenOn) {
1038 if (mScreenOn != screenOn) {
1039 mScreenOn = screenOn;
1040
1041 // If screen is turning on, then we now reset the start time of any foreground
1042 // services that were started while the screen was off.
1043 if (screenOn) {
1044 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborncb015632017-06-14 17:30:15 -07001045 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Screen turned on");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001046 for (int i = mServiceMap.size()-1; i >= 0; i--) {
1047 ServiceMap smap = mServiceMap.valueAt(i);
Dianne Hackborncb015632017-06-14 17:30:15 -07001048 long nextUpdateTime = Long.MAX_VALUE;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001049 boolean changed = false;
1050 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1051 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
Dianne Hackborncb015632017-06-14 17:30:15 -07001052 if (active.mEndTime == 0) {
1053 if (!active.mShownWhileScreenOn) {
1054 active.mShownWhileScreenOn = true;
1055 active.mStartVisibleTime = nowElapsed;
1056 }
1057 } else {
1058 if (!active.mShownWhileScreenOn
1059 && active.mStartVisibleTime == active.mStartTime) {
1060 // If this was never shown while the screen was on, then we will
1061 // count the time it started being visible as now, to tell the user
1062 // about it now that they have a screen to look at.
1063 active.mEndTime = active.mStartVisibleTime = nowElapsed;
1064 }
1065 if (foregroundAppShownEnoughLocked(active, nowElapsed)) {
1066 // Have been active for long enough that we will remove it
1067 // immediately.
1068 smap.mActiveForegroundApps.remove(active.mPackageName);
1069 smap.mActiveForegroundAppsChanged = true;
1070 changed = true;
1071 } else {
1072 if (active.mHideTime < nextUpdateTime) {
1073 nextUpdateTime = active.mHideTime;
1074 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001075 }
1076 }
1077 }
1078 if (changed) {
Dianne Hackborncb015632017-06-14 17:30:15 -07001079 // Need to immediately update.
Dianne Hackbornfb5d4b52017-05-16 17:03:44 -07001080 requestUpdateActiveForegroundAppsLocked(smap, 0);
Dianne Hackborncb015632017-06-14 17:30:15 -07001081 } else if (nextUpdateTime < Long.MAX_VALUE) {
1082 requestUpdateActiveForegroundAppsLocked(smap, nextUpdateTime);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001083 }
1084 }
1085 }
1086 }
1087 }
1088
Dianne Hackbornbe68d492017-05-03 18:04:05 -07001089 void foregroundServiceProcStateChangedLocked(UidRecord uidRec) {
1090 ServiceMap smap = mServiceMap.get(UserHandle.getUserId(uidRec.uid));
1091 if (smap != null) {
1092 boolean changed = false;
1093 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1094 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
1095 if (active.mUid == uidRec.uid) {
1096 if (uidRec.curProcState <= ActivityManager.PROCESS_STATE_TOP) {
1097 if (!active.mAppOnTop) {
1098 active.mAppOnTop = true;
1099 changed = true;
1100 }
1101 active.mShownWhileTop = true;
1102 } else if (active.mAppOnTop) {
1103 active.mAppOnTop = false;
1104 changed = true;
1105 }
1106 }
1107 }
1108 if (changed) {
1109 requestUpdateActiveForegroundAppsLocked(smap, 0);
1110 }
1111 }
1112 }
1113
Christopher Tatec7933ac2018-03-12 17:57:09 -07001114 /**
1115 * @param id Notification ID. Zero === exit foreground state for the given service.
1116 */
1117 private void setServiceForegroundInnerLocked(final ServiceRecord r, int id,
Christopher Tate42a386b2016-11-07 12:21:21 -08001118 Notification notification, int flags) {
1119 if (id != 0) {
1120 if (notification == null) {
1121 throw new IllegalArgumentException("null notification");
1122 }
Chad Brubaker97b383f2017-02-02 15:04:35 -08001123 // Instant apps need permission to create foreground services.
1124 if (r.appInfo.isInstantApp()) {
1125 final int mode = mAm.mAppOpsService.checkOperation(
1126 AppOpsManager.OP_INSTANT_APP_START_FOREGROUND,
1127 r.appInfo.uid,
1128 r.appInfo.packageName);
1129 switch (mode) {
1130 case AppOpsManager.MODE_ALLOWED:
1131 break;
1132 case AppOpsManager.MODE_IGNORED:
1133 Slog.w(TAG, "Instant app " + r.appInfo.packageName
1134 + " does not have permission to create foreground services"
1135 + ", ignoring.");
Sudheer Shankac9d94072017-02-22 22:13:55 +00001136 return;
Chad Brubaker97b383f2017-02-02 15:04:35 -08001137 case AppOpsManager.MODE_ERRORED:
1138 throw new SecurityException("Instant app " + r.appInfo.packageName
1139 + " does not have permission to create foreground services");
1140 default:
Dianne Hackborndd027b32018-01-19 17:44:46 -08001141 mAm.enforcePermission(
1142 android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
1143 r.app.pid, r.appInfo.uid, "startForeground");
Chad Brubaker97b383f2017-02-02 15:04:35 -08001144 }
Dianne Hackborndd027b32018-01-19 17:44:46 -08001145 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
1146 mAm.enforcePermission(
1147 android.Manifest.permission.FOREGROUND_SERVICE,
1148 r.app.pid, r.appInfo.uid, "startForeground");
Chad Brubaker97b383f2017-02-02 15:04:35 -08001149 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001150 boolean alreadyStartedOp = false;
Christopher Tate08992ac2017-03-21 11:37:06 -07001151 if (r.fgRequired) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001152 if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001153 Slog.i(TAG, "Service called startForeground() as required: " + r);
1154 }
1155 r.fgRequired = false;
1156 r.fgWaiting = false;
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001157 alreadyStartedOp = true;
Christopher Tate08992ac2017-03-21 11:37:06 -07001158 mAm.mHandler.removeMessages(
1159 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
1160 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001161
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001162 try {
1163 boolean ignoreForeground = false;
1164 final int mode = mAm.mAppOpsService.checkOperation(
1165 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
1166 switch (mode) {
1167 case AppOpsManager.MODE_ALLOWED:
1168 case AppOpsManager.MODE_DEFAULT:
1169 // All okay.
1170 break;
1171 case AppOpsManager.MODE_IGNORED:
1172 // Whoops, silently ignore this.
1173 Slog.w(TAG, "Service.startForeground() not allowed due to app op: service "
1174 + r.shortName);
1175 ignoreForeground = true;
1176 break;
1177 default:
1178 throw new SecurityException("Foreground not allowed as per app op");
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001179 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001180
1181 if (!ignoreForeground &&
1182 appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
1183 ignoreForeground = true;
1184 Slog.w(TAG,
1185 "Service.startForeground() not allowed due to bg restriction: service "
1186 + r.shortName);
1187 }
1188
1189 // Apps under strict background restrictions simply don't get to have foreground
1190 // services, so now that we've enforced the startForegroundService() contract
1191 // we only do the machinery of making the service foreground when the app
1192 // is not restricted.
1193 if (!ignoreForeground) {
1194 if (r.foregroundId != id) {
1195 cancelForegroundNotificationLocked(r);
1196 r.foregroundId = id;
Christopher Tatec7933ac2018-03-12 17:57:09 -07001197 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001198 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
1199 r.foregroundNoti = notification;
1200 if (!r.isForeground) {
1201 final ServiceMap smap = getServiceMapLocked(r.userId);
1202 if (smap != null) {
1203 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1204 if (active == null) {
1205 active = new ActiveForegroundApp();
1206 active.mPackageName = r.packageName;
1207 active.mUid = r.appInfo.uid;
1208 active.mShownWhileScreenOn = mScreenOn;
1209 if (r.app != null) {
1210 active.mAppOnTop = active.mShownWhileTop =
1211 r.app.uidRecord.curProcState
1212 <= ActivityManager.PROCESS_STATE_TOP;
1213 }
1214 active.mStartTime = active.mStartVisibleTime
1215 = SystemClock.elapsedRealtime();
1216 smap.mActiveForegroundApps.put(r.packageName, active);
1217 requestUpdateActiveForegroundAppsLocked(smap, 0);
1218 }
1219 active.mNumActive++;
1220 }
1221 r.isForeground = true;
1222 mAm.mAppOpsService.startOperation(
1223 AppOpsManager.getToken(mAm.mAppOpsService),
1224 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName,
1225 true);
1226 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
1227 r.appInfo.uid, r.shortName,
1228 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER);
1229 }
1230 r.postNotification();
1231 if (r.app != null) {
1232 updateServiceForegroundLocked(r.app, true);
1233 }
1234 getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
1235 mAm.notifyPackageUse(r.serviceInfo.packageName,
1236 PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
1237 } else {
1238 if (DEBUG_FOREGROUND_SERVICE) {
1239 Slog.d(TAG, "Suppressing startForeground() for FAS " + r);
1240 }
Christopher Tatec7933ac2018-03-12 17:57:09 -07001241 }
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001242 } finally {
1243 if (alreadyStartedOp) {
1244 // If we had previously done a start op for direct foreground start,
1245 // we have cleared the flag so can now drop it.
1246 mAm.mAppOpsService.finishOperation(
1247 AppOpsManager.getToken(mAm.mAppOpsService),
1248 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001249 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001250 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001251 } else {
1252 if (r.isForeground) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07001253 final ServiceMap smap = getServiceMapLocked(r.userId);
1254 if (smap != null) {
1255 decActiveForegroundAppLocked(smap, r);
1256 }
Christopher Tate42a386b2016-11-07 12:21:21 -08001257 r.isForeground = false;
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07001258 mAm.mAppOpsService.finishOperation(
1259 AppOpsManager.getToken(mAm.mAppOpsService),
1260 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Christopher Tatec7933ac2018-03-12 17:57:09 -07001261 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
1262 r.appInfo.uid, r.shortName,
Chenjie Yuccfe6452018-01-30 11:33:21 -08001263 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Christopher Tate42a386b2016-11-07 12:21:21 -08001264 if (r.app != null) {
1265 mAm.updateLruProcessLocked(r.app, false, null);
1266 updateServiceForegroundLocked(r.app, true);
1267 }
1268 }
1269 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
Christopher Tate08992ac2017-03-21 11:37:06 -07001270 cancelForegroundNotificationLocked(r);
Christopher Tate42a386b2016-11-07 12:21:21 -08001271 r.foregroundId = 0;
1272 r.foregroundNoti = null;
1273 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1274 r.stripForegroundServiceFlagFromNotification();
1275 if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
1276 r.foregroundId = 0;
1277 r.foregroundNoti = null;
1278 }
1279 }
1280 }
1281 }
1282
Christopher Tate08992ac2017-03-21 11:37:06 -07001283 private void cancelForegroundNotificationLocked(ServiceRecord r) {
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001284 if (r.foregroundId != 0) {
1285 // First check to see if this app has any other active foreground services
1286 // with the same notification ID. If so, we shouldn't actually cancel it,
1287 // because that would wipe away the notification that still needs to be shown
1288 // due the other service.
Dianne Hackbornad51be92016-08-16 16:27:36 -07001289 ServiceMap sm = getServiceMapLocked(r.userId);
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001290 if (sm != null) {
1291 for (int i = sm.mServicesByName.size()-1; i >= 0; i--) {
1292 ServiceRecord other = sm.mServicesByName.valueAt(i);
Dianne Hackborn569a4582016-08-04 14:00:22 -07001293 if (other != r && other.foregroundId == r.foregroundId
Dianne Hackborn0ba4c712016-08-01 17:49:41 -07001294 && other.packageName.equals(r.packageName)) {
1295 // Found one! Abort the cancel.
1296 return;
1297 }
1298 }
1299 }
1300 r.cancelNotification();
1301 }
1302 }
1303
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001304 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
1305 boolean anyForeground = false;
Dianne Hackbornc8230512013-07-13 21:32:12 -07001306 for (int i=proc.services.size()-1; i>=0; i--) {
1307 ServiceRecord sr = proc.services.valueAt(i);
Christopher Tatee23fa2b2017-04-20 14:48:13 -07001308 if (sr.isForeground || sr.fgRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001309 anyForeground = true;
1310 break;
1311 }
1312 }
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08001313 mAm.updateProcessForegroundLocked(proc, anyForeground, oomAdj);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001314 }
1315
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001316 private void updateWhitelistManagerLocked(ProcessRecord proc) {
1317 proc.whitelistManager = false;
1318 for (int i=proc.services.size()-1; i>=0; i--) {
1319 ServiceRecord sr = proc.services.valueAt(i);
1320 if (sr.whitelistManager) {
1321 proc.whitelistManager = true;
1322 break;
1323 }
1324 }
1325 }
1326
Dianne Hackborn465fa392014-09-14 14:21:18 -07001327 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
1328 ArraySet<ProcessRecord> updatedProcesses = null;
Wale Ogunwaled6ac7622016-05-26 09:02:25 -07001329 for (int i = 0; i < clientProc.connections.size(); i++) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001330 final ConnectionRecord conn = clientProc.connections.valueAt(i);
1331 final ProcessRecord proc = conn.binding.service.app;
1332 if (proc == null || proc == clientProc) {
1333 continue;
1334 } else if (updatedProcesses == null) {
1335 updatedProcesses = new ArraySet<>();
1336 } else if (updatedProcesses.contains(proc)) {
1337 continue;
1338 }
1339 updatedProcesses.add(proc);
1340 updateServiceClientActivitiesLocked(proc, null, false);
1341 }
1342 }
1343
Dianne Hackborndb926082013-10-31 16:32:44 -07001344 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
Dianne Hackborn465fa392014-09-14 14:21:18 -07001345 ConnectionRecord modCr, boolean updateLru) {
Dianne Hackborndb926082013-10-31 16:32:44 -07001346 if (modCr != null && modCr.binding.client != null) {
1347 if (modCr.binding.client.activities.size() <= 0) {
1348 // This connection is from a client without activities, so adding
1349 // and removing is not interesting.
1350 return false;
1351 }
1352 }
1353
1354 boolean anyClientActivities = false;
1355 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
1356 ServiceRecord sr = proc.services.valueAt(i);
1357 for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) {
1358 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni);
1359 for (int cri=clist.size()-1; cri>=0; cri--) {
1360 ConnectionRecord cr = clist.get(cri);
1361 if (cr.binding.client == null || cr.binding.client == proc) {
1362 // Binding to ourself is not interesting.
1363 continue;
1364 }
1365 if (cr.binding.client.activities.size() > 0) {
1366 anyClientActivities = true;
1367 break;
1368 }
1369 }
1370 }
1371 }
1372 if (anyClientActivities != proc.hasClientActivities) {
1373 proc.hasClientActivities = anyClientActivities;
Dianne Hackborn465fa392014-09-14 14:21:18 -07001374 if (updateLru) {
1375 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
1376 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001377 return true;
1378 }
1379 return false;
1380 }
1381
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001382 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
Svet Ganov9c165d72015-12-01 19:52:26 -08001383 String resolvedType, final IServiceConnection connection, int flags,
1384 String callingPackage, final int userId) throws TransactionTooLargeException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001385 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001386 + " type=" + resolvedType + " conn=" + connection.asBinder()
1387 + " flags=0x" + Integer.toHexString(flags));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001388 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
1389 if (callerApp == null) {
1390 throw new SecurityException(
1391 "Unable to find app for caller " + caller
1392 + " (pid=" + Binder.getCallingPid()
1393 + ") when binding service " + service);
1394 }
1395
1396 ActivityRecord activity = null;
1397 if (token != null) {
Craig Mautnerd2328952013-03-05 12:46:26 -08001398 activity = ActivityRecord.isInStackLocked(token);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001399 if (activity == null) {
1400 Slog.w(TAG, "Binding with unknown activity: " + token);
1401 return 0;
1402 }
1403 }
1404
1405 int clientLabel = 0;
1406 PendingIntent clientIntent = null;
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001407 final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001408
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001409 if (isCallerSystem) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001410 // Hacky kind of thing -- allow system stuff to tell us
1411 // what they are, so we can report this elsewhere for
1412 // others to know why certain services are running.
Jeff Sharkeyf0ec2e02016-03-21 12:37:54 -06001413 service.setDefusable(true);
1414 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001415 if (clientIntent != null) {
1416 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
1417 if (clientLabel != 0) {
1418 // There are no useful extras in the intent, trash them.
1419 // System code calling with this stuff just needs to know
1420 // this will happen.
1421 service = service.cloneFilter();
1422 }
1423 }
1424 }
1425
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001426 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1427 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
1428 "BIND_TREAT_LIKE_ACTIVITY");
1429 }
1430
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001431 if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
1432 throw new SecurityException(
1433 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1434 + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
1435 }
1436
Svet Ganovd223db32017-12-22 09:43:48 -08001437 if ((flags & Context.BIND_ALLOW_INSTANT) != 0 && !isCallerSystem) {
1438 throw new SecurityException(
1439 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1440 + ") set BIND_ALLOW_INSTANT when binding service " + service);
1441 }
1442
Dianne Hackborna49ad092016-03-03 13:39:10 -08001443 final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
Robert Sesekb9a86662015-12-09 16:22:45 -05001444 final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
Svet Ganovd223db32017-12-22 09:43:48 -08001445 final boolean allowInstant = (flags & Context.BIND_ALLOW_INSTANT) != 0;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001446
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001447 ServiceLookupResult res =
Robert Sesekb9a86662015-12-09 16:22:45 -05001448 retrieveServiceLocked(service, resolvedType, callingPackage, Binder.getCallingPid(),
Svet Ganovd223db32017-12-22 09:43:48 -08001449 Binder.getCallingUid(), userId, true, callerFg, isBindExternal, allowInstant);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001450 if (res == null) {
1451 return 0;
1452 }
1453 if (res.record == null) {
1454 return -1;
1455 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001456 ServiceRecord s = res.record;
1457
Svet Ganov9c165d72015-12-01 19:52:26 -08001458 boolean permissionsReviewRequired = false;
1459
1460 // If permissions need a review before any of the app components can run,
1461 // we schedule binding to the service but do not start its process, then
1462 // we launch a review activity to which is passed a callback to invoke
1463 // when done to start the bound service's process to completing the binding.
Svet Ganov77df6f32016-08-17 11:46:34 -07001464 if (mAm.mPermissionReviewRequired) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001465 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
1466 s.packageName, s.userId)) {
1467
1468 permissionsReviewRequired = true;
1469
1470 // Show a permission review UI only for binding from a foreground app
1471 if (!callerFg) {
1472 Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
1473 + s.packageName + " requires a permissions review");
1474 return 0;
1475 }
1476
1477 final ServiceRecord serviceRecord = s;
1478 final Intent serviceIntent = service;
1479
1480 RemoteCallback callback = new RemoteCallback(
1481 new RemoteCallback.OnResultListener() {
1482 @Override
1483 public void onResult(Bundle result) {
1484 synchronized(mAm) {
1485 final long identity = Binder.clearCallingIdentity();
1486 try {
1487 if (!mPendingServices.contains(serviceRecord)) {
1488 return;
1489 }
1490 // If there is still a pending record, then the service
1491 // binding request is still valid, so hook them up. We
1492 // proceed only if the caller cleared the review requirement
1493 // otherwise we unbind because the user didn't approve.
1494 if (!mAm.getPackageManagerInternalLocked()
1495 .isPermissionsReviewRequired(
1496 serviceRecord.packageName,
1497 serviceRecord.userId)) {
1498 try {
1499 bringUpServiceLocked(serviceRecord,
1500 serviceIntent.getFlags(),
1501 callerFg, false, false);
1502 } catch (RemoteException e) {
1503 /* ignore - local call */
1504 }
1505 } else {
1506 unbindServiceLocked(connection);
1507 }
1508 } finally {
1509 Binder.restoreCallingIdentity(identity);
1510 }
1511 }
1512 }
1513 });
1514
1515 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
1516 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1517 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1518 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
1519 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
1520
1521 if (DEBUG_PERMISSIONS_REVIEW) {
1522 Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
1523 + s.packageName);
1524 }
1525
1526 mAm.mHandler.post(new Runnable() {
1527 @Override
1528 public void run() {
1529 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
1530 }
1531 });
1532 }
1533 }
1534
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001535 final long origId = Binder.clearCallingIdentity();
1536
1537 try {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001538 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001539 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001540 + s);
1541 }
1542
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001543 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1544 s.lastActivity = SystemClock.uptimeMillis();
1545 if (!s.hasAutoCreateConnections()) {
1546 // This is the first binding, let the tracker know.
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001547 ServiceState stracker = s.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001548 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001549 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001550 s.lastActivity);
1551 }
1552 }
1553 }
1554
Joe Onorato05c9ecc2016-03-30 15:13:46 -07001555 mAm.startAssociationLocked(callerApp.uid, callerApp.processName, callerApp.curProcState,
Dianne Hackbornab2df062015-01-07 13:43:13 -08001556 s.appInfo.uid, s.name, s.processName);
Jesse Evans02af3ea2017-05-03 09:57:16 -07001557 // Once the apps have become associated, if one of them is caller is ephemeral
1558 // the target app should now be able to see the calling app
1559 mAm.grantEphemeralAccessLocked(callerApp.userId, service,
1560 s.appInfo.uid, UserHandle.getAppId(callerApp.uid));
Dianne Hackbornab2df062015-01-07 13:43:13 -08001561
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001562 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
1563 ConnectionRecord c = new ConnectionRecord(b, activity,
1564 connection, flags, clientLabel, clientIntent);
1565
1566 IBinder binder = connection.asBinder();
1567 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
1568 if (clist == null) {
1569 clist = new ArrayList<ConnectionRecord>();
1570 s.connections.put(binder, clist);
1571 }
1572 clist.add(c);
1573 b.connections.add(c);
1574 if (activity != null) {
1575 if (activity.connections == null) {
1576 activity.connections = new HashSet<ConnectionRecord>();
1577 }
1578 activity.connections.add(c);
1579 }
1580 b.client.connections.add(c);
1581 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
1582 b.client.hasAboveClient = true;
1583 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001584 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
1585 s.whitelistManager = true;
1586 }
Dianne Hackborndb926082013-10-31 16:32:44 -07001587 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07001588 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07001589 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001590 clist = mServiceConnections.get(binder);
1591 if (clist == null) {
1592 clist = new ArrayList<ConnectionRecord>();
1593 mServiceConnections.put(binder, clist);
1594 }
1595 clist.add(c);
1596
1597 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1598 s.lastActivity = SystemClock.uptimeMillis();
Svet Ganov9c165d72015-12-01 19:52:26 -08001599 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
1600 permissionsReviewRequired) != null) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001601 return 0;
1602 }
1603 }
1604
1605 if (s.app != null) {
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001606 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1607 s.app.treatLikeActivity = true;
1608 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07001609 if (s.whitelistManager) {
1610 s.app.whitelistManager = true;
1611 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001612 // This could have made the service more important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001613 mAm.updateLruProcessLocked(s.app, s.app.hasClientActivities
1614 || s.app.treatLikeActivity, b.client);
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001615 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001616 }
1617
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001618 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001619 + ": received=" + b.intent.received
1620 + " apps=" + b.intent.apps.size()
1621 + " doRebind=" + b.intent.doRebind);
1622
1623 if (s.app != null && b.intent.received) {
1624 // Service is already running, so we can immediately
1625 // publish the connection.
1626 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001627 c.conn.connected(s.name, b.intent.binder, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001628 } catch (Exception e) {
1629 Slog.w(TAG, "Failure sending service " + s.shortName
1630 + " to connection " + c.conn.asBinder()
1631 + " (in " + c.binding.client.processName + ")", e);
1632 }
1633
1634 // If this is the first app connected back to this binding,
1635 // and the service had previously asked to be told when
1636 // rebound, then do so.
1637 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001638 requestServiceBindingLocked(s, b.intent, callerFg, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001639 }
1640 } else if (!b.intent.requested) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001641 requestServiceBindingLocked(s, b.intent, callerFg, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001642 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001643
Dianne Hackbornad51be92016-08-16 16:27:36 -07001644 getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001645
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001646 } finally {
1647 Binder.restoreCallingIdentity(origId);
1648 }
1649
1650 return 1;
1651 }
1652
1653 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
1654 final long origId = Binder.clearCallingIdentity();
1655 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001656 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001657 + " " + intent + ": " + service);
1658 if (r != null) {
1659 Intent.FilterComparison filter
1660 = new Intent.FilterComparison(intent);
1661 IntentBindRecord b = r.bindings.get(filter);
1662 if (b != null && !b.received) {
1663 b.binder = service;
1664 b.requested = true;
1665 b.received = true;
Dianne Hackborn390517b2013-05-30 15:03:32 -07001666 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1667 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
1668 for (int i=0; i<clist.size(); i++) {
1669 ConnectionRecord c = clist.get(i);
1670 if (!filter.equals(c.binding.intent.intent)) {
1671 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001672 TAG_SERVICE, "Not publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001673 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001674 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001675 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001676 TAG_SERVICE, "Published intent: " + intent);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001677 continue;
1678 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001679 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001680 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07001681 c.conn.connected(r.name, service, false);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001682 } catch (Exception e) {
1683 Slog.w(TAG, "Failure sending service " + r.name +
1684 " to connection " + c.conn.asBinder() +
1685 " (in " + c.binding.client.processName + ")", e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001686 }
1687 }
1688 }
1689 }
1690
Dianne Hackborn164371f2013-10-01 19:10:13 -07001691 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001692 }
1693 } finally {
1694 Binder.restoreCallingIdentity(origId);
1695 }
1696 }
1697
1698 boolean unbindServiceLocked(IServiceConnection connection) {
1699 IBinder binder = connection.asBinder();
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001700 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001701 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1702 if (clist == null) {
1703 Slog.w(TAG, "Unbind failed: could not find connection for "
1704 + connection.asBinder());
1705 return false;
1706 }
1707
1708 final long origId = Binder.clearCallingIdentity();
1709 try {
1710 while (clist.size() > 0) {
1711 ConnectionRecord r = clist.get(0);
1712 removeConnectionLocked(r, null, null);
Dianne Hackborn25e1eca2014-09-23 10:13:13 -07001713 if (clist.size() > 0 && clist.get(0) == r) {
1714 // In case it didn't get removed above, do it now.
1715 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
1716 clist.remove(0);
1717 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001718
1719 if (r.binding.service.app != null) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001720 if (r.binding.service.app.whitelistManager) {
Felipe Lemea7778b02016-06-28 10:38:59 -07001721 updateWhitelistManagerLocked(r.binding.service.app);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001722 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001723 // This could have made the service less important.
Dianne Hackbornf0f94d12014-03-17 16:04:21 -07001724 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1725 r.binding.service.app.treatLikeActivity = true;
1726 mAm.updateLruProcessLocked(r.binding.service.app,
1727 r.binding.service.app.hasClientActivities
1728 || r.binding.service.app.treatLikeActivity, null);
1729 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07001730 mAm.updateOomAdjLocked(r.binding.service.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001731 }
1732 }
Amith Yamasanib2926b12017-05-11 11:13:52 -07001733
1734 mAm.updateOomAdjLocked();
1735
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001736 } finally {
1737 Binder.restoreCallingIdentity(origId);
1738 }
1739
1740 return true;
1741 }
1742
1743 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
1744 final long origId = Binder.clearCallingIdentity();
1745 try {
1746 if (r != null) {
1747 Intent.FilterComparison filter
1748 = new Intent.FilterComparison(intent);
1749 IntentBindRecord b = r.bindings.get(filter);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001750 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001751 + " at " + b + ": apps="
1752 + (b != null ? b.apps.size() : 0));
1753
Dianne Hackborn164371f2013-10-01 19:10:13 -07001754 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001755 if (b != null) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07001756 if (b.apps.size() > 0 && !inDestroying) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001757 // Applications have already bound since the last
1758 // unbind, so just rebind right here.
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001759 boolean inFg = false;
1760 for (int i=b.apps.size()-1; i>=0; i--) {
1761 ProcessRecord client = b.apps.valueAt(i).client;
1762 if (client != null && client.setSchedGroup
Dianne Hackborna49ad092016-03-03 13:39:10 -08001763 != ProcessList.SCHED_GROUP_BACKGROUND) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001764 inFg = true;
1765 break;
1766 }
1767 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07001768 try {
1769 requestServiceBindingLocked(r, b, inFg, true);
1770 } catch (TransactionTooLargeException e) {
1771 // Don't pass this back to ActivityThread, it's unrelated.
1772 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001773 } else {
1774 // Note to tell the service the next time there is
1775 // a new client.
1776 b.doRebind = true;
1777 }
1778 }
1779
Dianne Hackborn164371f2013-10-01 19:10:13 -07001780 serviceDoneExecutingLocked(r, inDestroying, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001781 }
1782 } finally {
1783 Binder.restoreCallingIdentity(origId);
1784 }
1785 }
1786
1787 private final ServiceRecord findServiceLocked(ComponentName name,
Dianne Hackborn41203752012-08-31 14:05:51 -07001788 IBinder token, int userId) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07001789 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001790 return r == token ? r : null;
1791 }
1792
1793 private final class ServiceLookupResult {
1794 final ServiceRecord record;
1795 final String permission;
1796
1797 ServiceLookupResult(ServiceRecord _record, String _permission) {
1798 record = _record;
1799 permission = _permission;
1800 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001801 }
1802
1803 private class ServiceRestarter implements Runnable {
1804 private ServiceRecord mService;
1805
1806 void setService(ServiceRecord service) {
1807 mService = service;
1808 }
1809
1810 public void run() {
1811 synchronized(mAm) {
1812 performServiceRestartLocked(mService);
1813 }
1814 }
1815 }
1816
1817 private ServiceLookupResult retrieveServiceLocked(Intent service,
Svet Ganov99b60432015-06-27 13:15:22 -07001818 String resolvedType, String callingPackage, int callingPid, int callingUid, int userId,
Svet Ganovd223db32017-12-22 09:43:48 -08001819 boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
1820 boolean allowInstant) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001821 ServiceRecord r = null;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001822 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001823 + " type=" + resolvedType + " callingUid=" + callingUid);
1824
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001825 userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
1826 ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE, "service", null);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001827
Dianne Hackbornad51be92016-08-16 16:27:36 -07001828 ServiceMap smap = getServiceMapLocked(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001829 final ComponentName comp = service.getComponent();
1830 if (comp != null) {
1831 r = smap.mServicesByName.get(comp);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001832 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001833 }
Robert Sesekb9a86662015-12-09 16:22:45 -05001834 if (r == null && !isBindExternal) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001835 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001836 r = smap.mServicesByIntent.get(filter);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001837 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001838 }
Robert Sesekb9a86662015-12-09 16:22:45 -05001839 if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
1840 && !callingPackage.equals(r.packageName)) {
1841 // If an external service is running within its own package, other packages
1842 // should not bind to that instance.
1843 r = null;
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001844 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Whoops, can't use existing external service");
Robert Sesekb9a86662015-12-09 16:22:45 -05001845 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001846 if (r == null) {
1847 try {
Svet Ganovd223db32017-12-22 09:43:48 -08001848 int flags = ActivityManagerService.STOCK_PM_FLAGS
1849 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
1850 if (allowInstant) {
1851 flags |= PackageManager.MATCH_INSTANT;
1852 }
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001853 // TODO: come back and remove this assumption to triage all services
Todd Kennedy51b3aac2017-03-30 17:50:42 -07001854 ResolveInfo rInfo = mAm.getPackageManagerInternalLocked().resolveService(service,
Svet Ganovd223db32017-12-22 09:43:48 -08001855 resolvedType, flags, userId, callingUid);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001856 ServiceInfo sInfo =
1857 rInfo != null ? rInfo.serviceInfo : null;
1858 if (sInfo == null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001859 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001860 ": not found");
1861 return null;
1862 }
1863 ComponentName name = new ComponentName(
1864 sInfo.applicationInfo.packageName, sInfo.name);
Robert Sesekb9a86662015-12-09 16:22:45 -05001865 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
1866 if (isBindExternal) {
1867 if (!sInfo.exported) {
1868 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1869 " is not exported");
1870 }
1871 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
1872 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1873 " is not an isolatedProcess");
1874 }
1875 // Run the service under the calling package's application.
1876 ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
1877 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
1878 if (aInfo == null) {
1879 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
1880 "could not resolve client package " + callingPackage);
1881 }
1882 sInfo = new ServiceInfo(sInfo);
1883 sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
1884 sInfo.applicationInfo.packageName = aInfo.packageName;
1885 sInfo.applicationInfo.uid = aInfo.uid;
1886 name = new ComponentName(aInfo.packageName, name.getClassName());
1887 service.setComponent(name);
1888 } else {
1889 throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
1890 name);
1891 }
1892 } else if (isBindExternal) {
1893 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1894 " is not an externalService");
1895 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001896 if (userId > 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001897 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
Amith Yamasani4b9d79c2014-05-21 19:14:21 -07001898 sInfo.name, sInfo.flags)
1899 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001900 userId = 0;
Dianne Hackbornad51be92016-08-16 16:27:36 -07001901 smap = getServiceMapLocked(0);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001902 }
1903 sInfo = new ServiceInfo(sInfo);
1904 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
1905 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001906 r = smap.mServicesByName.get(name);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001907 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE,
1908 "Retrieved via pm by intent: " + r);
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001909 if (r == null && createIfNeeded) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001910 final Intent.FilterComparison filter
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001911 = new Intent.FilterComparison(service.cloneFilter());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001912 final ServiceRestarter res = new ServiceRestarter();
1913 final BatteryStatsImpl.Uid.Pkg.Serv ss;
1914 final BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001915 synchronized (stats) {
1916 ss = stats.getServiceStatsLocked(
1917 sInfo.applicationInfo.uid, sInfo.packageName,
1918 sInfo.name);
1919 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001920 r = new ServiceRecord(mAm, ss, name, filter, sInfo, callingFromFg, res);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001921 res.setService(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07001922 smap.mServicesByName.put(name, r);
1923 smap.mServicesByIntent.put(filter, r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001924
1925 // Make sure this component isn't in the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08001926 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001927 final ServiceRecord pr = mPendingServices.get(i);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001928 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
1929 && pr.name.equals(name)) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001930 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001931 mPendingServices.remove(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001932 }
1933 }
Dianne Hackbornf82236e2017-04-19 10:26:01 -07001934 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001935 }
1936 } catch (RemoteException ex) {
1937 // pm is in same process, this will never happen.
1938 }
1939 }
1940 if (r != null) {
1941 if (mAm.checkComponentPermission(r.permission,
Bryce Lee290e5782017-02-01 16:41:20 -08001942 callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001943 if (!r.exported) {
1944 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1945 + " from pid=" + callingPid
1946 + ", uid=" + callingUid
1947 + " that is not exported from uid " + r.appInfo.uid);
1948 return new ServiceLookupResult(null, "not exported from uid "
1949 + r.appInfo.uid);
1950 }
1951 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1952 + " from pid=" + callingPid
1953 + ", uid=" + callingUid
1954 + " requires " + r.permission);
1955 return new ServiceLookupResult(null, r.permission);
Svet Ganov99b60432015-06-27 13:15:22 -07001956 } else if (r.permission != null && callingPackage != null) {
1957 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
1958 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation(
1959 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
1960 Slog.w(TAG, "Appop Denial: Accessing service " + r.name
1961 + " from pid=" + callingPid
1962 + ", uid=" + callingUid
1963 + " requires appop " + AppOpsManager.opToName(opCode));
1964 return null;
1965 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001966 }
Svet Ganov99b60432015-06-27 13:15:22 -07001967
Ben Gruverf5323fe2013-07-31 15:09:51 -07001968 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
1969 resolvedType, r.appInfo)) {
Ben Gruverb6223792013-07-29 16:35:40 -07001970 return null;
1971 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001972 return new ServiceLookupResult(r, null);
1973 }
1974 return null;
1975 }
1976
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001977 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001978 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001979 + why + " of " + r + " in app " + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001980 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001981 + why + " of " + r.shortName);
1982 long now = SystemClock.uptimeMillis();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001983 if (r.executeNesting == 0) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001984 r.executeFg = fg;
Joe Onorato4eb64fd2016-03-21 15:30:09 -07001985 ServiceState stracker = r.getTracker();
Dianne Hackbornbd754f42013-07-23 15:52:36 -07001986 if (stracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07001987 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001988 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001989 if (r.app != null) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001990 r.app.executingServices.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001991 r.app.execServicesFg |= fg;
Dianne Hackborn2be00932013-09-22 16:46:00 -07001992 if (r.app.executingServices.size() == 1) {
1993 scheduleServiceTimeoutLocked(r.app);
1994 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07001995 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001996 } else if (r.app != null && fg && !r.app.execServicesFg) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07001997 r.app.execServicesFg = true;
Dianne Hackborn2be00932013-09-22 16:46:00 -07001998 scheduleServiceTimeoutLocked(r.app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001999 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002000 r.executeFg |= fg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002001 r.executeNesting++;
2002 r.executingStart = now;
2003 }
2004
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002005 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
2006 boolean execInFg, boolean rebind) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002007 if (r.app == null || r.app.thread == null) {
2008 // If service is not currently running, can't yet bind.
2009 return false;
2010 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08002011 if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
2012 + " rebind=" + rebind);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002013 if ((!i.requested || rebind) && i.apps.size() > 0) {
2014 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002015 bumpServiceExecutingLocked(r, execInFg, "bind");
Dianne Hackborna413dc02013-07-12 12:02:55 -07002016 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
2017 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
2018 r.app.repProcState);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002019 if (!rebind) {
2020 i.requested = true;
2021 }
2022 i.hasBound = true;
2023 i.doRebind = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002024 } catch (TransactionTooLargeException e) {
2025 // Keep the executeNesting count accurate.
2026 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
2027 final boolean inDestroying = mDestroyingServices.contains(r);
2028 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2029 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002030 } catch (RemoteException e) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002031 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002032 // Keep the executeNesting count accurate.
2033 final boolean inDestroying = mDestroyingServices.contains(r);
2034 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002035 return false;
2036 }
2037 }
2038 return true;
2039 }
2040
Dianne Hackbornad51be92016-08-16 16:27:36 -07002041 private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002042 boolean canceled = false;
2043
Fyodor Kupolov9b80b942016-06-16 16:29:05 -07002044 if (mAm.isShuttingDownLocked()) {
2045 Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortName
2046 + " - system is shutting down");
2047 return false;
2048 }
2049
Dianne Hackbornad51be92016-08-16 16:27:36 -07002050 ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002051 if (smap.mServicesByName.get(r.name) != r) {
2052 ServiceRecord cur = smap.mServicesByName.get(r.name);
2053 Slog.wtf(TAG, "Attempting to schedule restart of " + r
2054 + " when found in map: " + cur);
2055 return false;
2056 }
2057
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002058 final long now = SystemClock.uptimeMillis();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002059
2060 if ((r.serviceInfo.applicationInfo.flags
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002061 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002062 long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION;
2063 long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002064
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002065 // Any delivered but not yet finished starts should be put back
2066 // on the pending list.
2067 final int N = r.deliveredStarts.size();
2068 if (N > 0) {
2069 for (int i=N-1; i>=0; i--) {
2070 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
2071 si.removeUriPermissionsLocked();
2072 if (si.intent == null) {
2073 // We'll generate this again if needed.
2074 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
2075 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
2076 r.pendingStarts.add(0, si);
2077 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
2078 dur *= 2;
2079 if (minDuration < dur) minDuration = dur;
2080 if (resetTime < dur) resetTime = dur;
2081 } else {
2082 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
2083 + r.name);
2084 canceled = true;
2085 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002086 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002087 r.deliveredStarts.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002088 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002089
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002090 r.totalRestartCount++;
2091 if (r.restartDelay == 0) {
2092 r.restartCount++;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002093 r.restartDelay = minDuration;
Amith Yamasanib0c8a882017-08-28 09:36:42 -07002094 } else if (r.crashCount > 1) {
2095 r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
2096 * (r.crashCount - 1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002097 } else {
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002098 // If it has been a "reasonably long time" since the service
2099 // was started, then reset our restart duration back to
2100 // the beginning, so we don't infinitely increase the duration
2101 // on a service that just occasionally gets killed (which is
2102 // a normal case, due to process being killed to reclaim memory).
2103 if (now > (r.restartTime+resetTime)) {
2104 r.restartCount = 1;
2105 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002106 } else {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002107 r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
Dianne Hackborn7b492722013-11-01 09:58:45 -07002108 if (r.restartDelay < minDuration) {
2109 r.restartDelay = minDuration;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002110 }
2111 }
2112 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002113
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002114 r.nextRestartTime = now + r.restartDelay;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002115
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002116 // Make sure that we don't end up restarting a bunch of services
2117 // all at the same time.
2118 boolean repeat;
2119 do {
2120 repeat = false;
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002121 final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002122 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2123 ServiceRecord r2 = mRestartingServices.get(i);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002124 if (r2 != r && r.nextRestartTime >= (r2.nextRestartTime-restartTimeBetween)
2125 && r.nextRestartTime < (r2.nextRestartTime+restartTimeBetween)) {
2126 r.nextRestartTime = r2.nextRestartTime + restartTimeBetween;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002127 r.restartDelay = r.nextRestartTime - now;
2128 repeat = true;
2129 break;
2130 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002131 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002132 } while (repeat);
2133
2134 } else {
Dianne Hackborn7b492722013-11-01 09:58:45 -07002135 // Persistent processes are immediately restarted, so there is no
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002136 // reason to hold of on restarting their services.
2137 r.totalRestartCount++;
2138 r.restartCount = 0;
2139 r.restartDelay = 0;
2140 r.nextRestartTime = now;
2141 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002142
2143 if (!mRestartingServices.contains(r)) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002144 r.createdFromFg = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002145 mRestartingServices.add(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002146 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002147 }
2148
Christopher Tate08992ac2017-03-21 11:37:06 -07002149 cancelForegroundNotificationLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002150
2151 mAm.mHandler.removeCallbacks(r.restarter);
2152 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
2153 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
2154 Slog.w(TAG, "Scheduling restart of crashed service "
2155 + r.shortName + " in " + r.restartDelay + "ms");
2156 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002157 r.userId, r.shortName, r.restartDelay);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002158
2159 return canceled;
2160 }
2161
2162 final void performServiceRestartLocked(ServiceRecord r) {
2163 if (!mRestartingServices.contains(r)) {
2164 return;
2165 }
Dianne Hackbornad51be92016-08-16 16:27:36 -07002166 if (!isServiceNeededLocked(r, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07002167 // Paranoia: is this service actually needed? In theory a service that is not
2168 // needed should never remain on the restart list. In practice... well, there
2169 // have been bugs where this happens, and bad things happen because the process
2170 // ends up just being cached, so quickly killed, then restarted again and again.
2171 // Let's not let that happen.
2172 Slog.wtf(TAG, "Restarting service that is not needed: " + r);
2173 return;
2174 }
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002175 try {
Svet Ganov9c165d72015-12-01 19:52:26 -08002176 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002177 } catch (TransactionTooLargeException e) {
2178 // Ignore, it's been logged and nothing upstack cares.
2179 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002180 }
2181
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002182 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
2183 boolean force) {
2184 if (!force && r.restartDelay == 0) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002185 return false;
2186 }
Dianne Hackborn7b492722013-11-01 09:58:45 -07002187 // Remove from the restarting list; if the service is currently on the
2188 // restarting list, or the call is coming from another app, then this
2189 // service has become of much more interest so we reset the restart interval.
2190 boolean removed = mRestartingServices.remove(r);
2191 if (removed || callingUid != r.appInfo.uid) {
2192 r.resetRestartCounter();
2193 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002194 if (removed) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002195 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002196 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002197 mAm.mHandler.removeCallbacks(r.restarter);
2198 return true;
2199 }
2200
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002201 private void clearRestartingIfNeededLocked(ServiceRecord r) {
2202 if (r.restartTracker != null) {
2203 // If this is the last restarting record with this tracker, then clear
2204 // the tracker's restarting state.
2205 boolean stillTracking = false;
2206 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2207 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
2208 stillTracking = true;
2209 break;
2210 }
2211 }
2212 if (!stillTracking) {
2213 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
2214 SystemClock.uptimeMillis());
2215 r.restartTracker = null;
2216 }
2217 }
2218 }
2219
Svet Ganov9c165d72015-12-01 19:52:26 -08002220 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
2221 boolean whileRestarting, boolean permissionsReviewRequired)
2222 throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002223 //Slog.i(TAG, "Bring up service:");
2224 //r.dump(" ");
2225
2226 if (r.app != null && r.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002227 sendServiceArgsLocked(r, execInFg, false);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002228 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002229 }
2230
Sudheer Shanka03d0f812017-04-20 16:57:50 -07002231 if (!whileRestarting && mRestartingServices.contains(r)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002232 // If waiting for a restart, then do nothing.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002233 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002234 }
2235
Christopher Tate08992ac2017-03-21 11:37:06 -07002236 if (DEBUG_SERVICE) {
2237 Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
2238 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002239
2240 // We are now bringing the service up, so no longer in the
2241 // restarting state.
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002242 if (mRestartingServices.remove(r)) {
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002243 clearRestartingIfNeededLocked(r);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002244 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002245
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002246 // Make sure this service is no longer considered delayed, we are starting it now.
2247 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002248 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002249 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002250 r.delayed = false;
2251 }
2252
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002253 // Make sure that the user who owns this service is started. If not,
2254 // we don't want to allow it to run.
Fyodor Kupolov610acda2015-10-19 18:44:07 -07002255 if (!mAm.mUserController.hasStartedUserState(r.userId)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002256 String msg = "Unable to launch app "
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002257 + r.appInfo.packageName + "/"
2258 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002259 + r.intent.getIntent() + ": user " + r.userId + " is stopped";
2260 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002261 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002262 return msg;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002263 }
2264
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002265 // Service is now being launched, its package can't be stopped.
2266 try {
2267 AppGlobals.getPackageManager().setPackageStoppedState(
2268 r.packageName, false, r.userId);
2269 } catch (RemoteException e) {
2270 } catch (IllegalArgumentException e) {
2271 Slog.w(TAG, "Failed trying to unstop package "
2272 + r.packageName + ": " + e);
2273 }
2274
2275 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
2276 final String procName = r.processName;
Robert Sesekc5f86642016-11-04 10:20:38 -04002277 String hostingType = "service";
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002278 ProcessRecord app;
2279
2280 if (!isolated) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07002281 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
2282 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
2283 + " app=" + app);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002284 if (app != null && app.thread != null) {
2285 try {
Patrick Baumannc2def582018-04-04 12:14:15 -07002286 app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode, mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002287 realStartServiceLocked(r, app, execInFg);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002288 return null;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002289 } catch (TransactionTooLargeException e) {
2290 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002291 } catch (RemoteException e) {
2292 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
2293 }
2294
2295 // If a dead object exception was thrown -- fall through to
2296 // restart the application.
2297 }
2298 } else {
2299 // If this service runs in an isolated process, then each time
2300 // we call startProcessLocked() we will get a new isolated
2301 // process, starting another process if we are currently waiting
2302 // for a previous process to come up. To deal with this, we store
2303 // in the service any current isolated process it is running in or
2304 // waiting to have come up.
2305 app = r.isolatedProc;
Robert Sesekc5f86642016-11-04 10:20:38 -04002306 if (WebViewZygote.isMultiprocessEnabled()
2307 && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
2308 hostingType = "webview_service";
2309 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002310 }
2311
2312 // Not running -- get it started, and enqueue this service record
2313 // to be executed when the app comes up.
Svet Ganov9c165d72015-12-01 19:52:26 -08002314 if (app == null && !permissionsReviewRequired) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002315 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
Robert Sesekc5f86642016-11-04 10:20:38 -04002316 hostingType, r.name, false, isolated, false)) == null) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002317 String msg = "Unable to launch app "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002318 + r.appInfo.packageName + "/"
2319 + r.appInfo.uid + " for service "
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002320 + r.intent.getIntent() + ": process is bad";
2321 Slog.w(TAG, msg);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002322 bringDownServiceLocked(r);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002323 return msg;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002324 }
2325 if (isolated) {
2326 r.isolatedProc = app;
2327 }
2328 }
2329
Christopher Tate1536cc22017-09-18 16:43:30 -07002330 if (r.fgRequired) {
2331 if (DEBUG_FOREGROUND_SERVICE) {
2332 Slog.v(TAG, "Whitelisting " + UserHandle.formatUid(r.appInfo.uid)
2333 + " for fg-service launch");
2334 }
2335 mAm.tempWhitelistUidLocked(r.appInfo.uid,
2336 SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch");
2337 }
2338
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002339 if (!mPendingServices.contains(r)) {
2340 mPendingServices.add(r);
2341 }
2342
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002343 if (r.delayedStop) {
2344 // Oh and hey we've already been asked to stop!
2345 r.delayedStop = false;
2346 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002347 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2348 "Applying delayed stop (in bring up): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002349 stopServiceLocked(r);
2350 }
2351 }
2352
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002353 return null;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002354 }
2355
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002356 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
2357 throws TransactionTooLargeException {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002358 for (int i=r.bindings.size()-1; i>=0; i--) {
2359 IntentBindRecord ibr = r.bindings.valueAt(i);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002360 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002361 break;
2362 }
2363 }
2364 }
2365
2366 private final void realStartServiceLocked(ServiceRecord r,
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002367 ProcessRecord app, boolean execInFg) throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002368 if (app.thread == null) {
2369 throw new RemoteException();
2370 }
2371 if (DEBUG_MU)
2372 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
2373 + ", ProcessRecord.uid = " + app.uid);
2374 r.app = app;
2375 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
2376
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002377 final boolean newService = app.services.add(r);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002378 bumpServiceExecutingLocked(r, execInFg, "create");
Dianne Hackborndb926082013-10-31 16:32:44 -07002379 mAm.updateLruProcessLocked(app, false, null);
Makoto Onuki0f421292017-04-28 15:03:33 -07002380 updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
2381 mAm.updateOomAdjLocked();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002382
2383 boolean created = false;
2384 try {
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002385 if (LOG_SERVICE_START_STOP) {
Dianne Hackbornab2df062015-01-07 13:43:13 -08002386 String nameTerm;
2387 int lastPeriod = r.shortName.lastIndexOf('.');
2388 nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002389 EventLogTags.writeAmCreateService(
2390 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
2391 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002392 synchronized (r.stats.getBatteryStats()) {
2393 r.stats.startLaunchedLocked();
2394 }
Brian Carlstromca82e612016-04-19 23:16:08 -07002395 mAm.notifyPackageUse(r.serviceInfo.packageName,
2396 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
Dianne Hackborna413dc02013-07-12 12:02:55 -07002397 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002398 app.thread.scheduleCreateService(r, r.serviceInfo,
Dianne Hackborna413dc02013-07-12 12:02:55 -07002399 mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
2400 app.repProcState);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002401 r.postNotification();
2402 created = true;
Craig Mautner4a8dddbf2014-08-13 10:49:26 -07002403 } catch (DeadObjectException e) {
2404 Slog.w(TAG, "Application dead when creating service " + r);
2405 mAm.appDiedLocked(app);
Wale Ogunwalebfac4682015-04-08 14:33:21 -07002406 throw e;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002407 } finally {
2408 if (!created) {
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002409 // Keep the executeNesting count accurate.
2410 final boolean inDestroying = mDestroyingServices.contains(r);
2411 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2412
2413 // Cleanup.
2414 if (newService) {
2415 app.services.remove(r);
2416 r.app = null;
2417 }
2418
2419 // Retry.
2420 if (!inDestroying) {
2421 scheduleServiceRestartLocked(r, false);
2422 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002423 }
2424 }
2425
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002426 if (r.whitelistManager) {
2427 app.whitelistManager = true;
2428 }
2429
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002430 requestServiceBindingsLocked(r, execInFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002431
Dianne Hackborn465fa392014-09-14 14:21:18 -07002432 updateServiceClientActivitiesLocked(app, null, true);
2433
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002434 // If the service is in the started state, and there are no
2435 // pending arguments, then fake up one so its onStartCommand() will
2436 // be called.
2437 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
2438 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Todd Kennedy51b3aac2017-03-30 17:50:42 -07002439 null, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002440 }
2441
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002442 sendServiceArgsLocked(r, execInFg, true);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002443
2444 if (r.delayed) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002445 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
Dianne Hackbornad51be92016-08-16 16:27:36 -07002446 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002447 r.delayed = false;
2448 }
2449
2450 if (r.delayedStop) {
2451 // Oh and hey we've already been asked to stop!
2452 r.delayedStop = false;
2453 if (r.startRequested) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002454 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2455 "Applying delayed stop (from start): " + r);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002456 stopServiceLocked(r);
2457 }
2458 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002459 }
2460
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002461 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002462 boolean oomAdjusted) throws TransactionTooLargeException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002463 final int N = r.pendingStarts.size();
2464 if (N == 0) {
2465 return;
2466 }
2467
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002468 ArrayList<ServiceStartArgs> args = new ArrayList<>();
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002469
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002470 while (r.pendingStarts.size() > 0) {
2471 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
2472 if (DEBUG_SERVICE) {
2473 Slog.v(TAG_SERVICE, "Sending arguments to: "
2474 + r + " " + r.intent + " args=" + si.intent);
2475 }
2476 if (si.intent == null && N > 1) {
2477 // If somehow we got a dummy null intent in the middle,
2478 // then skip it. DO NOT skip a null intent when it is
2479 // the only one in the list -- this is to support the
2480 // onStartCommand(null) case.
2481 continue;
2482 }
2483 si.deliveredTime = SystemClock.uptimeMillis();
2484 r.deliveredStarts.add(si);
2485 si.deliveryCount++;
2486 if (si.neededGrants != null) {
2487 mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
2488 si.getUriPermissionsLocked());
2489 }
2490 mAm.grantEphemeralAccessLocked(r.userId, si.intent,
2491 r.appInfo.uid, UserHandle.getAppId(si.callingId));
2492 bumpServiceExecutingLocked(r, execInFg, "start");
2493 if (!oomAdjusted) {
2494 oomAdjusted = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002495 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002496 }
2497 if (r.fgRequired && !r.fgWaiting) {
2498 if (!r.isForeground) {
2499 if (DEBUG_BACKGROUND_CHECK) {
2500 Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r);
2501 }
2502 scheduleServiceForegroundTransitionTimeoutLocked(r);
2503 } else {
2504 if (DEBUG_BACKGROUND_CHECK) {
2505 Slog.i(TAG, "Service already foreground; no new timeout: " + r);
2506 }
2507 r.fgRequired = false;
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002508 }
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07002509 }
2510 int flags = 0;
2511 if (si.deliveryCount > 1) {
2512 flags |= Service.START_FLAG_RETRY;
2513 }
2514 if (si.doneExecutingCount > 0) {
2515 flags |= Service.START_FLAG_REDELIVERY;
2516 }
2517 args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
2518 }
2519
2520 ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
2521 slice.setInlineCountLimit(4);
2522 Exception caughtException = null;
2523 try {
2524 r.app.thread.scheduleServiceArgs(r, slice);
2525 } catch (TransactionTooLargeException e) {
2526 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
2527 + " args, first: " + args.get(0).args);
2528 Slog.w(TAG, "Failed delivering service starts", e);
2529 caughtException = e;
2530 } catch (RemoteException e) {
2531 // Remote process gone... we'll let the normal cleanup take care of this.
2532 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
2533 Slog.w(TAG, "Failed delivering service starts", e);
2534 caughtException = e;
2535 } catch (Exception e) {
2536 Slog.w(TAG, "Unexpected exception", e);
2537 caughtException = e;
2538 }
2539
2540 if (caughtException != null) {
2541 // Keep nesting count correct
2542 final boolean inDestroying = mDestroyingServices.contains(r);
2543 for (int i = 0; i < args.size(); i++) {
2544 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2545 }
2546 if (caughtException instanceof TransactionTooLargeException) {
2547 throw (TransactionTooLargeException)caughtException;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002548 }
2549 }
2550 }
2551
Dianne Hackbornad51be92016-08-16 16:27:36 -07002552 private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn,
2553 boolean hasConn) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002554 // Are we still explicitly being asked to run?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002555 if (r.startRequested) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002556 return true;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002557 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002558
Dianne Hackborncb015632017-06-14 17:30:15 -07002559 // Is someone still bound to us keeping us running?
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002560 if (!knowConn) {
2561 hasConn = r.hasAutoCreateConnections();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002562 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002563 if (hasConn) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002564 return true;
2565 }
2566
2567 return false;
2568 }
2569
2570 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
2571 boolean hasConn) {
2572 //Slog.i(TAG, "Bring down service:");
2573 //r.dump(" ");
2574
Dianne Hackbornad51be92016-08-16 16:27:36 -07002575 if (isServiceNeededLocked(r, knowConn, hasConn)) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002576 return;
2577 }
2578
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002579 // Are we in the process of launching?
2580 if (mPendingServices.contains(r)) {
2581 return;
2582 }
2583
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002584 bringDownServiceLocked(r);
2585 }
2586
2587 private final void bringDownServiceLocked(ServiceRecord r) {
2588 //Slog.i(TAG, "Bring down service:");
2589 //r.dump(" ");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002590
Dianne Hackborn390517b2013-05-30 15:03:32 -07002591 // Report to all of the connections that the service is no longer
2592 // available.
2593 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2594 ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
2595 for (int i=0; i<c.size(); i++) {
2596 ConnectionRecord cr = c.get(i);
2597 // There is still a connection to the service that is
2598 // being brought down. Mark it as dead.
2599 cr.serviceDead = true;
2600 try {
Dianne Hackborn94846032017-03-31 17:55:23 -07002601 cr.conn.connected(r.name, null, true);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002602 } catch (Exception e) {
2603 Slog.w(TAG, "Failure disconnecting service " + r.name +
2604 " to connection " + c.get(i).conn.asBinder() +
2605 " (in " + c.get(i).binding.client.processName + ")", e);
2606 }
2607 }
2608 }
2609
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002610 // Tell the service that it has been unbound.
Dianne Hackborn390517b2013-05-30 15:03:32 -07002611 if (r.app != null && r.app.thread != null) {
2612 for (int i=r.bindings.size()-1; i>=0; i--) {
2613 IntentBindRecord ibr = r.bindings.valueAt(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002614 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002615 + ": hasBound=" + ibr.hasBound);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002616 if (ibr.hasBound) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002617 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002618 bumpServiceExecutingLocked(r, false, "bring down unbind");
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002619 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002620 ibr.hasBound = false;
Dianne Hackborn85e35642017-01-12 15:10:57 -08002621 ibr.requested = false;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002622 r.app.thread.scheduleUnbindService(r,
2623 ibr.intent.getIntent());
2624 } catch (Exception e) {
2625 Slog.w(TAG, "Exception when unbinding service "
2626 + r.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002627 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002628 }
2629 }
2630 }
2631 }
2632
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002633 // Check to see if the service had been started as foreground, but being
2634 // brought down before actually showing a notification. That is not allowed.
2635 if (r.fgRequired) {
2636 Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
2637 + r);
2638 r.fgRequired = false;
2639 r.fgWaiting = false;
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07002640 mAm.mAppOpsService.finishOperation(AppOpsManager.getToken(mAm.mAppOpsService),
2641 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002642 mAm.mHandler.removeMessages(
2643 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
2644 if (r.app != null) {
2645 Message msg = mAm.mHandler.obtainMessage(
2646 ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
2647 msg.obj = r.app;
Kodlee Yin7e951262018-04-05 12:59:56 -07002648 msg.getData().putCharSequence(
2649 ActivityManagerService.SERVICE_RECORD_KEY, r.toString());
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002650 mAm.mHandler.sendMessage(msg);
2651 }
2652 }
2653
2654 if (DEBUG_SERVICE) {
2655 RuntimeException here = new RuntimeException();
2656 here.fillInStackTrace();
2657 Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here);
2658 }
Craig Mautner66c4a822015-01-16 12:48:16 -08002659 r.destroyTime = SystemClock.uptimeMillis();
Dianne Hackbornf85e7af2014-10-14 10:43:43 -07002660 if (LOG_SERVICE_START_STOP) {
2661 EventLogTags.writeAmDestroyService(
2662 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
2663 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002664
Dianne Hackbornad51be92016-08-16 16:27:36 -07002665 final ServiceMap smap = getServiceMapLocked(r.userId);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002666 ServiceRecord found = smap.mServicesByName.remove(r.name);
Makoto Onuki1b9dfda2017-04-28 16:27:15 -07002667
2668 // Note when this method is called by bringUpServiceLocked(), the service is not found
2669 // in mServicesByName and found will be null.
2670 if (found != null && found != r) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07002671 // This is not actually the service we think is running... this should not happen,
2672 // but if it does, fail hard.
2673 smap.mServicesByName.put(r.name, found);
2674 throw new IllegalStateException("Bringing down " + r + " but actually running "
2675 + found);
2676 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002677 smap.mServicesByIntent.remove(r.intent);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002678 r.totalRestartCount = 0;
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002679 unscheduleServiceRestartLocked(r, 0, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002680
2681 // Also make sure it is not on the pending list.
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08002682 for (int i=mPendingServices.size()-1; i>=0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002683 if (mPendingServices.get(i) == r) {
2684 mPendingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002685 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002686 }
2687 }
2688
Christopher Tate08992ac2017-03-21 11:37:06 -07002689 cancelForegroundNotificationLocked(r);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002690 if (r.isForeground) {
2691 decActiveForegroundAppLocked(smap, r);
Dianne Hackborne9d9b4b2018-03-28 13:51:46 -07002692 mAm.mAppOpsService.finishOperation(
2693 AppOpsManager.getToken(mAm.mAppOpsService),
2694 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
Chenjie Yu1b9b21c2018-02-13 10:21:59 -08002695 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED, r.appInfo.uid, r.shortName,
Chenjie Yuccfe6452018-01-30 11:33:21 -08002696 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002697 }
Chenjie Yuccfe6452018-01-30 11:33:21 -08002698
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002699 r.isForeground = false;
2700 r.foregroundId = 0;
2701 r.foregroundNoti = null;
2702
2703 // Clear start entries.
2704 r.clearDeliveredStartsLocked();
2705 r.pendingStarts.clear();
2706
2707 if (r.app != null) {
2708 synchronized (r.stats.getBatteryStats()) {
2709 r.stats.stopLaunchedLocked();
2710 }
2711 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002712 if (r.whitelistManager) {
2713 updateWhitelistManagerLocked(r.app);
2714 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002715 if (r.app.thread != null) {
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002716 updateServiceForegroundLocked(r.app, false);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002717 try {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002718 bumpServiceExecutingLocked(r, false, "destroy");
2719 mDestroyingServices.add(r);
Dianne Hackborn455625e2015-01-21 09:55:13 -08002720 r.destroying = true;
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002721 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002722 r.app.thread.scheduleStopService(r);
2723 } catch (Exception e) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002724 Slog.w(TAG, "Exception when destroying service "
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002725 + r.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002726 serviceProcessGoneLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002727 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002728 } else {
2729 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002730 TAG_SERVICE, "Removed service that has no process: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002731 }
2732 } else {
2733 if (DEBUG_SERVICE) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002734 TAG_SERVICE, "Removed service that is not running: " + r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002735 }
2736
2737 if (r.bindings.size() > 0) {
2738 r.bindings.clear();
2739 }
2740
2741 if (r.restarter instanceof ServiceRestarter) {
2742 ((ServiceRestarter)r.restarter).setService(null);
2743 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002744
Dianne Hackbornd2932242013-08-05 18:18:42 -07002745 int memFactor = mAm.mProcessStats.getMemFactorLocked();
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002746 long now = SystemClock.uptimeMillis();
2747 if (r.tracker != null) {
2748 r.tracker.setStarted(false, memFactor, now);
2749 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002750 if (r.executeNesting == 0) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07002751 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002752 r.tracker = null;
2753 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002754 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07002755
Dianne Hackbornad51be92016-08-16 16:27:36 -07002756 smap.ensureNotStartingBackgroundLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002757 }
2758
2759 void removeConnectionLocked(
2760 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
2761 IBinder binder = c.conn.asBinder();
2762 AppBindRecord b = c.binding;
2763 ServiceRecord s = b.service;
2764 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
2765 if (clist != null) {
2766 clist.remove(c);
2767 if (clist.size() == 0) {
2768 s.connections.remove(binder);
2769 }
2770 }
2771 b.connections.remove(c);
2772 if (c.activity != null && c.activity != skipAct) {
2773 if (c.activity.connections != null) {
2774 c.activity.connections.remove(c);
2775 }
2776 }
2777 if (b.client != skipApp) {
2778 b.client.connections.remove(c);
2779 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
2780 b.client.updateHasAboveClientLocked();
2781 }
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002782 // If this connection requested whitelist management, see if we should
2783 // now clear that state.
2784 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
2785 s.updateWhitelistManager();
2786 if (!s.whitelistManager && s.app != null) {
2787 updateWhitelistManagerLocked(s.app);
2788 }
2789 }
Dianne Hackborndb926082013-10-31 16:32:44 -07002790 if (s.app != null) {
Dianne Hackborn465fa392014-09-14 14:21:18 -07002791 updateServiceClientActivitiesLocked(s.app, c, true);
Dianne Hackborndb926082013-10-31 16:32:44 -07002792 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002793 }
2794 clist = mServiceConnections.get(binder);
2795 if (clist != null) {
2796 clist.remove(c);
2797 if (clist.size() == 0) {
2798 mServiceConnections.remove(binder);
2799 }
2800 }
2801
Dianne Hackbornab2df062015-01-07 13:43:13 -08002802 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid, s.name);
2803
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002804 if (b.connections.size() == 0) {
2805 b.intent.apps.remove(b.client);
2806 }
2807
2808 if (!c.serviceDead) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002809 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002810 + ": shouldUnbind=" + b.intent.hasBound);
2811 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
2812 && b.intent.hasBound) {
2813 try {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002814 bumpServiceExecutingLocked(s, false, "unbind");
Dianne Hackborndb926082013-10-31 16:32:44 -07002815 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
Dianne Hackbornf097d422017-12-15 16:32:19 -08002816 && s.app.setProcState <= ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
Dianne Hackborndb926082013-10-31 16:32:44 -07002817 // If this service's process is not already in the cached list,
2818 // then update it in the LRU list here because this may be causing
2819 // it to go down there and we want it to start out near the top.
2820 mAm.updateLruProcessLocked(s.app, false, null);
2821 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002822 mAm.updateOomAdjLocked(s.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002823 b.intent.hasBound = false;
2824 // Assume the client doesn't want to know about a rebind;
2825 // we will deal with that later if it asks for one.
2826 b.intent.doRebind = false;
2827 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
2828 } catch (Exception e) {
2829 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002830 serviceProcessGoneLocked(s);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002831 }
2832 }
2833
Svet Ganov9c165d72015-12-01 19:52:26 -08002834 // If unbound while waiting to start, remove the pending service
2835 mPendingServices.remove(s);
2836
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002837 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002838 boolean hasAutoCreate = s.hasAutoCreateConnections();
2839 if (!hasAutoCreate) {
2840 if (s.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002841 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002842 SystemClock.uptimeMillis());
2843 }
2844 }
2845 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002846 }
2847 }
2848 }
2849
2850 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07002851 boolean inDestroying = mDestroyingServices.contains(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002852 if (r != null) {
Dianne Hackborn455625e2015-01-21 09:55:13 -08002853 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002854 // This is a call from a service start... take care of
2855 // book-keeping.
2856 r.callStart = true;
2857 switch (res) {
2858 case Service.START_STICKY_COMPATIBILITY:
2859 case Service.START_STICKY: {
2860 // We are done with the associated start arguments.
2861 r.findDeliveredStart(startId, true);
2862 // Don't stop if killed.
2863 r.stopIfKilled = false;
2864 break;
2865 }
2866 case Service.START_NOT_STICKY: {
2867 // We are done with the associated start arguments.
2868 r.findDeliveredStart(startId, true);
2869 if (r.getLastStartId() == startId) {
2870 // There is no more work, and this service
2871 // doesn't want to hang around if killed.
2872 r.stopIfKilled = true;
2873 }
2874 break;
2875 }
2876 case Service.START_REDELIVER_INTENT: {
2877 // We'll keep this item until they explicitly
2878 // call stop for it, but keep track of the fact
2879 // that it was delivered.
2880 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
2881 if (si != null) {
2882 si.deliveryCount = 0;
2883 si.doneExecutingCount++;
2884 // Don't stop if killed.
2885 r.stopIfKilled = true;
2886 }
2887 break;
2888 }
2889 case Service.START_TASK_REMOVED_COMPLETE: {
2890 // Special processing for onTaskRemoved(). Don't
2891 // impact normal onStartCommand() processing.
2892 r.findDeliveredStart(startId, true);
2893 break;
2894 }
2895 default:
2896 throw new IllegalArgumentException(
2897 "Unknown service start result: " + res);
2898 }
2899 if (res == Service.START_STICKY_COMPATIBILITY) {
2900 r.callStart = false;
2901 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08002902 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
2903 // This is the final call from destroying the service... we should
2904 // actually be getting rid of the service at this point. Do some
2905 // validation of its state, and ensure it will be fully removed.
2906 if (!inDestroying) {
2907 // Not sure what else to do with this... if it is not actually in the
2908 // destroying list, we don't need to make sure to remove it from it.
Amith Yamasanid0418222016-05-10 15:49:51 -07002909 // If the app is null, then it was probably removed because the process died,
2910 // otherwise wtf
2911 if (r.app != null) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07002912 Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
Amith Yamasanid0418222016-05-10 15:49:51 -07002913 + r + ", app=" + r.app);
2914 }
Dianne Hackborn455625e2015-01-21 09:55:13 -08002915 } else if (r.executeNesting != 1) {
Joe Onorato9d97ee22016-05-31 10:49:08 -07002916 Slog.w(TAG, "Service done with onDestroy, but executeNesting="
Dianne Hackborn455625e2015-01-21 09:55:13 -08002917 + r.executeNesting + ": " + r);
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07002918 // Fake it to keep from ANR due to orphaned entry.
Dianne Hackborn455625e2015-01-21 09:55:13 -08002919 r.executeNesting = 1;
2920 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002921 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002922 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn164371f2013-10-01 19:10:13 -07002923 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002924 Binder.restoreCallingIdentity(origId);
2925 } else {
2926 Slog.w(TAG, "Done executing unknown service from pid "
2927 + Binder.getCallingPid());
2928 }
2929 }
2930
Dianne Hackborn878deb32013-10-14 16:55:09 -07002931 private void serviceProcessGoneLocked(ServiceRecord r) {
2932 if (r.tracker != null) {
2933 int memFactor = mAm.mProcessStats.getMemFactorLocked();
2934 long now = SystemClock.uptimeMillis();
2935 r.tracker.setExecuting(false, memFactor, now);
2936 r.tracker.setBound(false, memFactor, now);
Dianne Hackbornbc72dce2013-11-11 10:43:38 -08002937 r.tracker.setStarted(false, memFactor, now);
Dianne Hackborn878deb32013-10-14 16:55:09 -07002938 }
2939 serviceDoneExecutingLocked(r, true, true);
2940 }
2941
Dianne Hackborn164371f2013-10-01 19:10:13 -07002942 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
2943 boolean finishing) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002944 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002945 + ": nesting=" + r.executeNesting
Dianne Hackborn164371f2013-10-01 19:10:13 -07002946 + ", inDestroying=" + inDestroying + ", app=" + r.app);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002947 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
2948 "<<< DONE EXECUTING " + r.shortName);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002949 r.executeNesting--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002950 if (r.executeNesting <= 0) {
2951 if (r.app != null) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002952 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002953 "Nesting at 0 of " + r.shortName);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002954 r.app.execServicesFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002955 r.app.executingServices.remove(r);
2956 if (r.app.executingServices.size() == 0) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002957 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002958 "No more executingServices of " + r.shortName);
2959 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002960 } else if (r.executeFg) {
2961 // Need to re-evaluate whether the app still needs to be in the foreground.
2962 for (int i=r.app.executingServices.size()-1; i>=0; i--) {
2963 if (r.app.executingServices.valueAt(i).executeFg) {
2964 r.app.execServicesFg = true;
2965 break;
2966 }
2967 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002968 }
Dianne Hackborn164371f2013-10-01 19:10:13 -07002969 if (inDestroying) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08002970 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
Dianne Hackborn164371f2013-10-01 19:10:13 -07002971 "doneExecuting remove destroying " + r);
2972 mDestroyingServices.remove(r);
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002973 r.bindings.clear();
2974 }
Amith Yamasani385c3ad2017-05-04 14:27:11 -07002975 mAm.updateOomAdjLocked(r.app, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002976 }
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07002977 r.executeFg = false;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002978 if (r.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07002979 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002980 SystemClock.uptimeMillis());
Dianne Hackborn164371f2013-10-01 19:10:13 -07002981 if (finishing) {
Dianne Hackborn878deb32013-10-14 16:55:09 -07002982 r.tracker.clearCurrentOwner(r, false);
Dianne Hackbornbd754f42013-07-23 15:52:36 -07002983 r.tracker = null;
2984 }
Dianne Hackborn91268cf2013-06-13 19:06:50 -07002985 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002986 if (finishing) {
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08002987 if (r.app != null && !r.app.persistent) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002988 r.app.services.remove(r);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07002989 if (r.whitelistManager) {
2990 updateWhitelistManagerLocked(r.app);
2991 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08002992 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08002993 r.app = null;
2994 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07002995 }
2996 }
2997
Dianne Hackbornff072722014-09-24 10:56:28 -07002998 boolean attachApplicationLocked(ProcessRecord proc, String processName)
2999 throws RemoteException {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003000 boolean didSomething = false;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003001 // Collect any services that are waiting for this process to come up.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003002 if (mPendingServices.size() > 0) {
3003 ServiceRecord sr = null;
3004 try {
3005 for (int i=0; i<mPendingServices.size(); i++) {
3006 sr = mPendingServices.get(i);
3007 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3008 || !processName.equals(sr.processName))) {
3009 continue;
3010 }
3011
3012 mPendingServices.remove(i);
3013 i--;
Patrick Baumannc2def582018-04-04 12:14:15 -07003014 proc.addPackage(sr.appInfo.packageName, sr.appInfo.longVersionCode,
Dianne Hackbornf7097a52014-05-13 09:56:14 -07003015 mAm.mProcessStats);
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003016 realStartServiceLocked(sr, proc, sr.createdFromFg);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003017 didSomething = true;
Dianne Hackbornad51be92016-08-16 16:27:36 -07003018 if (!isServiceNeededLocked(sr, false, false)) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003019 // We were waiting for this service to start, but it is actually no
3020 // longer needed. This could happen because bringDownServiceIfNeeded
3021 // won't bring down a service that is pending... so now the pending
3022 // is done, so let's drop it.
3023 bringDownServiceLocked(sr);
3024 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003025 }
Dianne Hackbornff072722014-09-24 10:56:28 -07003026 } catch (RemoteException e) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003027 Slog.w(TAG, "Exception in new application when starting service "
3028 + sr.shortName, e);
3029 throw e;
3030 }
3031 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003032 // Also, if there are any services that are waiting to restart and
3033 // would run in this process, now is a good time to start them. It would
3034 // be weird to bring up the process but arbitrarily not let the services
3035 // run at this point just because their restart time hasn't come up.
3036 if (mRestartingServices.size() > 0) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07003037 ServiceRecord sr;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003038 for (int i=0; i<mRestartingServices.size(); i++) {
3039 sr = mRestartingServices.get(i);
3040 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
3041 || !processName.equals(sr.processName))) {
3042 continue;
3043 }
3044 mAm.mHandler.removeCallbacks(sr.restarter);
3045 mAm.mHandler.post(sr.restarter);
3046 }
3047 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003048 return didSomething;
3049 }
3050
3051 void processStartTimedOutLocked(ProcessRecord proc) {
3052 for (int i=0; i<mPendingServices.size(); i++) {
3053 ServiceRecord sr = mPendingServices.get(i);
3054 if ((proc.uid == sr.appInfo.uid
3055 && proc.processName.equals(sr.processName))
3056 || sr.isolatedProc == proc) {
3057 Slog.w(TAG, "Forcing bringing down service: " + sr);
3058 sr.isolatedProc = null;
3059 mPendingServices.remove(i);
3060 i--;
Dianne Hackborn91268cf2013-06-13 19:06:50 -07003061 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003062 }
3063 }
3064 }
3065
Wale Ogunwale540e1232015-05-01 15:35:39 -07003066 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003067 boolean evenPersistent, boolean doit, boolean killProcess,
3068 ArrayMap<ComponentName, ServiceRecord> services) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003069 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003070 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003071 ServiceRecord service = services.valueAt(i);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003072 final boolean sameComponent = packageName == null
3073 || (service.packageName.equals(packageName)
3074 && (filterByClasses == null
3075 || filterByClasses.contains(service.name.getClassName())));
3076 if (sameComponent
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003077 && (service.app == null || evenPersistent || !service.app.persistent)) {
3078 if (!doit) {
3079 return true;
3080 }
3081 didSomething = true;
3082 Slog.i(TAG, " Force stopping service " + service);
3083 if (service.app != null) {
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003084 service.app.removed = killProcess;
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08003085 if (!service.app.persistent) {
3086 service.app.services.remove(service);
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003087 if (service.whitelistManager) {
3088 updateWhitelistManagerLocked(service.app);
3089 }
Dianne Hackborn90e9b1d2013-11-21 12:50:01 -08003090 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003091 }
3092 service.app = null;
3093 service.isolatedProc = null;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003094 if (mTmpCollectionResults == null) {
3095 mTmpCollectionResults = new ArrayList<>();
3096 }
3097 mTmpCollectionResults.add(service);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003098 }
3099 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003100 return didSomething;
3101 }
3102
Wale Ogunwale540e1232015-05-01 15:35:39 -07003103 boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003104 int userId, boolean evenPersistent, boolean killProcess, boolean doit) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003105 boolean didSomething = false;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003106
3107 if (mTmpCollectionResults != null) {
3108 mTmpCollectionResults.clear();
3109 }
3110
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003111 if (userId == UserHandle.USER_ALL) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003112 for (int i = mServiceMap.size() - 1; i >= 0; i--) {
3113 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003114 evenPersistent, doit, killProcess, mServiceMap.valueAt(i).mServicesByName);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003115 if (!doit && didSomething) {
3116 return true;
3117 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003118 if (doit && filterByClasses == null) {
3119 forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId);
3120 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003121 }
3122 } else {
Amith Yamasani540b6592013-10-01 13:02:52 -07003123 ServiceMap smap = mServiceMap.get(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003124 if (smap != null) {
3125 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByName;
Wale Ogunwale540e1232015-05-01 15:35:39 -07003126 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
Wale Ogunwale2cb2dd42015-09-02 14:53:29 -07003127 evenPersistent, doit, killProcess, items);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003128 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003129 if (doit && filterByClasses == null) {
3130 forceStopPackageLocked(packageName, userId);
3131 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003132 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003133
Wale Ogunwale540e1232015-05-01 15:35:39 -07003134 if (mTmpCollectionResults != null) {
3135 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
3136 bringDownServiceLocked(mTmpCollectionResults.get(i));
3137 }
3138 mTmpCollectionResults.clear();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003139 }
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003140
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003141 return didSomething;
3142 }
3143
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003144 void forceStopPackageLocked(String packageName, int userId) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003145 ServiceMap smap = mServiceMap.get(userId);
3146 if (smap != null && smap.mActiveForegroundApps.size() > 0) {
Dianne Hackbornaf597682017-05-01 10:54:07 -07003147 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003148 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
3149 if (aa.mPackageName.equals(packageName)) {
3150 smap.mActiveForegroundApps.removeAt(i);
3151 smap.mActiveForegroundAppsChanged = true;
3152 }
3153 }
3154 if (smap.mActiveForegroundAppsChanged) {
3155 requestUpdateActiveForegroundAppsLocked(smap, 0);
3156 }
3157 }
3158 }
3159
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003160 void cleanUpRemovedTaskLocked(TaskRecord tr, ComponentName component, Intent baseIntent) {
Wale Ogunwale540e1232015-05-01 15:35:39 -07003161 ArrayList<ServiceRecord> services = new ArrayList<>();
Dianne Hackbornad51be92016-08-16 16:27:36 -07003162 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(tr.userId);
Wale Ogunwale540e1232015-05-01 15:35:39 -07003163 for (int i = alls.size() - 1; i >= 0; i--) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003164 ServiceRecord sr = alls.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003165 if (sr.packageName.equals(component.getPackageName())) {
3166 services.add(sr);
3167 }
3168 }
3169
3170 // Take care of any running services associated with the app.
Wale Ogunwale540e1232015-05-01 15:35:39 -07003171 for (int i = services.size() - 1; i >= 0; i--) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003172 ServiceRecord sr = services.get(i);
3173 if (sr.startRequested) {
3174 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
3175 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
3176 stopServiceLocked(sr);
3177 } else {
3178 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Todd Kennedy51b3aac2017-03-30 17:50:42 -07003179 sr.makeNextStartId(), baseIntent, null, 0));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003180 if (sr.app != null && sr.app.thread != null) {
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003181 // We always run in the foreground, since this is called as
3182 // part of the "remove task" UI operation.
Craig Mautner5f2bb4c2015-03-12 16:10:27 -07003183 try {
3184 sendServiceArgsLocked(sr, true, false);
3185 } catch (TransactionTooLargeException e) {
3186 // Ignore, keep going.
3187 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003188 }
3189 }
3190 }
3191 }
3192 }
3193
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003194 final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003195 // Report disconnected services.
3196 if (false) {
3197 // XXX we are letting the client link to the service for
3198 // death notifications.
3199 if (app.services.size() > 0) {
3200 Iterator<ServiceRecord> it = app.services.iterator();
3201 while (it.hasNext()) {
3202 ServiceRecord r = it.next();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003203 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3204 ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
3205 for (int i=0; i<cl.size(); i++) {
3206 ConnectionRecord c = cl.get(i);
3207 if (c.binding.client != app) {
3208 try {
3209 //c.conn.connected(r.className, null);
3210 } catch (Exception e) {
3211 // todo: this should be asynchronous!
3212 Slog.w(TAG, "Exception thrown disconnected servce "
3213 + r.shortName
3214 + " from app " + app.processName, e);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003215 }
3216 }
3217 }
3218 }
3219 }
3220 }
3221 }
3222
louis_chang40e259c2015-03-26 13:31:14 +08003223 // Clean up any connections this application has to other services.
3224 for (int i = app.connections.size() - 1; i >= 0; i--) {
3225 ConnectionRecord r = app.connections.valueAt(i);
3226 removeConnectionLocked(r, app, null);
3227 }
3228 updateServiceConnectionActivitiesLocked(app);
3229 app.connections.clear();
3230
Dianne Hackborna590d2b2016-06-27 15:07:18 -07003231 app.whitelistManager = false;
3232
louis_chang40e259c2015-03-26 13:31:14 +08003233 // Clear app state from services.
3234 for (int i = app.services.size() - 1; i >= 0; i--) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003235 ServiceRecord sr = app.services.valueAt(i);
3236 synchronized (sr.stats.getBatteryStats()) {
3237 sr.stats.stopLaunchedLocked();
3238 }
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003239 if (sr.app != app && sr.app != null && !sr.app.persistent) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003240 sr.app.services.remove(sr);
3241 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003242 sr.app = null;
3243 sr.isolatedProc = null;
3244 sr.executeNesting = 0;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003245 sr.forceClearTracker();
3246 if (mDestroyingServices.remove(sr)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003247 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackbornc8230512013-07-13 21:32:12 -07003248 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003249
Dianne Hackbornc8230512013-07-13 21:32:12 -07003250 final int numClients = sr.bindings.size();
3251 for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
3252 IntentBindRecord b = sr.bindings.valueAt(bindingi);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003253 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
Dianne Hackbornc8230512013-07-13 21:32:12 -07003254 + ": shouldUnbind=" + b.hasBound);
3255 b.binder = null;
3256 b.requested = b.received = b.hasBound = false;
Dianne Hackborn465fa392014-09-14 14:21:18 -07003257 // If this binding is coming from a cached process and is asking to keep
3258 // the service created, then we'll kill the cached process as well -- we
3259 // don't want to be thrashing around restarting processes that are only
3260 // there to be cached.
3261 for (int appi=b.apps.size()-1; appi>=0; appi--) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003262 final ProcessRecord proc = b.apps.keyAt(appi);
3263 // If the process is already gone, skip it.
3264 if (proc.killedByAm || proc.thread == null) {
3265 continue;
3266 }
3267 // Only do this for processes that have an auto-create binding;
3268 // otherwise the binding can be left, because it won't cause the
3269 // service to restart.
3270 final AppBindRecord abind = b.apps.valueAt(appi);
3271 boolean hasCreate = false;
3272 for (int conni=abind.connections.size()-1; conni>=0; conni--) {
3273 ConnectionRecord conn = abind.connections.valueAt(conni);
Dianne Hackborn0fe3c252014-09-19 15:09:39 -07003274 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
3275 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
Dianne Hackborn24c98e82014-09-14 17:23:54 -07003276 hasCreate = true;
3277 break;
3278 }
3279 }
3280 if (!hasCreate) {
3281 continue;
3282 }
Dianne Hackborncd97c962014-09-25 18:34:02 -07003283 // XXX turned off for now until we have more time to get a better policy.
3284 if (false && proc != null && !proc.persistent && proc.thread != null
Dianne Hackborn465fa392014-09-14 14:21:18 -07003285 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
3286 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
3287 proc.kill("bound to service " + sr.name.flattenToShortString()
3288 + " in dying proc " + (app != null ? app.processName : "??"), true);
3289 }
3290 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003291 }
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003292 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003293
Dianne Hackbornad51be92016-08-16 16:27:36 -07003294 ServiceMap smap = getServiceMapLocked(app.userId);
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003295
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003296 // Now do remaining service cleanup.
3297 for (int i=app.services.size()-1; i>=0; i--) {
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003298 ServiceRecord sr = app.services.valueAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003299
3300 // Unless the process is persistent, this process record is going away,
3301 // so make sure the service is cleaned out of it.
3302 if (!app.persistent) {
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003303 app.services.removeAt(i);
Dianne Hackbornaa9875e2013-12-09 11:26:11 -08003304 }
3305
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003306 // Sanity check: if the service listed for the app is not one
Dianne Hackborn4190fc52013-12-09 18:20:16 -08003307 // we actually are maintaining, just let it drop.
Dianne Hackborn40c87252014-03-19 16:55:40 -07003308 final ServiceRecord curRec = smap.mServicesByName.get(sr.name);
3309 if (curRec != sr) {
3310 if (curRec != null) {
3311 Slog.wtf(TAG, "Service " + sr + " in process " + app
3312 + " not same as in map: " + curRec);
3313 }
Dianne Hackbornddc19e92013-11-14 14:32:17 -08003314 continue;
3315 }
3316
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003317 // Any services running in the application may need to be placed
3318 // back in the pending list.
Amith Yamasanib0c8a882017-08-28 09:36:42 -07003319 if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
3320 && (sr.serviceInfo.applicationInfo.flags
3321 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003322 Slog.w(TAG, "Service crashed " + sr.crashCount
3323 + " times, stopping: " + sr);
3324 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
3325 sr.userId, sr.crashCount, sr.shortName, app.pid);
3326 bringDownServiceLocked(sr);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003327 } else if (!allowRestart
Fyodor Kupolov1b3edac2017-09-19 15:48:06 -07003328 || !mAm.mUserController.isUserRunning(sr.userId, 0)) {
Dianne Hackbornc8230512013-07-13 21:32:12 -07003329 bringDownServiceLocked(sr);
3330 } else {
3331 boolean canceled = scheduleServiceRestartLocked(sr, true);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003332
Dianne Hackbornc8230512013-07-13 21:32:12 -07003333 // Should the service remain running? Note that in the
3334 // extreme case of so many attempts to deliver a command
3335 // that it failed we also will stop it here.
3336 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
3337 if (sr.pendingStarts.size() == 0) {
3338 sr.startRequested = false;
3339 if (sr.tracker != null) {
Dianne Hackbornd2932242013-08-05 18:18:42 -07003340 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
Dianne Hackbornc8230512013-07-13 21:32:12 -07003341 SystemClock.uptimeMillis());
3342 }
3343 if (!sr.hasAutoCreateConnections()) {
3344 // Whoops, no reason to restart!
3345 bringDownServiceLocked(sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003346 }
3347 }
3348 }
3349 }
Dianne Hackbornc8230512013-07-13 21:32:12 -07003350 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003351
Dianne Hackbornc8230512013-07-13 21:32:12 -07003352 if (!allowRestart) {
3353 app.services.clear();
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003354
3355 // Make sure there are no more restarting services for this process.
3356 for (int i=mRestartingServices.size()-1; i>=0; i--) {
3357 ServiceRecord r = mRestartingServices.get(i);
3358 if (r.processName.equals(app.processName) &&
3359 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3360 mRestartingServices.remove(i);
Dianne Hackbornd6f5b622013-11-11 17:25:37 -08003361 clearRestartingIfNeededLocked(r);
3362 }
3363 }
3364 for (int i=mPendingServices.size()-1; i>=0; i--) {
3365 ServiceRecord r = mPendingServices.get(i);
3366 if (r.processName.equals(app.processName) &&
3367 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3368 mPendingServices.remove(i);
Dianne Hackborndaa0d5c2013-11-06 16:30:29 -08003369 }
3370 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003371 }
3372
3373 // Make sure we have no more records on the stopping list.
Dianne Hackborn164371f2013-10-01 19:10:13 -07003374 int i = mDestroyingServices.size();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003375 while (i > 0) {
3376 i--;
Dianne Hackborn164371f2013-10-01 19:10:13 -07003377 ServiceRecord sr = mDestroyingServices.get(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003378 if (sr.app == app) {
Dianne Hackborn164371f2013-10-01 19:10:13 -07003379 sr.forceClearTracker();
3380 mDestroyingServices.remove(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -08003381 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003382 }
3383 }
3384
3385 app.executingServices.clear();
3386 }
3387
3388 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
3389 ActivityManager.RunningServiceInfo info =
3390 new ActivityManager.RunningServiceInfo();
3391 info.service = r.name;
3392 if (r.app != null) {
3393 info.pid = r.app.pid;
3394 }
3395 info.uid = r.appInfo.uid;
3396 info.process = r.processName;
3397 info.foreground = r.isForeground;
Yi Jin6b514142017-10-30 14:54:12 -07003398 info.activeSince = r.createRealTime;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003399 info.started = r.startRequested;
3400 info.clientCount = r.connections.size();
3401 info.crashCount = r.crashCount;
3402 info.lastActivityTime = r.lastActivity;
3403 if (r.isForeground) {
3404 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
3405 }
3406 if (r.startRequested) {
3407 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
3408 }
3409 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
3410 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
3411 }
3412 if (r.app != null && r.app.persistent) {
3413 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
3414 }
3415
Dianne Hackborn390517b2013-05-30 15:03:32 -07003416 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3417 ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003418 for (int i=0; i<connl.size(); i++) {
3419 ConnectionRecord conn = connl.get(i);
3420 if (conn.clientLabel != 0) {
3421 info.clientPackage = conn.binding.client.info.packageName;
3422 info.clientLabel = conn.clientLabel;
3423 return info;
3424 }
3425 }
3426 }
3427 return info;
3428 }
3429
Bryce Lee290e5782017-02-01 16:41:20 -08003430 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags,
Shunta Sato55af6c52016-10-19 15:58:52 +09003431 int callingUid, boolean allowed, boolean canInteractAcrossUsers) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003432 ArrayList<ActivityManager.RunningServiceInfo> res
3433 = new ArrayList<ActivityManager.RunningServiceInfo>();
3434
Dianne Hackborn0c380492012-08-20 17:23:30 -07003435 final long ident = Binder.clearCallingIdentity();
3436 try {
Shunta Sato55af6c52016-10-19 15:58:52 +09003437 if (canInteractAcrossUsers) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07003438 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003439 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003440 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003441 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3442 ServiceRecord sr = alls.valueAt(i);
3443 res.add(makeRunningServiceInfoLocked(sr));
Dianne Hackborn0c380492012-08-20 17:23:30 -07003444 }
3445 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003446
Dianne Hackborn0c380492012-08-20 17:23:30 -07003447 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3448 ServiceRecord r = mRestartingServices.get(i);
3449 ActivityManager.RunningServiceInfo info =
3450 makeRunningServiceInfoLocked(r);
3451 info.restarting = r.nextRestartTime;
3452 res.add(info);
3453 }
3454 } else {
Bryce Lee290e5782017-02-01 16:41:20 -08003455 int userId = UserHandle.getUserId(callingUid);
Dianne Hackbornad51be92016-08-16 16:27:36 -07003456 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003457 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3458 ServiceRecord sr = alls.valueAt(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003459
3460 if (allowed || (sr.app != null && sr.app.uid == callingUid)) {
3461 res.add(makeRunningServiceInfoLocked(sr));
3462 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07003463 }
3464
3465 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3466 ServiceRecord r = mRestartingServices.get(i);
Bryce Lee290e5782017-02-01 16:41:20 -08003467 if (r.userId == userId
3468 && (allowed || (r.app != null && r.app.uid == callingUid))) {
Dianne Hackborn0c380492012-08-20 17:23:30 -07003469 ActivityManager.RunningServiceInfo info =
3470 makeRunningServiceInfoLocked(r);
3471 info.restarting = r.nextRestartTime;
3472 res.add(info);
3473 }
3474 }
3475 }
3476 } finally {
3477 Binder.restoreCallingIdentity(ident);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003478 }
3479
3480 return res;
3481 }
3482
3483 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003484 int userId = UserHandle.getUserId(Binder.getCallingUid());
Dianne Hackbornad51be92016-08-16 16:27:36 -07003485 ServiceRecord r = getServiceByNameLocked(name, userId);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003486 if (r != null) {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003487 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3488 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003489 for (int i=0; i<conn.size(); i++) {
3490 if (conn.get(i).clientIntent != null) {
3491 return conn.get(i).clientIntent;
3492 }
3493 }
3494 }
3495 }
3496 return null;
3497 }
3498
3499 void serviceTimeout(ProcessRecord proc) {
3500 String anrMessage = null;
3501
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07003502 synchronized(mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003503 if (proc.executingServices.size() == 0 || proc.thread == null) {
3504 return;
3505 }
Dianne Hackbornab2df062015-01-07 13:43:13 -08003506 final long now = SystemClock.uptimeMillis();
3507 final long maxTime = now -
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003508 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003509 ServiceRecord timeout = null;
3510 long nextTime = 0;
Dianne Hackbornc8230512013-07-13 21:32:12 -07003511 for (int i=proc.executingServices.size()-1; i>=0; i--) {
3512 ServiceRecord sr = proc.executingServices.valueAt(i);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003513 if (sr.executingStart < maxTime) {
3514 timeout = sr;
3515 break;
3516 }
3517 if (sr.executingStart > nextTime) {
3518 nextTime = sr.executingStart;
3519 }
3520 }
3521 if (timeout != null && mAm.mLruProcesses.contains(proc)) {
3522 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackborncff1bbf2015-01-20 13:43:32 -08003523 StringWriter sw = new StringWriter();
3524 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
3525 pw.println(timeout);
3526 timeout.dump(pw, " ");
3527 pw.close();
3528 mLastAnrDump = sw.toString();
3529 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
3530 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
3531 anrMessage = "executing service " + timeout.shortName;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003532 } else {
3533 Message msg = mAm.mHandler.obtainMessage(
3534 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3535 msg.obj = proc;
Dianne Hackbornbf36ee22013-07-26 18:24:10 -07003536 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
Dianne Hackborn2be00932013-09-22 16:46:00 -07003537 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003538 }
3539 }
3540
3541 if (anrMessage != null) {
Adrian Roos20d7df32016-01-12 18:59:43 +01003542 mAm.mAppErrors.appNotResponding(proc, null, null, false, anrMessage);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003543 }
3544 }
3545
Christopher Tate08992ac2017-03-21 11:37:06 -07003546 void serviceForegroundTimeout(ServiceRecord r) {
3547 ProcessRecord app;
3548 synchronized (mAm) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003549 if (!r.fgRequired || r.destroying) {
Christopher Tate08992ac2017-03-21 11:37:06 -07003550 return;
3551 }
3552
Christopher Tate54f51b02018-02-16 11:07:12 -08003553 app = r.app;
3554 if (app != null && app.debugging) {
3555 // The app's being debugged; let it ride
3556 return;
3557 }
3558
Christopher Tate08992ac2017-03-21 11:37:06 -07003559 if (DEBUG_BACKGROUND_CHECK) {
3560 Slog.i(TAG, "Service foreground-required timeout for " + r);
3561 }
Christopher Tate08992ac2017-03-21 11:37:06 -07003562 r.fgWaiting = false;
3563 stopServiceLocked(r);
3564 }
3565
3566 if (app != null) {
3567 mAm.mAppErrors.appNotResponding(app, null, null, false,
Kodlee Yin7e951262018-04-05 12:59:56 -07003568 "Context.startForegroundService() did not then call Service.startForeground(): "
3569 + r);
Christopher Tate08992ac2017-03-21 11:37:06 -07003570 }
3571 }
3572
Kodlee Yin7e951262018-04-05 12:59:56 -07003573 void serviceForegroundCrash(ProcessRecord app, CharSequence serviceRecord) {
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003574 mAm.crashApplication(app.uid, app.pid, app.info.packageName, app.userId,
Kodlee Yin7e951262018-04-05 12:59:56 -07003575 "Context.startForegroundService() did not then call Service.startForeground(): "
3576 + serviceRecord);
Dianne Hackbornf82236e2017-04-19 10:26:01 -07003577 }
3578
Dianne Hackborn2be00932013-09-22 16:46:00 -07003579 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
3580 if (proc.executingServices.size() == 0 || proc.thread == null) {
3581 return;
3582 }
Dianne Hackborn2be00932013-09-22 16:46:00 -07003583 Message msg = mAm.mHandler.obtainMessage(
3584 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3585 msg.obj = proc;
Christopher Tate08992ac2017-03-21 11:37:06 -07003586 mAm.mHandler.sendMessageDelayed(msg,
3587 proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
3588 }
3589
3590 void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
3591 if (r.app.executingServices.size() == 0 || r.app.thread == null) {
3592 return;
3593 }
3594 Message msg = mAm.mHandler.obtainMessage(
3595 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG);
3596 msg.obj = r;
3597 r.fgWaiting = true;
3598 mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT);
Dianne Hackborn2be00932013-09-22 16:46:00 -07003599 }
3600
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003601 final class ServiceDumper {
3602 private final FileDescriptor fd;
3603 private final PrintWriter pw;
3604 private final String[] args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003605 private final boolean dumpAll;
3606 private final String dumpPackage;
3607 private final ItemMatcher matcher;
3608 private final ArrayList<ServiceRecord> services = new ArrayList<>();
3609
3610 private final long nowReal = SystemClock.elapsedRealtime();
3611
3612 private boolean needSep = false;
3613 private boolean printedAnything = false;
3614 private boolean printed = false;
3615
3616 /**
3617 * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
3618 * must be called with the lock held).
3619 */
3620 ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
3621 int opti, boolean dumpAll, String dumpPackage) {
3622 this.fd = fd;
3623 this.pw = pw;
3624 this.args = args;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003625 this.dumpAll = dumpAll;
3626 this.dumpPackage = dumpPackage;
3627 matcher = new ItemMatcher();
3628 matcher.build(args, opti);
3629
3630 final int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003631 for (int user : users) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003632 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003633 if (smap.mServicesByName.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003634 for (int si=0; si<smap.mServicesByName.size(); si++) {
3635 ServiceRecord r = smap.mServicesByName.valueAt(si);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003636 if (!matcher.match(r, r.name)) {
3637 continue;
3638 }
3639 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3640 continue;
3641 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003642 services.add(r);
3643 }
3644 }
3645 }
3646 }
3647
3648 private void dumpHeaderLocked() {
3649 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
3650 if (mLastAnrDump != null) {
3651 pw.println(" Last ANR service:");
3652 pw.print(mLastAnrDump);
3653 pw.println();
3654 }
3655 }
3656
3657 void dumpLocked() {
3658 dumpHeaderLocked();
3659
3660 try {
3661 int[] users = mAm.mUserController.getUsers();
3662 for (int user : users) {
3663 // Find the first service for this user.
3664 int serviceIdx = 0;
3665 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3666 serviceIdx++;
3667 }
3668 printed = false;
3669 if (serviceIdx < services.size()) {
3670 needSep = false;
3671 while (serviceIdx < services.size()) {
3672 ServiceRecord r = services.get(serviceIdx);
3673 serviceIdx++;
3674 if (r.userId != user) {
3675 break;
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07003676 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003677 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003678 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003679 needSep |= printed;
3680 }
3681
3682 dumpUserRemainsLocked(user);
3683 }
3684 } catch (Exception e) {
3685 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3686 }
3687
3688 dumpRemainsLocked();
3689 }
3690
3691 void dumpWithClient() {
3692 synchronized(mAm) {
3693 dumpHeaderLocked();
3694 }
3695
3696 try {
3697 int[] users = mAm.mUserController.getUsers();
3698 for (int user : users) {
3699 // Find the first service for this user.
3700 int serviceIdx = 0;
3701 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3702 serviceIdx++;
3703 }
3704 printed = false;
3705 if (serviceIdx < services.size()) {
3706 needSep = false;
3707 while (serviceIdx < services.size()) {
3708 ServiceRecord r = services.get(serviceIdx);
3709 serviceIdx++;
3710 if (r.userId != user) {
3711 break;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003712 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003713 synchronized(mAm) {
3714 dumpServiceLocalLocked(r);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003715 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003716 dumpServiceClient(r);
3717 }
3718 needSep |= printed;
3719 }
3720
3721 synchronized(mAm) {
3722 dumpUserRemainsLocked(user);
3723 }
3724 }
3725 } catch (Exception e) {
3726 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3727 }
3728
3729 synchronized(mAm) {
3730 dumpRemainsLocked();
3731 }
3732 }
3733
3734 private void dumpUserHeaderLocked(int user) {
3735 if (!printed) {
3736 if (printedAnything) {
3737 pw.println();
3738 }
3739 pw.println(" User " + user + " active services:");
3740 printed = true;
3741 }
3742 printedAnything = true;
3743 if (needSep) {
3744 pw.println();
3745 }
3746 }
3747
3748 private void dumpServiceLocalLocked(ServiceRecord r) {
3749 dumpUserHeaderLocked(r.userId);
3750 pw.print(" * ");
3751 pw.println(r);
3752 if (dumpAll) {
3753 r.dump(pw, " ");
3754 needSep = true;
3755 } else {
3756 pw.print(" app=");
3757 pw.println(r.app);
3758 pw.print(" created=");
Yi Jin6b514142017-10-30 14:54:12 -07003759 TimeUtils.formatDuration(r.createRealTime, nowReal, pw);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003760 pw.print(" started=");
3761 pw.print(r.startRequested);
3762 pw.print(" connections=");
3763 pw.println(r.connections.size());
3764 if (r.connections.size() > 0) {
3765 pw.println(" Connections:");
3766 for (int conni=0; conni<r.connections.size(); conni++) {
3767 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
3768 for (int i = 0; i < clist.size(); i++) {
3769 ConnectionRecord conn = clist.get(i);
3770 pw.print(" ");
3771 pw.print(conn.binding.intent.intent.getIntent()
3772 .toShortString(false, false, false, false));
3773 pw.print(" -> ");
3774 ProcessRecord proc = conn.binding.client;
3775 pw.println(proc != null ? proc.toShortString() : "null");
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003776 }
3777 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003778 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003779 }
3780 }
3781
3782 private void dumpServiceClient(ServiceRecord r) {
3783 final ProcessRecord proc = r.app;
3784 if (proc == null) {
3785 return;
3786 }
3787 final IApplicationThread thread = proc.thread;
3788 if (thread == null) {
3789 return;
3790 }
3791 pw.println(" Client:");
3792 pw.flush();
3793 try {
3794 TransferPipe tp = new TransferPipe();
3795 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003796 thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003797 tp.setBufferPrefix(" ");
3798 // Short timeout, since blocking here can
3799 // deadlock with the application.
3800 tp.go(fd, 2000);
3801 } finally {
3802 tp.kill();
3803 }
3804 } catch (IOException e) {
3805 pw.println(" Failure while dumping the service: " + e);
3806 } catch (RemoteException e) {
3807 pw.println(" Got a RemoteException while dumping the service");
3808 }
3809 needSep = true;
3810 }
3811
3812 private void dumpUserRemainsLocked(int user) {
Dianne Hackbornad51be92016-08-16 16:27:36 -07003813 ServiceMap smap = getServiceMapLocked(user);
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003814 printed = false;
3815 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
3816 ServiceRecord r = smap.mDelayedStartList.get(si);
3817 if (!matcher.match(r, r.name)) {
3818 continue;
3819 }
3820 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3821 continue;
3822 }
3823 if (!printed) {
3824 if (printedAnything) {
3825 pw.println();
3826 }
3827 pw.println(" User " + user + " delayed start services:");
3828 printed = true;
3829 }
3830 printedAnything = true;
3831 pw.print(" * Delayed start "); pw.println(r);
3832 }
3833 printed = false;
3834 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
3835 ServiceRecord r = smap.mStartingBackground.get(si);
3836 if (!matcher.match(r, r.name)) {
3837 continue;
3838 }
3839 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3840 continue;
3841 }
3842 if (!printed) {
3843 if (printedAnything) {
3844 pw.println();
3845 }
3846 pw.println(" User " + user + " starting in background:");
3847 printed = true;
3848 }
3849 printedAnything = true;
3850 pw.print(" * Starting bg "); pw.println(r);
3851 }
3852 }
3853
3854 private void dumpRemainsLocked() {
3855 if (mPendingServices.size() > 0) {
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003856 printed = false;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003857 for (int i=0; i<mPendingServices.size(); i++) {
3858 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003859 if (!matcher.match(r, r.name)) {
3860 continue;
3861 }
3862 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3863 continue;
3864 }
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003865 printedAnything = true;
3866 if (!printed) {
3867 if (needSep) pw.println();
3868 needSep = true;
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003869 pw.println(" Pending services:");
Dianne Hackborn9210bc82013-09-05 12:31:16 -07003870 printed = true;
3871 }
Dianne Hackborn777a06d2016-05-16 17:36:15 -07003872 pw.print(" * Pending "); pw.println(r);
3873 r.dump(pw, " ");
3874 }
3875 needSep = true;
3876 }
3877
3878 if (mRestartingServices.size() > 0) {
3879 printed = false;
3880 for (int i=0; i<mRestartingServices.size(); i++) {
3881 ServiceRecord r = mRestartingServices.get(i);
3882 if (!matcher.match(r, r.name)) {
3883 continue;
3884 }
3885 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3886 continue;
3887 }
3888 printedAnything = true;
3889 if (!printed) {
3890 if (needSep) pw.println();
3891 needSep = true;
3892 pw.println(" Restarting services:");
3893 printed = true;
3894 }
3895 pw.print(" * Restarting "); pw.println(r);
3896 r.dump(pw, " ");
3897 }
3898 needSep = true;
3899 }
3900
3901 if (mDestroyingServices.size() > 0) {
3902 printed = false;
3903 for (int i=0; i< mDestroyingServices.size(); i++) {
3904 ServiceRecord r = mDestroyingServices.get(i);
3905 if (!matcher.match(r, r.name)) {
3906 continue;
3907 }
3908 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3909 continue;
3910 }
3911 printedAnything = true;
3912 if (!printed) {
3913 if (needSep) pw.println();
3914 needSep = true;
3915 pw.println(" Destroying services:");
3916 printed = true;
3917 }
3918 pw.print(" * Destroy "); pw.println(r);
3919 r.dump(pw, " ");
3920 }
3921 needSep = true;
3922 }
3923
3924 if (dumpAll) {
3925 printed = false;
3926 for (int ic=0; ic<mServiceConnections.size(); ic++) {
3927 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
3928 for (int i=0; i<r.size(); i++) {
3929 ConnectionRecord cr = r.get(i);
3930 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
3931 continue;
3932 }
3933 if (dumpPackage != null && (cr.binding.client == null
3934 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
3935 continue;
3936 }
3937 printedAnything = true;
3938 if (!printed) {
3939 if (needSep) pw.println();
3940 needSep = true;
3941 pw.println(" Connection bindings to services:");
3942 printed = true;
3943 }
3944 pw.print(" * "); pw.println(cr);
3945 cr.dump(pw, " ");
3946 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003947 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003948 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003949
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003950 if (matcher.all) {
3951 final long nowElapsed = SystemClock.elapsedRealtime();
3952 final int[] users = mAm.mUserController.getUsers();
3953 for (int user : users) {
3954 boolean printedUser = false;
3955 ServiceMap smap = mServiceMap.get(user);
3956 if (smap == null) {
3957 continue;
3958 }
3959 for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) {
3960 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
3961 if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) {
3962 continue;
3963 }
3964 if (!printedUser) {
3965 printedUser = true;
3966 printedAnything = true;
3967 if (needSep) pw.println();
3968 needSep = true;
3969 pw.print("Active foreground apps - user ");
3970 pw.print(user);
3971 pw.println(":");
3972 }
3973 pw.print(" #");
3974 pw.print(i);
3975 pw.print(": ");
3976 pw.println(aa.mPackageName);
3977 if (aa.mLabel != null) {
3978 pw.print(" mLabel=");
3979 pw.println(aa.mLabel);
3980 }
3981 pw.print(" mNumActive=");
3982 pw.print(aa.mNumActive);
Dianne Hackbornbe68d492017-05-03 18:04:05 -07003983 pw.print(" mAppOnTop=");
3984 pw.print(aa.mAppOnTop);
3985 pw.print(" mShownWhileTop=");
3986 pw.print(aa.mShownWhileTop);
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003987 pw.print(" mShownWhileScreenOn=");
3988 pw.println(aa.mShownWhileScreenOn);
3989 pw.print(" mStartTime=");
3990 TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw);
3991 pw.print(" mStartVisibleTime=");
3992 TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw);
3993 pw.println();
3994 if (aa.mEndTime != 0) {
3995 pw.print(" mEndTime=");
3996 TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw);
3997 pw.println();
3998 }
3999 }
Dianne Hackborncb015632017-06-14 17:30:15 -07004000 if (smap.hasMessagesOrCallbacks()) {
4001 if (needSep) {
4002 pw.println();
4003 }
4004 printedAnything = true;
4005 needSep = true;
4006 pw.print(" Handler - user ");
4007 pw.print(user);
4008 pw.println(":");
4009 smap.dumpMine(new PrintWriterPrinter(pw), " ");
4010 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07004011 }
4012 }
4013
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004014 if (!printedAnything) {
4015 pw.println(" (nothing)");
4016 }
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07004017 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004018 }
4019
Dianne Hackborn777a06d2016-05-16 17:36:15 -07004020 ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4021 int opti, boolean dumpAll, String dumpPackage) {
4022 return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
4023 }
4024
Yi Jin2b30f322018-02-20 15:41:47 -08004025 protected void writeToProto(ProtoOutputStream proto, long fieldId) {
Yi Jin6b514142017-10-30 14:54:12 -07004026 synchronized (mAm) {
Yi Jin2b30f322018-02-20 15:41:47 -08004027 final long outterToken = proto.start(fieldId);
Yi Jin6b514142017-10-30 14:54:12 -07004028 int[] users = mAm.mUserController.getUsers();
4029 for (int user : users) {
4030 ServiceMap smap = mServiceMap.get(user);
4031 if (smap == null) {
4032 continue;
4033 }
4034 long token = proto.start(ActiveServicesProto.SERVICES_BY_USERS);
4035 proto.write(ActiveServicesProto.ServicesByUser.USER_ID, user);
4036 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
4037 for (int i=0; i<alls.size(); i++) {
4038 alls.valueAt(i).writeToProto(proto,
4039 ActiveServicesProto.ServicesByUser.SERVICE_RECORDS);
4040 }
4041 proto.end(token);
4042 }
Yi Jin2b30f322018-02-20 15:41:47 -08004043 proto.end(outterToken);
Yi Jin6b514142017-10-30 14:54:12 -07004044 }
4045 }
4046
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004047 /**
4048 * There are three ways to call this:
4049 * - no service specified: dump all the services
4050 * - a flattened component name that matched an existing service was specified as the
4051 * first arg: dump that one service
4052 * - the first arg isn't the flattened component name of an existing service:
4053 * dump all services whose component contains the first arg as a substring
4054 */
4055 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4056 int opti, boolean dumpAll) {
4057 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
4058
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004059 synchronized (mAm) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07004060 int[] users = mAm.mUserController.getUsers();
Dianne Hackborn1676c852012-09-10 14:52:30 -07004061 if ("all".equals(name)) {
4062 for (int user : users) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -07004063 ServiceMap smap = mServiceMap.get(user);
4064 if (smap == null) {
4065 continue;
4066 }
4067 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004068 for (int i=0; i<alls.size(); i++) {
4069 ServiceRecord r1 = alls.valueAt(i);
Amith Yamasani258848d2012-08-10 17:06:33 -07004070 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004071 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004072 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07004073 } else {
4074 ComponentName componentName = name != null
4075 ? ComponentName.unflattenFromString(name) : null;
4076 int objectId = 0;
4077 if (componentName == null) {
4078 // Not a '/' separated full component name; maybe an object ID?
4079 try {
4080 objectId = Integer.parseInt(name, 16);
4081 name = null;
4082 componentName = null;
4083 } catch (RuntimeException e) {
4084 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004085 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004086
Dianne Hackborn1676c852012-09-10 14:52:30 -07004087 for (int user : users) {
Dianne Hackborn13c590d2013-10-07 14:32:00 -07004088 ServiceMap smap = mServiceMap.get(user);
4089 if (smap == null) {
4090 continue;
4091 }
4092 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
Dianne Hackborn9210bc82013-09-05 12:31:16 -07004093 for (int i=0; i<alls.size(); i++) {
4094 ServiceRecord r1 = alls.valueAt(i);
Amith Yamasani258848d2012-08-10 17:06:33 -07004095 if (componentName != null) {
4096 if (r1.name.equals(componentName)) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004097 services.add(r1);
4098 }
Amith Yamasani258848d2012-08-10 17:06:33 -07004099 } else if (name != null) {
4100 if (r1.name.flattenToString().contains(name)) {
4101 services.add(r1);
4102 }
4103 } else if (System.identityHashCode(r1) == objectId) {
4104 services.add(r1);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004105 }
4106 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004107 }
4108 }
4109 }
4110
4111 if (services.size() <= 0) {
4112 return false;
4113 }
4114
4115 boolean needSep = false;
4116 for (int i=0; i<services.size(); i++) {
4117 if (needSep) {
4118 pw.println();
4119 }
4120 needSep = true;
4121 dumpService("", fd, pw, services.get(i), args, dumpAll);
4122 }
4123 return true;
4124 }
4125
4126 /**
4127 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
4128 * there is a thread associated with the service.
4129 */
4130 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
4131 final ServiceRecord r, String[] args, boolean dumpAll) {
4132 String innerPrefix = prefix + " ";
Dianne Hackbornc2f6f942014-09-22 13:36:42 -07004133 synchronized (mAm) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004134 pw.print(prefix); pw.print("SERVICE ");
4135 pw.print(r.shortName); pw.print(" ");
4136 pw.print(Integer.toHexString(System.identityHashCode(r)));
4137 pw.print(" pid=");
4138 if (r.app != null) pw.println(r.app.pid);
4139 else pw.println("(not running)");
4140 if (dumpAll) {
4141 r.dump(pw, innerPrefix);
4142 }
4143 }
4144 if (r.app != null && r.app.thread != null) {
4145 pw.print(prefix); pw.println(" Client:");
4146 pw.flush();
4147 try {
4148 TransferPipe tp = new TransferPipe();
4149 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004150 r.app.thread.dumpService(tp.getWriteFd(), r, args);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004151 tp.setBufferPrefix(prefix + " ");
4152 tp.go(fd);
4153 } finally {
4154 tp.kill();
4155 }
4156 } catch (IOException e) {
4157 pw.println(prefix + " Failure while dumping the service: " + e);
4158 } catch (RemoteException e) {
4159 pw.println(prefix + " Got a RemoteException while dumping the service");
4160 }
4161 }
4162 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004163}