1 /* 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 17 package com.android.server.am; 18 19 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 20 import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST; 21 22 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK; 23 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOREGROUND_SERVICE; 24 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU; 25 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW; 26 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE; 27 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE_EXECUTING; 28 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU; 29 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE; 30 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE_EXECUTING; 31 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM; 32 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME; 33 34 import android.app.ActivityManager; 35 import android.app.ActivityManagerInternal; 36 import android.app.ActivityThread; 37 import android.app.AppGlobals; 38 import android.app.AppOpsManager; 39 import android.app.IApplicationThread; 40 import android.app.IServiceConnection; 41 import android.app.Notification; 42 import android.app.NotificationManager; 43 import android.app.PendingIntent; 44 import android.app.Service; 45 import android.app.ServiceStartArgs; 46 import android.content.ComponentName; 47 import android.content.ComponentName.WithComponentName; 48 import android.content.Context; 49 import android.content.IIntentSender; 50 import android.content.Intent; 51 import android.content.IntentSender; 52 import android.content.pm.ApplicationInfo; 53 import android.content.pm.PackageManager; 54 import android.content.pm.ParceledListSlice; 55 import android.content.pm.ResolveInfo; 56 import android.content.pm.ServiceInfo; 57 import android.net.Uri; 58 import android.os.Binder; 59 import android.os.Build; 60 import android.os.Bundle; 61 import android.os.DeadObjectException; 62 import android.os.Handler; 63 import android.os.IBinder; 64 import android.os.Looper; 65 import android.os.Message; 66 import android.os.Process; 67 import android.os.RemoteCallback; 68 import android.os.RemoteException; 69 import android.os.SystemClock; 70 import android.os.SystemProperties; 71 import android.os.TransactionTooLargeException; 72 import android.os.UserHandle; 73 import android.provider.Settings; 74 import android.util.ArrayMap; 75 import android.util.ArraySet; 76 import android.util.EventLog; 77 import android.util.PrintWriterPrinter; 78 import android.util.Slog; 79 import android.util.SparseArray; 80 import android.util.StatsLog; 81 import android.util.TimeUtils; 82 import android.util.proto.ProtoOutputStream; 83 import android.webkit.WebViewZygote; 84 85 import com.android.internal.R; 86 import com.android.internal.app.procstats.ServiceState; 87 import com.android.internal.messages.nano.SystemMessageProto; 88 import com.android.internal.notification.SystemNotificationChannels; 89 import com.android.internal.os.BatteryStatsImpl; 90 import com.android.internal.os.TransferPipe; 91 import com.android.internal.util.DumpUtils; 92 import com.android.internal.util.FastPrintWriter; 93 import com.android.server.AppStateTracker; 94 import com.android.server.LocalServices; 95 import com.android.server.SystemService; 96 import com.android.server.am.ActivityManagerService.ItemMatcher; 97 import com.android.server.uri.NeededUriGrants; 98 import com.android.server.wm.ActivityServiceConnectionsHolder; 99 100 import java.io.FileDescriptor; 101 import java.io.IOException; 102 import java.io.PrintWriter; 103 import java.io.StringWriter; 104 import java.util.ArrayList; 105 import java.util.Comparator; 106 import java.util.Iterator; 107 import java.util.List; 108 import java.util.Set; 109 import java.util.function.Predicate; 110 111 public final class ActiveServices { 112 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM; 113 private static final String TAG_MU = TAG + POSTFIX_MU; 114 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE; 115 private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING; 116 117 private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE; 118 private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE; 119 120 private static final boolean LOG_SERVICE_START_STOP = false; 121 122 private static final boolean SHOW_DUNGEON_NOTIFICATION = false; 123 124 // How long we wait for a service to finish executing. 125 static final int SERVICE_TIMEOUT = 20*1000; 126 127 // How long we wait for a service to finish executing. 128 static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10; 129 130 // How long the startForegroundService() grace period is to get around to 131 // calling startForeground() before we ANR + stop it. 132 static final int SERVICE_START_FOREGROUND_TIMEOUT = 10*1000; 133 134 final ActivityManagerService mAm; 135 136 // Maximum number of services that we allow to start in the background 137 // at the same time. 138 final int mMaxStartingBackground; 139 140 final SparseArray<ServiceMap> mServiceMap = new SparseArray<>(); 141 142 /** 143 * All currently bound service connections. Keys are the IBinder of 144 * the client's IServiceConnection. 145 */ 146 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>(); 147 148 /** 149 * List of services that we have been asked to start, 150 * but haven't yet been able to. It is used to hold start requests 151 * while waiting for their corresponding application thread to get 152 * going. 153 */ 154 final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>(); 155 156 /** 157 * List of services that are scheduled to restart following a crash. 158 */ 159 final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>(); 160 161 /** 162 * List of services that are in the process of being destroyed. 163 */ 164 final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>(); 165 166 /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */ 167 private ArrayList<ServiceRecord> mTmpCollectionResults = null; 168 169 /** 170 * For keeping ActiveForegroundApps retaining state while the screen is off. 171 */ 172 boolean mScreenOn = true; 173 174 /** Amount of time to allow a last ANR message to exist before freeing the memory. */ 175 static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours 176 177 String mLastAnrDump; 178 179 final Runnable mLastAnrDumpClearer = new Runnable() { 180 @Override public void run() { 181 synchronized (mAm) { 182 mLastAnrDump = null; 183 } 184 } 185 }; 186 187 /** 188 * Watch for apps being put into forced app standby, so we can step their fg 189 * services down. 190 */ 191 class ForcedStandbyListener extends AppStateTracker.Listener { 192 @Override stopForegroundServicesForUidPackage(final int uid, final String packageName)193 public void stopForegroundServicesForUidPackage(final int uid, final String packageName) { 194 synchronized (mAm) { 195 final ServiceMap smap = getServiceMapLocked(UserHandle.getUserId(uid)); 196 final int N = smap.mServicesByInstanceName.size(); 197 final ArrayList<ServiceRecord> toStop = new ArrayList<>(N); 198 for (int i = 0; i < N; i++) { 199 final ServiceRecord r = smap.mServicesByInstanceName.valueAt(i); 200 if (uid == r.serviceInfo.applicationInfo.uid 201 || packageName.equals(r.serviceInfo.packageName)) { 202 if (r.isForeground) { 203 toStop.add(r); 204 } 205 } 206 } 207 208 // Now stop them all 209 final int numToStop = toStop.size(); 210 if (numToStop > 0 && DEBUG_FOREGROUND_SERVICE) { 211 Slog.i(TAG, "Package " + packageName + "/" + uid 212 + " entering FAS with foreground services"); 213 } 214 for (int i = 0; i < numToStop; i++) { 215 final ServiceRecord r = toStop.get(i); 216 if (DEBUG_FOREGROUND_SERVICE) { 217 Slog.i(TAG, " Stopping fg for service " + r); 218 } 219 setServiceForegroundInnerLocked(r, 0, null, 0, 0); 220 } 221 } 222 } 223 } 224 225 /** 226 * Information about an app that is currently running one or more foreground services. 227 * (This maps directly to the running apps we show in the notification.) 228 */ 229 static final class ActiveForegroundApp { 230 String mPackageName; 231 int mUid; 232 CharSequence mLabel; 233 boolean mShownWhileScreenOn; 234 boolean mAppOnTop; 235 boolean mShownWhileTop; 236 long mStartTime; 237 long mStartVisibleTime; 238 long mEndTime; 239 int mNumActive; 240 241 // Temp output of foregroundAppShownEnoughLocked 242 long mHideTime; 243 } 244 245 /** 246 * Information about services for a single user. 247 */ 248 final class ServiceMap extends Handler { 249 final int mUserId; 250 final ArrayMap<ComponentName, ServiceRecord> mServicesByInstanceName = new ArrayMap<>(); 251 final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>(); 252 253 final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>(); 254 /* XXX eventually I'd like to have this based on processes instead of services. 255 * That is, if we try to start two services in a row both running in the same 256 * process, this should be one entry in mStartingBackground for that one process 257 * that remains until all services in it are done. 258 final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap 259 = new ArrayMap<ProcessRecord, DelayingProcess>(); 260 final ArrayList<DelayingProcess> mStartingProcessList 261 = new ArrayList<DelayingProcess>(); 262 */ 263 264 final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>(); 265 266 final ArrayMap<String, ActiveForegroundApp> mActiveForegroundApps = new ArrayMap<>(); 267 boolean mActiveForegroundAppsChanged; 268 269 static final int MSG_BG_START_TIMEOUT = 1; 270 static final int MSG_UPDATE_FOREGROUND_APPS = 2; 271 ServiceMap(Looper looper, int userId)272 ServiceMap(Looper looper, int userId) { 273 super(looper); 274 mUserId = userId; 275 } 276 277 @Override handleMessage(Message msg)278 public void handleMessage(Message msg) { 279 switch (msg.what) { 280 case MSG_BG_START_TIMEOUT: { 281 synchronized (mAm) { 282 rescheduleDelayedStartsLocked(); 283 } 284 } break; 285 case MSG_UPDATE_FOREGROUND_APPS: { 286 updateForegroundApps(this); 287 } break; 288 } 289 } 290 ensureNotStartingBackgroundLocked(ServiceRecord r)291 void ensureNotStartingBackgroundLocked(ServiceRecord r) { 292 if (mStartingBackground.remove(r)) { 293 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, 294 "No longer background starting: " + r); 295 rescheduleDelayedStartsLocked(); 296 } 297 if (mDelayedStartList.remove(r)) { 298 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r); 299 } 300 } 301 rescheduleDelayedStartsLocked()302 void rescheduleDelayedStartsLocked() { 303 removeMessages(MSG_BG_START_TIMEOUT); 304 final long now = SystemClock.uptimeMillis(); 305 for (int i=0, N=mStartingBackground.size(); i<N; i++) { 306 ServiceRecord r = mStartingBackground.get(i); 307 if (r.startingBgTimeout <= now) { 308 Slog.i(TAG, "Waited long enough for: " + r); 309 mStartingBackground.remove(i); 310 N--; 311 i--; 312 } 313 } 314 while (mDelayedStartList.size() > 0 315 && mStartingBackground.size() < mMaxStartingBackground) { 316 ServiceRecord r = mDelayedStartList.remove(0); 317 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, 318 "REM FR DELAY LIST (exec next): " + r); 319 if (DEBUG_DELAYED_SERVICE) { 320 if (mDelayedStartList.size() > 0) { 321 Slog.v(TAG_SERVICE, "Remaining delayed list:"); 322 for (int i=0; i<mDelayedStartList.size(); i++) { 323 Slog.v(TAG_SERVICE, " #" + i + ": " + mDelayedStartList.get(i)); 324 } 325 } 326 } 327 r.delayed = false; 328 if (r.pendingStarts.size() <= 0) { 329 Slog.wtf(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested 330 + " delayedStop=" + r.delayedStop); 331 } else { 332 try { 333 startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false, 334 true); 335 } catch (TransactionTooLargeException e) { 336 // Ignore, nobody upstack cares. 337 } 338 } 339 } 340 if (mStartingBackground.size() > 0) { 341 ServiceRecord next = mStartingBackground.get(0); 342 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now; 343 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next 344 + ", can delay others up to " + when); 345 Message msg = obtainMessage(MSG_BG_START_TIMEOUT); 346 sendMessageAtTime(msg, when); 347 } 348 if (mStartingBackground.size() < mMaxStartingBackground) { 349 mAm.backgroundServicesFinishedLocked(mUserId); 350 } 351 } 352 } 353 ActiveServices(ActivityManagerService service)354 public ActiveServices(ActivityManagerService service) { 355 mAm = service; 356 int maxBg = 0; 357 try { 358 maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0")); 359 } catch(RuntimeException e) { 360 } 361 mMaxStartingBackground = maxBg > 0 362 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8; 363 } 364 systemServicesReady()365 void systemServicesReady() { 366 AppStateTracker ast = LocalServices.getService(AppStateTracker.class); 367 ast.addListener(new ForcedStandbyListener()); 368 } 369 getServiceByNameLocked(ComponentName name, int callingUser)370 ServiceRecord getServiceByNameLocked(ComponentName name, int callingUser) { 371 // TODO: Deal with global services 372 if (DEBUG_MU) 373 Slog.v(TAG_MU, "getServiceByNameLocked(" + name + "), callingUser = " + callingUser); 374 return getServiceMapLocked(callingUser).mServicesByInstanceName.get(name); 375 } 376 hasBackgroundServicesLocked(int callingUser)377 boolean hasBackgroundServicesLocked(int callingUser) { 378 ServiceMap smap = mServiceMap.get(callingUser); 379 return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false; 380 } 381 getServiceMapLocked(int callingUser)382 private ServiceMap getServiceMapLocked(int callingUser) { 383 ServiceMap smap = mServiceMap.get(callingUser); 384 if (smap == null) { 385 smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser); 386 mServiceMap.put(callingUser, smap); 387 } 388 return smap; 389 } 390 getServicesLocked(int callingUser)391 ArrayMap<ComponentName, ServiceRecord> getServicesLocked(int callingUser) { 392 return getServiceMapLocked(callingUser).mServicesByInstanceName; 393 } 394 appRestrictedAnyInBackground(final int uid, final String packageName)395 private boolean appRestrictedAnyInBackground(final int uid, final String packageName) { 396 final int mode = mAm.mAppOpsService.checkOperation( 397 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, uid, packageName); 398 return (mode != AppOpsManager.MODE_ALLOWED); 399 } 400 startServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)401 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType, 402 int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId) 403 throws TransactionTooLargeException { 404 return startServiceLocked(caller, service, resolvedType, callingPid, callingUid, fgRequired, 405 callingPackage, userId, false); 406 } 407 startServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId, boolean allowBackgroundActivityStarts)408 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType, 409 int callingPid, int callingUid, boolean fgRequired, String callingPackage, 410 final int userId, boolean allowBackgroundActivityStarts) 411 throws TransactionTooLargeException { 412 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service 413 + " type=" + resolvedType + " args=" + service.getExtras()); 414 415 final boolean callerFg; 416 if (caller != null) { 417 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller); 418 if (callerApp == null) { 419 throw new SecurityException( 420 "Unable to find app for caller " + caller 421 + " (pid=" + callingPid 422 + ") when starting service " + service); 423 } 424 callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND; 425 } else { 426 callerFg = true; 427 } 428 429 ServiceLookupResult res = 430 retrieveServiceLocked(service, null, resolvedType, callingPackage, 431 callingPid, callingUid, userId, true, callerFg, false, false); 432 if (res == null) { 433 return null; 434 } 435 if (res.record == null) { 436 return new ComponentName("!", res.permission != null 437 ? res.permission : "private to package"); 438 } 439 440 ServiceRecord r = res.record; 441 442 if (!mAm.mUserController.exists(r.userId)) { 443 Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId); 444 return null; 445 } 446 447 // If we're starting indirectly (e.g. from PendingIntent), figure out whether 448 // we're launching into an app in a background state. This keys off of the same 449 // idleness state tracking as e.g. O+ background service start policy. 450 final boolean bgLaunch = !mAm.isUidActiveLocked(r.appInfo.uid); 451 452 // If the app has strict background restrictions, we treat any bg service 453 // start analogously to the legacy-app forced-restrictions case, regardless 454 // of its target SDK version. 455 boolean forcedStandby = false; 456 if (bgLaunch && appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) { 457 if (DEBUG_FOREGROUND_SERVICE) { 458 Slog.d(TAG, "Forcing bg-only service start only for " + r.shortInstanceName 459 + " : bgLaunch=" + bgLaunch + " callerFg=" + callerFg); 460 } 461 forcedStandby = true; 462 } 463 464 // If this is a direct-to-foreground start, make sure it is allowed as per the app op. 465 boolean forceSilentAbort = false; 466 if (fgRequired) { 467 final int mode = mAm.mAppOpsService.checkOperation( 468 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName); 469 switch (mode) { 470 case AppOpsManager.MODE_ALLOWED: 471 case AppOpsManager.MODE_DEFAULT: 472 // All okay. 473 break; 474 case AppOpsManager.MODE_IGNORED: 475 // Not allowed, fall back to normal start service, failing siliently 476 // if background check restricts that. 477 Slog.w(TAG, "startForegroundService not allowed due to app op: service " 478 + service + " to " + r.shortInstanceName 479 + " from pid=" + callingPid + " uid=" + callingUid 480 + " pkg=" + callingPackage); 481 fgRequired = false; 482 forceSilentAbort = true; 483 break; 484 default: 485 return new ComponentName("!!", "foreground not allowed as per app op"); 486 } 487 } 488 489 // If this isn't a direct-to-foreground start, check our ability to kick off an 490 // arbitrary service 491 if (forcedStandby || (!r.startRequested && !fgRequired)) { 492 // Before going further -- if this app is not allowed to start services in the 493 // background, then at this point we aren't going to let it period. 494 final int allowed = mAm.getAppStartModeLocked(r.appInfo.uid, r.packageName, 495 r.appInfo.targetSdkVersion, callingPid, false, false, forcedStandby); 496 if (allowed != ActivityManager.APP_START_MODE_NORMAL) { 497 Slog.w(TAG, "Background start not allowed: service " 498 + service + " to " + r.shortInstanceName 499 + " from pid=" + callingPid + " uid=" + callingUid 500 + " pkg=" + callingPackage + " startFg?=" + fgRequired); 501 if (allowed == ActivityManager.APP_START_MODE_DELAYED || forceSilentAbort) { 502 // In this case we are silently disabling the app, to disrupt as 503 // little as possible existing apps. 504 return null; 505 } 506 if (forcedStandby) { 507 // This is an O+ app, but we might be here because the user has placed 508 // it under strict background restrictions. Don't punish the app if it's 509 // trying to do the right thing but we're denying it for that reason. 510 if (fgRequired) { 511 if (DEBUG_BACKGROUND_CHECK) { 512 Slog.v(TAG, "Silently dropping foreground service launch due to FAS"); 513 } 514 return null; 515 } 516 } 517 // This app knows it is in the new model where this operation is not 518 // allowed, so tell it what has happened. 519 UidRecord uidRec = mAm.mProcessList.getUidRecordLocked(r.appInfo.uid); 520 return new ComponentName("?", "app is in background uid " + uidRec); 521 } 522 } 523 524 // At this point we've applied allowed-to-start policy based on whether this was 525 // an ordinary startService() or a startForegroundService(). Now, only require that 526 // the app follow through on the startForegroundService() -> startForeground() 527 // contract if it actually targets O+. 528 if (r.appInfo.targetSdkVersion < Build.VERSION_CODES.O && fgRequired) { 529 if (DEBUG_BACKGROUND_CHECK || DEBUG_FOREGROUND_SERVICE) { 530 Slog.i(TAG, "startForegroundService() but host targets " 531 + r.appInfo.targetSdkVersion + " - not requiring startForeground()"); 532 } 533 fgRequired = false; 534 } 535 536 NeededUriGrants neededGrants = mAm.mUgmInternal.checkGrantUriPermissionFromIntent( 537 callingUid, r.packageName, service, service.getFlags(), null, r.userId); 538 539 // If permissions need a review before any of the app components can run, 540 // we do not start the service and launch a review activity if the calling app 541 // is in the foreground passing it a pending intent to start the service when 542 // review is completed. 543 544 // XXX This is not dealing with fgRequired! 545 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage, 546 callingUid, service, callerFg, userId)) { 547 return null; 548 } 549 550 if (unscheduleServiceRestartLocked(r, callingUid, false)) { 551 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r); 552 } 553 r.lastActivity = SystemClock.uptimeMillis(); 554 r.startRequested = true; 555 r.delayedStop = false; 556 r.fgRequired = fgRequired; 557 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(), 558 service, neededGrants, callingUid)); 559 560 if (fgRequired) { 561 // We are now effectively running a foreground service. 562 ServiceState stracker = r.getTracker(); 563 if (stracker != null) { 564 stracker.setForeground(true, mAm.mProcessStats.getMemFactorLocked(), 565 r.lastActivity); 566 } 567 mAm.mAppOpsService.startOperation(AppOpsManager.getToken(mAm.mAppOpsService), 568 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, true); 569 } 570 571 final ServiceMap smap = getServiceMapLocked(r.userId); 572 boolean addToStarting = false; 573 if (!callerFg && !fgRequired && r.app == null 574 && mAm.mUserController.hasStartedUserState(r.userId)) { 575 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false); 576 if (proc == null || proc.getCurProcState() > ActivityManager.PROCESS_STATE_RECEIVER) { 577 // If this is not coming from a foreground caller, then we may want 578 // to delay the start if there are already other background services 579 // that are starting. This is to avoid process start spam when lots 580 // of applications are all handling things like connectivity broadcasts. 581 // We only do this for cached processes, because otherwise an application 582 // can have assumptions about calling startService() for a service to run 583 // in its own process, and for that process to not be killed before the 584 // service is started. This is especially the case for receivers, which 585 // may start a service in onReceive() to do some additional work and have 586 // initialized some global state as part of that. 587 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of " 588 + r + " in " + proc); 589 if (r.delayed) { 590 // This service is already scheduled for a delayed start; just leave 591 // it still waiting. 592 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r); 593 return r.name; 594 } 595 if (smap.mStartingBackground.size() >= mMaxStartingBackground) { 596 // Something else is starting, delay! 597 Slog.i(TAG_SERVICE, "Delaying start of: " + r); 598 smap.mDelayedStartList.add(r); 599 r.delayed = true; 600 return r.name; 601 } 602 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r); 603 addToStarting = true; 604 } else if (proc.getCurProcState() >= ActivityManager.PROCESS_STATE_SERVICE) { 605 // We slightly loosen when we will enqueue this new service as a background 606 // starting service we are waiting for, to also include processes that are 607 // currently running other services or receivers. 608 addToStarting = true; 609 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, 610 "Not delaying, but counting as bg: " + r); 611 } else if (DEBUG_DELAYED_STARTS) { 612 StringBuilder sb = new StringBuilder(128); 613 sb.append("Not potential delay (state=").append(proc.getCurProcState()) 614 .append(' ').append(proc.adjType); 615 String reason = proc.makeAdjReason(); 616 if (reason != null) { 617 sb.append(' '); 618 sb.append(reason); 619 } 620 sb.append("): "); 621 sb.append(r.toString()); 622 Slog.v(TAG_SERVICE, sb.toString()); 623 } 624 } else if (DEBUG_DELAYED_STARTS) { 625 if (callerFg || fgRequired) { 626 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid=" 627 + callingUid + " pid=" + callingPid + " fgRequired=" + fgRequired + "): " + r); 628 } else if (r.app != null) { 629 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r); 630 } else { 631 Slog.v(TAG_SERVICE, 632 "Not potential delay (user " + r.userId + " not started): " + r); 633 } 634 } 635 636 if (allowBackgroundActivityStarts) { 637 r.whitelistBgActivityStartsOnServiceStart(); 638 } 639 640 ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting); 641 return cmp; 642 } 643 requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r, String callingPackage, int callingUid, Intent service, boolean callerFg, final int userId)644 private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r, 645 String callingPackage, int callingUid, Intent service, boolean callerFg, 646 final int userId) { 647 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired( 648 r.packageName, r.userId)) { 649 650 // Show a permission review UI only for starting from a foreground app 651 if (!callerFg) { 652 Slog.w(TAG, "u" + r.userId + " Starting a service in package" 653 + r.packageName + " requires a permissions review"); 654 return false; 655 } 656 657 IIntentSender target = mAm.mPendingIntentController.getIntentSender( 658 ActivityManager.INTENT_SENDER_SERVICE, callingPackage, 659 callingUid, userId, null, null, 0, new Intent[]{service}, 660 new String[]{service.resolveType(mAm.mContext.getContentResolver())}, 661 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT 662 | PendingIntent.FLAG_IMMUTABLE, null); 663 664 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS); 665 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 666 | Intent.FLAG_ACTIVITY_MULTIPLE_TASK 667 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 668 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName); 669 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target)); 670 671 if (DEBUG_PERMISSIONS_REVIEW) { 672 Slog.i(TAG, "u" + r.userId + " Launching permission review for package " 673 + r.packageName); 674 } 675 676 mAm.mHandler.post(new Runnable() { 677 @Override 678 public void run() { 679 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId)); 680 } 681 }); 682 683 return false; 684 } 685 686 return true; 687 } 688 startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r, boolean callerFg, boolean addToStarting)689 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r, 690 boolean callerFg, boolean addToStarting) throws TransactionTooLargeException { 691 ServiceState stracker = r.getTracker(); 692 if (stracker != null) { 693 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity); 694 } 695 r.callStart = false; 696 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid, r.name.getPackageName(), 697 r.name.getClassName(), StatsLog.SERVICE_STATE_CHANGED__STATE__START); 698 synchronized (r.stats.getBatteryStats()) { 699 r.stats.startRunningLocked(); 700 } 701 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false); 702 if (error != null) { 703 return new ComponentName("!!", error); 704 } 705 706 if (r.startRequested && addToStarting) { 707 boolean first = smap.mStartingBackground.size() == 0; 708 smap.mStartingBackground.add(r); 709 r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT; 710 if (DEBUG_DELAYED_SERVICE) { 711 RuntimeException here = new RuntimeException("here"); 712 here.fillInStackTrace(); 713 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here); 714 } else if (DEBUG_DELAYED_STARTS) { 715 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r); 716 } 717 if (first) { 718 smap.rescheduleDelayedStartsLocked(); 719 } 720 } else if (callerFg || r.fgRequired) { 721 smap.ensureNotStartingBackgroundLocked(r); 722 } 723 724 return r.name; 725 } 726 stopServiceLocked(ServiceRecord service)727 private void stopServiceLocked(ServiceRecord service) { 728 if (service.delayed) { 729 // If service isn't actually running, but is being held in the 730 // delayed list, then we need to keep it started but note that it 731 // should be stopped once no longer delayed. 732 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service); 733 service.delayedStop = true; 734 return; 735 } 736 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, service.appInfo.uid, 737 service.name.getPackageName(), service.name.getClassName(), 738 StatsLog.SERVICE_STATE_CHANGED__STATE__STOP); 739 synchronized (service.stats.getBatteryStats()) { 740 service.stats.stopRunningLocked(); 741 } 742 service.startRequested = false; 743 if (service.tracker != null) { 744 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(), 745 SystemClock.uptimeMillis()); 746 } 747 service.callStart = false; 748 749 bringDownServiceIfNeededLocked(service, false, false); 750 } 751 stopServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int userId)752 int stopServiceLocked(IApplicationThread caller, Intent service, 753 String resolvedType, int userId) { 754 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service 755 + " type=" + resolvedType); 756 757 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller); 758 if (caller != null && callerApp == null) { 759 throw new SecurityException( 760 "Unable to find app for caller " + caller 761 + " (pid=" + Binder.getCallingPid() 762 + ") when stopping service " + service); 763 } 764 765 // If this service is active, make sure it is stopped. 766 ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, null, 767 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false, false); 768 if (r != null) { 769 if (r.record != null) { 770 final long origId = Binder.clearCallingIdentity(); 771 try { 772 stopServiceLocked(r.record); 773 } finally { 774 Binder.restoreCallingIdentity(origId); 775 } 776 return 1; 777 } 778 return -1; 779 } 780 781 return 0; 782 } 783 stopInBackgroundLocked(int uid)784 void stopInBackgroundLocked(int uid) { 785 // Stop all services associated with this uid due to it going to the background 786 // stopped state. 787 ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid)); 788 ArrayList<ServiceRecord> stopping = null; 789 if (services != null) { 790 for (int i = services.mServicesByInstanceName.size() - 1; i >= 0; i--) { 791 ServiceRecord service = services.mServicesByInstanceName.valueAt(i); 792 if (service.appInfo.uid == uid && service.startRequested) { 793 if (mAm.getAppStartModeLocked(service.appInfo.uid, service.packageName, 794 service.appInfo.targetSdkVersion, -1, false, false, false) 795 != ActivityManager.APP_START_MODE_NORMAL) { 796 if (stopping == null) { 797 stopping = new ArrayList<>(); 798 } 799 String compName = service.shortInstanceName; 800 EventLogTags.writeAmStopIdleService(service.appInfo.uid, compName); 801 StringBuilder sb = new StringBuilder(64); 802 sb.append("Stopping service due to app idle: "); 803 UserHandle.formatUid(sb, service.appInfo.uid); 804 sb.append(" "); 805 TimeUtils.formatDuration(service.createRealTime 806 - SystemClock.elapsedRealtime(), sb); 807 sb.append(" "); 808 sb.append(compName); 809 Slog.w(TAG, sb.toString()); 810 stopping.add(service); 811 812 // If the app is under bg restrictions, also make sure that 813 // any notification is dismissed 814 if (appRestrictedAnyInBackground( 815 service.appInfo.uid, service.packageName)) { 816 cancelForegroundNotificationLocked(service); 817 } 818 } 819 } 820 } 821 if (stopping != null) { 822 for (int i=stopping.size()-1; i>=0; i--) { 823 ServiceRecord service = stopping.get(i); 824 service.delayed = false; 825 services.ensureNotStartingBackgroundLocked(service); 826 stopServiceLocked(service); 827 } 828 } 829 } 830 } 831 killMisbehavingService(ServiceRecord r, int appUid, int appPid, String localPackageName)832 void killMisbehavingService(ServiceRecord r, 833 int appUid, int appPid, String localPackageName) { 834 synchronized (mAm) { 835 stopServiceLocked(r); 836 mAm.crashApplication(appUid, appPid, localPackageName, -1, 837 "Bad notification for startForeground", true /*force*/); 838 } 839 } 840 peekServiceLocked(Intent service, String resolvedType, String callingPackage)841 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) { 842 ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, callingPackage, 843 Binder.getCallingPid(), Binder.getCallingUid(), 844 UserHandle.getCallingUserId(), false, false, false, false); 845 846 IBinder ret = null; 847 if (r != null) { 848 // r.record is null if findServiceLocked() failed the caller permission check 849 if (r.record == null) { 850 throw new SecurityException( 851 "Permission Denial: Accessing service" 852 + " from pid=" + Binder.getCallingPid() 853 + ", uid=" + Binder.getCallingUid() 854 + " requires " + r.permission); 855 } 856 IntentBindRecord ib = r.record.bindings.get(r.record.intent); 857 if (ib != null) { 858 ret = ib.binder; 859 } 860 } 861 862 return ret; 863 } 864 stopServiceTokenLocked(ComponentName className, IBinder token, int startId)865 boolean stopServiceTokenLocked(ComponentName className, IBinder token, 866 int startId) { 867 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className 868 + " " + token + " startId=" + startId); 869 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId()); 870 if (r != null) { 871 if (startId >= 0) { 872 // Asked to only stop if done with all work. Note that 873 // to avoid leaks, we will take this as dropping all 874 // start items up to and including this one. 875 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false); 876 if (si != null) { 877 while (r.deliveredStarts.size() > 0) { 878 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0); 879 cur.removeUriPermissionsLocked(); 880 if (cur == si) { 881 break; 882 } 883 } 884 } 885 886 if (r.getLastStartId() != startId) { 887 return false; 888 } 889 890 if (r.deliveredStarts.size() > 0) { 891 Slog.w(TAG, "stopServiceToken startId " + startId 892 + " is last, but have " + r.deliveredStarts.size() 893 + " remaining args"); 894 } 895 } 896 897 StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, r.appInfo.uid, r.name.getPackageName(), 898 r.name.getClassName(), StatsLog.SERVICE_STATE_CHANGED__STATE__STOP); 899 synchronized (r.stats.getBatteryStats()) { 900 r.stats.stopRunningLocked(); 901 } 902 r.startRequested = false; 903 if (r.tracker != null) { 904 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(), 905 SystemClock.uptimeMillis()); 906 } 907 r.callStart = false; 908 final long origId = Binder.clearCallingIdentity(); 909 bringDownServiceIfNeededLocked(r, false, false); 910 Binder.restoreCallingIdentity(origId); 911 return true; 912 } 913 return false; 914 } 915 setServiceForegroundLocked(ComponentName className, IBinder token, int id, Notification notification, int flags, int foregroundServiceType)916 public void setServiceForegroundLocked(ComponentName className, IBinder token, 917 int id, Notification notification, int flags, int foregroundServiceType) { 918 final int userId = UserHandle.getCallingUserId(); 919 final long origId = Binder.clearCallingIdentity(); 920 try { 921 ServiceRecord r = findServiceLocked(className, token, userId); 922 if (r != null) { 923 setServiceForegroundInnerLocked(r, id, notification, flags, foregroundServiceType); 924 } 925 } finally { 926 Binder.restoreCallingIdentity(origId); 927 } 928 } 929 930 /** 931 * Return the current foregroundServiceType of the ServiceRecord. 932 * @param className ComponentName of the Service class. 933 * @param token IBinder token. 934 * @return current foreground service type. 935 */ getForegroundServiceTypeLocked(ComponentName className, IBinder token)936 public int getForegroundServiceTypeLocked(ComponentName className, IBinder token) { 937 final int userId = UserHandle.getCallingUserId(); 938 final long origId = Binder.clearCallingIdentity(); 939 int ret = ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE; 940 try { 941 ServiceRecord r = findServiceLocked(className, token, userId); 942 if (r != null) { 943 ret = r.foregroundServiceType; 944 } 945 } finally { 946 Binder.restoreCallingIdentity(origId); 947 } 948 return ret; 949 } 950 foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed)951 boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) { 952 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid=" 953 + aa.mUid); 954 boolean canRemove = false; 955 aa.mHideTime = Long.MAX_VALUE; 956 if (aa.mShownWhileTop) { 957 // If the app was ever at the top of the screen while the foreground 958 // service was running, then we can always just immediately remove it. 959 canRemove = true; 960 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown while on top"); 961 } else if (mScreenOn || aa.mShownWhileScreenOn) { 962 final long minTime = aa.mStartVisibleTime 963 + (aa.mStartTime != aa.mStartVisibleTime 964 ? mAm.mConstants.FGSERVICE_SCREEN_ON_AFTER_TIME 965 : mAm.mConstants.FGSERVICE_MIN_SHOWN_TIME); 966 if (nowElapsed >= minTime) { 967 // If shown while the screen is on, and it has been shown for 968 // at least the minimum show time, then we can now remove it. 969 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown long enough with screen on"); 970 canRemove = true; 971 } else { 972 // This is when we will be okay to stop telling the user. 973 long reportTime = nowElapsed + mAm.mConstants.FGSERVICE_MIN_REPORT_TIME; 974 aa.mHideTime = reportTime > minTime ? reportTime : minTime; 975 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed) 976 + " with screen on"); 977 } 978 } else { 979 final long minTime = aa.mEndTime 980 + mAm.mConstants.FGSERVICE_SCREEN_ON_BEFORE_TIME; 981 if (nowElapsed >= minTime) { 982 // If the foreground service has only run while the screen is 983 // off, but it has been gone now for long enough that we won't 984 // care to tell the user about it when the screen comes back on, 985 // then we can remove it now. 986 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - gone long enough with screen off"); 987 canRemove = true; 988 } else { 989 // This is when we won't care about this old fg service. 990 aa.mHideTime = minTime; 991 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed) 992 + " with screen off"); 993 } 994 } 995 return canRemove; 996 } 997 updateForegroundApps(ServiceMap smap)998 void updateForegroundApps(ServiceMap smap) { 999 // This is called from the handler without the lock held. 1000 ArrayList<ActiveForegroundApp> active = null; 1001 synchronized (mAm) { 1002 final long now = SystemClock.elapsedRealtime(); 1003 long nextUpdateTime = Long.MAX_VALUE; 1004 if (smap != null) { 1005 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Updating foreground apps for user " 1006 + smap.mUserId); 1007 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) { 1008 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i); 1009 if (aa.mEndTime != 0) { 1010 boolean canRemove = foregroundAppShownEnoughLocked(aa, now); 1011 if (canRemove) { 1012 // This was up for longer than the timeout, so just remove immediately. 1013 smap.mActiveForegroundApps.removeAt(i); 1014 smap.mActiveForegroundAppsChanged = true; 1015 continue; 1016 } 1017 if (aa.mHideTime < nextUpdateTime) { 1018 nextUpdateTime = aa.mHideTime; 1019 } 1020 } 1021 if (!aa.mAppOnTop) { 1022 if (active == null) { 1023 active = new ArrayList<>(); 1024 } 1025 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg=" 1026 + aa.mPackageName + ", uid=" + aa.mUid); 1027 active.add(aa); 1028 } 1029 } 1030 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS); 1031 if (nextUpdateTime < Long.MAX_VALUE) { 1032 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Next update time in: " 1033 + (nextUpdateTime-now)); 1034 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS); 1035 smap.sendMessageAtTime(msg, nextUpdateTime 1036 + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime()); 1037 } 1038 } 1039 if (!smap.mActiveForegroundAppsChanged) { 1040 return; 1041 } 1042 smap.mActiveForegroundAppsChanged = false; 1043 } 1044 1045 if (!SHOW_DUNGEON_NOTIFICATION) { 1046 return; 1047 } 1048 1049 final NotificationManager nm = (NotificationManager) mAm.mContext.getSystemService( 1050 Context.NOTIFICATION_SERVICE); 1051 final Context context = mAm.mContext; 1052 1053 if (active != null) { 1054 for (int i = 0; i < active.size(); i++) { 1055 ActiveForegroundApp aa = active.get(i); 1056 if (aa.mLabel == null) { 1057 PackageManager pm = context.getPackageManager(); 1058 try { 1059 ApplicationInfo ai = pm.getApplicationInfoAsUser(aa.mPackageName, 1060 PackageManager.MATCH_KNOWN_PACKAGES, smap.mUserId); 1061 aa.mLabel = ai.loadLabel(pm); 1062 } catch (PackageManager.NameNotFoundException e) { 1063 aa.mLabel = aa.mPackageName; 1064 } 1065 } 1066 } 1067 1068 Intent intent; 1069 String title; 1070 String msg; 1071 String[] pkgs; 1072 final long nowElapsed = SystemClock.elapsedRealtime(); 1073 long oldestStartTime = nowElapsed; 1074 if (active.size() == 1) { 1075 intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); 1076 intent.setData(Uri.fromParts("package", active.get(0).mPackageName, null)); 1077 title = context.getString( 1078 R.string.foreground_service_app_in_background, active.get(0).mLabel); 1079 msg = context.getString(R.string.foreground_service_tap_for_details); 1080 pkgs = new String[] { active.get(0).mPackageName }; 1081 oldestStartTime = active.get(0).mStartTime; 1082 } else { 1083 intent = new Intent(Settings.ACTION_FOREGROUND_SERVICES_SETTINGS); 1084 pkgs = new String[active.size()]; 1085 for (int i = 0; i < active.size(); i++) { 1086 pkgs[i] = active.get(i).mPackageName; 1087 oldestStartTime = Math.min(oldestStartTime, active.get(i).mStartTime); 1088 } 1089 intent.putExtra("packages", pkgs); 1090 title = context.getString( 1091 R.string.foreground_service_apps_in_background, active.size()); 1092 msg = active.get(0).mLabel.toString(); 1093 for (int i = 1; i < active.size(); i++) { 1094 msg = context.getString(R.string.foreground_service_multiple_separator, 1095 msg, active.get(i).mLabel); 1096 } 1097 } 1098 Bundle notificationBundle = new Bundle(); 1099 notificationBundle.putStringArray(Notification.EXTRA_FOREGROUND_APPS, pkgs); 1100 Notification.Builder n = 1101 new Notification.Builder(context, 1102 SystemNotificationChannels.FOREGROUND_SERVICE) 1103 .addExtras(notificationBundle) 1104 .setSmallIcon(R.drawable.stat_sys_vitals) 1105 .setOngoing(true) 1106 .setShowWhen(oldestStartTime < nowElapsed) 1107 .setWhen(System.currentTimeMillis() - (nowElapsed - oldestStartTime)) 1108 .setColor(context.getColor( 1109 com.android.internal.R.color.system_notification_accent_color)) 1110 .setContentTitle(title) 1111 .setContentText(msg) 1112 .setContentIntent( 1113 PendingIntent.getActivityAsUser(context, 0, intent, 1114 PendingIntent.FLAG_UPDATE_CURRENT, 1115 null, new UserHandle(smap.mUserId))); 1116 nm.notifyAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES, 1117 n.build(), new UserHandle(smap.mUserId)); 1118 } else { 1119 nm.cancelAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES, 1120 new UserHandle(smap.mUserId)); 1121 } 1122 } 1123 requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed)1124 private void requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed) { 1125 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS); 1126 if (timeElapsed != 0) { 1127 smap.sendMessageAtTime(msg, 1128 timeElapsed + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime()); 1129 } else { 1130 smap.mActiveForegroundAppsChanged = true; 1131 smap.sendMessage(msg); 1132 } 1133 } 1134 decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r)1135 private void decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r) { 1136 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName); 1137 if (active != null) { 1138 active.mNumActive--; 1139 if (active.mNumActive <= 0) { 1140 active.mEndTime = SystemClock.elapsedRealtime(); 1141 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Ended running of service"); 1142 if (foregroundAppShownEnoughLocked(active, active.mEndTime)) { 1143 // Have been active for long enough that we will remove it immediately. 1144 smap.mActiveForegroundApps.remove(r.packageName); 1145 smap.mActiveForegroundAppsChanged = true; 1146 requestUpdateActiveForegroundAppsLocked(smap, 0); 1147 } else if (active.mHideTime < Long.MAX_VALUE){ 1148 requestUpdateActiveForegroundAppsLocked(smap, active.mHideTime); 1149 } 1150 } 1151 } 1152 } 1153 updateScreenStateLocked(boolean screenOn)1154 void updateScreenStateLocked(boolean screenOn) { 1155 if (mScreenOn != screenOn) { 1156 mScreenOn = screenOn; 1157 1158 // If screen is turning on, then we now reset the start time of any foreground 1159 // services that were started while the screen was off. 1160 if (screenOn) { 1161 final long nowElapsed = SystemClock.elapsedRealtime(); 1162 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Screen turned on"); 1163 for (int i = mServiceMap.size()-1; i >= 0; i--) { 1164 ServiceMap smap = mServiceMap.valueAt(i); 1165 long nextUpdateTime = Long.MAX_VALUE; 1166 boolean changed = false; 1167 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) { 1168 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j); 1169 if (active.mEndTime == 0) { 1170 if (!active.mShownWhileScreenOn) { 1171 active.mShownWhileScreenOn = true; 1172 active.mStartVisibleTime = nowElapsed; 1173 } 1174 } else { 1175 if (!active.mShownWhileScreenOn 1176 && active.mStartVisibleTime == active.mStartTime) { 1177 // If this was never shown while the screen was on, then we will 1178 // count the time it started being visible as now, to tell the user 1179 // about it now that they have a screen to look at. 1180 active.mEndTime = active.mStartVisibleTime = nowElapsed; 1181 } 1182 if (foregroundAppShownEnoughLocked(active, nowElapsed)) { 1183 // Have been active for long enough that we will remove it 1184 // immediately. 1185 smap.mActiveForegroundApps.remove(active.mPackageName); 1186 smap.mActiveForegroundAppsChanged = true; 1187 changed = true; 1188 } else { 1189 if (active.mHideTime < nextUpdateTime) { 1190 nextUpdateTime = active.mHideTime; 1191 } 1192 } 1193 } 1194 } 1195 if (changed) { 1196 // Need to immediately update. 1197 requestUpdateActiveForegroundAppsLocked(smap, 0); 1198 } else if (nextUpdateTime < Long.MAX_VALUE) { 1199 requestUpdateActiveForegroundAppsLocked(smap, nextUpdateTime); 1200 } 1201 } 1202 } 1203 } 1204 } 1205 foregroundServiceProcStateChangedLocked(UidRecord uidRec)1206 void foregroundServiceProcStateChangedLocked(UidRecord uidRec) { 1207 ServiceMap smap = mServiceMap.get(UserHandle.getUserId(uidRec.uid)); 1208 if (smap != null) { 1209 boolean changed = false; 1210 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) { 1211 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j); 1212 if (active.mUid == uidRec.uid) { 1213 if (uidRec.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP) { 1214 if (!active.mAppOnTop) { 1215 active.mAppOnTop = true; 1216 changed = true; 1217 } 1218 active.mShownWhileTop = true; 1219 } else if (active.mAppOnTop) { 1220 active.mAppOnTop = false; 1221 changed = true; 1222 } 1223 } 1224 } 1225 if (changed) { 1226 requestUpdateActiveForegroundAppsLocked(smap, 0); 1227 } 1228 } 1229 } 1230 appIsTopLocked(int uid)1231 private boolean appIsTopLocked(int uid) { 1232 return mAm.getUidState(uid) <= ActivityManager.PROCESS_STATE_TOP; 1233 } 1234 1235 /** 1236 * @param id Notification ID. Zero === exit foreground state for the given service. 1237 */ setServiceForegroundInnerLocked(final ServiceRecord r, int id, Notification notification, int flags, int foregroundServiceType)1238 private void setServiceForegroundInnerLocked(final ServiceRecord r, int id, 1239 Notification notification, int flags, int foregroundServiceType) { 1240 if (id != 0) { 1241 if (notification == null) { 1242 throw new IllegalArgumentException("null notification"); 1243 } 1244 // Instant apps need permission to create foreground services. 1245 if (r.appInfo.isInstantApp()) { 1246 final int mode = mAm.mAppOpsService.checkOperation( 1247 AppOpsManager.OP_INSTANT_APP_START_FOREGROUND, 1248 r.appInfo.uid, 1249 r.appInfo.packageName); 1250 switch (mode) { 1251 case AppOpsManager.MODE_ALLOWED: 1252 break; 1253 case AppOpsManager.MODE_IGNORED: 1254 Slog.w(TAG, "Instant app " + r.appInfo.packageName 1255 + " does not have permission to create foreground services" 1256 + ", ignoring."); 1257 return; 1258 case AppOpsManager.MODE_ERRORED: 1259 throw new SecurityException("Instant app " + r.appInfo.packageName 1260 + " does not have permission to create foreground services"); 1261 default: 1262 mAm.enforcePermission( 1263 android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE, 1264 r.app.pid, r.appInfo.uid, "startForeground"); 1265 } 1266 } else { 1267 if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.P) { 1268 mAm.enforcePermission( 1269 android.Manifest.permission.FOREGROUND_SERVICE, 1270 r.app.pid, r.appInfo.uid, "startForeground"); 1271 } 1272 1273 int manifestType = r.serviceInfo.getForegroundServiceType(); 1274 // If passed in foreground service type is FOREGROUND_SERVICE_TYPE_MANIFEST, 1275 // consider it is the same as manifest foreground service type. 1276 if (foregroundServiceType == FOREGROUND_SERVICE_TYPE_MANIFEST) { 1277 foregroundServiceType = manifestType; 1278 } 1279 // Check the passed in foreground service type flags is a subset of manifest 1280 // foreground service type flags. 1281 if ((foregroundServiceType & manifestType) != foregroundServiceType) { 1282 throw new IllegalArgumentException("foregroundServiceType " 1283 + String.format("0x%08X", foregroundServiceType) 1284 + " is not a subset of foregroundServiceType attribute " 1285 + String.format("0x%08X", manifestType) 1286 + " in service element of manifest file"); 1287 } 1288 } 1289 boolean alreadyStartedOp = false; 1290 boolean stopProcStatsOp = false; 1291 if (r.fgRequired) { 1292 if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) { 1293 Slog.i(TAG, "Service called startForeground() as required: " + r); 1294 } 1295 r.fgRequired = false; 1296 r.fgWaiting = false; 1297 alreadyStartedOp = stopProcStatsOp = true; 1298 mAm.mHandler.removeMessages( 1299 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r); 1300 } 1301 1302 try { 1303 boolean ignoreForeground = false; 1304 final int mode = mAm.mAppOpsService.checkOperation( 1305 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName); 1306 switch (mode) { 1307 case AppOpsManager.MODE_ALLOWED: 1308 case AppOpsManager.MODE_DEFAULT: 1309 // All okay. 1310 break; 1311 case AppOpsManager.MODE_IGNORED: 1312 // Whoops, silently ignore this. 1313 Slog.w(TAG, "Service.startForeground() not allowed due to app op: service " 1314 + r.shortInstanceName); 1315 ignoreForeground = true; 1316 break; 1317 default: 1318 throw new SecurityException("Foreground not allowed as per app op"); 1319 } 1320 1321 // Apps that are TOP or effectively similar may call startForeground() on 1322 // their services even if they are restricted from doing that while in bg. 1323 if (!ignoreForeground 1324 && !appIsTopLocked(r.appInfo.uid) 1325 && appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) { 1326 Slog.w(TAG, 1327 "Service.startForeground() not allowed due to bg restriction: service " 1328 + r.shortInstanceName); 1329 // Back off of any foreground expectations around this service, since we've 1330 // just turned down its fg request. 1331 updateServiceForegroundLocked(r.app, false); 1332 ignoreForeground = true; 1333 } 1334 1335 // Apps under strict background restrictions simply don't get to have foreground 1336 // services, so now that we've enforced the startForegroundService() contract 1337 // we only do the machinery of making the service foreground when the app 1338 // is not restricted. 1339 if (!ignoreForeground) { 1340 if (r.foregroundId != id) { 1341 cancelForegroundNotificationLocked(r); 1342 r.foregroundId = id; 1343 } 1344 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE; 1345 r.foregroundNoti = notification; 1346 r.foregroundServiceType = foregroundServiceType; 1347 if (!r.isForeground) { 1348 final ServiceMap smap = getServiceMapLocked(r.userId); 1349 if (smap != null) { 1350 ActiveForegroundApp active = smap.mActiveForegroundApps 1351 .get(r.packageName); 1352 if (active == null) { 1353 active = new ActiveForegroundApp(); 1354 active.mPackageName = r.packageName; 1355 active.mUid = r.appInfo.uid; 1356 active.mShownWhileScreenOn = mScreenOn; 1357 if (r.app != null) { 1358 active.mAppOnTop = active.mShownWhileTop = 1359 r.app.uidRecord.getCurProcState() 1360 <= ActivityManager.PROCESS_STATE_TOP; 1361 } 1362 active.mStartTime = active.mStartVisibleTime 1363 = SystemClock.elapsedRealtime(); 1364 smap.mActiveForegroundApps.put(r.packageName, active); 1365 requestUpdateActiveForegroundAppsLocked(smap, 0); 1366 } 1367 active.mNumActive++; 1368 } 1369 r.isForeground = true; 1370 if (!stopProcStatsOp) { 1371 ServiceState stracker = r.getTracker(); 1372 if (stracker != null) { 1373 stracker.setForeground(true, 1374 mAm.mProcessStats.getMemFactorLocked(), r.lastActivity); 1375 } 1376 } else { 1377 stopProcStatsOp = false; 1378 } 1379 mAm.mAppOpsService.startOperation( 1380 AppOpsManager.getToken(mAm.mAppOpsService), 1381 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, 1382 true); 1383 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED, 1384 r.appInfo.uid, r.shortInstanceName, 1385 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER); 1386 mAm.updateForegroundServiceUsageStats(r.name, r.userId, true); 1387 } 1388 r.postNotification(); 1389 if (r.app != null) { 1390 updateServiceForegroundLocked(r.app, true); 1391 } 1392 getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r); 1393 mAm.notifyPackageUse(r.serviceInfo.packageName, 1394 PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE); 1395 } else { 1396 if (DEBUG_FOREGROUND_SERVICE) { 1397 Slog.d(TAG, "Suppressing startForeground() for FAS " + r); 1398 } 1399 } 1400 } finally { 1401 if (stopProcStatsOp) { 1402 // We got through to this point with it actively being started foreground, 1403 // and never decided we wanted to keep it like that, so drop it. 1404 ServiceState stracker = r.getTracker(); 1405 if (stracker != null) { 1406 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(), 1407 r.lastActivity); 1408 } 1409 } 1410 if (alreadyStartedOp) { 1411 // If we had previously done a start op for direct foreground start, 1412 // we have cleared the flag so can now drop it. 1413 mAm.mAppOpsService.finishOperation( 1414 AppOpsManager.getToken(mAm.mAppOpsService), 1415 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName); 1416 } 1417 } 1418 } else { 1419 if (r.isForeground) { 1420 final ServiceMap smap = getServiceMapLocked(r.userId); 1421 if (smap != null) { 1422 decActiveForegroundAppLocked(smap, r); 1423 } 1424 r.isForeground = false; 1425 ServiceState stracker = r.getTracker(); 1426 if (stracker != null) { 1427 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(), 1428 r.lastActivity); 1429 } 1430 mAm.mAppOpsService.finishOperation( 1431 AppOpsManager.getToken(mAm.mAppOpsService), 1432 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName); 1433 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED, 1434 r.appInfo.uid, r.shortInstanceName, 1435 StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT); 1436 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false); 1437 if (r.app != null) { 1438 mAm.updateLruProcessLocked(r.app, false, null); 1439 updateServiceForegroundLocked(r.app, true); 1440 } 1441 } 1442 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) { 1443 cancelForegroundNotificationLocked(r); 1444 r.foregroundId = 0; 1445 r.foregroundNoti = null; 1446 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) { 1447 r.stripForegroundServiceFlagFromNotification(); 1448 if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) { 1449 r.foregroundId = 0; 1450 r.foregroundNoti = null; 1451 } 1452 } 1453 } 1454 } 1455 cancelForegroundNotificationLocked(ServiceRecord r)1456 private void cancelForegroundNotificationLocked(ServiceRecord r) { 1457 if (r.foregroundId != 0) { 1458 // First check to see if this app has any other active foreground services 1459 // with the same notification ID. If so, we shouldn't actually cancel it, 1460 // because that would wipe away the notification that still needs to be shown 1461 // due the other service. 1462 ServiceMap sm = getServiceMapLocked(r.userId); 1463 if (sm != null) { 1464 for (int i = sm.mServicesByInstanceName.size() - 1; i >= 0; i--) { 1465 ServiceRecord other = sm.mServicesByInstanceName.valueAt(i); 1466 if (other != r && other.foregroundId == r.foregroundId 1467 && other.packageName.equals(r.packageName)) { 1468 // Found one! Abort the cancel. 1469 return; 1470 } 1471 } 1472 } 1473 r.cancelNotification(); 1474 } 1475 } 1476 updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj)1477 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) { 1478 boolean anyForeground = false; 1479 int fgServiceTypes = 0; 1480 for (int i = proc.services.size() - 1; i >= 0; i--) { 1481 ServiceRecord sr = proc.services.valueAt(i); 1482 if (sr.isForeground || sr.fgRequired) { 1483 anyForeground = true; 1484 fgServiceTypes |= sr.foregroundServiceType; 1485 } 1486 } 1487 mAm.updateProcessForegroundLocked(proc, anyForeground, fgServiceTypes, oomAdj); 1488 } 1489 updateWhitelistManagerLocked(ProcessRecord proc)1490 private void updateWhitelistManagerLocked(ProcessRecord proc) { 1491 proc.whitelistManager = false; 1492 for (int i=proc.services.size()-1; i>=0; i--) { 1493 ServiceRecord sr = proc.services.valueAt(i); 1494 if (sr.whitelistManager) { 1495 proc.whitelistManager = true; 1496 break; 1497 } 1498 } 1499 } 1500 updateServiceConnectionActivitiesLocked(ProcessRecord clientProc)1501 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) { 1502 ArraySet<ProcessRecord> updatedProcesses = null; 1503 for (int i = 0; i < clientProc.connections.size(); i++) { 1504 final ConnectionRecord conn = clientProc.connections.valueAt(i); 1505 final ProcessRecord proc = conn.binding.service.app; 1506 if (proc == null || proc == clientProc) { 1507 continue; 1508 } else if (updatedProcesses == null) { 1509 updatedProcesses = new ArraySet<>(); 1510 } else if (updatedProcesses.contains(proc)) { 1511 continue; 1512 } 1513 updatedProcesses.add(proc); 1514 updateServiceClientActivitiesLocked(proc, null, false); 1515 } 1516 } 1517 updateServiceClientActivitiesLocked(ProcessRecord proc, ConnectionRecord modCr, boolean updateLru)1518 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc, 1519 ConnectionRecord modCr, boolean updateLru) { 1520 if (modCr != null && modCr.binding.client != null) { 1521 if (!modCr.binding.client.hasActivities()) { 1522 // This connection is from a client without activities, so adding 1523 // and removing is not interesting. 1524 return false; 1525 } 1526 } 1527 1528 boolean anyClientActivities = false; 1529 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) { 1530 ServiceRecord sr = proc.services.valueAt(i); 1531 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = sr.getConnections(); 1532 for (int conni = connections.size() - 1; conni >= 0 && !anyClientActivities; conni--) { 1533 ArrayList<ConnectionRecord> clist = connections.valueAt(conni); 1534 for (int cri=clist.size()-1; cri>=0; cri--) { 1535 ConnectionRecord cr = clist.get(cri); 1536 if (cr.binding.client == null || cr.binding.client == proc) { 1537 // Binding to ourself is not interesting. 1538 continue; 1539 } 1540 if (cr.binding.client.hasActivities()) { 1541 anyClientActivities = true; 1542 break; 1543 } 1544 } 1545 } 1546 } 1547 if (anyClientActivities != proc.hasClientActivities()) { 1548 proc.setHasClientActivities(anyClientActivities); 1549 if (updateLru) { 1550 mAm.updateLruProcessLocked(proc, anyClientActivities, null); 1551 } 1552 return true; 1553 } 1554 return false; 1555 } 1556 bindServiceLocked(IApplicationThread caller, IBinder token, Intent service, String resolvedType, final IServiceConnection connection, int flags, String instanceName, String callingPackage, final int userId)1557 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service, 1558 String resolvedType, final IServiceConnection connection, int flags, 1559 String instanceName, String callingPackage, final int userId) 1560 throws TransactionTooLargeException { 1561 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service 1562 + " type=" + resolvedType + " conn=" + connection.asBinder() 1563 + " flags=0x" + Integer.toHexString(flags)); 1564 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller); 1565 if (callerApp == null) { 1566 throw new SecurityException( 1567 "Unable to find app for caller " + caller 1568 + " (pid=" + Binder.getCallingPid() 1569 + ") when binding service " + service); 1570 } 1571 1572 ActivityServiceConnectionsHolder<ConnectionRecord> activity = null; 1573 if (token != null) { 1574 activity = mAm.mAtmInternal.getServiceConnectionsHolder(token); 1575 if (activity == null) { 1576 Slog.w(TAG, "Binding with unknown activity: " + token); 1577 return 0; 1578 } 1579 } 1580 1581 int clientLabel = 0; 1582 PendingIntent clientIntent = null; 1583 final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID; 1584 1585 if (isCallerSystem) { 1586 // Hacky kind of thing -- allow system stuff to tell us 1587 // what they are, so we can report this elsewhere for 1588 // others to know why certain services are running. 1589 service.setDefusable(true); 1590 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT); 1591 if (clientIntent != null) { 1592 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0); 1593 if (clientLabel != 0) { 1594 // There are no useful extras in the intent, trash them. 1595 // System code calling with this stuff just needs to know 1596 // this will happen. 1597 service = service.cloneFilter(); 1598 } 1599 } 1600 } 1601 1602 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) { 1603 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 1604 "BIND_TREAT_LIKE_ACTIVITY"); 1605 } 1606 1607 if ((flags & Context.BIND_SCHEDULE_LIKE_TOP_APP) != 0 && !isCallerSystem) { 1608 throw new SecurityException("Non-system caller (pid=" + Binder.getCallingPid() 1609 + ") set BIND_SCHEDULE_LIKE_TOP_APP when binding service " + service); 1610 } 1611 1612 if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) { 1613 throw new SecurityException( 1614 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid() 1615 + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service); 1616 } 1617 1618 if ((flags & Context.BIND_ALLOW_INSTANT) != 0 && !isCallerSystem) { 1619 throw new SecurityException( 1620 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid() 1621 + ") set BIND_ALLOW_INSTANT when binding service " + service); 1622 } 1623 1624 if ((flags & Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS) != 0) { 1625 mAm.enforceCallingPermission( 1626 android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND, 1627 "BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS"); 1628 } 1629 1630 final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND; 1631 final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0; 1632 final boolean allowInstant = (flags & Context.BIND_ALLOW_INSTANT) != 0; 1633 1634 ServiceLookupResult res = 1635 retrieveServiceLocked(service, instanceName, resolvedType, callingPackage, 1636 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, 1637 callerFg, isBindExternal, allowInstant); 1638 if (res == null) { 1639 return 0; 1640 } 1641 if (res.record == null) { 1642 return -1; 1643 } 1644 ServiceRecord s = res.record; 1645 1646 boolean permissionsReviewRequired = false; 1647 1648 // If permissions need a review before any of the app components can run, 1649 // we schedule binding to the service but do not start its process, then 1650 // we launch a review activity to which is passed a callback to invoke 1651 // when done to start the bound service's process to completing the binding. 1652 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired( 1653 s.packageName, s.userId)) { 1654 1655 permissionsReviewRequired = true; 1656 1657 // Show a permission review UI only for binding from a foreground app 1658 if (!callerFg) { 1659 Slog.w(TAG, "u" + s.userId + " Binding to a service in package" 1660 + s.packageName + " requires a permissions review"); 1661 return 0; 1662 } 1663 1664 final ServiceRecord serviceRecord = s; 1665 final Intent serviceIntent = service; 1666 1667 RemoteCallback callback = new RemoteCallback( 1668 new RemoteCallback.OnResultListener() { 1669 @Override 1670 public void onResult(Bundle result) { 1671 synchronized(mAm) { 1672 final long identity = Binder.clearCallingIdentity(); 1673 try { 1674 if (!mPendingServices.contains(serviceRecord)) { 1675 return; 1676 } 1677 // If there is still a pending record, then the service 1678 // binding request is still valid, so hook them up. We 1679 // proceed only if the caller cleared the review requirement 1680 // otherwise we unbind because the user didn't approve. 1681 if (!mAm.getPackageManagerInternalLocked() 1682 .isPermissionsReviewRequired( 1683 serviceRecord.packageName, 1684 serviceRecord.userId)) { 1685 try { 1686 bringUpServiceLocked(serviceRecord, 1687 serviceIntent.getFlags(), 1688 callerFg, false, false); 1689 } catch (RemoteException e) { 1690 /* ignore - local call */ 1691 } 1692 } else { 1693 unbindServiceLocked(connection); 1694 } 1695 } finally { 1696 Binder.restoreCallingIdentity(identity); 1697 } 1698 } 1699 } 1700 }); 1701 1702 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS); 1703 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 1704 | Intent.FLAG_ACTIVITY_MULTIPLE_TASK 1705 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 1706 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName); 1707 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback); 1708 1709 if (DEBUG_PERMISSIONS_REVIEW) { 1710 Slog.i(TAG, "u" + s.userId + " Launching permission review for package " 1711 + s.packageName); 1712 } 1713 1714 mAm.mHandler.post(new Runnable() { 1715 @Override 1716 public void run() { 1717 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId)); 1718 } 1719 }); 1720 } 1721 1722 final long origId = Binder.clearCallingIdentity(); 1723 1724 try { 1725 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) { 1726 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: " 1727 + s); 1728 } 1729 1730 if ((flags&Context.BIND_AUTO_CREATE) != 0) { 1731 s.lastActivity = SystemClock.uptimeMillis(); 1732 if (!s.hasAutoCreateConnections()) { 1733 // This is the first binding, let the tracker know. 1734 ServiceState stracker = s.getTracker(); 1735 if (stracker != null) { 1736 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(), 1737 s.lastActivity); 1738 } 1739 } 1740 } 1741 1742 if ((flags & Context.BIND_RESTRICT_ASSOCIATIONS) != 0) { 1743 mAm.requireAllowedAssociationsLocked(s.appInfo.packageName); 1744 } 1745 1746 mAm.startAssociationLocked(callerApp.uid, callerApp.processName, 1747 callerApp.getCurProcState(), s.appInfo.uid, s.appInfo.longVersionCode, 1748 s.instanceName, s.processName); 1749 // Once the apps have become associated, if one of them is caller is ephemeral 1750 // the target app should now be able to see the calling app 1751 mAm.grantEphemeralAccessLocked(callerApp.userId, service, 1752 UserHandle.getAppId(s.appInfo.uid), UserHandle.getAppId(callerApp.uid)); 1753 1754 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp); 1755 ConnectionRecord c = new ConnectionRecord(b, activity, 1756 connection, flags, clientLabel, clientIntent, 1757 callerApp.uid, callerApp.processName, callingPackage); 1758 1759 IBinder binder = connection.asBinder(); 1760 s.addConnection(binder, c); 1761 b.connections.add(c); 1762 if (activity != null) { 1763 activity.addConnection(c); 1764 } 1765 b.client.connections.add(c); 1766 c.startAssociationIfNeeded(); 1767 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) { 1768 b.client.hasAboveClient = true; 1769 } 1770 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) { 1771 s.whitelistManager = true; 1772 } 1773 if ((flags & Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS) != 0) { 1774 s.setHasBindingWhitelistingBgActivityStarts(true); 1775 } 1776 if (s.app != null) { 1777 updateServiceClientActivitiesLocked(s.app, c, true); 1778 } 1779 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder); 1780 if (clist == null) { 1781 clist = new ArrayList<>(); 1782 mServiceConnections.put(binder, clist); 1783 } 1784 clist.add(c); 1785 1786 if ((flags&Context.BIND_AUTO_CREATE) != 0) { 1787 s.lastActivity = SystemClock.uptimeMillis(); 1788 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false, 1789 permissionsReviewRequired) != null) { 1790 return 0; 1791 } 1792 } 1793 1794 if (s.app != null) { 1795 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) { 1796 s.app.treatLikeActivity = true; 1797 } 1798 if (s.whitelistManager) { 1799 s.app.whitelistManager = true; 1800 } 1801 // This could have made the service more important. 1802 mAm.updateLruProcessLocked(s.app, 1803 (callerApp.hasActivitiesOrRecentTasks() && s.app.hasClientActivities()) 1804 || (callerApp.getCurProcState() <= ActivityManager.PROCESS_STATE_TOP 1805 && (flags & Context.BIND_TREAT_LIKE_ACTIVITY) != 0), 1806 b.client); 1807 mAm.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_BIND_SERVICE); 1808 } 1809 1810 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b 1811 + ": received=" + b.intent.received 1812 + " apps=" + b.intent.apps.size() 1813 + " doRebind=" + b.intent.doRebind); 1814 1815 if (s.app != null && b.intent.received) { 1816 // Service is already running, so we can immediately 1817 // publish the connection. 1818 try { 1819 c.conn.connected(s.name, b.intent.binder, false); 1820 } catch (Exception e) { 1821 Slog.w(TAG, "Failure sending service " + s.shortInstanceName 1822 + " to connection " + c.conn.asBinder() 1823 + " (in " + c.binding.client.processName + ")", e); 1824 } 1825 1826 // If this is the first app connected back to this binding, 1827 // and the service had previously asked to be told when 1828 // rebound, then do so. 1829 if (b.intent.apps.size() == 1 && b.intent.doRebind) { 1830 requestServiceBindingLocked(s, b.intent, callerFg, true); 1831 } 1832 } else if (!b.intent.requested) { 1833 requestServiceBindingLocked(s, b.intent, callerFg, false); 1834 } 1835 1836 getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s); 1837 1838 } finally { 1839 Binder.restoreCallingIdentity(origId); 1840 } 1841 1842 return 1; 1843 } 1844 publishServiceLocked(ServiceRecord r, Intent intent, IBinder service)1845 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) { 1846 final long origId = Binder.clearCallingIdentity(); 1847 try { 1848 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r 1849 + " " + intent + ": " + service); 1850 if (r != null) { 1851 Intent.FilterComparison filter 1852 = new Intent.FilterComparison(intent); 1853 IntentBindRecord b = r.bindings.get(filter); 1854 if (b != null && !b.received) { 1855 b.binder = service; 1856 b.requested = true; 1857 b.received = true; 1858 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections(); 1859 for (int conni = connections.size() - 1; conni >= 0; conni--) { 1860 ArrayList<ConnectionRecord> clist = connections.valueAt(conni); 1861 for (int i=0; i<clist.size(); i++) { 1862 ConnectionRecord c = clist.get(i); 1863 if (!filter.equals(c.binding.intent.intent)) { 1864 if (DEBUG_SERVICE) Slog.v( 1865 TAG_SERVICE, "Not publishing to: " + c); 1866 if (DEBUG_SERVICE) Slog.v( 1867 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent); 1868 if (DEBUG_SERVICE) Slog.v( 1869 TAG_SERVICE, "Published intent: " + intent); 1870 continue; 1871 } 1872 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c); 1873 try { 1874 c.conn.connected(r.name, service, false); 1875 } catch (Exception e) { 1876 Slog.w(TAG, "Failure sending service " + r.shortInstanceName 1877 + " to connection " + c.conn.asBinder() 1878 + " (in " + c.binding.client.processName + ")", e); 1879 } 1880 } 1881 } 1882 } 1883 1884 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false); 1885 } 1886 } finally { 1887 Binder.restoreCallingIdentity(origId); 1888 } 1889 } 1890 updateServiceGroupLocked(IServiceConnection connection, int group, int importance)1891 void updateServiceGroupLocked(IServiceConnection connection, int group, int importance) { 1892 final IBinder binder = connection.asBinder(); 1893 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "updateServiceGroup: conn=" + binder); 1894 final ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder); 1895 if (clist == null) { 1896 throw new IllegalArgumentException("Could not find connection for " 1897 + connection.asBinder()); 1898 } 1899 for (int i = clist.size() - 1; i >= 0; i--) { 1900 final ConnectionRecord crec = clist.get(i); 1901 final ServiceRecord srec = crec.binding.service; 1902 if (srec != null && (srec.serviceInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) != 0) { 1903 if (srec.app != null) { 1904 if (group > 0) { 1905 srec.app.connectionService = srec; 1906 srec.app.connectionGroup = group; 1907 srec.app.connectionImportance = importance; 1908 } else { 1909 srec.app.connectionService = null; 1910 srec.app.connectionGroup = 0; 1911 srec.app.connectionImportance = 0; 1912 } 1913 } else { 1914 if (group > 0) { 1915 srec.pendingConnectionGroup = group; 1916 srec.pendingConnectionImportance = importance; 1917 } else { 1918 srec.pendingConnectionGroup = 0; 1919 srec.pendingConnectionImportance = 0; 1920 } 1921 } 1922 } 1923 } 1924 } 1925 unbindServiceLocked(IServiceConnection connection)1926 boolean unbindServiceLocked(IServiceConnection connection) { 1927 IBinder binder = connection.asBinder(); 1928 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder); 1929 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder); 1930 if (clist == null) { 1931 Slog.w(TAG, "Unbind failed: could not find connection for " 1932 + connection.asBinder()); 1933 return false; 1934 } 1935 1936 final long origId = Binder.clearCallingIdentity(); 1937 try { 1938 while (clist.size() > 0) { 1939 ConnectionRecord r = clist.get(0); 1940 removeConnectionLocked(r, null, null); 1941 if (clist.size() > 0 && clist.get(0) == r) { 1942 // In case it didn't get removed above, do it now. 1943 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder); 1944 clist.remove(0); 1945 } 1946 1947 if (r.binding.service.app != null) { 1948 if (r.binding.service.app.whitelistManager) { 1949 updateWhitelistManagerLocked(r.binding.service.app); 1950 } 1951 // This could have made the service less important. 1952 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) { 1953 r.binding.service.app.treatLikeActivity = true; 1954 mAm.updateLruProcessLocked(r.binding.service.app, 1955 r.binding.service.app.hasClientActivities() 1956 || r.binding.service.app.treatLikeActivity, null); 1957 } 1958 } 1959 } 1960 1961 mAm.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE); 1962 1963 } finally { 1964 Binder.restoreCallingIdentity(origId); 1965 } 1966 1967 return true; 1968 } 1969 unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind)1970 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) { 1971 final long origId = Binder.clearCallingIdentity(); 1972 try { 1973 if (r != null) { 1974 Intent.FilterComparison filter 1975 = new Intent.FilterComparison(intent); 1976 IntentBindRecord b = r.bindings.get(filter); 1977 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r 1978 + " at " + b + ": apps=" 1979 + (b != null ? b.apps.size() : 0)); 1980 1981 boolean inDestroying = mDestroyingServices.contains(r); 1982 if (b != null) { 1983 if (b.apps.size() > 0 && !inDestroying) { 1984 // Applications have already bound since the last 1985 // unbind, so just rebind right here. 1986 boolean inFg = false; 1987 for (int i=b.apps.size()-1; i>=0; i--) { 1988 ProcessRecord client = b.apps.valueAt(i).client; 1989 if (client != null && client.setSchedGroup 1990 != ProcessList.SCHED_GROUP_BACKGROUND) { 1991 inFg = true; 1992 break; 1993 } 1994 } 1995 try { 1996 requestServiceBindingLocked(r, b, inFg, true); 1997 } catch (TransactionTooLargeException e) { 1998 // Don't pass this back to ActivityThread, it's unrelated. 1999 } 2000 } else { 2001 // Note to tell the service the next time there is 2002 // a new client. 2003 b.doRebind = true; 2004 } 2005 } 2006 2007 serviceDoneExecutingLocked(r, inDestroying, false); 2008 } 2009 } finally { 2010 Binder.restoreCallingIdentity(origId); 2011 } 2012 } 2013 findServiceLocked(ComponentName name, IBinder token, int userId)2014 private final ServiceRecord findServiceLocked(ComponentName name, 2015 IBinder token, int userId) { 2016 ServiceRecord r = getServiceByNameLocked(name, userId); 2017 return r == token ? r : null; 2018 } 2019 2020 private final class ServiceLookupResult { 2021 final ServiceRecord record; 2022 final String permission; 2023 ServiceLookupResult(ServiceRecord _record, String _permission)2024 ServiceLookupResult(ServiceRecord _record, String _permission) { 2025 record = _record; 2026 permission = _permission; 2027 } 2028 } 2029 2030 private class ServiceRestarter implements Runnable { 2031 private ServiceRecord mService; 2032 setService(ServiceRecord service)2033 void setService(ServiceRecord service) { 2034 mService = service; 2035 } 2036 run()2037 public void run() { 2038 synchronized(mAm) { 2039 performServiceRestartLocked(mService); 2040 } 2041 } 2042 } 2043 retrieveServiceLocked(Intent service, String instanceName, String resolvedType, String callingPackage, int callingPid, int callingUid, int userId, boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal, boolean allowInstant)2044 private ServiceLookupResult retrieveServiceLocked(Intent service, 2045 String instanceName, String resolvedType, String callingPackage, 2046 int callingPid, int callingUid, int userId, 2047 boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal, 2048 boolean allowInstant) { 2049 ServiceRecord r = null; 2050 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service 2051 + " type=" + resolvedType + " callingUid=" + callingUid); 2052 2053 userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false, 2054 ActivityManagerInternal.ALLOW_NON_FULL_IN_PROFILE, "service", 2055 callingPackage); 2056 2057 ServiceMap smap = getServiceMapLocked(userId); 2058 final ComponentName comp; 2059 if (instanceName == null) { 2060 comp = service.getComponent(); 2061 } else { 2062 final ComponentName realComp = service.getComponent(); 2063 if (realComp == null) { 2064 throw new IllegalArgumentException("Can't use custom instance name '" + instanceName 2065 + "' without expicit component in Intent"); 2066 } 2067 comp = new ComponentName(realComp.getPackageName(), 2068 realComp.getClassName() + ":" + instanceName); 2069 } 2070 if (comp != null) { 2071 r = smap.mServicesByInstanceName.get(comp); 2072 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r); 2073 } 2074 if (r == null && !isBindExternal && instanceName == null) { 2075 Intent.FilterComparison filter = new Intent.FilterComparison(service); 2076 r = smap.mServicesByIntent.get(filter); 2077 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r); 2078 } 2079 if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0 2080 && !callingPackage.equals(r.packageName)) { 2081 // If an external service is running within its own package, other packages 2082 // should not bind to that instance. 2083 r = null; 2084 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Whoops, can't use existing external service"); 2085 } 2086 if (r == null) { 2087 try { 2088 int flags = ActivityManagerService.STOCK_PM_FLAGS 2089 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 2090 if (allowInstant) { 2091 flags |= PackageManager.MATCH_INSTANT; 2092 } 2093 // TODO: come back and remove this assumption to triage all services 2094 ResolveInfo rInfo = mAm.getPackageManagerInternalLocked().resolveService(service, 2095 resolvedType, flags, userId, callingUid); 2096 ServiceInfo sInfo = rInfo != null ? rInfo.serviceInfo : null; 2097 if (sInfo == null) { 2098 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId + 2099 ": not found"); 2100 return null; 2101 } 2102 if (instanceName != null 2103 && (sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) { 2104 throw new IllegalArgumentException("Can't use instance name '" + instanceName 2105 + "' with non-isolated service '" + sInfo.name + "'"); 2106 } 2107 ComponentName className = new ComponentName( 2108 sInfo.applicationInfo.packageName, sInfo.name); 2109 ComponentName name = comp != null ? comp : className; 2110 if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid, 2111 name.getPackageName(), sInfo.applicationInfo.uid)) { 2112 String msg = "association not allowed between packages " 2113 + callingPackage + " and " + name.getPackageName(); 2114 Slog.w(TAG, "Service lookup failed: " + msg); 2115 return new ServiceLookupResult(null, msg); 2116 } 2117 2118 // Store the defining packageName and uid, as they might be changed in 2119 // the ApplicationInfo for external services (which run with the package name 2120 // and uid of the caller). 2121 String definingPackageName = sInfo.applicationInfo.packageName; 2122 int definingUid = sInfo.applicationInfo.uid; 2123 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) { 2124 if (isBindExternal) { 2125 if (!sInfo.exported) { 2126 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " 2127 + className + " is not exported"); 2128 } 2129 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) { 2130 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " 2131 + className + " is not an isolatedProcess"); 2132 } 2133 // Run the service under the calling package's application. 2134 ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo( 2135 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId); 2136 if (aInfo == null) { 2137 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + 2138 "could not resolve client package " + callingPackage); 2139 } 2140 sInfo = new ServiceInfo(sInfo); 2141 sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo); 2142 sInfo.applicationInfo.packageName = aInfo.packageName; 2143 sInfo.applicationInfo.uid = aInfo.uid; 2144 name = new ComponentName(aInfo.packageName, name.getClassName()); 2145 className = new ComponentName(aInfo.packageName, 2146 instanceName == null ? className.getClassName() 2147 : (className.getClassName() + ":" + instanceName)); 2148 service.setComponent(name); 2149 } else { 2150 throw new SecurityException("BIND_EXTERNAL_SERVICE required for " + 2151 name); 2152 } 2153 } else if (isBindExternal) { 2154 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name + 2155 " is not an externalService"); 2156 } 2157 if (userId > 0) { 2158 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo, 2159 sInfo.name, sInfo.flags) 2160 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) { 2161 userId = 0; 2162 smap = getServiceMapLocked(0); 2163 } 2164 sInfo = new ServiceInfo(sInfo); 2165 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId); 2166 } 2167 r = smap.mServicesByInstanceName.get(name); 2168 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, 2169 "Retrieved via pm by intent: " + r); 2170 if (r == null && createIfNeeded) { 2171 final Intent.FilterComparison filter 2172 = new Intent.FilterComparison(service.cloneFilter()); 2173 final ServiceRestarter res = new ServiceRestarter(); 2174 final BatteryStatsImpl.Uid.Pkg.Serv ss; 2175 final BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics(); 2176 synchronized (stats) { 2177 ss = stats.getServiceStatsLocked( 2178 sInfo.applicationInfo.uid, name.getPackageName(), 2179 name.getClassName()); 2180 } 2181 r = new ServiceRecord(mAm, ss, className, name, definingPackageName, 2182 definingUid, filter, sInfo, callingFromFg, res); 2183 res.setService(r); 2184 smap.mServicesByInstanceName.put(name, r); 2185 smap.mServicesByIntent.put(filter, r); 2186 2187 // Make sure this component isn't in the pending list. 2188 for (int i=mPendingServices.size()-1; i>=0; i--) { 2189 final ServiceRecord pr = mPendingServices.get(i); 2190 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid 2191 && pr.instanceName.equals(name)) { 2192 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr); 2193 mPendingServices.remove(i); 2194 } 2195 } 2196 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r); 2197 } 2198 } catch (RemoteException ex) { 2199 // pm is in same process, this will never happen. 2200 } 2201 } 2202 if (r != null) { 2203 if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid, r.packageName, 2204 r.appInfo.uid)) { 2205 String msg = "association not allowed between packages " 2206 + callingPackage + " and " + r.packageName; 2207 Slog.w(TAG, "Service lookup failed: " + msg); 2208 return new ServiceLookupResult(null, msg); 2209 } 2210 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid, 2211 resolvedType, r.appInfo)) { 2212 return new ServiceLookupResult(null, "blocked by firewall"); 2213 } 2214 if (mAm.checkComponentPermission(r.permission, 2215 callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) { 2216 if (!r.exported) { 2217 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName 2218 + " from pid=" + callingPid 2219 + ", uid=" + callingUid 2220 + " that is not exported from uid " + r.appInfo.uid); 2221 return new ServiceLookupResult(null, "not exported from uid " 2222 + r.appInfo.uid); 2223 } 2224 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName 2225 + " from pid=" + callingPid 2226 + ", uid=" + callingUid 2227 + " requires " + r.permission); 2228 return new ServiceLookupResult(null, r.permission); 2229 } else if (r.permission != null && callingPackage != null) { 2230 final int opCode = AppOpsManager.permissionToOpCode(r.permission); 2231 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.checkOperation( 2232 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) { 2233 Slog.w(TAG, "Appop Denial: Accessing service " + r.shortInstanceName 2234 + " from pid=" + callingPid 2235 + ", uid=" + callingUid 2236 + " requires appop " + AppOpsManager.opToName(opCode)); 2237 return null; 2238 } 2239 } 2240 return new ServiceLookupResult(r, null); 2241 } 2242 return null; 2243 } 2244 bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why)2245 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) { 2246 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING " 2247 + why + " of " + r + " in app " + r.app); 2248 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING " 2249 + why + " of " + r.shortInstanceName); 2250 2251 // For b/34123235: Services within the system server won't start until SystemServer 2252 // does Looper.loop(), so we shouldn't try to start/bind to them too early in the boot 2253 // process. However, since there's a little point of showing the ANR dialog in that case, 2254 // let's suppress the timeout until PHASE_THIRD_PARTY_APPS_CAN_START. 2255 // 2256 // (Note there are multiple services start at PHASE_THIRD_PARTY_APPS_CAN_START too, 2257 // which technically could also trigger this timeout if there's a system server 2258 // that takes a long time to handle PHASE_THIRD_PARTY_APPS_CAN_START, but that shouldn't 2259 // happen.) 2260 boolean timeoutNeeded = true; 2261 if ((mAm.mBootPhase < SystemService.PHASE_THIRD_PARTY_APPS_CAN_START) 2262 && (r.app != null) && (r.app.pid == android.os.Process.myPid())) { 2263 2264 Slog.w(TAG, "Too early to start/bind service in system_server: Phase=" + mAm.mBootPhase 2265 + " " + r.getComponentName()); 2266 timeoutNeeded = false; 2267 } 2268 2269 long now = SystemClock.uptimeMillis(); 2270 if (r.executeNesting == 0) { 2271 r.executeFg = fg; 2272 ServiceState stracker = r.getTracker(); 2273 if (stracker != null) { 2274 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now); 2275 } 2276 if (r.app != null) { 2277 r.app.executingServices.add(r); 2278 r.app.execServicesFg |= fg; 2279 if (timeoutNeeded && r.app.executingServices.size() == 1) { 2280 scheduleServiceTimeoutLocked(r.app); 2281 } 2282 } 2283 } else if (r.app != null && fg && !r.app.execServicesFg) { 2284 r.app.execServicesFg = true; 2285 if (timeoutNeeded) { 2286 scheduleServiceTimeoutLocked(r.app); 2287 } 2288 } 2289 r.executeFg |= fg; 2290 r.executeNesting++; 2291 r.executingStart = now; 2292 } 2293 requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i, boolean execInFg, boolean rebind)2294 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i, 2295 boolean execInFg, boolean rebind) throws TransactionTooLargeException { 2296 if (r.app == null || r.app.thread == null) { 2297 // If service is not currently running, can't yet bind. 2298 return false; 2299 } 2300 if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested 2301 + " rebind=" + rebind); 2302 if ((!i.requested || rebind) && i.apps.size() > 0) { 2303 try { 2304 bumpServiceExecutingLocked(r, execInFg, "bind"); 2305 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE); 2306 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind, 2307 r.app.getReportedProcState()); 2308 if (!rebind) { 2309 i.requested = true; 2310 } 2311 i.hasBound = true; 2312 i.doRebind = false; 2313 } catch (TransactionTooLargeException e) { 2314 // Keep the executeNesting count accurate. 2315 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e); 2316 final boolean inDestroying = mDestroyingServices.contains(r); 2317 serviceDoneExecutingLocked(r, inDestroying, inDestroying); 2318 throw e; 2319 } catch (RemoteException e) { 2320 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r); 2321 // Keep the executeNesting count accurate. 2322 final boolean inDestroying = mDestroyingServices.contains(r); 2323 serviceDoneExecutingLocked(r, inDestroying, inDestroying); 2324 return false; 2325 } 2326 } 2327 return true; 2328 } 2329 scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel)2330 private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) { 2331 boolean canceled = false; 2332 2333 if (mAm.mAtmInternal.isShuttingDown()) { 2334 Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortInstanceName 2335 + " - system is shutting down"); 2336 return false; 2337 } 2338 2339 ServiceMap smap = getServiceMapLocked(r.userId); 2340 if (smap.mServicesByInstanceName.get(r.instanceName) != r) { 2341 ServiceRecord cur = smap.mServicesByInstanceName.get(r.instanceName); 2342 Slog.wtf(TAG, "Attempting to schedule restart of " + r 2343 + " when found in map: " + cur); 2344 return false; 2345 } 2346 2347 final long now = SystemClock.uptimeMillis(); 2348 2349 if ((r.serviceInfo.applicationInfo.flags 2350 &ApplicationInfo.FLAG_PERSISTENT) == 0) { 2351 long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION; 2352 long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION; 2353 2354 // Any delivered but not yet finished starts should be put back 2355 // on the pending list. 2356 final int N = r.deliveredStarts.size(); 2357 if (N > 0) { 2358 for (int i=N-1; i>=0; i--) { 2359 ServiceRecord.StartItem si = r.deliveredStarts.get(i); 2360 si.removeUriPermissionsLocked(); 2361 if (si.intent == null) { 2362 // We'll generate this again if needed. 2363 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT 2364 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) { 2365 r.pendingStarts.add(0, si); 2366 long dur = SystemClock.uptimeMillis() - si.deliveredTime; 2367 dur *= 2; 2368 if (minDuration < dur) minDuration = dur; 2369 if (resetTime < dur) resetTime = dur; 2370 } else { 2371 Slog.w(TAG, "Canceling start item " + si.intent + " in service " 2372 + r.shortInstanceName); 2373 canceled = true; 2374 } 2375 } 2376 r.deliveredStarts.clear(); 2377 } 2378 2379 r.totalRestartCount++; 2380 if (r.restartDelay == 0) { 2381 r.restartCount++; 2382 r.restartDelay = minDuration; 2383 } else if (r.crashCount > 1) { 2384 r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION 2385 * (r.crashCount - 1); 2386 } else { 2387 // If it has been a "reasonably long time" since the service 2388 // was started, then reset our restart duration back to 2389 // the beginning, so we don't infinitely increase the duration 2390 // on a service that just occasionally gets killed (which is 2391 // a normal case, due to process being killed to reclaim memory). 2392 if (now > (r.restartTime+resetTime)) { 2393 r.restartCount = 1; 2394 r.restartDelay = minDuration; 2395 } else { 2396 r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR; 2397 if (r.restartDelay < minDuration) { 2398 r.restartDelay = minDuration; 2399 } 2400 } 2401 } 2402 2403 r.nextRestartTime = now + r.restartDelay; 2404 2405 // Make sure that we don't end up restarting a bunch of services 2406 // all at the same time. 2407 boolean repeat; 2408 do { 2409 repeat = false; 2410 final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN; 2411 for (int i=mRestartingServices.size()-1; i>=0; i--) { 2412 ServiceRecord r2 = mRestartingServices.get(i); 2413 if (r2 != r && r.nextRestartTime >= (r2.nextRestartTime-restartTimeBetween) 2414 && r.nextRestartTime < (r2.nextRestartTime+restartTimeBetween)) { 2415 r.nextRestartTime = r2.nextRestartTime + restartTimeBetween; 2416 r.restartDelay = r.nextRestartTime - now; 2417 repeat = true; 2418 break; 2419 } 2420 } 2421 } while (repeat); 2422 2423 } else { 2424 // Persistent processes are immediately restarted, so there is no 2425 // reason to hold of on restarting their services. 2426 r.totalRestartCount++; 2427 r.restartCount = 0; 2428 r.restartDelay = 0; 2429 r.nextRestartTime = now; 2430 } 2431 2432 if (!mRestartingServices.contains(r)) { 2433 r.createdFromFg = false; 2434 mRestartingServices.add(r); 2435 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now); 2436 } 2437 2438 cancelForegroundNotificationLocked(r); 2439 2440 mAm.mHandler.removeCallbacks(r.restarter); 2441 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime); 2442 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay; 2443 Slog.w(TAG, "Scheduling restart of crashed service " 2444 + r.shortInstanceName + " in " + r.restartDelay + "ms"); 2445 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART, 2446 r.userId, r.shortInstanceName, r.restartDelay); 2447 2448 return canceled; 2449 } 2450 performServiceRestartLocked(ServiceRecord r)2451 final void performServiceRestartLocked(ServiceRecord r) { 2452 if (!mRestartingServices.contains(r)) { 2453 return; 2454 } 2455 if (!isServiceNeededLocked(r, false, false)) { 2456 // Paranoia: is this service actually needed? In theory a service that is not 2457 // needed should never remain on the restart list. In practice... well, there 2458 // have been bugs where this happens, and bad things happen because the process 2459 // ends up just being cached, so quickly killed, then restarted again and again. 2460 // Let's not let that happen. 2461 Slog.wtf(TAG, "Restarting service that is not needed: " + r); 2462 return; 2463 } 2464 try { 2465 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false); 2466 } catch (TransactionTooLargeException e) { 2467 // Ignore, it's been logged and nothing upstack cares. 2468 } 2469 } 2470 unscheduleServiceRestartLocked(ServiceRecord r, int callingUid, boolean force)2471 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid, 2472 boolean force) { 2473 if (!force && r.restartDelay == 0) { 2474 return false; 2475 } 2476 // Remove from the restarting list; if the service is currently on the 2477 // restarting list, or the call is coming from another app, then this 2478 // service has become of much more interest so we reset the restart interval. 2479 boolean removed = mRestartingServices.remove(r); 2480 if (removed || callingUid != r.appInfo.uid) { 2481 r.resetRestartCounter(); 2482 } 2483 if (removed) { 2484 clearRestartingIfNeededLocked(r); 2485 } 2486 mAm.mHandler.removeCallbacks(r.restarter); 2487 return true; 2488 } 2489 clearRestartingIfNeededLocked(ServiceRecord r)2490 private void clearRestartingIfNeededLocked(ServiceRecord r) { 2491 if (r.restartTracker != null) { 2492 // If this is the last restarting record with this tracker, then clear 2493 // the tracker's restarting state. 2494 boolean stillTracking = false; 2495 for (int i=mRestartingServices.size()-1; i>=0; i--) { 2496 if (mRestartingServices.get(i).restartTracker == r.restartTracker) { 2497 stillTracking = true; 2498 break; 2499 } 2500 } 2501 if (!stillTracking) { 2502 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(), 2503 SystemClock.uptimeMillis()); 2504 r.restartTracker = null; 2505 } 2506 } 2507 } 2508 bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg, boolean whileRestarting, boolean permissionsReviewRequired)2509 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg, 2510 boolean whileRestarting, boolean permissionsReviewRequired) 2511 throws TransactionTooLargeException { 2512 if (r.app != null && r.app.thread != null) { 2513 sendServiceArgsLocked(r, execInFg, false); 2514 return null; 2515 } 2516 2517 if (!whileRestarting && mRestartingServices.contains(r)) { 2518 // If waiting for a restart, then do nothing. 2519 return null; 2520 } 2521 2522 if (DEBUG_SERVICE) { 2523 Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired); 2524 } 2525 2526 // We are now bringing the service up, so no longer in the 2527 // restarting state. 2528 if (mRestartingServices.remove(r)) { 2529 clearRestartingIfNeededLocked(r); 2530 } 2531 2532 // Make sure this service is no longer considered delayed, we are starting it now. 2533 if (r.delayed) { 2534 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r); 2535 getServiceMapLocked(r.userId).mDelayedStartList.remove(r); 2536 r.delayed = false; 2537 } 2538 2539 // Make sure that the user who owns this service is started. If not, 2540 // we don't want to allow it to run. 2541 if (!mAm.mUserController.hasStartedUserState(r.userId)) { 2542 String msg = "Unable to launch app " 2543 + r.appInfo.packageName + "/" 2544 + r.appInfo.uid + " for service " 2545 + r.intent.getIntent() + ": user " + r.userId + " is stopped"; 2546 Slog.w(TAG, msg); 2547 bringDownServiceLocked(r); 2548 return msg; 2549 } 2550 2551 // Service is now being launched, its package can't be stopped. 2552 try { 2553 AppGlobals.getPackageManager().setPackageStoppedState( 2554 r.packageName, false, r.userId); 2555 } catch (RemoteException e) { 2556 } catch (IllegalArgumentException e) { 2557 Slog.w(TAG, "Failed trying to unstop package " 2558 + r.packageName + ": " + e); 2559 } 2560 2561 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0; 2562 final String procName = r.processName; 2563 HostingRecord hostingRecord = new HostingRecord("service", r.instanceName); 2564 ProcessRecord app; 2565 2566 if (!isolated) { 2567 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false); 2568 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid 2569 + " app=" + app); 2570 if (app != null && app.thread != null) { 2571 try { 2572 app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode, mAm.mProcessStats); 2573 realStartServiceLocked(r, app, execInFg); 2574 return null; 2575 } catch (TransactionTooLargeException e) { 2576 throw e; 2577 } catch (RemoteException e) { 2578 Slog.w(TAG, "Exception when starting service " + r.shortInstanceName, e); 2579 } 2580 2581 // If a dead object exception was thrown -- fall through to 2582 // restart the application. 2583 } 2584 } else { 2585 // If this service runs in an isolated process, then each time 2586 // we call startProcessLocked() we will get a new isolated 2587 // process, starting another process if we are currently waiting 2588 // for a previous process to come up. To deal with this, we store 2589 // in the service any current isolated process it is running in or 2590 // waiting to have come up. 2591 app = r.isolatedProc; 2592 if (WebViewZygote.isMultiprocessEnabled() 2593 && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) { 2594 hostingRecord = HostingRecord.byWebviewZygote(r.instanceName); 2595 } 2596 if ((r.serviceInfo.flags & ServiceInfo.FLAG_USE_APP_ZYGOTE) != 0) { 2597 hostingRecord = HostingRecord.byAppZygote(r.instanceName, r.definingPackageName, 2598 r.definingUid); 2599 } 2600 } 2601 2602 // Not running -- get it started, and enqueue this service record 2603 // to be executed when the app comes up. 2604 if (app == null && !permissionsReviewRequired) { 2605 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags, 2606 hostingRecord, false, isolated, false)) == null) { 2607 String msg = "Unable to launch app " 2608 + r.appInfo.packageName + "/" 2609 + r.appInfo.uid + " for service " 2610 + r.intent.getIntent() + ": process is bad"; 2611 Slog.w(TAG, msg); 2612 bringDownServiceLocked(r); 2613 return msg; 2614 } 2615 if (isolated) { 2616 r.isolatedProc = app; 2617 } 2618 } 2619 2620 if (r.fgRequired) { 2621 if (DEBUG_FOREGROUND_SERVICE) { 2622 Slog.v(TAG, "Whitelisting " + UserHandle.formatUid(r.appInfo.uid) 2623 + " for fg-service launch"); 2624 } 2625 mAm.tempWhitelistUidLocked(r.appInfo.uid, 2626 SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch"); 2627 } 2628 2629 if (!mPendingServices.contains(r)) { 2630 mPendingServices.add(r); 2631 } 2632 2633 if (r.delayedStop) { 2634 // Oh and hey we've already been asked to stop! 2635 r.delayedStop = false; 2636 if (r.startRequested) { 2637 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, 2638 "Applying delayed stop (in bring up): " + r); 2639 stopServiceLocked(r); 2640 } 2641 } 2642 2643 return null; 2644 } 2645 requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)2646 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg) 2647 throws TransactionTooLargeException { 2648 for (int i=r.bindings.size()-1; i>=0; i--) { 2649 IntentBindRecord ibr = r.bindings.valueAt(i); 2650 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) { 2651 break; 2652 } 2653 } 2654 } 2655 2656 /** 2657 * Note the name of this method should not be confused with the started services concept. 2658 * The "start" here means bring up the instance in the client, and this method is called 2659 * from bindService() as well. 2660 */ realStartServiceLocked(ServiceRecord r, ProcessRecord app, boolean execInFg)2661 private final void realStartServiceLocked(ServiceRecord r, 2662 ProcessRecord app, boolean execInFg) throws RemoteException { 2663 if (app.thread == null) { 2664 throw new RemoteException(); 2665 } 2666 if (DEBUG_MU) 2667 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid 2668 + ", ProcessRecord.uid = " + app.uid); 2669 r.setProcess(app); 2670 r.restartTime = r.lastActivity = SystemClock.uptimeMillis(); 2671 2672 final boolean newService = app.services.add(r); 2673 bumpServiceExecutingLocked(r, execInFg, "create"); 2674 mAm.updateLruProcessLocked(app, false, null); 2675 updateServiceForegroundLocked(r.app, /* oomAdj= */ false); 2676 mAm.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_START_SERVICE); 2677 2678 boolean created = false; 2679 try { 2680 if (LOG_SERVICE_START_STOP) { 2681 String nameTerm; 2682 int lastPeriod = r.shortInstanceName.lastIndexOf('.'); 2683 nameTerm = lastPeriod >= 0 ? r.shortInstanceName.substring(lastPeriod) 2684 : r.shortInstanceName; 2685 EventLogTags.writeAmCreateService( 2686 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid); 2687 } 2688 StatsLog.write(StatsLog.SERVICE_LAUNCH_REPORTED, r.appInfo.uid, r.name.getPackageName(), 2689 r.name.getClassName()); 2690 synchronized (r.stats.getBatteryStats()) { 2691 r.stats.startLaunchedLocked(); 2692 } 2693 mAm.notifyPackageUse(r.serviceInfo.packageName, 2694 PackageManager.NOTIFY_PACKAGE_USE_SERVICE); 2695 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE); 2696 app.thread.scheduleCreateService(r, r.serviceInfo, 2697 mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo), 2698 app.getReportedProcState()); 2699 r.postNotification(); 2700 created = true; 2701 } catch (DeadObjectException e) { 2702 Slog.w(TAG, "Application dead when creating service " + r); 2703 mAm.appDiedLocked(app); 2704 throw e; 2705 } finally { 2706 if (!created) { 2707 // Keep the executeNesting count accurate. 2708 final boolean inDestroying = mDestroyingServices.contains(r); 2709 serviceDoneExecutingLocked(r, inDestroying, inDestroying); 2710 2711 // Cleanup. 2712 if (newService) { 2713 app.services.remove(r); 2714 r.setProcess(null); 2715 } 2716 2717 // Retry. 2718 if (!inDestroying) { 2719 scheduleServiceRestartLocked(r, false); 2720 } 2721 } 2722 } 2723 2724 if (r.whitelistManager) { 2725 app.whitelistManager = true; 2726 } 2727 2728 requestServiceBindingsLocked(r, execInFg); 2729 2730 updateServiceClientActivitiesLocked(app, null, true); 2731 2732 if (newService && created) { 2733 app.addBoundClientUidsOfNewService(r); 2734 } 2735 2736 // If the service is in the started state, and there are no 2737 // pending arguments, then fake up one so its onStartCommand() will 2738 // be called. 2739 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) { 2740 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(), 2741 null, null, 0)); 2742 } 2743 2744 sendServiceArgsLocked(r, execInFg, true); 2745 2746 if (r.delayed) { 2747 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r); 2748 getServiceMapLocked(r.userId).mDelayedStartList.remove(r); 2749 r.delayed = false; 2750 } 2751 2752 if (r.delayedStop) { 2753 // Oh and hey we've already been asked to stop! 2754 r.delayedStop = false; 2755 if (r.startRequested) { 2756 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, 2757 "Applying delayed stop (from start): " + r); 2758 stopServiceLocked(r); 2759 } 2760 } 2761 } 2762 sendServiceArgsLocked(ServiceRecord r, boolean execInFg, boolean oomAdjusted)2763 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg, 2764 boolean oomAdjusted) throws TransactionTooLargeException { 2765 final int N = r.pendingStarts.size(); 2766 if (N == 0) { 2767 return; 2768 } 2769 2770 ArrayList<ServiceStartArgs> args = new ArrayList<>(); 2771 2772 while (r.pendingStarts.size() > 0) { 2773 ServiceRecord.StartItem si = r.pendingStarts.remove(0); 2774 if (DEBUG_SERVICE) { 2775 Slog.v(TAG_SERVICE, "Sending arguments to: " 2776 + r + " " + r.intent + " args=" + si.intent); 2777 } 2778 if (si.intent == null && N > 1) { 2779 // If somehow we got a dummy null intent in the middle, 2780 // then skip it. DO NOT skip a null intent when it is 2781 // the only one in the list -- this is to support the 2782 // onStartCommand(null) case. 2783 continue; 2784 } 2785 si.deliveredTime = SystemClock.uptimeMillis(); 2786 r.deliveredStarts.add(si); 2787 si.deliveryCount++; 2788 if (si.neededGrants != null) { 2789 mAm.mUgmInternal.grantUriPermissionUncheckedFromIntent(si.neededGrants, 2790 si.getUriPermissionsLocked()); 2791 } 2792 mAm.grantEphemeralAccessLocked(r.userId, si.intent, UserHandle.getAppId(r.appInfo.uid), 2793 UserHandle.getAppId(si.callingId)); 2794 bumpServiceExecutingLocked(r, execInFg, "start"); 2795 if (!oomAdjusted) { 2796 oomAdjusted = true; 2797 mAm.updateOomAdjLocked(r.app, true, OomAdjuster.OOM_ADJ_REASON_START_SERVICE); 2798 } 2799 if (r.fgRequired && !r.fgWaiting) { 2800 if (!r.isForeground) { 2801 if (DEBUG_BACKGROUND_CHECK) { 2802 Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r); 2803 } 2804 scheduleServiceForegroundTransitionTimeoutLocked(r); 2805 } else { 2806 if (DEBUG_BACKGROUND_CHECK) { 2807 Slog.i(TAG, "Service already foreground; no new timeout: " + r); 2808 } 2809 r.fgRequired = false; 2810 } 2811 } 2812 int flags = 0; 2813 if (si.deliveryCount > 1) { 2814 flags |= Service.START_FLAG_RETRY; 2815 } 2816 if (si.doneExecutingCount > 0) { 2817 flags |= Service.START_FLAG_REDELIVERY; 2818 } 2819 args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent)); 2820 } 2821 2822 ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args); 2823 slice.setInlineCountLimit(4); 2824 Exception caughtException = null; 2825 try { 2826 r.app.thread.scheduleServiceArgs(r, slice); 2827 } catch (TransactionTooLargeException e) { 2828 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size() 2829 + " args, first: " + args.get(0).args); 2830 Slog.w(TAG, "Failed delivering service starts", e); 2831 caughtException = e; 2832 } catch (RemoteException e) { 2833 // Remote process gone... we'll let the normal cleanup take care of this. 2834 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r); 2835 Slog.w(TAG, "Failed delivering service starts", e); 2836 caughtException = e; 2837 } catch (Exception e) { 2838 Slog.w(TAG, "Unexpected exception", e); 2839 caughtException = e; 2840 } 2841 2842 if (caughtException != null) { 2843 // Keep nesting count correct 2844 final boolean inDestroying = mDestroyingServices.contains(r); 2845 for (int i = 0; i < args.size(); i++) { 2846 serviceDoneExecutingLocked(r, inDestroying, inDestroying); 2847 } 2848 if (caughtException instanceof TransactionTooLargeException) { 2849 throw (TransactionTooLargeException)caughtException; 2850 } 2851 } 2852 } 2853 isServiceNeededLocked(ServiceRecord r, boolean knowConn, boolean hasConn)2854 private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn, 2855 boolean hasConn) { 2856 // Are we still explicitly being asked to run? 2857 if (r.startRequested) { 2858 return true; 2859 } 2860 2861 // Is someone still bound to us keeping us running? 2862 if (!knowConn) { 2863 hasConn = r.hasAutoCreateConnections(); 2864 } 2865 if (hasConn) { 2866 return true; 2867 } 2868 2869 return false; 2870 } 2871 bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn, boolean hasConn)2872 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn, 2873 boolean hasConn) { 2874 //Slog.i(TAG, "Bring down service:"); 2875 //r.dump(" "); 2876 2877 if (isServiceNeededLocked(r, knowConn, hasConn)) { 2878 return; 2879 } 2880 2881 // Are we in the process of launching? 2882 if (mPendingServices.contains(r)) { 2883 return; 2884 } 2885 2886 bringDownServiceLocked(r); 2887 } 2888 bringDownServiceLocked(ServiceRecord r)2889 private final void bringDownServiceLocked(ServiceRecord r) { 2890 //Slog.i(TAG, "Bring down service:"); 2891 //r.dump(" "); 2892 2893 // Report to all of the connections that the service is no longer 2894 // available. 2895 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections(); 2896 for (int conni = connections.size() - 1; conni >= 0; conni--) { 2897 ArrayList<ConnectionRecord> c = connections.valueAt(conni); 2898 for (int i=0; i<c.size(); i++) { 2899 ConnectionRecord cr = c.get(i); 2900 // There is still a connection to the service that is 2901 // being brought down. Mark it as dead. 2902 cr.serviceDead = true; 2903 cr.stopAssociation(); 2904 try { 2905 cr.conn.connected(r.name, null, true); 2906 } catch (Exception e) { 2907 Slog.w(TAG, "Failure disconnecting service " + r.shortInstanceName 2908 + " to connection " + c.get(i).conn.asBinder() 2909 + " (in " + c.get(i).binding.client.processName + ")", e); 2910 } 2911 } 2912 } 2913 2914 // Tell the service that it has been unbound. 2915 if (r.app != null && r.app.thread != null) { 2916 boolean needOomAdj = false; 2917 for (int i = r.bindings.size() - 1; i >= 0; i--) { 2918 IntentBindRecord ibr = r.bindings.valueAt(i); 2919 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr 2920 + ": hasBound=" + ibr.hasBound); 2921 if (ibr.hasBound) { 2922 try { 2923 bumpServiceExecutingLocked(r, false, "bring down unbind"); 2924 needOomAdj = true; 2925 ibr.hasBound = false; 2926 ibr.requested = false; 2927 r.app.thread.scheduleUnbindService(r, 2928 ibr.intent.getIntent()); 2929 } catch (Exception e) { 2930 Slog.w(TAG, "Exception when unbinding service " 2931 + r.shortInstanceName, e); 2932 serviceProcessGoneLocked(r); 2933 } 2934 } 2935 } 2936 if (needOomAdj) { 2937 mAm.updateOomAdjLocked(r.app, true, 2938 OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE); 2939 } 2940 } 2941 2942 // Check to see if the service had been started as foreground, but being 2943 // brought down before actually showing a notification. That is not allowed. 2944 if (r.fgRequired) { 2945 Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: " 2946 + r); 2947 r.fgRequired = false; 2948 r.fgWaiting = false; 2949 ServiceState stracker = r.getTracker(); 2950 if (stracker != null) { 2951 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(), 2952 r.lastActivity); 2953 } 2954 mAm.mAppOpsService.finishOperation(AppOpsManager.getToken(mAm.mAppOpsService), 2955 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName); 2956 mAm.mHandler.removeMessages( 2957 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r); 2958 if (r.app != null) { 2959 Message msg = mAm.mHandler.obtainMessage( 2960 ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG); 2961 msg.obj = r.app; 2962 msg.getData().putCharSequence( 2963 ActivityManagerService.SERVICE_RECORD_KEY, r.toString()); 2964 mAm.mHandler.sendMessage(msg); 2965 } 2966 } 2967 2968 if (DEBUG_SERVICE) { 2969 RuntimeException here = new RuntimeException(); 2970 here.fillInStackTrace(); 2971 Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here); 2972 } 2973 r.destroyTime = SystemClock.uptimeMillis(); 2974 if (LOG_SERVICE_START_STOP) { 2975 EventLogTags.writeAmDestroyService( 2976 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1); 2977 } 2978 2979 final ServiceMap smap = getServiceMapLocked(r.userId); 2980 ServiceRecord found = smap.mServicesByInstanceName.remove(r.instanceName); 2981 2982 // Note when this method is called by bringUpServiceLocked(), the service is not found 2983 // in mServicesByInstanceName and found will be null. 2984 if (found != null && found != r) { 2985 // This is not actually the service we think is running... this should not happen, 2986 // but if it does, fail hard. 2987 smap.mServicesByInstanceName.put(r.instanceName, found); 2988 throw new IllegalStateException("Bringing down " + r + " but actually running " 2989 + found); 2990 } 2991 smap.mServicesByIntent.remove(r.intent); 2992 r.totalRestartCount = 0; 2993 unscheduleServiceRestartLocked(r, 0, true); 2994 2995 // Also make sure it is not on the pending list. 2996 for (int i=mPendingServices.size()-1; i>=0; i--) { 2997 if (mPendingServices.get(i) == r) { 2998 mPendingServices.remove(i); 2999 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r); 3000 } 3001 } 3002 3003 cancelForegroundNotificationLocked(r); 3004 if (r.isForeground) { 3005 decActiveForegroundAppLocked(smap, r); 3006 ServiceState stracker = r.getTracker(); 3007 if (stracker != null) { 3008 stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(), 3009 r.lastActivity); 3010 } 3011 mAm.mAppOpsService.finishOperation( 3012 AppOpsManager.getToken(mAm.mAppOpsService), 3013 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName); 3014 StatsLog.write(StatsLog.FOREGROUND_SERVICE_STATE_CHANGED, r.appInfo.uid, 3015 r.shortInstanceName, StatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT); 3016 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false); 3017 } 3018 3019 r.isForeground = false; 3020 r.foregroundId = 0; 3021 r.foregroundNoti = null; 3022 3023 // Clear start entries. 3024 r.clearDeliveredStartsLocked(); 3025 r.pendingStarts.clear(); 3026 smap.mDelayedStartList.remove(r); 3027 3028 if (r.app != null) { 3029 synchronized (r.stats.getBatteryStats()) { 3030 r.stats.stopLaunchedLocked(); 3031 } 3032 r.app.services.remove(r); 3033 r.app.updateBoundClientUids(); 3034 if (r.whitelistManager) { 3035 updateWhitelistManagerLocked(r.app); 3036 } 3037 if (r.app.thread != null) { 3038 updateServiceForegroundLocked(r.app, false); 3039 try { 3040 bumpServiceExecutingLocked(r, false, "destroy"); 3041 mDestroyingServices.add(r); 3042 r.destroying = true; 3043 mAm.updateOomAdjLocked(r.app, true, 3044 OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE); 3045 r.app.thread.scheduleStopService(r); 3046 } catch (Exception e) { 3047 Slog.w(TAG, "Exception when destroying service " 3048 + r.shortInstanceName, e); 3049 serviceProcessGoneLocked(r); 3050 } 3051 } else { 3052 if (DEBUG_SERVICE) Slog.v( 3053 TAG_SERVICE, "Removed service that has no process: " + r); 3054 } 3055 } else { 3056 if (DEBUG_SERVICE) Slog.v( 3057 TAG_SERVICE, "Removed service that is not running: " + r); 3058 } 3059 3060 if (r.bindings.size() > 0) { 3061 r.bindings.clear(); 3062 } 3063 3064 if (r.restarter instanceof ServiceRestarter) { 3065 ((ServiceRestarter)r.restarter).setService(null); 3066 } 3067 3068 int memFactor = mAm.mProcessStats.getMemFactorLocked(); 3069 long now = SystemClock.uptimeMillis(); 3070 if (r.tracker != null) { 3071 r.tracker.setStarted(false, memFactor, now); 3072 r.tracker.setBound(false, memFactor, now); 3073 if (r.executeNesting == 0) { 3074 r.tracker.clearCurrentOwner(r, false); 3075 r.tracker = null; 3076 } 3077 } 3078 3079 smap.ensureNotStartingBackgroundLocked(r); 3080 } 3081 removeConnectionLocked(ConnectionRecord c, ProcessRecord skipApp, ActivityServiceConnectionsHolder skipAct)3082 void removeConnectionLocked(ConnectionRecord c, ProcessRecord skipApp, 3083 ActivityServiceConnectionsHolder skipAct) { 3084 IBinder binder = c.conn.asBinder(); 3085 AppBindRecord b = c.binding; 3086 ServiceRecord s = b.service; 3087 ArrayList<ConnectionRecord> clist = s.getConnections().get(binder); 3088 if (clist != null) { 3089 clist.remove(c); 3090 if (clist.size() == 0) { 3091 s.removeConnection(binder); 3092 } 3093 } 3094 b.connections.remove(c); 3095 c.stopAssociation(); 3096 if (c.activity != null && c.activity != skipAct) { 3097 c.activity.removeConnection(c); 3098 } 3099 if (b.client != skipApp) { 3100 b.client.connections.remove(c); 3101 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) { 3102 b.client.updateHasAboveClientLocked(); 3103 } 3104 // If this connection requested whitelist management, see if we should 3105 // now clear that state. 3106 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) { 3107 s.updateWhitelistManager(); 3108 if (!s.whitelistManager && s.app != null) { 3109 updateWhitelistManagerLocked(s.app); 3110 } 3111 } 3112 // And do the same for bg activity starts whitelisting. 3113 if ((c.flags & Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS) != 0) { 3114 s.updateHasBindingWhitelistingBgActivityStarts(); 3115 } 3116 if (s.app != null) { 3117 updateServiceClientActivitiesLocked(s.app, c, true); 3118 } 3119 } 3120 clist = mServiceConnections.get(binder); 3121 if (clist != null) { 3122 clist.remove(c); 3123 if (clist.size() == 0) { 3124 mServiceConnections.remove(binder); 3125 } 3126 } 3127 3128 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid, 3129 s.appInfo.longVersionCode, s.instanceName, s.processName); 3130 3131 if (b.connections.size() == 0) { 3132 b.intent.apps.remove(b.client); 3133 } 3134 3135 if (!c.serviceDead) { 3136 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent 3137 + ": shouldUnbind=" + b.intent.hasBound); 3138 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0 3139 && b.intent.hasBound) { 3140 try { 3141 bumpServiceExecutingLocked(s, false, "unbind"); 3142 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0 3143 && s.app.setProcState <= ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) { 3144 // If this service's process is not already in the cached list, 3145 // then update it in the LRU list here because this may be causing 3146 // it to go down there and we want it to start out near the top. 3147 mAm.updateLruProcessLocked(s.app, false, null); 3148 } 3149 mAm.updateOomAdjLocked(s.app, true, 3150 OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE); 3151 b.intent.hasBound = false; 3152 // Assume the client doesn't want to know about a rebind; 3153 // we will deal with that later if it asks for one. 3154 b.intent.doRebind = false; 3155 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent()); 3156 } catch (Exception e) { 3157 Slog.w(TAG, "Exception when unbinding service " + s.shortInstanceName, e); 3158 serviceProcessGoneLocked(s); 3159 } 3160 } 3161 3162 // If unbound while waiting to start, remove the pending service 3163 mPendingServices.remove(s); 3164 3165 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) { 3166 boolean hasAutoCreate = s.hasAutoCreateConnections(); 3167 if (!hasAutoCreate) { 3168 if (s.tracker != null) { 3169 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(), 3170 SystemClock.uptimeMillis()); 3171 } 3172 } 3173 bringDownServiceIfNeededLocked(s, true, hasAutoCreate); 3174 } 3175 } 3176 } 3177 serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res)3178 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) { 3179 boolean inDestroying = mDestroyingServices.contains(r); 3180 if (r != null) { 3181 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) { 3182 // This is a call from a service start... take care of 3183 // book-keeping. 3184 r.callStart = true; 3185 switch (res) { 3186 case Service.START_STICKY_COMPATIBILITY: 3187 case Service.START_STICKY: { 3188 // We are done with the associated start arguments. 3189 r.findDeliveredStart(startId, false, true); 3190 // Don't stop if killed. 3191 r.stopIfKilled = false; 3192 break; 3193 } 3194 case Service.START_NOT_STICKY: { 3195 // We are done with the associated start arguments. 3196 r.findDeliveredStart(startId, false, true); 3197 if (r.getLastStartId() == startId) { 3198 // There is no more work, and this service 3199 // doesn't want to hang around if killed. 3200 r.stopIfKilled = true; 3201 } 3202 break; 3203 } 3204 case Service.START_REDELIVER_INTENT: { 3205 // We'll keep this item until they explicitly 3206 // call stop for it, but keep track of the fact 3207 // that it was delivered. 3208 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false); 3209 if (si != null) { 3210 si.deliveryCount = 0; 3211 si.doneExecutingCount++; 3212 // Don't stop if killed. 3213 r.stopIfKilled = true; 3214 } 3215 break; 3216 } 3217 case Service.START_TASK_REMOVED_COMPLETE: { 3218 // Special processing for onTaskRemoved(). Don't 3219 // impact normal onStartCommand() processing. 3220 r.findDeliveredStart(startId, true, true); 3221 break; 3222 } 3223 default: 3224 throw new IllegalArgumentException( 3225 "Unknown service start result: " + res); 3226 } 3227 if (res == Service.START_STICKY_COMPATIBILITY) { 3228 r.callStart = false; 3229 } 3230 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) { 3231 // This is the final call from destroying the service... we should 3232 // actually be getting rid of the service at this point. Do some 3233 // validation of its state, and ensure it will be fully removed. 3234 if (!inDestroying) { 3235 // Not sure what else to do with this... if it is not actually in the 3236 // destroying list, we don't need to make sure to remove it from it. 3237 // If the app is null, then it was probably removed because the process died, 3238 // otherwise wtf 3239 if (r.app != null) { 3240 Slog.w(TAG, "Service done with onDestroy, but not inDestroying: " 3241 + r + ", app=" + r.app); 3242 } 3243 } else if (r.executeNesting != 1) { 3244 Slog.w(TAG, "Service done with onDestroy, but executeNesting=" 3245 + r.executeNesting + ": " + r); 3246 // Fake it to keep from ANR due to orphaned entry. 3247 r.executeNesting = 1; 3248 } 3249 } 3250 final long origId = Binder.clearCallingIdentity(); 3251 serviceDoneExecutingLocked(r, inDestroying, inDestroying); 3252 Binder.restoreCallingIdentity(origId); 3253 } else { 3254 Slog.w(TAG, "Done executing unknown service from pid " 3255 + Binder.getCallingPid()); 3256 } 3257 } 3258 serviceProcessGoneLocked(ServiceRecord r)3259 private void serviceProcessGoneLocked(ServiceRecord r) { 3260 if (r.tracker != null) { 3261 int memFactor = mAm.mProcessStats.getMemFactorLocked(); 3262 long now = SystemClock.uptimeMillis(); 3263 r.tracker.setExecuting(false, memFactor, now); 3264 r.tracker.setForeground(false, memFactor, now); 3265 r.tracker.setBound(false, memFactor, now); 3266 r.tracker.setStarted(false, memFactor, now); 3267 } 3268 serviceDoneExecutingLocked(r, true, true); 3269 } 3270 serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying, boolean finishing)3271 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying, 3272 boolean finishing) { 3273 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r 3274 + ": nesting=" + r.executeNesting 3275 + ", inDestroying=" + inDestroying + ", app=" + r.app); 3276 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, 3277 "<<< DONE EXECUTING " + r.shortInstanceName); 3278 r.executeNesting--; 3279 if (r.executeNesting <= 0) { 3280 if (r.app != null) { 3281 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, 3282 "Nesting at 0 of " + r.shortInstanceName); 3283 r.app.execServicesFg = false; 3284 r.app.executingServices.remove(r); 3285 if (r.app.executingServices.size() == 0) { 3286 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, 3287 "No more executingServices of " + r.shortInstanceName); 3288 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app); 3289 } else if (r.executeFg) { 3290 // Need to re-evaluate whether the app still needs to be in the foreground. 3291 for (int i=r.app.executingServices.size()-1; i>=0; i--) { 3292 if (r.app.executingServices.valueAt(i).executeFg) { 3293 r.app.execServicesFg = true; 3294 break; 3295 } 3296 } 3297 } 3298 if (inDestroying) { 3299 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, 3300 "doneExecuting remove destroying " + r); 3301 mDestroyingServices.remove(r); 3302 r.bindings.clear(); 3303 } 3304 mAm.updateOomAdjLocked(r.app, true, OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE); 3305 } 3306 r.executeFg = false; 3307 if (r.tracker != null) { 3308 final int memFactor = mAm.mProcessStats.getMemFactorLocked(); 3309 final long now = SystemClock.uptimeMillis(); 3310 r.tracker.setExecuting(false, memFactor, now); 3311 r.tracker.setForeground(false, memFactor, now); 3312 if (finishing) { 3313 r.tracker.clearCurrentOwner(r, false); 3314 r.tracker = null; 3315 } 3316 } 3317 if (finishing) { 3318 if (r.app != null && !r.app.isPersistent()) { 3319 r.app.services.remove(r); 3320 r.app.updateBoundClientUids(); 3321 if (r.whitelistManager) { 3322 updateWhitelistManagerLocked(r.app); 3323 } 3324 } 3325 r.setProcess(null); 3326 } 3327 } 3328 } 3329 attachApplicationLocked(ProcessRecord proc, String processName)3330 boolean attachApplicationLocked(ProcessRecord proc, String processName) 3331 throws RemoteException { 3332 boolean didSomething = false; 3333 // Collect any services that are waiting for this process to come up. 3334 if (mPendingServices.size() > 0) { 3335 ServiceRecord sr = null; 3336 try { 3337 for (int i=0; i<mPendingServices.size(); i++) { 3338 sr = mPendingServices.get(i); 3339 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid 3340 || !processName.equals(sr.processName))) { 3341 continue; 3342 } 3343 3344 mPendingServices.remove(i); 3345 i--; 3346 proc.addPackage(sr.appInfo.packageName, sr.appInfo.longVersionCode, 3347 mAm.mProcessStats); 3348 realStartServiceLocked(sr, proc, sr.createdFromFg); 3349 didSomething = true; 3350 if (!isServiceNeededLocked(sr, false, false)) { 3351 // We were waiting for this service to start, but it is actually no 3352 // longer needed. This could happen because bringDownServiceIfNeeded 3353 // won't bring down a service that is pending... so now the pending 3354 // is done, so let's drop it. 3355 bringDownServiceLocked(sr); 3356 } 3357 } 3358 } catch (RemoteException e) { 3359 Slog.w(TAG, "Exception in new application when starting service " 3360 + sr.shortInstanceName, e); 3361 throw e; 3362 } 3363 } 3364 // Also, if there are any services that are waiting to restart and 3365 // would run in this process, now is a good time to start them. It would 3366 // be weird to bring up the process but arbitrarily not let the services 3367 // run at this point just because their restart time hasn't come up. 3368 if (mRestartingServices.size() > 0) { 3369 ServiceRecord sr; 3370 for (int i=0; i<mRestartingServices.size(); i++) { 3371 sr = mRestartingServices.get(i); 3372 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid 3373 || !processName.equals(sr.processName))) { 3374 continue; 3375 } 3376 mAm.mHandler.removeCallbacks(sr.restarter); 3377 mAm.mHandler.post(sr.restarter); 3378 } 3379 } 3380 return didSomething; 3381 } 3382 processStartTimedOutLocked(ProcessRecord proc)3383 void processStartTimedOutLocked(ProcessRecord proc) { 3384 for (int i=0; i<mPendingServices.size(); i++) { 3385 ServiceRecord sr = mPendingServices.get(i); 3386 if ((proc.uid == sr.appInfo.uid 3387 && proc.processName.equals(sr.processName)) 3388 || sr.isolatedProc == proc) { 3389 Slog.w(TAG, "Forcing bringing down service: " + sr); 3390 sr.isolatedProc = null; 3391 mPendingServices.remove(i); 3392 i--; 3393 bringDownServiceLocked(sr); 3394 } 3395 } 3396 } 3397 collectPackageServicesLocked(String packageName, Set<String> filterByClasses, boolean evenPersistent, boolean doit, ArrayMap<ComponentName, ServiceRecord> services)3398 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses, 3399 boolean evenPersistent, boolean doit, ArrayMap<ComponentName, ServiceRecord> services) { 3400 boolean didSomething = false; 3401 for (int i = services.size() - 1; i >= 0; i--) { 3402 ServiceRecord service = services.valueAt(i); 3403 final boolean sameComponent = packageName == null 3404 || (service.packageName.equals(packageName) 3405 && (filterByClasses == null 3406 || filterByClasses.contains(service.name.getClassName()))); 3407 if (sameComponent 3408 && (service.app == null || evenPersistent || !service.app.isPersistent())) { 3409 if (!doit) { 3410 return true; 3411 } 3412 didSomething = true; 3413 Slog.i(TAG, " Force stopping service " + service); 3414 if (service.app != null && !service.app.isPersistent()) { 3415 service.app.services.remove(service); 3416 service.app.updateBoundClientUids(); 3417 if (service.whitelistManager) { 3418 updateWhitelistManagerLocked(service.app); 3419 } 3420 } 3421 service.setProcess(null); 3422 service.isolatedProc = null; 3423 if (mTmpCollectionResults == null) { 3424 mTmpCollectionResults = new ArrayList<>(); 3425 } 3426 mTmpCollectionResults.add(service); 3427 } 3428 } 3429 return didSomething; 3430 } 3431 bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses, int userId, boolean evenPersistent, boolean doit)3432 boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses, 3433 int userId, boolean evenPersistent, boolean doit) { 3434 boolean didSomething = false; 3435 3436 if (mTmpCollectionResults != null) { 3437 mTmpCollectionResults.clear(); 3438 } 3439 3440 if (userId == UserHandle.USER_ALL) { 3441 for (int i = mServiceMap.size() - 1; i >= 0; i--) { 3442 didSomething |= collectPackageServicesLocked(packageName, filterByClasses, 3443 evenPersistent, doit, mServiceMap.valueAt(i).mServicesByInstanceName); 3444 if (!doit && didSomething) { 3445 return true; 3446 } 3447 if (doit && filterByClasses == null) { 3448 forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId); 3449 } 3450 } 3451 } else { 3452 ServiceMap smap = mServiceMap.get(userId); 3453 if (smap != null) { 3454 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByInstanceName; 3455 didSomething = collectPackageServicesLocked(packageName, filterByClasses, 3456 evenPersistent, doit, items); 3457 } 3458 if (doit && filterByClasses == null) { 3459 forceStopPackageLocked(packageName, userId); 3460 } 3461 } 3462 3463 if (mTmpCollectionResults != null) { 3464 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) { 3465 bringDownServiceLocked(mTmpCollectionResults.get(i)); 3466 } 3467 mTmpCollectionResults.clear(); 3468 } 3469 3470 return didSomething; 3471 } 3472 forceStopPackageLocked(String packageName, int userId)3473 void forceStopPackageLocked(String packageName, int userId) { 3474 ServiceMap smap = mServiceMap.get(userId); 3475 if (smap != null && smap.mActiveForegroundApps.size() > 0) { 3476 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) { 3477 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i); 3478 if (aa.mPackageName.equals(packageName)) { 3479 smap.mActiveForegroundApps.removeAt(i); 3480 smap.mActiveForegroundAppsChanged = true; 3481 } 3482 } 3483 if (smap.mActiveForegroundAppsChanged) { 3484 requestUpdateActiveForegroundAppsLocked(smap, 0); 3485 } 3486 } 3487 } 3488 cleanUpServices(int userId, ComponentName component, Intent baseIntent)3489 void cleanUpServices(int userId, ComponentName component, Intent baseIntent) { 3490 ArrayList<ServiceRecord> services = new ArrayList<>(); 3491 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId); 3492 for (int i = alls.size() - 1; i >= 0; i--) { 3493 ServiceRecord sr = alls.valueAt(i); 3494 if (sr.packageName.equals(component.getPackageName())) { 3495 services.add(sr); 3496 } 3497 } 3498 3499 // Take care of any running services associated with the app. 3500 for (int i = services.size() - 1; i >= 0; i--) { 3501 ServiceRecord sr = services.get(i); 3502 if (sr.startRequested) { 3503 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) { 3504 Slog.i(TAG, "Stopping service " + sr.shortInstanceName + ": remove task"); 3505 stopServiceLocked(sr); 3506 } else { 3507 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true, 3508 sr.getLastStartId(), baseIntent, null, 0)); 3509 if (sr.app != null && sr.app.thread != null) { 3510 // We always run in the foreground, since this is called as 3511 // part of the "remove task" UI operation. 3512 try { 3513 sendServiceArgsLocked(sr, true, false); 3514 } catch (TransactionTooLargeException e) { 3515 // Ignore, keep going. 3516 } 3517 } 3518 } 3519 } 3520 } 3521 } 3522 killServicesLocked(ProcessRecord app, boolean allowRestart)3523 final void killServicesLocked(ProcessRecord app, boolean allowRestart) { 3524 // Report disconnected services. 3525 if (false) { 3526 // XXX we are letting the client link to the service for 3527 // death notifications. 3528 if (app.services.size() > 0) { 3529 Iterator<ServiceRecord> it = app.services.iterator(); 3530 while (it.hasNext()) { 3531 ServiceRecord r = it.next(); 3532 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections(); 3533 for (int conni=connections.size()-1; conni>=0; conni--) { 3534 ArrayList<ConnectionRecord> cl = connections.valueAt(conni); 3535 for (int i=0; i<cl.size(); i++) { 3536 ConnectionRecord c = cl.get(i); 3537 if (c.binding.client != app) { 3538 try { 3539 //c.conn.connected(r.className, null); 3540 } catch (Exception e) { 3541 // todo: this should be asynchronous! 3542 Slog.w(TAG, "Exception thrown disconnected servce " 3543 + r.shortInstanceName 3544 + " from app " + app.processName, e); 3545 } 3546 } 3547 } 3548 } 3549 } 3550 } 3551 } 3552 3553 // Clean up any connections this application has to other services. 3554 for (int i = app.connections.size() - 1; i >= 0; i--) { 3555 ConnectionRecord r = app.connections.valueAt(i); 3556 removeConnectionLocked(r, app, null); 3557 } 3558 updateServiceConnectionActivitiesLocked(app); 3559 app.connections.clear(); 3560 3561 app.whitelistManager = false; 3562 3563 // Clear app state from services. 3564 for (int i = app.services.size() - 1; i >= 0; i--) { 3565 ServiceRecord sr = app.services.valueAt(i); 3566 synchronized (sr.stats.getBatteryStats()) { 3567 sr.stats.stopLaunchedLocked(); 3568 } 3569 if (sr.app != app && sr.app != null && !sr.app.isPersistent()) { 3570 sr.app.services.remove(sr); 3571 sr.app.updateBoundClientUids(); 3572 } 3573 sr.setProcess(null); 3574 sr.isolatedProc = null; 3575 sr.executeNesting = 0; 3576 sr.forceClearTracker(); 3577 if (mDestroyingServices.remove(sr)) { 3578 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr); 3579 } 3580 3581 final int numClients = sr.bindings.size(); 3582 for (int bindingi=numClients-1; bindingi>=0; bindingi--) { 3583 IntentBindRecord b = sr.bindings.valueAt(bindingi); 3584 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b 3585 + ": shouldUnbind=" + b.hasBound); 3586 b.binder = null; 3587 b.requested = b.received = b.hasBound = false; 3588 // If this binding is coming from a cached process and is asking to keep 3589 // the service created, then we'll kill the cached process as well -- we 3590 // don't want to be thrashing around restarting processes that are only 3591 // there to be cached. 3592 for (int appi=b.apps.size()-1; appi>=0; appi--) { 3593 final ProcessRecord proc = b.apps.keyAt(appi); 3594 // If the process is already gone, skip it. 3595 if (proc.killedByAm || proc.thread == null) { 3596 continue; 3597 } 3598 // Only do this for processes that have an auto-create binding; 3599 // otherwise the binding can be left, because it won't cause the 3600 // service to restart. 3601 final AppBindRecord abind = b.apps.valueAt(appi); 3602 boolean hasCreate = false; 3603 for (int conni=abind.connections.size()-1; conni>=0; conni--) { 3604 ConnectionRecord conn = abind.connections.valueAt(conni); 3605 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT 3606 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) { 3607 hasCreate = true; 3608 break; 3609 } 3610 } 3611 if (!hasCreate) { 3612 continue; 3613 } 3614 // XXX turned off for now until we have more time to get a better policy. 3615 if (false && proc != null && !proc.isPersistent() && proc.thread != null 3616 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID 3617 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) { 3618 proc.kill("bound to service " + sr.shortInstanceName 3619 + " in dying proc " + (app != null ? app.processName : "??"), true); 3620 } 3621 } 3622 } 3623 } 3624 3625 ServiceMap smap = getServiceMapLocked(app.userId); 3626 3627 // Now do remaining service cleanup. 3628 for (int i=app.services.size()-1; i>=0; i--) { 3629 ServiceRecord sr = app.services.valueAt(i); 3630 3631 // Unless the process is persistent, this process record is going away, 3632 // so make sure the service is cleaned out of it. 3633 if (!app.isPersistent()) { 3634 app.services.removeAt(i); 3635 app.updateBoundClientUids(); 3636 } 3637 3638 // Sanity check: if the service listed for the app is not one 3639 // we actually are maintaining, just let it drop. 3640 final ServiceRecord curRec = smap.mServicesByInstanceName.get(sr.instanceName); 3641 if (curRec != sr) { 3642 if (curRec != null) { 3643 Slog.wtf(TAG, "Service " + sr + " in process " + app 3644 + " not same as in map: " + curRec); 3645 } 3646 continue; 3647 } 3648 3649 // Any services running in the application may need to be placed 3650 // back in the pending list. 3651 if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY 3652 && (sr.serviceInfo.applicationInfo.flags 3653 &ApplicationInfo.FLAG_PERSISTENT) == 0) { 3654 Slog.w(TAG, "Service crashed " + sr.crashCount 3655 + " times, stopping: " + sr); 3656 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH, 3657 sr.userId, sr.crashCount, sr.shortInstanceName, app.pid); 3658 bringDownServiceLocked(sr); 3659 } else if (!allowRestart 3660 || !mAm.mUserController.isUserRunning(sr.userId, 0)) { 3661 bringDownServiceLocked(sr); 3662 } else { 3663 boolean canceled = scheduleServiceRestartLocked(sr, true); 3664 3665 // Should the service remain running? Note that in the 3666 // extreme case of so many attempts to deliver a command 3667 // that it failed we also will stop it here. 3668 if (sr.startRequested && (sr.stopIfKilled || canceled)) { 3669 if (sr.pendingStarts.size() == 0) { 3670 sr.startRequested = false; 3671 if (sr.tracker != null) { 3672 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(), 3673 SystemClock.uptimeMillis()); 3674 } 3675 if (!sr.hasAutoCreateConnections()) { 3676 // Whoops, no reason to restart! 3677 bringDownServiceLocked(sr); 3678 } 3679 } 3680 } 3681 } 3682 } 3683 3684 if (!allowRestart) { 3685 app.services.clear(); 3686 app.clearBoundClientUids(); 3687 3688 // Make sure there are no more restarting services for this process. 3689 for (int i=mRestartingServices.size()-1; i>=0; i--) { 3690 ServiceRecord r = mRestartingServices.get(i); 3691 if (r.processName.equals(app.processName) && 3692 r.serviceInfo.applicationInfo.uid == app.info.uid) { 3693 mRestartingServices.remove(i); 3694 clearRestartingIfNeededLocked(r); 3695 } 3696 } 3697 for (int i=mPendingServices.size()-1; i>=0; i--) { 3698 ServiceRecord r = mPendingServices.get(i); 3699 if (r.processName.equals(app.processName) && 3700 r.serviceInfo.applicationInfo.uid == app.info.uid) { 3701 mPendingServices.remove(i); 3702 } 3703 } 3704 } 3705 3706 // Make sure we have no more records on the stopping list. 3707 int i = mDestroyingServices.size(); 3708 while (i > 0) { 3709 i--; 3710 ServiceRecord sr = mDestroyingServices.get(i); 3711 if (sr.app == app) { 3712 sr.forceClearTracker(); 3713 mDestroyingServices.remove(i); 3714 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr); 3715 } 3716 } 3717 3718 app.executingServices.clear(); 3719 } 3720 makeRunningServiceInfoLocked(ServiceRecord r)3721 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) { 3722 ActivityManager.RunningServiceInfo info = 3723 new ActivityManager.RunningServiceInfo(); 3724 info.service = r.name; 3725 if (r.app != null) { 3726 info.pid = r.app.pid; 3727 } 3728 info.uid = r.appInfo.uid; 3729 info.process = r.processName; 3730 info.foreground = r.isForeground; 3731 info.activeSince = r.createRealTime; 3732 info.started = r.startRequested; 3733 info.clientCount = r.getConnections().size(); 3734 info.crashCount = r.crashCount; 3735 info.lastActivityTime = r.lastActivity; 3736 if (r.isForeground) { 3737 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND; 3738 } 3739 if (r.startRequested) { 3740 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED; 3741 } 3742 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) { 3743 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS; 3744 } 3745 if (r.app != null && r.app.isPersistent()) { 3746 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS; 3747 } 3748 3749 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections(); 3750 for (int conni = connections.size() - 1; conni >= 0; conni--) { 3751 ArrayList<ConnectionRecord> connl = connections.valueAt(conni); 3752 for (int i=0; i<connl.size(); i++) { 3753 ConnectionRecord conn = connl.get(i); 3754 if (conn.clientLabel != 0) { 3755 info.clientPackage = conn.binding.client.info.packageName; 3756 info.clientLabel = conn.clientLabel; 3757 return info; 3758 } 3759 } 3760 } 3761 return info; 3762 } 3763 getRunningServiceInfoLocked(int maxNum, int flags, int callingUid, boolean allowed, boolean canInteractAcrossUsers)3764 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags, 3765 int callingUid, boolean allowed, boolean canInteractAcrossUsers) { 3766 ArrayList<ActivityManager.RunningServiceInfo> res 3767 = new ArrayList<ActivityManager.RunningServiceInfo>(); 3768 3769 final long ident = Binder.clearCallingIdentity(); 3770 try { 3771 if (canInteractAcrossUsers) { 3772 int[] users = mAm.mUserController.getUsers(); 3773 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) { 3774 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]); 3775 for (int i=0; i<alls.size() && res.size() < maxNum; i++) { 3776 ServiceRecord sr = alls.valueAt(i); 3777 res.add(makeRunningServiceInfoLocked(sr)); 3778 } 3779 } 3780 3781 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) { 3782 ServiceRecord r = mRestartingServices.get(i); 3783 ActivityManager.RunningServiceInfo info = 3784 makeRunningServiceInfoLocked(r); 3785 info.restarting = r.nextRestartTime; 3786 res.add(info); 3787 } 3788 } else { 3789 int userId = UserHandle.getUserId(callingUid); 3790 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId); 3791 for (int i=0; i<alls.size() && res.size() < maxNum; i++) { 3792 ServiceRecord sr = alls.valueAt(i); 3793 3794 if (allowed || (sr.app != null && sr.app.uid == callingUid)) { 3795 res.add(makeRunningServiceInfoLocked(sr)); 3796 } 3797 } 3798 3799 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) { 3800 ServiceRecord r = mRestartingServices.get(i); 3801 if (r.userId == userId 3802 && (allowed || (r.app != null && r.app.uid == callingUid))) { 3803 ActivityManager.RunningServiceInfo info = 3804 makeRunningServiceInfoLocked(r); 3805 info.restarting = r.nextRestartTime; 3806 res.add(info); 3807 } 3808 } 3809 } 3810 } finally { 3811 Binder.restoreCallingIdentity(ident); 3812 } 3813 3814 return res; 3815 } 3816 getRunningServiceControlPanelLocked(ComponentName name)3817 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) { 3818 int userId = UserHandle.getUserId(Binder.getCallingUid()); 3819 ServiceRecord r = getServiceByNameLocked(name, userId); 3820 if (r != null) { 3821 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections(); 3822 for (int conni = connections.size() - 1; conni >= 0; conni--) { 3823 ArrayList<ConnectionRecord> conn = connections.valueAt(conni); 3824 for (int i=0; i<conn.size(); i++) { 3825 if (conn.get(i).clientIntent != null) { 3826 return conn.get(i).clientIntent; 3827 } 3828 } 3829 } 3830 } 3831 return null; 3832 } 3833 serviceTimeout(ProcessRecord proc)3834 void serviceTimeout(ProcessRecord proc) { 3835 String anrMessage = null; 3836 synchronized(mAm) { 3837 if (proc.isDebugging()) { 3838 // The app's being debugged, ignore timeout. 3839 return; 3840 } 3841 if (proc.executingServices.size() == 0 || proc.thread == null) { 3842 return; 3843 } 3844 final long now = SystemClock.uptimeMillis(); 3845 final long maxTime = now - 3846 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT); 3847 ServiceRecord timeout = null; 3848 long nextTime = 0; 3849 for (int i=proc.executingServices.size()-1; i>=0; i--) { 3850 ServiceRecord sr = proc.executingServices.valueAt(i); 3851 if (sr.executingStart < maxTime) { 3852 timeout = sr; 3853 break; 3854 } 3855 if (sr.executingStart > nextTime) { 3856 nextTime = sr.executingStart; 3857 } 3858 } 3859 if (timeout != null && mAm.mProcessList.mLruProcesses.contains(proc)) { 3860 Slog.w(TAG, "Timeout executing service: " + timeout); 3861 StringWriter sw = new StringWriter(); 3862 PrintWriter pw = new FastPrintWriter(sw, false, 1024); 3863 pw.println(timeout); 3864 timeout.dump(pw, " "); 3865 pw.close(); 3866 mLastAnrDump = sw.toString(); 3867 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer); 3868 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS); 3869 anrMessage = "executing service " + timeout.shortInstanceName; 3870 } else { 3871 Message msg = mAm.mHandler.obtainMessage( 3872 ActivityManagerService.SERVICE_TIMEOUT_MSG); 3873 msg.obj = proc; 3874 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg 3875 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT)); 3876 } 3877 } 3878 3879 if (anrMessage != null) { 3880 proc.appNotResponding(null, null, null, null, false, anrMessage); 3881 } 3882 } 3883 serviceForegroundTimeout(ServiceRecord r)3884 void serviceForegroundTimeout(ServiceRecord r) { 3885 ProcessRecord app; 3886 synchronized (mAm) { 3887 if (!r.fgRequired || r.destroying) { 3888 return; 3889 } 3890 3891 app = r.app; 3892 if (app != null && app.isDebugging()) { 3893 // The app's being debugged; let it ride 3894 return; 3895 } 3896 3897 if (DEBUG_BACKGROUND_CHECK) { 3898 Slog.i(TAG, "Service foreground-required timeout for " + r); 3899 } 3900 r.fgWaiting = false; 3901 stopServiceLocked(r); 3902 } 3903 3904 if (app != null) { 3905 app.appNotResponding(null, null, null, null, false, 3906 "Context.startForegroundService() did not then call Service.startForeground(): " 3907 + r); 3908 } 3909 } 3910 updateServiceApplicationInfoLocked(ApplicationInfo applicationInfo)3911 public void updateServiceApplicationInfoLocked(ApplicationInfo applicationInfo) { 3912 final int userId = UserHandle.getUserId(applicationInfo.uid); 3913 ServiceMap serviceMap = mServiceMap.get(userId); 3914 if (serviceMap != null) { 3915 ArrayMap<ComponentName, ServiceRecord> servicesByName 3916 = serviceMap.mServicesByInstanceName; 3917 for (int j = servicesByName.size() - 1; j >= 0; j--) { 3918 ServiceRecord serviceRecord = servicesByName.valueAt(j); 3919 if (applicationInfo.packageName.equals(serviceRecord.appInfo.packageName)) { 3920 serviceRecord.appInfo = applicationInfo; 3921 serviceRecord.serviceInfo.applicationInfo = applicationInfo; 3922 } 3923 } 3924 } 3925 } 3926 serviceForegroundCrash(ProcessRecord app, CharSequence serviceRecord)3927 void serviceForegroundCrash(ProcessRecord app, CharSequence serviceRecord) { 3928 mAm.crashApplication(app.uid, app.pid, app.info.packageName, app.userId, 3929 "Context.startForegroundService() did not then call Service.startForeground(): " 3930 + serviceRecord, false /*force*/); 3931 } 3932 scheduleServiceTimeoutLocked(ProcessRecord proc)3933 void scheduleServiceTimeoutLocked(ProcessRecord proc) { 3934 if (proc.executingServices.size() == 0 || proc.thread == null) { 3935 return; 3936 } 3937 Message msg = mAm.mHandler.obtainMessage( 3938 ActivityManagerService.SERVICE_TIMEOUT_MSG); 3939 msg.obj = proc; 3940 mAm.mHandler.sendMessageDelayed(msg, 3941 proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT); 3942 } 3943 scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r)3944 void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) { 3945 if (r.app.executingServices.size() == 0 || r.app.thread == null) { 3946 return; 3947 } 3948 Message msg = mAm.mHandler.obtainMessage( 3949 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG); 3950 msg.obj = r; 3951 r.fgWaiting = true; 3952 mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT); 3953 } 3954 3955 final class ServiceDumper { 3956 private final FileDescriptor fd; 3957 private final PrintWriter pw; 3958 private final String[] args; 3959 private final boolean dumpAll; 3960 private final String dumpPackage; 3961 private final ItemMatcher matcher; 3962 private final ArrayList<ServiceRecord> services = new ArrayList<>(); 3963 3964 private final long nowReal = SystemClock.elapsedRealtime(); 3965 3966 private boolean needSep = false; 3967 private boolean printedAnything = false; 3968 private boolean printed = false; 3969 3970 /** 3971 * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this 3972 * must be called with the lock held). 3973 */ ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)3974 ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args, 3975 int opti, boolean dumpAll, String dumpPackage) { 3976 this.fd = fd; 3977 this.pw = pw; 3978 this.args = args; 3979 this.dumpAll = dumpAll; 3980 this.dumpPackage = dumpPackage; 3981 matcher = new ItemMatcher(); 3982 matcher.build(args, opti); 3983 3984 final int[] users = mAm.mUserController.getUsers(); 3985 for (int user : users) { 3986 ServiceMap smap = getServiceMapLocked(user); 3987 if (smap.mServicesByInstanceName.size() > 0) { 3988 for (int si=0; si<smap.mServicesByInstanceName.size(); si++) { 3989 ServiceRecord r = smap.mServicesByInstanceName.valueAt(si); 3990 if (!matcher.match(r, r.name)) { 3991 continue; 3992 } 3993 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) { 3994 continue; 3995 } 3996 services.add(r); 3997 } 3998 } 3999 } 4000 } 4001 dumpHeaderLocked()4002 private void dumpHeaderLocked() { 4003 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)"); 4004 if (mLastAnrDump != null) { 4005 pw.println(" Last ANR service:"); 4006 pw.print(mLastAnrDump); 4007 pw.println(); 4008 } 4009 } 4010 dumpLocked()4011 void dumpLocked() { 4012 dumpHeaderLocked(); 4013 4014 try { 4015 int[] users = mAm.mUserController.getUsers(); 4016 for (int user : users) { 4017 // Find the first service for this user. 4018 int serviceIdx = 0; 4019 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) { 4020 serviceIdx++; 4021 } 4022 printed = false; 4023 if (serviceIdx < services.size()) { 4024 needSep = false; 4025 while (serviceIdx < services.size()) { 4026 ServiceRecord r = services.get(serviceIdx); 4027 serviceIdx++; 4028 if (r.userId != user) { 4029 break; 4030 } 4031 dumpServiceLocalLocked(r); 4032 } 4033 needSep |= printed; 4034 } 4035 4036 dumpUserRemainsLocked(user); 4037 } 4038 } catch (Exception e) { 4039 Slog.w(TAG, "Exception in dumpServicesLocked", e); 4040 } 4041 4042 dumpRemainsLocked(); 4043 } 4044 dumpWithClient()4045 void dumpWithClient() { 4046 synchronized(mAm) { 4047 dumpHeaderLocked(); 4048 } 4049 4050 try { 4051 int[] users = mAm.mUserController.getUsers(); 4052 for (int user : users) { 4053 // Find the first service for this user. 4054 int serviceIdx = 0; 4055 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) { 4056 serviceIdx++; 4057 } 4058 printed = false; 4059 if (serviceIdx < services.size()) { 4060 needSep = false; 4061 while (serviceIdx < services.size()) { 4062 ServiceRecord r = services.get(serviceIdx); 4063 serviceIdx++; 4064 if (r.userId != user) { 4065 break; 4066 } 4067 synchronized(mAm) { 4068 dumpServiceLocalLocked(r); 4069 } 4070 dumpServiceClient(r); 4071 } 4072 needSep |= printed; 4073 } 4074 4075 synchronized(mAm) { 4076 dumpUserRemainsLocked(user); 4077 } 4078 } 4079 } catch (Exception e) { 4080 Slog.w(TAG, "Exception in dumpServicesLocked", e); 4081 } 4082 4083 synchronized(mAm) { 4084 dumpRemainsLocked(); 4085 } 4086 } 4087 dumpUserHeaderLocked(int user)4088 private void dumpUserHeaderLocked(int user) { 4089 if (!printed) { 4090 if (printedAnything) { 4091 pw.println(); 4092 } 4093 pw.println(" User " + user + " active services:"); 4094 printed = true; 4095 } 4096 printedAnything = true; 4097 if (needSep) { 4098 pw.println(); 4099 } 4100 } 4101 dumpServiceLocalLocked(ServiceRecord r)4102 private void dumpServiceLocalLocked(ServiceRecord r) { 4103 dumpUserHeaderLocked(r.userId); 4104 pw.print(" * "); 4105 pw.println(r); 4106 if (dumpAll) { 4107 r.dump(pw, " "); 4108 needSep = true; 4109 } else { 4110 pw.print(" app="); 4111 pw.println(r.app); 4112 pw.print(" created="); 4113 TimeUtils.formatDuration(r.createRealTime, nowReal, pw); 4114 pw.print(" started="); 4115 pw.print(r.startRequested); 4116 pw.print(" connections="); 4117 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections(); 4118 pw.println(connections.size()); 4119 if (connections.size() > 0) { 4120 pw.println(" Connections:"); 4121 for (int conni = 0; conni < connections.size(); conni++) { 4122 ArrayList<ConnectionRecord> clist = connections.valueAt(conni); 4123 for (int i = 0; i < clist.size(); i++) { 4124 ConnectionRecord conn = clist.get(i); 4125 pw.print(" "); 4126 pw.print(conn.binding.intent.intent.getIntent() 4127 .toShortString(false, false, false, false)); 4128 pw.print(" -> "); 4129 ProcessRecord proc = conn.binding.client; 4130 pw.println(proc != null ? proc.toShortString() : "null"); 4131 } 4132 } 4133 } 4134 } 4135 } 4136 dumpServiceClient(ServiceRecord r)4137 private void dumpServiceClient(ServiceRecord r) { 4138 final ProcessRecord proc = r.app; 4139 if (proc == null) { 4140 return; 4141 } 4142 final IApplicationThread thread = proc.thread; 4143 if (thread == null) { 4144 return; 4145 } 4146 pw.println(" Client:"); 4147 pw.flush(); 4148 try { 4149 TransferPipe tp = new TransferPipe(); 4150 try { 4151 thread.dumpService(tp.getWriteFd(), r, args); 4152 tp.setBufferPrefix(" "); 4153 // Short timeout, since blocking here can 4154 // deadlock with the application. 4155 tp.go(fd, 2000); 4156 } finally { 4157 tp.kill(); 4158 } 4159 } catch (IOException e) { 4160 pw.println(" Failure while dumping the service: " + e); 4161 } catch (RemoteException e) { 4162 pw.println(" Got a RemoteException while dumping the service"); 4163 } 4164 needSep = true; 4165 } 4166 dumpUserRemainsLocked(int user)4167 private void dumpUserRemainsLocked(int user) { 4168 ServiceMap smap = getServiceMapLocked(user); 4169 printed = false; 4170 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) { 4171 ServiceRecord r = smap.mDelayedStartList.get(si); 4172 if (!matcher.match(r, r.name)) { 4173 continue; 4174 } 4175 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) { 4176 continue; 4177 } 4178 if (!printed) { 4179 if (printedAnything) { 4180 pw.println(); 4181 } 4182 pw.println(" User " + user + " delayed start services:"); 4183 printed = true; 4184 } 4185 printedAnything = true; 4186 pw.print(" * Delayed start "); pw.println(r); 4187 } 4188 printed = false; 4189 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) { 4190 ServiceRecord r = smap.mStartingBackground.get(si); 4191 if (!matcher.match(r, r.name)) { 4192 continue; 4193 } 4194 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) { 4195 continue; 4196 } 4197 if (!printed) { 4198 if (printedAnything) { 4199 pw.println(); 4200 } 4201 pw.println(" User " + user + " starting in background:"); 4202 printed = true; 4203 } 4204 printedAnything = true; 4205 pw.print(" * Starting bg "); pw.println(r); 4206 } 4207 } 4208 dumpRemainsLocked()4209 private void dumpRemainsLocked() { 4210 if (mPendingServices.size() > 0) { 4211 printed = false; 4212 for (int i=0; i<mPendingServices.size(); i++) { 4213 ServiceRecord r = mPendingServices.get(i); 4214 if (!matcher.match(r, r.name)) { 4215 continue; 4216 } 4217 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) { 4218 continue; 4219 } 4220 printedAnything = true; 4221 if (!printed) { 4222 if (needSep) pw.println(); 4223 needSep = true; 4224 pw.println(" Pending services:"); 4225 printed = true; 4226 } 4227 pw.print(" * Pending "); pw.println(r); 4228 r.dump(pw, " "); 4229 } 4230 needSep = true; 4231 } 4232 4233 if (mRestartingServices.size() > 0) { 4234 printed = false; 4235 for (int i=0; i<mRestartingServices.size(); i++) { 4236 ServiceRecord r = mRestartingServices.get(i); 4237 if (!matcher.match(r, r.name)) { 4238 continue; 4239 } 4240 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) { 4241 continue; 4242 } 4243 printedAnything = true; 4244 if (!printed) { 4245 if (needSep) pw.println(); 4246 needSep = true; 4247 pw.println(" Restarting services:"); 4248 printed = true; 4249 } 4250 pw.print(" * Restarting "); pw.println(r); 4251 r.dump(pw, " "); 4252 } 4253 needSep = true; 4254 } 4255 4256 if (mDestroyingServices.size() > 0) { 4257 printed = false; 4258 for (int i=0; i< mDestroyingServices.size(); i++) { 4259 ServiceRecord r = mDestroyingServices.get(i); 4260 if (!matcher.match(r, r.name)) { 4261 continue; 4262 } 4263 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) { 4264 continue; 4265 } 4266 printedAnything = true; 4267 if (!printed) { 4268 if (needSep) pw.println(); 4269 needSep = true; 4270 pw.println(" Destroying services:"); 4271 printed = true; 4272 } 4273 pw.print(" * Destroy "); pw.println(r); 4274 r.dump(pw, " "); 4275 } 4276 needSep = true; 4277 } 4278 4279 if (dumpAll) { 4280 printed = false; 4281 for (int ic=0; ic<mServiceConnections.size(); ic++) { 4282 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic); 4283 for (int i=0; i<r.size(); i++) { 4284 ConnectionRecord cr = r.get(i); 4285 if (!matcher.match(cr.binding.service, cr.binding.service.name)) { 4286 continue; 4287 } 4288 if (dumpPackage != null && (cr.binding.client == null 4289 || !dumpPackage.equals(cr.binding.client.info.packageName))) { 4290 continue; 4291 } 4292 printedAnything = true; 4293 if (!printed) { 4294 if (needSep) pw.println(); 4295 needSep = true; 4296 pw.println(" Connection bindings to services:"); 4297 printed = true; 4298 } 4299 pw.print(" * "); pw.println(cr); 4300 cr.dump(pw, " "); 4301 } 4302 } 4303 } 4304 4305 if (matcher.all) { 4306 final long nowElapsed = SystemClock.elapsedRealtime(); 4307 final int[] users = mAm.mUserController.getUsers(); 4308 for (int user : users) { 4309 boolean printedUser = false; 4310 ServiceMap smap = mServiceMap.get(user); 4311 if (smap == null) { 4312 continue; 4313 } 4314 for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) { 4315 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i); 4316 if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) { 4317 continue; 4318 } 4319 if (!printedUser) { 4320 printedUser = true; 4321 printedAnything = true; 4322 if (needSep) pw.println(); 4323 needSep = true; 4324 pw.print("Active foreground apps - user "); 4325 pw.print(user); 4326 pw.println(":"); 4327 } 4328 pw.print(" #"); 4329 pw.print(i); 4330 pw.print(": "); 4331 pw.println(aa.mPackageName); 4332 if (aa.mLabel != null) { 4333 pw.print(" mLabel="); 4334 pw.println(aa.mLabel); 4335 } 4336 pw.print(" mNumActive="); 4337 pw.print(aa.mNumActive); 4338 pw.print(" mAppOnTop="); 4339 pw.print(aa.mAppOnTop); 4340 pw.print(" mShownWhileTop="); 4341 pw.print(aa.mShownWhileTop); 4342 pw.print(" mShownWhileScreenOn="); 4343 pw.println(aa.mShownWhileScreenOn); 4344 pw.print(" mStartTime="); 4345 TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw); 4346 pw.print(" mStartVisibleTime="); 4347 TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw); 4348 pw.println(); 4349 if (aa.mEndTime != 0) { 4350 pw.print(" mEndTime="); 4351 TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw); 4352 pw.println(); 4353 } 4354 } 4355 if (smap.hasMessagesOrCallbacks()) { 4356 if (needSep) { 4357 pw.println(); 4358 } 4359 printedAnything = true; 4360 needSep = true; 4361 pw.print(" Handler - user "); 4362 pw.print(user); 4363 pw.println(":"); 4364 smap.dumpMine(new PrintWriterPrinter(pw), " "); 4365 } 4366 } 4367 } 4368 4369 if (!printedAnything) { 4370 pw.println(" (nothing)"); 4371 } 4372 } 4373 } 4374 newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)4375 ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args, 4376 int opti, boolean dumpAll, String dumpPackage) { 4377 return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage); 4378 } 4379 writeToProto(ProtoOutputStream proto, long fieldId)4380 protected void writeToProto(ProtoOutputStream proto, long fieldId) { 4381 synchronized (mAm) { 4382 final long outterToken = proto.start(fieldId); 4383 int[] users = mAm.mUserController.getUsers(); 4384 for (int user : users) { 4385 ServiceMap smap = mServiceMap.get(user); 4386 if (smap == null) { 4387 continue; 4388 } 4389 long token = proto.start(ActiveServicesProto.SERVICES_BY_USERS); 4390 proto.write(ActiveServicesProto.ServicesByUser.USER_ID, user); 4391 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName; 4392 for (int i=0; i<alls.size(); i++) { 4393 alls.valueAt(i).writeToProto(proto, 4394 ActiveServicesProto.ServicesByUser.SERVICE_RECORDS); 4395 } 4396 proto.end(token); 4397 } 4398 proto.end(outterToken); 4399 } 4400 } 4401 4402 /** 4403 * There are three ways to call this: 4404 * - no service specified: dump all the services 4405 * - a flattened component name that matched an existing service was specified as the 4406 * first arg: dump that one service 4407 * - the first arg isn't the flattened component name of an existing service: 4408 * dump all services whose component contains the first arg as a substring 4409 */ dumpService(FileDescriptor fd, PrintWriter pw, final String name, String[] args, int opti, boolean dumpAll)4410 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, final String name, 4411 String[] args, int opti, boolean dumpAll) { 4412 final ArrayList<ServiceRecord> services = new ArrayList<>(); 4413 4414 final Predicate<ServiceRecord> filter = DumpUtils.filterRecord(name); 4415 4416 synchronized (mAm) { 4417 int[] users = mAm.mUserController.getUsers(); 4418 4419 for (int user : users) { 4420 ServiceMap smap = mServiceMap.get(user); 4421 if (smap == null) { 4422 continue; 4423 } 4424 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName; 4425 for (int i=0; i<alls.size(); i++) { 4426 ServiceRecord r1 = alls.valueAt(i); 4427 4428 if (filter.test(r1)) { 4429 services.add(r1); 4430 } 4431 } 4432 } 4433 } 4434 4435 if (services.size() <= 0) { 4436 return false; 4437 } 4438 4439 // Sort by component name. 4440 services.sort(Comparator.comparing(WithComponentName::getComponentName)); 4441 4442 boolean needSep = false; 4443 for (int i=0; i<services.size(); i++) { 4444 if (needSep) { 4445 pw.println(); 4446 } 4447 needSep = true; 4448 dumpService("", fd, pw, services.get(i), args, dumpAll); 4449 } 4450 return true; 4451 } 4452 4453 /** 4454 * Invokes IApplicationThread.dumpService() on the thread of the specified service if 4455 * there is a thread associated with the service. 4456 */ dumpService(String prefix, FileDescriptor fd, PrintWriter pw, final ServiceRecord r, String[] args, boolean dumpAll)4457 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw, 4458 final ServiceRecord r, String[] args, boolean dumpAll) { 4459 String innerPrefix = prefix + " "; 4460 synchronized (mAm) { 4461 pw.print(prefix); pw.print("SERVICE "); 4462 pw.print(r.shortInstanceName); pw.print(" "); 4463 pw.print(Integer.toHexString(System.identityHashCode(r))); 4464 pw.print(" pid="); 4465 if (r.app != null) pw.println(r.app.pid); 4466 else pw.println("(not running)"); 4467 if (dumpAll) { 4468 r.dump(pw, innerPrefix); 4469 } 4470 } 4471 if (r.app != null && r.app.thread != null) { 4472 pw.print(prefix); pw.println(" Client:"); 4473 pw.flush(); 4474 try { 4475 TransferPipe tp = new TransferPipe(); 4476 try { 4477 r.app.thread.dumpService(tp.getWriteFd(), r, args); 4478 tp.setBufferPrefix(prefix + " "); 4479 tp.go(fd); 4480 } finally { 4481 tp.kill(); 4482 } 4483 } catch (IOException e) { 4484 pw.println(prefix + " Failure while dumping the service: " + e); 4485 } catch (RemoteException e) { 4486 pw.println(prefix + " Got a RemoteException while dumping the service"); 4487 } 4488 } 4489 } 4490 } 4491