1 /* 2 * Copyright (C) 2006 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.app.ActivityManager.PROCESS_STATE_NONEXISTENT; 20 import static android.app.PendingIntent.FLAG_IMMUTABLE; 21 import static android.app.PendingIntent.FLAG_UPDATE_CURRENT; 22 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_BOUND_SERVICE; 23 import static android.os.PowerExemptionManager.REASON_DENIED; 24 import static android.os.PowerExemptionManager.reasonCodeToString; 25 import static android.os.Process.INVALID_UID; 26 27 import static com.android.internal.util.Preconditions.checkArgument; 28 import static com.android.server.am.ActiveServices.TAG_SERVICE; 29 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOREGROUND_SERVICE; 30 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM; 31 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME; 32 33 import android.annotation.ElapsedRealtimeLong; 34 import android.annotation.NonNull; 35 import android.annotation.Nullable; 36 import android.annotation.UptimeMillisLong; 37 import android.app.BackgroundStartPrivileges; 38 import android.app.IApplicationThread; 39 import android.app.Notification; 40 import android.app.PendingIntent; 41 import android.app.RemoteServiceException.CannotPostForegroundServiceNotificationException; 42 import android.app.compat.CompatChanges; 43 import android.compat.annotation.ChangeId; 44 import android.compat.annotation.EnabledAfter; 45 import android.content.ComponentName; 46 import android.content.Context; 47 import android.content.Intent; 48 import android.content.pm.ApplicationInfo; 49 import android.content.pm.PackageManager; 50 import android.content.pm.ServiceInfo; 51 import android.net.Uri; 52 import android.os.Binder; 53 import android.os.Build; 54 import android.os.Build.VERSION_CODES; 55 import android.os.IBinder; 56 import android.os.PowerExemptionManager; 57 import android.os.SystemClock; 58 import android.os.UserHandle; 59 import android.provider.Settings; 60 import android.util.ArrayMap; 61 import android.util.Slog; 62 import android.util.TimeUtils; 63 import android.util.proto.ProtoOutputStream; 64 import android.util.proto.ProtoUtils; 65 66 import com.android.internal.annotations.GuardedBy; 67 import com.android.internal.app.procstats.ServiceState; 68 import com.android.server.LocalServices; 69 import com.android.server.notification.NotificationManagerInternal; 70 import com.android.server.uri.NeededUriGrants; 71 import com.android.server.uri.UriPermissionOwner; 72 73 import java.io.PrintWriter; 74 import java.util.ArrayList; 75 import java.util.List; 76 import java.util.Objects; 77 78 /** 79 * A running application service. 80 */ 81 final class ServiceRecord extends Binder implements ComponentName.WithComponentName { 82 private static final String TAG = TAG_WITH_CLASS_NAME ? "ServiceRecord" : TAG_AM; 83 84 // Maximum number of delivery attempts before giving up. 85 static final int MAX_DELIVERY_COUNT = 3; 86 87 // Maximum number of times it can fail during execution before giving up. 88 static final int MAX_DONE_EXECUTING_COUNT = 6; 89 90 91 // Compat IDs for the new FGS logic. For now, we just disable all of them. 92 // TODO: Enable them at some point, but only for V+ builds. 93 94 /** 95 * Compat ID to enable the new FGS start logic, for permission calculation used for 96 * per-FGS-type eligibility calculation. 97 * (See also android.app.ForegroundServiceTypePolicy) 98 */ 99 @ChangeId 100 @EnabledAfter(targetSdkVersion = VERSION_CODES.UPSIDE_DOWN_CAKE) 101 static final long USE_NEW_WIU_LOGIC_FOR_START = 311208629L; 102 103 /** 104 * Compat ID to enable the new FGS start logic, for capability calculation. 105 */ 106 @ChangeId 107 @EnabledAfter(targetSdkVersion = VERSION_CODES.UPSIDE_DOWN_CAKE) 108 static final long USE_NEW_WIU_LOGIC_FOR_CAPABILITIES = 313677553L; 109 110 /** 111 * Compat ID to enable the new FGS start logic, for deciding whether to allow FGS start from 112 * the background. 113 */ 114 @ChangeId 115 @EnabledAfter(targetSdkVersion = VERSION_CODES.UPSIDE_DOWN_CAKE) 116 static final long USE_NEW_BFSL_LOGIC = 311208749L; 117 118 final ActivityManagerService ams; 119 final ComponentName name; // service component. 120 final ComponentName instanceName; // service component's per-instance name. 121 final String shortInstanceName; // instanceName.flattenToShortString(). 122 final String definingPackageName; 123 // Can be different from appInfo.packageName for external services 124 final int definingUid; 125 // Can be different from appInfo.uid for external services 126 final Intent.FilterComparison intent; 127 // original intent used to find service. 128 final ServiceInfo serviceInfo; 129 // all information about the service. 130 ApplicationInfo appInfo; 131 // information about service's app. 132 final int userId; // user that this service is running as 133 final String packageName; // the package implementing intent's component 134 final String processName; // process where this component wants to run 135 final String permission;// permission needed to access service 136 final boolean exported; // from ServiceInfo.exported 137 final Runnable restarter; // used to schedule retries of starting the service 138 final long createRealTime; // when this service was created 139 final boolean isSdkSandbox; // whether this is a sdk sandbox service 140 final int sdkSandboxClientAppUid; // the app uid for which this sdk sandbox service is running 141 final String sdkSandboxClientAppPackage; // the app package for which this sdk sandbox service 142 // is running 143 final ArrayMap<Intent.FilterComparison, IntentBindRecord> bindings 144 = new ArrayMap<Intent.FilterComparison, IntentBindRecord>(); 145 // All active bindings to the service. 146 private final ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections 147 = new ArrayMap<IBinder, ArrayList<ConnectionRecord>>(); 148 // IBinder -> ConnectionRecord of all bound clients 149 150 ProcessRecord app; // where this service is running or null. 151 ProcessRecord isolationHostProc; // process which we've started for this service (used for 152 // isolated and sdk sandbox processes) 153 ServiceState tracker; // tracking service execution, may be null 154 ServiceState restartTracker; // tracking service restart 155 boolean allowlistManager; // any bindings to this service have BIND_ALLOW_WHITELIST_MANAGEMENT? 156 boolean delayed; // are we waiting to start this service in the background? 157 boolean fgRequired; // is the service required to go foreground after starting? 158 boolean fgWaiting; // is a timeout for going foreground already scheduled? 159 boolean isNotAppComponentUsage; // is service binding not considered component/package usage? 160 boolean isForeground; // is service currently in foreground mode? 161 boolean systemRequestedFgToBg; // system requested service to transition to background. 162 boolean inSharedIsolatedProcess; // is the service in a shared isolated process 163 int foregroundId; // Notification ID of last foreground req. 164 Notification foregroundNoti; // Notification record of foreground state. 165 long fgDisplayTime; // time at which the FGS notification should become visible 166 int foregroundServiceType; // foreground service types. 167 long lastActivity; // last time there was some activity on the service. 168 long startingBgTimeout; // time at which we scheduled this for a delayed start. 169 boolean startRequested; // someone explicitly called start? 170 boolean delayedStop; // service has been stopped but is in a delayed start? 171 boolean stopIfKilled; // last onStart() said to stop if service killed? 172 boolean callStart; // last onStart() has asked to always be called on restart. 173 int startCommandResult; // last result from onStartCommand(), only for dumpsys. 174 int executeNesting; // number of outstanding operations keeping foreground. 175 boolean executeFg; // should we be executing in the foreground? 176 long executingStart; // start time of last execute request. 177 boolean createdFromFg; // was this service last created due to a foreground process call? 178 int crashCount; // number of times proc has crashed with service running 179 int totalRestartCount; // number of times we have had to restart. 180 int restartCount; // number of restarts performed in a row. 181 long restartDelay; // delay until next restart attempt. 182 long restartTime; // time of last restart. 183 long nextRestartTime; // time when restartDelay will expire. 184 boolean destroying; // set when we have started destroying the service 185 long destroyTime; // time at which destory was initiated. 186 int pendingConnectionGroup; // To be filled in to ProcessRecord once it connects 187 int pendingConnectionImportance; // To be filled in to ProcessRecord once it connects 188 189 /** 190 * The last time (in uptime timebase) a bind request was made with BIND_ALMOST_PERCEPTIBLE for 191 * this service while on TOP. 192 */ 193 long lastTopAlmostPerceptibleBindRequestUptimeMs; 194 195 // any current binding to this service has BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS flag? 196 private boolean mIsAllowedBgActivityStartsByBinding; 197 // used to clean up the state of mIsAllowedBgActivityStartsByStart after a timeout 198 private Runnable mCleanUpAllowBgActivityStartsByStartCallback; 199 private ProcessRecord mAppForAllowingBgActivityStartsByStart; 200 // These are the privileges that currently allow bg activity starts by service start. 201 // Each time the contents of this list change #mBackgroundStartPrivilegesByStartMerged has to 202 // be updated to reflect the merged state. The merged state retains the attribution to the 203 // originating token only if it is the only cause for being privileged. 204 @GuardedBy("ams") 205 private ArrayList<BackgroundStartPrivileges> mBackgroundStartPrivilegesByStart = 206 new ArrayList<>(); 207 208 // merged privileges for mBackgroundStartPrivilegesByStart (for performance) 209 private BackgroundStartPrivileges mBackgroundStartPrivilegesByStartMerged = 210 BackgroundStartPrivileges.NONE; 211 212 // Reason code for allow while-in-use permissions in foreground service. 213 // If it's not DENIED, while-in-use permissions are allowed. 214 // while-in-use permissions in FGS started from background might be restricted. 215 @PowerExemptionManager.ReasonCode 216 int mAllowWiu_noBinding = REASON_DENIED; 217 218 // A copy of mAllowWhileInUsePermissionInFgs's value when the service is entering FGS state. 219 boolean mAllowWhileInUsePermissionInFgsAtEntering; 220 /** Allow scheduling user-initiated jobs from the background. */ 221 boolean mAllowUiJobScheduling; 222 223 // the most recent package that start/bind this service. 224 String mRecentCallingPackage; 225 // the most recent uid that start/bind this service. 226 int mRecentCallingUid; 227 // ApplicationInfo of the most recent callingPackage that start/bind this service. 228 @Nullable ApplicationInfo mRecentCallerApplicationInfo; 229 230 // The uptime when the service enters FGS state. 231 long mFgsEnterTime = 0; 232 // The uptime when the service exits FGS state. 233 long mFgsExitTime = 0; 234 // FGS notification is deferred. 235 boolean mFgsNotificationDeferred; 236 // FGS notification was deferred. 237 boolean mFgsNotificationWasDeferred; 238 // FGS notification was shown before the FGS finishes, or it wasn't deferred in the first place. 239 boolean mFgsNotificationShown; 240 // Whether FGS package has permissions to show notifications. 241 boolean mFgsHasNotificationPermission; 242 243 // allow the service becomes foreground service? Service started from background may not be 244 // allowed to become a foreground service. 245 @PowerExemptionManager.ReasonCode 246 int mAllowStart_noBinding = REASON_DENIED; 247 // A copy of mAllowStartForeground's value when the service is entering FGS state. 248 @PowerExemptionManager.ReasonCode 249 int mAllowStartForegroundAtEntering = REASON_DENIED; 250 // Debug info why mAllowStartForeground is allowed or denied. 251 String mInfoAllowStartForeground; 252 // Debug info if mAllowStartForeground is allowed because of a temp-allowlist. 253 ActivityManagerService.FgsTempAllowListItem mInfoTempFgsAllowListReason; 254 // Is the same mInfoAllowStartForeground string has been logged before? Used for dedup. 255 boolean mLoggedInfoAllowStartForeground; 256 257 @PowerExemptionManager.ReasonCode 258 int mAllowWiu_inBindService = REASON_DENIED; 259 260 @PowerExemptionManager.ReasonCode 261 int mAllowWiu_byBindings = REASON_DENIED; 262 263 @PowerExemptionManager.ReasonCode 264 int mAllowStart_inBindService = REASON_DENIED; 265 266 @PowerExemptionManager.ReasonCode 267 int mAllowStart_byBindings = REASON_DENIED; 268 269 /** 270 * The oom adj seq number snapshot of the host process. We're taking a snapshot 271 * before executing the service. Since we may or may not bump the host process's 272 * proc state / oom adj value before that, at the end of the execution, we could 273 * compare this seq against the current seq of the host process to see if we could 274 * skip the oom adj update from there too. 275 */ 276 int mAdjSeq; 277 278 /** 279 * Whether to use the new "while-in-use permission" logic for FGS start 280 */ useNewWiuLogic_forStart()281 private boolean useNewWiuLogic_forStart() { 282 return CompatChanges.isChangeEnabled(USE_NEW_WIU_LOGIC_FOR_START, appInfo.uid); 283 } 284 285 /** 286 * Whether to use the new "while-in-use permission" logic for capabilities 287 */ useNewWiuLogic_forCapabilities()288 private boolean useNewWiuLogic_forCapabilities() { 289 return CompatChanges.isChangeEnabled(USE_NEW_WIU_LOGIC_FOR_CAPABILITIES, appInfo.uid); 290 } 291 292 /** 293 * Whether to use the new "FGS BG start exemption" logic. 294 */ useNewBfslLogic()295 private boolean useNewBfslLogic() { 296 return CompatChanges.isChangeEnabled(USE_NEW_BFSL_LOGIC, appInfo.uid); 297 } 298 299 300 @PowerExemptionManager.ReasonCode getFgsAllowWiu_legacy()301 private int getFgsAllowWiu_legacy() { 302 // In the legacy mode (U-), we use mAllowWiu_inBindService and mAllowWiu_noBinding. 303 return reasonOr( 304 mAllowWiu_noBinding, 305 mAllowWiu_inBindService 306 ); 307 } 308 309 @PowerExemptionManager.ReasonCode getFgsAllowWiu_new()310 private int getFgsAllowWiu_new() { 311 // In the new mode, use by-bindings instead of in-bind-service 312 return reasonOr( 313 mAllowWiu_noBinding, 314 mAllowWiu_byBindings 315 ); 316 } 317 318 /** 319 * We use this logic for ForegroundServiceTypePolicy and UIDT eligibility check. 320 */ 321 @PowerExemptionManager.ReasonCode getFgsAllowWiu_forStart()322 int getFgsAllowWiu_forStart() { 323 if (useNewWiuLogic_forStart()) { 324 return getFgsAllowWiu_new(); 325 } else { 326 return getFgsAllowWiu_legacy(); 327 } 328 } 329 330 /** 331 * We use this logic for the capability calculation in oom-adjuster. 332 */ 333 @PowerExemptionManager.ReasonCode getFgsAllowWiu_forCapabilities()334 int getFgsAllowWiu_forCapabilities() { 335 if (useNewWiuLogic_forCapabilities()) { 336 return getFgsAllowWiu_new(); 337 } else { 338 // If alwaysUseNewLogicForWiuCapabilities() isn't set, just use the same logic as 339 // getFgsAllowWiu_forStart(). 340 return getFgsAllowWiu_forStart(); 341 } 342 } 343 344 /** 345 * We use this logic for ForegroundServiceTypePolicy and UIDT eligibility check. 346 */ isFgsAllowedWiu_forStart()347 boolean isFgsAllowedWiu_forStart() { 348 return getFgsAllowWiu_forStart() != REASON_DENIED; 349 } 350 351 /** 352 * We use this logic for the capability calculation in oom-adjuster. 353 */ isFgsAllowedWiu_forCapabilities()354 boolean isFgsAllowedWiu_forCapabilities() { 355 return getFgsAllowWiu_forCapabilities() != REASON_DENIED; 356 } 357 358 @PowerExemptionManager.ReasonCode getFgsAllowStart_legacy()359 private int getFgsAllowStart_legacy() { 360 // This is used for BFSL (background FGS launch) exemption. 361 // Originally -- on U-QPR1 and before -- we only used [in-bind-service] + [no-binding]. 362 // This would exclude certain "valid" situations, so in U-QPR2, we started 363 // using [by-bindings] too. 364 return reasonOr( 365 mAllowStart_noBinding, 366 mAllowStart_inBindService, 367 mAllowStart_byBindings 368 ); 369 } 370 371 @PowerExemptionManager.ReasonCode getFgsAllowStart_new()372 private int getFgsAllowStart_new() { 373 // In the new mode, we don't use [in-bind-service]. 374 return reasonOr( 375 mAllowStart_noBinding, 376 mAllowStart_byBindings 377 ); 378 } 379 380 /** 381 * Calculate a BFSL exemption code. 382 */ 383 @PowerExemptionManager.ReasonCode getFgsAllowStart()384 int getFgsAllowStart() { 385 if (useNewBfslLogic()) { 386 return getFgsAllowStart_new(); 387 } else { 388 return getFgsAllowStart_legacy(); 389 } 390 } 391 392 /** 393 * Return whether BFSL is allowed or not. 394 */ isFgsAllowedStart()395 boolean isFgsAllowedStart() { 396 return getFgsAllowStart() != REASON_DENIED; 397 } 398 clearFgsAllowWiu()399 void clearFgsAllowWiu() { 400 mAllowWiu_noBinding = REASON_DENIED; 401 mAllowWiu_inBindService = REASON_DENIED; 402 mAllowWiu_byBindings = REASON_DENIED; 403 } 404 clearFgsAllowStart()405 void clearFgsAllowStart() { 406 mAllowStart_noBinding = REASON_DENIED; 407 mAllowStart_inBindService = REASON_DENIED; 408 mAllowStart_byBindings = REASON_DENIED; 409 } 410 411 @PowerExemptionManager.ReasonCode reasonOr( @owerExemptionManager.ReasonCode int first, @PowerExemptionManager.ReasonCode int second)412 static int reasonOr( 413 @PowerExemptionManager.ReasonCode int first, 414 @PowerExemptionManager.ReasonCode int second) { 415 return first != REASON_DENIED ? first : second; 416 } 417 418 @PowerExemptionManager.ReasonCode reasonOr( @owerExemptionManager.ReasonCode int first, @PowerExemptionManager.ReasonCode int second, @PowerExemptionManager.ReasonCode int third)419 static int reasonOr( 420 @PowerExemptionManager.ReasonCode int first, 421 @PowerExemptionManager.ReasonCode int second, 422 @PowerExemptionManager.ReasonCode int third) { 423 return first != REASON_DENIED ? first : reasonOr(second, third); 424 } 425 allowedChanged( @owerExemptionManager.ReasonCode int legacyCode, @PowerExemptionManager.ReasonCode int newCode)426 boolean allowedChanged( 427 @PowerExemptionManager.ReasonCode int legacyCode, 428 @PowerExemptionManager.ReasonCode int newCode) { 429 return (legacyCode == REASON_DENIED) != (newCode == REASON_DENIED); 430 } 431 getFgsInfoForWtf()432 private String getFgsInfoForWtf() { 433 return " cmp: " + this.getComponentName().toShortString() 434 + " sdk: " + this.appInfo.targetSdkVersion 435 ; 436 } 437 maybeLogFgsLogicChange()438 void maybeLogFgsLogicChange() { 439 final int wiuLegacy = getFgsAllowWiu_legacy(); 440 final int wiuNew = getFgsAllowWiu_new(); 441 442 final int startLegacy = getFgsAllowStart_legacy(); 443 final int startNew = getFgsAllowStart_new(); 444 445 final boolean wiuChanged = allowedChanged(wiuLegacy, wiuNew); 446 final boolean startChanged = allowedChanged(startLegacy, startNew); 447 448 if (!wiuChanged && !startChanged) { 449 return; 450 } 451 final String message = "FGS logic changed:" 452 + (wiuChanged ? " [WIU changed]" : "") 453 + (startChanged ? " [BFSL changed]" : "") 454 + " Orig WIU:" 455 + reasonCodeToString(wiuLegacy) 456 + " New WIU:" 457 + reasonCodeToString(wiuNew) 458 + " Orig BFSL:" 459 + reasonCodeToString(startLegacy) 460 + " New BFSL:" 461 + reasonCodeToString(startNew) 462 + getFgsInfoForWtf(); 463 Slog.wtf(TAG_SERVICE, message); 464 } 465 466 // The number of times Service.startForeground() is called, after this service record is 467 // created. (i.e. due to "bound" or "start".) It never decreases, even when stopForeground() 468 // is called. 469 int mStartForegroundCount; 470 471 // This is a service record of a FGS delegate (not a service record of a real service) 472 boolean mIsFgsDelegate; 473 @Nullable ForegroundServiceDelegation mFgsDelegation; 474 475 String stringName; // caching of toString 476 477 private int lastStartId; // identifier of most recent start request. 478 479 boolean mKeepWarming; // Whether or not it'll keep critical code path of the host warm 480 481 /** 482 * The original earliest restart time, which considers the number of crashes, etc., 483 * but doesn't include the extra delays we put in between to scatter the restarts; 484 * it's the earliest time this auto service restart could happen alone(except those 485 * batch restarts which happens at time of process attach). 486 */ 487 long mEarliestRestartTime; 488 489 /** 490 * The original time when the service start is scheduled, it does NOT include the reschedules. 491 * 492 * <p>The {@link #restartDelay} would be updated when its restart is rescheduled, but this field 493 * won't, so it could be used when dumping how long the restart is delayed actually.</p> 494 */ 495 long mRestartSchedulingTime; 496 497 /** 498 * The snapshot process state when the service is requested (either start or bind). 499 */ 500 int mProcessStateOnRequest; 501 502 static class StartItem { 503 final ServiceRecord sr; 504 final boolean taskRemoved; 505 final int id; 506 final int callingId; 507 final String mCallingProcessName; 508 final Intent intent; 509 final NeededUriGrants neededGrants; 510 final @Nullable String mCallingPackageName; 511 final int mCallingProcessState; 512 long deliveredTime; 513 int deliveryCount; 514 int doneExecutingCount; 515 UriPermissionOwner uriPermissions; 516 517 String stringName; // caching of toString 518 StartItem(ServiceRecord _sr, boolean _taskRemoved, int _id, Intent _intent, NeededUriGrants _neededGrants, int _callingId, String callingProcessName, @Nullable String callingPackageName, int callingProcessState)519 StartItem(ServiceRecord _sr, boolean _taskRemoved, int _id, 520 Intent _intent, NeededUriGrants _neededGrants, int _callingId, 521 String callingProcessName, @Nullable String callingPackageName, 522 int callingProcessState) { 523 sr = _sr; 524 taskRemoved = _taskRemoved; 525 id = _id; 526 intent = _intent; 527 neededGrants = _neededGrants; 528 callingId = _callingId; 529 mCallingProcessName = callingProcessName; 530 mCallingPackageName = callingPackageName; 531 mCallingProcessState = callingProcessState; 532 } 533 getUriPermissionsLocked()534 UriPermissionOwner getUriPermissionsLocked() { 535 if (uriPermissions == null) { 536 uriPermissions = new UriPermissionOwner(sr.ams.mUgmInternal, this); 537 } 538 return uriPermissions; 539 } 540 removeUriPermissionsLocked()541 void removeUriPermissionsLocked() { 542 if (uriPermissions != null) { 543 uriPermissions.removeUriPermissions(); 544 uriPermissions = null; 545 } 546 } 547 dumpDebug(ProtoOutputStream proto, long fieldId, long now)548 public void dumpDebug(ProtoOutputStream proto, long fieldId, long now) { 549 long token = proto.start(fieldId); 550 proto.write(ServiceRecordProto.StartItem.ID, id); 551 ProtoUtils.toDuration(proto, 552 ServiceRecordProto.StartItem.DURATION, deliveredTime, now); 553 proto.write(ServiceRecordProto.StartItem.DELIVERY_COUNT, deliveryCount); 554 proto.write(ServiceRecordProto.StartItem.DONE_EXECUTING_COUNT, doneExecutingCount); 555 if (intent != null) { 556 intent.dumpDebug(proto, ServiceRecordProto.StartItem.INTENT, true, true, 557 true, false); 558 } 559 if (neededGrants != null) { 560 neededGrants.dumpDebug(proto, ServiceRecordProto.StartItem.NEEDED_GRANTS); 561 } 562 if (uriPermissions != null) { 563 uriPermissions.dumpDebug(proto, ServiceRecordProto.StartItem.URI_PERMISSIONS); 564 } 565 proto.end(token); 566 } 567 toString()568 public String toString() { 569 if (stringName != null) { 570 return stringName; 571 } 572 StringBuilder sb = new StringBuilder(128); 573 sb.append("ServiceRecord{") 574 .append(Integer.toHexString(System.identityHashCode(sr))) 575 .append(' ').append(sr.shortInstanceName) 576 .append(" StartItem ") 577 .append(Integer.toHexString(System.identityHashCode(this))) 578 .append(" id=").append(id).append('}'); 579 return stringName = sb.toString(); 580 } 581 } 582 583 final ArrayList<StartItem> deliveredStarts = new ArrayList<StartItem>(); 584 // start() arguments which been delivered. 585 final ArrayList<StartItem> pendingStarts = new ArrayList<StartItem>(); 586 // start() arguments that haven't yet been delivered. 587 588 /** 589 * Information specific to "SHORT_SERVICE" FGS. 590 */ 591 class ShortFgsInfo { 592 /** Time FGS started */ 593 private final long mStartTime; 594 595 /** 596 * Copied from {@link #mStartForegroundCount}. If this is different from the parent's, 597 * that means this instance is stale. 598 */ 599 private int mStartForegroundCount; 600 601 /** Service's "start ID" when this short-service started. */ 602 private int mStartId; 603 ShortFgsInfo(long startTime)604 ShortFgsInfo(long startTime) { 605 mStartTime = startTime; 606 update(); 607 } 608 609 /** 610 * Update {@link #mStartForegroundCount} and {@link #mStartId}. 611 * (but not {@link #mStartTime}) 612 */ update()613 public void update() { 614 this.mStartForegroundCount = ServiceRecord.this.mStartForegroundCount; 615 this.mStartId = getLastStartId(); 616 } 617 getStartTime()618 long getStartTime() { 619 return mStartTime; 620 } 621 getStartForegroundCount()622 int getStartForegroundCount() { 623 return mStartForegroundCount; 624 } 625 getStartId()626 int getStartId() { 627 return mStartId; 628 } 629 630 /** 631 * @return whether this {@link ShortFgsInfo} is still "current" or not -- i.e. 632 * it's "start foreground count" is the same as that of the ServiceRecord's. 633 * 634 * Note, we do _not_ check the "start id" here, because the start id increments if the 635 * app calls startService() or startForegroundService() on the same service, 636 * but that will _not_ update the ShortFgsInfo, and will not extend the timeout. 637 */ isCurrent()638 boolean isCurrent() { 639 return this.mStartForegroundCount == ServiceRecord.this.mStartForegroundCount; 640 } 641 642 /** Time when Service.onTimeout() should be called */ getTimeoutTime()643 long getTimeoutTime() { 644 return mStartTime + ams.mConstants.mShortFgsTimeoutDuration; 645 } 646 647 /** Time when the procstate should be lowered. */ getProcStateDemoteTime()648 long getProcStateDemoteTime() { 649 return mStartTime + ams.mConstants.mShortFgsTimeoutDuration 650 + ams.mConstants.mShortFgsProcStateExtraWaitDuration; 651 } 652 653 /** Time when the app should be declared ANR. */ getAnrTime()654 long getAnrTime() { 655 return mStartTime + ams.mConstants.mShortFgsTimeoutDuration 656 + ams.mConstants.mShortFgsAnrExtraWaitDuration; 657 } 658 getDescription()659 String getDescription() { 660 return "sfc=" + this.mStartForegroundCount 661 + " sid=" + this.mStartId 662 + " stime=" + this.mStartTime 663 + " tt=" + this.getTimeoutTime() 664 + " dt=" + this.getProcStateDemoteTime() 665 + " at=" + this.getAnrTime(); 666 } 667 } 668 669 /** 670 * Keep track of short-fgs specific information. This field gets cleared when the timeout 671 * stops. 672 */ 673 private ShortFgsInfo mShortFgsInfo; 674 675 /** 676 * Data container class to help track certain fgs info for time-restricted types. 677 */ 678 static class TimeLimitedFgsInfo { 679 @UptimeMillisLong 680 private long mFirstFgsStartUptime; 681 // The first fgs start time is maintained here separately in realtime-base 682 // for the 24-hour window reset logic. 683 @ElapsedRealtimeLong 684 private long mFirstFgsStartRealtime; 685 @UptimeMillisLong 686 private long mLastFgsStartTime; 687 @UptimeMillisLong 688 private long mTimeLimitExceededAt = Long.MIN_VALUE; 689 @UptimeMillisLong 690 private long mTotalRuntime = 0; 691 private int mNumParallelServices = 0; 692 noteFgsFgsStart(@ptimeMillisLong long startTime)693 public void noteFgsFgsStart(@UptimeMillisLong long startTime) { 694 mNumParallelServices++; 695 if (mNumParallelServices == 1) { 696 mFirstFgsStartUptime = startTime; 697 mFirstFgsStartRealtime = SystemClock.elapsedRealtime(); 698 } 699 mLastFgsStartTime = startTime; 700 } 701 702 @UptimeMillisLong getFirstFgsStartUptime()703 public long getFirstFgsStartUptime() { 704 return mFirstFgsStartUptime; 705 } 706 707 @ElapsedRealtimeLong getFirstFgsStartRealtime()708 public long getFirstFgsStartRealtime() { 709 return mFirstFgsStartRealtime; 710 } 711 712 @UptimeMillisLong getLastFgsStartTime()713 public long getLastFgsStartTime() { 714 return mLastFgsStartTime; 715 } 716 decNumParallelServices()717 public void decNumParallelServices() { 718 if (mNumParallelServices > 0) { 719 mNumParallelServices--; 720 } 721 if (mNumParallelServices == 0) { 722 mLastFgsStartTime = 0; 723 } 724 } 725 updateTotalRuntime(@ptimeMillisLong long nowUptime)726 public void updateTotalRuntime(@UptimeMillisLong long nowUptime) { 727 mTotalRuntime += nowUptime - mLastFgsStartTime; 728 mLastFgsStartTime = nowUptime; 729 } 730 731 @UptimeMillisLong getTotalRuntime()732 public long getTotalRuntime() { 733 return mTotalRuntime; 734 } 735 setTimeLimitExceededAt(@ptimeMillisLong long timeLimitExceededAt)736 public void setTimeLimitExceededAt(@UptimeMillisLong long timeLimitExceededAt) { 737 mTimeLimitExceededAt = timeLimitExceededAt; 738 } 739 740 @UptimeMillisLong getTimeLimitExceededAt()741 public long getTimeLimitExceededAt() { 742 return mTimeLimitExceededAt; 743 } 744 reset()745 public void reset() { 746 mNumParallelServices = 0; 747 mFirstFgsStartUptime = 0; 748 mFirstFgsStartRealtime = 0; 749 mLastFgsStartTime = 0; 750 mTotalRuntime = 0; 751 mTimeLimitExceededAt = Long.MIN_VALUE; 752 } 753 } 754 dumpStartList(PrintWriter pw, String prefix, List<StartItem> list, long now)755 void dumpStartList(PrintWriter pw, String prefix, List<StartItem> list, long now) { 756 final int N = list.size(); 757 for (int i=0; i<N; i++) { 758 StartItem si = list.get(i); 759 pw.print(prefix); pw.print("#"); pw.print(i); 760 pw.print(" id="); pw.print(si.id); 761 if (now != 0) { 762 pw.print(" dur="); 763 TimeUtils.formatDuration(si.deliveredTime, now, pw); 764 } 765 if (si.deliveryCount != 0) { 766 pw.print(" dc="); pw.print(si.deliveryCount); 767 } 768 if (si.doneExecutingCount != 0) { 769 pw.print(" dxc="); pw.print(si.doneExecutingCount); 770 } 771 pw.println(""); 772 pw.print(prefix); pw.print(" intent="); 773 if (si.intent != null) pw.println(si.intent.toString()); 774 else pw.println("null"); 775 if (si.neededGrants != null) { 776 pw.print(prefix); pw.print(" neededGrants="); 777 pw.println(si.neededGrants); 778 } 779 if (si.uriPermissions != null) { 780 si.uriPermissions.dump(pw, prefix); 781 } 782 } 783 } 784 dumpDebug(ProtoOutputStream proto, long fieldId)785 void dumpDebug(ProtoOutputStream proto, long fieldId) { 786 long token = proto.start(fieldId); 787 proto.write(ServiceRecordProto.SHORT_NAME, this.shortInstanceName); 788 proto.write(ServiceRecordProto.IS_RUNNING, app != null); 789 if (app != null) { 790 proto.write(ServiceRecordProto.PID, app.getPid()); 791 } 792 if (intent != null) { 793 intent.getIntent().dumpDebug(proto, ServiceRecordProto.INTENT, false, true, false, 794 false); 795 } 796 proto.write(ServiceRecordProto.PACKAGE_NAME, packageName); 797 proto.write(ServiceRecordProto.PROCESS_NAME, processName); 798 proto.write(ServiceRecordProto.PERMISSION, permission); 799 800 long now = SystemClock.uptimeMillis(); 801 long nowReal = SystemClock.elapsedRealtime(); 802 if (appInfo != null) { 803 long appInfoToken = proto.start(ServiceRecordProto.APPINFO); 804 proto.write(ServiceRecordProto.AppInfo.BASE_DIR, appInfo.sourceDir); 805 if (!Objects.equals(appInfo.sourceDir, appInfo.publicSourceDir)) { 806 proto.write(ServiceRecordProto.AppInfo.RES_DIR, appInfo.publicSourceDir); 807 } 808 proto.write(ServiceRecordProto.AppInfo.DATA_DIR, appInfo.dataDir); 809 proto.write(ServiceRecordProto.AppInfo.TARGET_SDK_VERSION, appInfo.targetSdkVersion); 810 proto.end(appInfoToken); 811 } 812 if (app != null) { 813 app.dumpDebug(proto, ServiceRecordProto.APP); 814 } 815 if (isolationHostProc != null) { 816 isolationHostProc.dumpDebug(proto, ServiceRecordProto.ISOLATED_PROC); 817 } 818 proto.write(ServiceRecordProto.WHITELIST_MANAGER, allowlistManager); 819 proto.write(ServiceRecordProto.DELAYED, delayed); 820 if (isForeground || foregroundId != 0) { 821 long fgToken = proto.start(ServiceRecordProto.FOREGROUND); 822 proto.write(ServiceRecordProto.Foreground.ID, foregroundId); 823 foregroundNoti.dumpDebug(proto, ServiceRecordProto.Foreground.NOTIFICATION); 824 proto.write(ServiceRecordProto.Foreground.FOREGROUND_SERVICE_TYPE, 825 foregroundServiceType); 826 proto.end(fgToken); 827 } 828 ProtoUtils.toDuration(proto, ServiceRecordProto.CREATE_REAL_TIME, createRealTime, nowReal); 829 ProtoUtils.toDuration(proto, 830 ServiceRecordProto.STARTING_BG_TIMEOUT, startingBgTimeout, now); 831 ProtoUtils.toDuration(proto, ServiceRecordProto.LAST_ACTIVITY_TIME, lastActivity, now); 832 ProtoUtils.toDuration(proto, ServiceRecordProto.RESTART_TIME, restartTime, now); 833 proto.write(ServiceRecordProto.CREATED_FROM_FG, createdFromFg); 834 835 // TODO: Log "forStart" too. 836 proto.write(ServiceRecordProto.ALLOW_WHILE_IN_USE_PERMISSION_IN_FGS, 837 isFgsAllowedWiu_forCapabilities()); 838 839 if (startRequested || delayedStop || lastStartId != 0) { 840 long startToken = proto.start(ServiceRecordProto.START); 841 proto.write(ServiceRecordProto.Start.START_REQUESTED, startRequested); 842 proto.write(ServiceRecordProto.Start.DELAYED_STOP, delayedStop); 843 proto.write(ServiceRecordProto.Start.STOP_IF_KILLED, stopIfKilled); 844 proto.write(ServiceRecordProto.Start.LAST_START_ID, lastStartId); 845 proto.write(ServiceRecordProto.Start.START_COMMAND_RESULT, startCommandResult); 846 proto.end(startToken); 847 } 848 849 if (executeNesting != 0) { 850 long executNestingToken = proto.start(ServiceRecordProto.EXECUTE); 851 proto.write(ServiceRecordProto.ExecuteNesting.EXECUTE_NESTING, executeNesting); 852 proto.write(ServiceRecordProto.ExecuteNesting.EXECUTE_FG, executeFg); 853 ProtoUtils.toDuration(proto, 854 ServiceRecordProto.ExecuteNesting.EXECUTING_START, executingStart, now); 855 proto.end(executNestingToken); 856 } 857 if (destroying || destroyTime != 0) { 858 ProtoUtils.toDuration(proto, ServiceRecordProto.DESTORY_TIME, destroyTime, now); 859 } 860 if (crashCount != 0 || restartCount != 0 || (nextRestartTime - mRestartSchedulingTime) != 0 861 || nextRestartTime != 0) { 862 long crashToken = proto.start(ServiceRecordProto.CRASH); 863 proto.write(ServiceRecordProto.Crash.RESTART_COUNT, restartCount); 864 ProtoUtils.toDuration(proto, ServiceRecordProto.Crash.RESTART_DELAY, 865 (nextRestartTime - mRestartSchedulingTime), now); 866 ProtoUtils.toDuration(proto, 867 ServiceRecordProto.Crash.NEXT_RESTART_TIME, nextRestartTime, now); 868 proto.write(ServiceRecordProto.Crash.CRASH_COUNT, crashCount); 869 proto.end(crashToken); 870 } 871 872 if (deliveredStarts.size() > 0) { 873 final int N = deliveredStarts.size(); 874 for (int i = 0; i < N; i++) { 875 deliveredStarts.get(i).dumpDebug(proto, 876 ServiceRecordProto.DELIVERED_STARTS, now); 877 } 878 } 879 if (pendingStarts.size() > 0) { 880 final int N = pendingStarts.size(); 881 for (int i = 0; i < N; i++) { 882 pendingStarts.get(i).dumpDebug(proto, ServiceRecordProto.PENDING_STARTS, now); 883 } 884 } 885 if (bindings.size() > 0) { 886 final int N = bindings.size(); 887 for (int i=0; i<N; i++) { 888 IntentBindRecord b = bindings.valueAt(i); 889 b.dumpDebug(proto, ServiceRecordProto.BINDINGS); 890 } 891 } 892 if (connections.size() > 0) { 893 final int N = connections.size(); 894 for (int conni=0; conni<N; conni++) { 895 ArrayList<ConnectionRecord> c = connections.valueAt(conni); 896 for (int i=0; i<c.size(); i++) { 897 c.get(i).dumpDebug(proto, ServiceRecordProto.CONNECTIONS); 898 } 899 } 900 } 901 if (mShortFgsInfo != null && mShortFgsInfo.isCurrent()) { 902 final long shortFgsToken = proto.start(ServiceRecordProto.SHORT_FGS_INFO); 903 proto.write(ServiceRecordProto.ShortFgsInfo.START_TIME, 904 mShortFgsInfo.getStartTime()); 905 proto.write(ServiceRecordProto.ShortFgsInfo.START_ID, 906 mShortFgsInfo.getStartId()); 907 proto.write(ServiceRecordProto.ShortFgsInfo.TIMEOUT_TIME, 908 mShortFgsInfo.getTimeoutTime()); 909 proto.write(ServiceRecordProto.ShortFgsInfo.PROC_STATE_DEMOTE_TIME, 910 mShortFgsInfo.getProcStateDemoteTime()); 911 proto.write(ServiceRecordProto.ShortFgsInfo.ANR_TIME, 912 mShortFgsInfo.getAnrTime()); 913 proto.end(shortFgsToken); 914 } 915 916 // TODO: Dump all the mAllowWiu* and mAllowStart* fields as needed. 917 918 proto.end(token); 919 } 920 dumpReasonCode(PrintWriter pw, String prefix, String fieldName, int code)921 void dumpReasonCode(PrintWriter pw, String prefix, String fieldName, int code) { 922 pw.print(prefix); 923 pw.print(fieldName); 924 pw.print("="); 925 pw.println(PowerExemptionManager.reasonCodeToString(code)); 926 } 927 dump(PrintWriter pw, String prefix)928 void dump(PrintWriter pw, String prefix) { 929 pw.print(prefix); pw.print("intent={"); 930 pw.print(intent.getIntent().toShortString(false, true, false, false)); 931 pw.println('}'); 932 pw.print(prefix); pw.print("packageName="); pw.println(packageName); 933 pw.print(prefix); pw.print("processName="); pw.println(processName); 934 pw.print(prefix); pw.print("targetSdkVersion="); pw.println(appInfo.targetSdkVersion); 935 if (permission != null) { 936 pw.print(prefix); pw.print("permission="); pw.println(permission); 937 } 938 long now = SystemClock.uptimeMillis(); 939 long nowReal = SystemClock.elapsedRealtime(); 940 if (appInfo != null) { 941 pw.print(prefix); pw.print("baseDir="); pw.println(appInfo.sourceDir); 942 if (!Objects.equals(appInfo.sourceDir, appInfo.publicSourceDir)) { 943 pw.print(prefix); pw.print("resDir="); pw.println(appInfo.publicSourceDir); 944 } 945 pw.print(prefix); pw.print("dataDir="); pw.println(appInfo.dataDir); 946 } 947 pw.print(prefix); pw.print("app="); pw.println(app); 948 if (isolationHostProc != null) { 949 pw.print(prefix); pw.print("isolationHostProc="); pw.println(isolationHostProc); 950 } 951 if (allowlistManager) { 952 pw.print(prefix); pw.print("allowlistManager="); pw.println(allowlistManager); 953 } 954 if (mIsAllowedBgActivityStartsByBinding) { 955 pw.print(prefix); pw.print("mIsAllowedBgActivityStartsByBinding="); 956 pw.println(mIsAllowedBgActivityStartsByBinding); 957 } 958 if (mBackgroundStartPrivilegesByStartMerged.allowsAny()) { 959 pw.print(prefix); pw.print("mIsAllowedBgActivityStartsByStart="); 960 pw.println(mBackgroundStartPrivilegesByStartMerged); 961 } 962 963 pw.print(prefix); pw.print("useNewWiuLogic_forCapabilities()="); 964 pw.println(useNewWiuLogic_forCapabilities()); 965 pw.print(prefix); pw.print("useNewWiuLogic_forStart()="); 966 pw.println(useNewWiuLogic_forStart()); 967 pw.print(prefix); pw.print("useNewBfslLogic()="); 968 pw.println(useNewBfslLogic()); 969 970 dumpReasonCode(pw, prefix, "mAllowWiu_noBinding", mAllowWiu_noBinding); 971 dumpReasonCode(pw, prefix, "mAllowWiu_inBindService", mAllowWiu_inBindService); 972 dumpReasonCode(pw, prefix, "mAllowWiu_byBindings", mAllowWiu_byBindings); 973 974 dumpReasonCode(pw, prefix, "getFgsAllowWiu_legacy", getFgsAllowWiu_legacy()); 975 dumpReasonCode(pw, prefix, "getFgsAllowWiu_new", getFgsAllowWiu_new()); 976 977 dumpReasonCode(pw, prefix, "getFgsAllowWiu_forStart", getFgsAllowWiu_forStart()); 978 dumpReasonCode(pw, prefix, "getFgsAllowWiu_forCapabilities", 979 getFgsAllowWiu_forCapabilities()); 980 981 pw.print(prefix); pw.print("allowUiJobScheduling="); pw.println(mAllowUiJobScheduling); 982 pw.print(prefix); pw.print("recentCallingPackage="); 983 pw.println(mRecentCallingPackage); 984 pw.print(prefix); pw.print("recentCallingUid="); 985 pw.println(mRecentCallingUid); 986 987 dumpReasonCode(pw, prefix, "mAllowStart_noBinding", mAllowStart_noBinding); 988 dumpReasonCode(pw, prefix, "mAllowStart_inBindService", mAllowStart_inBindService); 989 dumpReasonCode(pw, prefix, "mAllowStart_byBindings", mAllowStart_byBindings); 990 991 dumpReasonCode(pw, prefix, "getFgsAllowStart_legacy", getFgsAllowStart_legacy()); 992 dumpReasonCode(pw, prefix, "getFgsAllowStart_new", getFgsAllowStart_new()); 993 dumpReasonCode(pw, prefix, "getFgsAllowStart", getFgsAllowStart()); 994 995 pw.print(prefix); pw.print("startForegroundCount="); 996 pw.println(mStartForegroundCount); 997 pw.print(prefix); pw.print("infoAllowStartForeground="); 998 pw.println(mInfoAllowStartForeground); 999 1000 if (delayed) { 1001 pw.print(prefix); pw.print("delayed="); pw.println(delayed); 1002 } 1003 if (isForeground || foregroundId != 0) { 1004 pw.print(prefix); pw.print("isForeground="); pw.print(isForeground); 1005 pw.print(" foregroundId="); pw.print(foregroundId); 1006 pw.printf(" types=0x%08X", foregroundServiceType); 1007 pw.print(" foregroundNoti="); pw.println(foregroundNoti); 1008 1009 if (isShortFgs() && mShortFgsInfo != null) { 1010 pw.print(prefix); pw.print("isShortFgs=true"); 1011 pw.print(" startId="); pw.print(mShortFgsInfo.getStartId()); 1012 pw.print(" startForegroundCount="); 1013 pw.print(mShortFgsInfo.getStartForegroundCount()); 1014 pw.print(" startTime="); 1015 TimeUtils.formatDuration(mShortFgsInfo.getStartTime(), now, pw); 1016 pw.print(" timeout="); 1017 TimeUtils.formatDuration(mShortFgsInfo.getTimeoutTime(), now, pw); 1018 pw.print(" demoteTime="); 1019 TimeUtils.formatDuration(mShortFgsInfo.getProcStateDemoteTime(), now, pw); 1020 pw.print(" anrTime="); 1021 TimeUtils.formatDuration(mShortFgsInfo.getAnrTime(), now, pw); 1022 pw.println(); 1023 } 1024 } 1025 if (mIsFgsDelegate) { 1026 pw.print(prefix); pw.print("isFgsDelegate="); pw.println(mIsFgsDelegate); 1027 } 1028 pw.print(prefix); pw.print("createTime="); 1029 TimeUtils.formatDuration(createRealTime, nowReal, pw); 1030 pw.print(" startingBgTimeout="); 1031 TimeUtils.formatDuration(startingBgTimeout, now, pw); 1032 pw.println(); 1033 pw.print(prefix); pw.print("lastActivity="); 1034 TimeUtils.formatDuration(lastActivity, now, pw); 1035 pw.print(" restartTime="); 1036 TimeUtils.formatDuration(restartTime, now, pw); 1037 pw.print(" createdFromFg="); pw.println(createdFromFg); 1038 if (pendingConnectionGroup != 0) { 1039 pw.print(prefix); pw.print(" pendingConnectionGroup="); 1040 pw.print(pendingConnectionGroup); 1041 pw.print(" Importance="); pw.println(pendingConnectionImportance); 1042 } 1043 if (startRequested || delayedStop || lastStartId != 0) { 1044 pw.print(prefix); pw.print("startRequested="); pw.print(startRequested); 1045 pw.print(" delayedStop="); pw.print(delayedStop); 1046 pw.print(" stopIfKilled="); pw.print(stopIfKilled); 1047 pw.print(" callStart="); pw.print(callStart); 1048 pw.print(" lastStartId="); pw.println(lastStartId); 1049 pw.print(" startCommandResult="); pw.println(startCommandResult); 1050 } 1051 if (executeNesting != 0) { 1052 pw.print(prefix); pw.print("executeNesting="); pw.print(executeNesting); 1053 pw.print(" executeFg="); pw.print(executeFg); 1054 pw.print(" executingStart="); 1055 TimeUtils.formatDuration(executingStart, now, pw); 1056 pw.println(); 1057 } 1058 if (destroying || destroyTime != 0) { 1059 pw.print(prefix); pw.print("destroying="); pw.print(destroying); 1060 pw.print(" destroyTime="); 1061 TimeUtils.formatDuration(destroyTime, now, pw); 1062 pw.println(); 1063 } 1064 if (crashCount != 0 || restartCount != 0 1065 || (nextRestartTime - mRestartSchedulingTime) != 0 || nextRestartTime != 0) { 1066 pw.print(prefix); pw.print("restartCount="); pw.print(restartCount); 1067 pw.print(" restartDelay="); 1068 TimeUtils.formatDuration(nextRestartTime - mRestartSchedulingTime, now, pw); 1069 pw.print(" nextRestartTime="); 1070 TimeUtils.formatDuration(nextRestartTime, now, pw); 1071 pw.print(" crashCount="); pw.println(crashCount); 1072 } 1073 if (deliveredStarts.size() > 0) { 1074 pw.print(prefix); pw.println("Delivered Starts:"); 1075 dumpStartList(pw, prefix, deliveredStarts, now); 1076 } 1077 if (pendingStarts.size() > 0) { 1078 pw.print(prefix); pw.println("Pending Starts:"); 1079 dumpStartList(pw, prefix, pendingStarts, 0); 1080 } 1081 if (bindings.size() > 0) { 1082 pw.print(prefix); pw.println("Bindings:"); 1083 for (int i=0; i<bindings.size(); i++) { 1084 IntentBindRecord b = bindings.valueAt(i); 1085 pw.print(prefix); pw.print("* IntentBindRecord{"); 1086 pw.print(Integer.toHexString(System.identityHashCode(b))); 1087 if ((b.collectFlags()&Context.BIND_AUTO_CREATE) != 0) { 1088 pw.append(" CREATE"); 1089 } 1090 pw.println("}:"); 1091 b.dumpInService(pw, prefix + " "); 1092 } 1093 } 1094 if (connections.size() > 0) { 1095 pw.print(prefix); pw.println("All Connections:"); 1096 for (int conni=0; conni<connections.size(); conni++) { 1097 ArrayList<ConnectionRecord> c = connections.valueAt(conni); 1098 for (int i=0; i<c.size(); i++) { 1099 pw.print(prefix); pw.print(" "); pw.println(c.get(i)); 1100 } 1101 } 1102 } 1103 } 1104 1105 /** Used only for tests */ ServiceRecord(ActivityManagerService ams)1106 private ServiceRecord(ActivityManagerService ams) { 1107 this.ams = ams; 1108 name = null; 1109 instanceName = null; 1110 shortInstanceName = null; 1111 definingPackageName = null; 1112 definingUid = 0; 1113 intent = null; 1114 serviceInfo = null; 1115 userId = 0; 1116 packageName = null; 1117 processName = null; 1118 permission = null; 1119 exported = false; 1120 restarter = null; 1121 createRealTime = 0; 1122 isSdkSandbox = false; 1123 sdkSandboxClientAppUid = 0; 1124 sdkSandboxClientAppPackage = null; 1125 inSharedIsolatedProcess = false; 1126 } 1127 newEmptyInstanceForTest(ActivityManagerService ams)1128 public static ServiceRecord newEmptyInstanceForTest(ActivityManagerService ams) { 1129 return new ServiceRecord(ams); 1130 } 1131 ServiceRecord(ActivityManagerService ams, ComponentName name, ComponentName instanceName, String definingPackageName, int definingUid, Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg, Runnable restarter)1132 ServiceRecord(ActivityManagerService ams, ComponentName name, 1133 ComponentName instanceName, String definingPackageName, int definingUid, 1134 Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg, 1135 Runnable restarter) { 1136 this(ams, name, instanceName, definingPackageName, definingUid, intent, sInfo, callerIsFg, 1137 restarter, sInfo.processName, INVALID_UID, null, false); 1138 } 1139 ServiceRecord(ActivityManagerService ams, ComponentName name, ComponentName instanceName, String definingPackageName, int definingUid, Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg, Runnable restarter, String processName, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, boolean inSharedIsolatedProcess)1140 ServiceRecord(ActivityManagerService ams, ComponentName name, 1141 ComponentName instanceName, String definingPackageName, int definingUid, 1142 Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg, 1143 Runnable restarter, String processName, int sdkSandboxClientAppUid, 1144 String sdkSandboxClientAppPackage, boolean inSharedIsolatedProcess) { 1145 this.ams = ams; 1146 this.name = name; 1147 this.instanceName = instanceName; 1148 shortInstanceName = instanceName.flattenToShortString(); 1149 this.definingPackageName = definingPackageName; 1150 this.definingUid = definingUid; 1151 this.intent = intent; 1152 serviceInfo = sInfo; 1153 appInfo = sInfo.applicationInfo; 1154 packageName = sInfo.applicationInfo.packageName; 1155 this.isSdkSandbox = sdkSandboxClientAppUid != INVALID_UID; 1156 this.sdkSandboxClientAppUid = sdkSandboxClientAppUid; 1157 this.sdkSandboxClientAppPackage = sdkSandboxClientAppPackage; 1158 this.inSharedIsolatedProcess = inSharedIsolatedProcess; 1159 this.processName = processName; 1160 permission = sInfo.permission; 1161 exported = sInfo.exported; 1162 this.restarter = restarter; 1163 createRealTime = SystemClock.elapsedRealtime(); 1164 lastActivity = SystemClock.uptimeMillis(); 1165 userId = UserHandle.getUserId(appInfo.uid); 1166 createdFromFg = callerIsFg; 1167 updateKeepWarmLocked(); 1168 // initialize notification permission state; this'll be updated whenever there's an attempt 1169 // to post or update a notification, but that doesn't cover the time before the first 1170 // notification 1171 updateFgsHasNotificationPermission(); 1172 } 1173 getTracker()1174 public ServiceState getTracker() { 1175 if (tracker != null) { 1176 return tracker; 1177 } 1178 if ((serviceInfo.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) == 0) { 1179 tracker = ams.mProcessStats.getServiceState(serviceInfo.packageName, 1180 serviceInfo.applicationInfo.uid, 1181 serviceInfo.applicationInfo.longVersionCode, 1182 serviceInfo.processName, serviceInfo.name); 1183 if (tracker != null) { 1184 tracker.applyNewOwner(this); 1185 } 1186 } 1187 return tracker; 1188 } 1189 forceClearTracker()1190 public void forceClearTracker() { 1191 if (tracker != null) { 1192 tracker.clearCurrentOwner(this, true); 1193 tracker = null; 1194 } 1195 } 1196 makeRestarting(int memFactor, long now)1197 public void makeRestarting(int memFactor, long now) { 1198 if (restartTracker == null) { 1199 if ((serviceInfo.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) == 0) { 1200 restartTracker = ams.mProcessStats.getServiceState( 1201 serviceInfo.packageName, 1202 serviceInfo.applicationInfo.uid, 1203 serviceInfo.applicationInfo.longVersionCode, 1204 serviceInfo.processName, serviceInfo.name); 1205 } 1206 if (restartTracker == null) { 1207 return; 1208 } 1209 } 1210 restartTracker.setRestarting(true, memFactor, now); 1211 } 1212 setProcess(ProcessRecord proc, IApplicationThread thread, int pid, UidRecord uidRecord)1213 public void setProcess(ProcessRecord proc, IApplicationThread thread, int pid, 1214 UidRecord uidRecord) { 1215 if (proc != null) { 1216 // We're starting a new process for this service, but a previous one is allowed to start 1217 // background activities. Remove that ability now (unless the new process is the same as 1218 // the previous one, which is a common case). 1219 if (mAppForAllowingBgActivityStartsByStart != null) { 1220 if (mAppForAllowingBgActivityStartsByStart != proc) { 1221 mAppForAllowingBgActivityStartsByStart 1222 .removeBackgroundStartPrivileges(this); 1223 ams.mHandler.removeCallbacks(mCleanUpAllowBgActivityStartsByStartCallback); 1224 } 1225 } 1226 // Make sure the cleanup callback knows about the new process. 1227 mAppForAllowingBgActivityStartsByStart = 1228 mBackgroundStartPrivilegesByStartMerged.allowsAny() 1229 ? proc : null; 1230 BackgroundStartPrivileges backgroundStartPrivileges = 1231 getBackgroundStartPrivilegesWithExclusiveToken(); 1232 if (backgroundStartPrivileges.allowsAny()) { 1233 proc.addOrUpdateBackgroundStartPrivileges(this, 1234 backgroundStartPrivileges); 1235 } else { 1236 proc.removeBackgroundStartPrivileges(this); 1237 } 1238 } 1239 if (app != null && app != proc) { 1240 // If the old app is allowed to start bg activities because of a service start, leave it 1241 // that way until the cleanup callback runs. Otherwise we can remove its bg activity 1242 // start ability immediately (it can't be bound now). 1243 if (mBackgroundStartPrivilegesByStartMerged.allowsNothing()) { 1244 app.removeBackgroundStartPrivileges(this); 1245 } 1246 app.mServices.updateBoundClientUids(); 1247 app.mServices.updateHostingComonentTypeForBindingsLocked(); 1248 } 1249 ams.mProcessStateController.setHostProcess(this, proc); 1250 updateProcessStateOnRequest(); 1251 if (pendingConnectionGroup > 0 && proc != null) { 1252 final ProcessServiceRecord psr = proc.mServices; 1253 psr.setConnectionService(this); 1254 psr.setConnectionGroup(pendingConnectionGroup); 1255 psr.setConnectionImportance(pendingConnectionImportance); 1256 pendingConnectionGroup = pendingConnectionImportance = 0; 1257 } 1258 if (ActivityManagerService.TRACK_PROCSTATS_ASSOCIATIONS) { 1259 for (int conni = connections.size() - 1; conni >= 0; conni--) { 1260 ArrayList<ConnectionRecord> cr = connections.valueAt(conni); 1261 for (int i = 0; i < cr.size(); i++) { 1262 final ConnectionRecord conn = cr.get(i); 1263 if (proc != null) { 1264 conn.startAssociationIfNeeded(); 1265 } else { 1266 conn.stopAssociation(); 1267 } 1268 } 1269 } 1270 } 1271 if (proc != null) { 1272 proc.mServices.updateBoundClientUids(); 1273 proc.mServices.updateHostingComonentTypeForBindingsLocked(); 1274 } 1275 } 1276 updateProcessStateOnRequest()1277 void updateProcessStateOnRequest() { 1278 mProcessStateOnRequest = app != null && app.getThread() != null && !app.isKilled() 1279 ? app.mState.getCurProcState() : PROCESS_STATE_NONEXISTENT; 1280 } 1281 1282 @NonNull getConnections()1283 ArrayMap<IBinder, ArrayList<ConnectionRecord>> getConnections() { 1284 return connections; 1285 } 1286 addConnection(IBinder binder, ConnectionRecord c)1287 void addConnection(IBinder binder, ConnectionRecord c) { 1288 ArrayList<ConnectionRecord> clist = connections.get(binder); 1289 if (clist == null) { 1290 clist = new ArrayList<>(); 1291 connections.put(binder, clist); 1292 } 1293 clist.add(c); 1294 1295 // if we have a process attached, add bound client uid of this connection to it 1296 if (app != null) { 1297 app.mServices.addBoundClientUid(c.clientUid, c.clientPackageName, c.getFlags()); 1298 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_BOUND_SERVICE); 1299 } 1300 } 1301 removeConnection(IBinder binder)1302 void removeConnection(IBinder binder) { 1303 connections.remove(binder); 1304 // if we have a process attached, tell it to update the state of bound clients 1305 if (app != null) { 1306 app.mServices.updateBoundClientUids(); 1307 app.mServices.updateHostingComonentTypeForBindingsLocked(); 1308 } 1309 } 1310 1311 /** 1312 * @return {@code true} if the killed service which was started by {@link Context#startService} 1313 * has no reason to start again. Note this condition doesn't consider the bindings. 1314 */ canStopIfKilled(boolean isStartCanceled)1315 boolean canStopIfKilled(boolean isStartCanceled) { 1316 if (isShortFgs()) { // Short-FGS should always stop if killed. 1317 return true; 1318 } 1319 return startRequested && (stopIfKilled || isStartCanceled) && pendingStarts.isEmpty(); 1320 } 1321 updateIsAllowedBgActivityStartsByBinding()1322 void updateIsAllowedBgActivityStartsByBinding() { 1323 boolean isAllowedByBinding = false; 1324 for (int conni = connections.size() - 1; conni >= 0; conni--) { 1325 ArrayList<ConnectionRecord> cr = connections.valueAt(conni); 1326 for (int i = 0; i < cr.size(); i++) { 1327 if (cr.get(i).hasFlag(Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS)) { 1328 isAllowedByBinding = true; 1329 break; 1330 } 1331 } 1332 if (isAllowedByBinding) { 1333 break; 1334 } 1335 } 1336 setAllowedBgActivityStartsByBinding(isAllowedByBinding); 1337 } 1338 setAllowedBgActivityStartsByBinding(boolean newValue)1339 void setAllowedBgActivityStartsByBinding(boolean newValue) { 1340 mIsAllowedBgActivityStartsByBinding = newValue; 1341 updateParentProcessBgActivityStartsToken(); 1342 } 1343 1344 /** 1345 * Called when the service is started with allowBackgroundActivityStarts set. We allow 1346 * it for background activity starts, setting up a callback to remove this ability after a 1347 * timeout. Note that the ability for starting background activities persists for the process 1348 * even if the service is subsequently stopped. 1349 */ allowBgActivityStartsOnServiceStart(BackgroundStartPrivileges backgroundStartPrivileges)1350 void allowBgActivityStartsOnServiceStart(BackgroundStartPrivileges backgroundStartPrivileges) { 1351 checkArgument(backgroundStartPrivileges.allowsAny()); 1352 mBackgroundStartPrivilegesByStart.add(backgroundStartPrivileges); 1353 setAllowedBgActivityStartsByStart( 1354 backgroundStartPrivileges.merge(mBackgroundStartPrivilegesByStartMerged)); 1355 if (app != null) { 1356 mAppForAllowingBgActivityStartsByStart = app; 1357 } 1358 1359 // This callback is stateless, so we create it once when we first need it. 1360 if (mCleanUpAllowBgActivityStartsByStartCallback == null) { 1361 mCleanUpAllowBgActivityStartsByStartCallback = () -> { 1362 synchronized (ams) { 1363 mBackgroundStartPrivilegesByStart.remove(0); 1364 if (!mBackgroundStartPrivilegesByStart.isEmpty()) { 1365 // recalculate the merged token 1366 mBackgroundStartPrivilegesByStartMerged = 1367 BackgroundStartPrivileges.merge(mBackgroundStartPrivilegesByStart); 1368 1369 // There are other callbacks in the queue, let's just update the originating 1370 // token 1371 if (mBackgroundStartPrivilegesByStartMerged.allowsAny()) { 1372 // mAppForAllowingBgActivityStartsByStart can be null here for example 1373 // if get 2 calls to allowBgActivityStartsOnServiceStart() without a 1374 // process attached to this ServiceRecord, so we need to perform a null 1375 // check here. 1376 if (mAppForAllowingBgActivityStartsByStart != null) { 1377 mAppForAllowingBgActivityStartsByStart 1378 .addOrUpdateBackgroundStartPrivileges(this, 1379 getBackgroundStartPrivilegesWithExclusiveToken()); 1380 } 1381 } else { 1382 Slog.wtf(TAG, 1383 "Service callback to revoke bg activity starts by service " 1384 + "start triggered but " 1385 + "mBackgroundStartPrivilegesByStartMerged = " 1386 + mBackgroundStartPrivilegesByStartMerged 1387 + ". This should never happen."); 1388 } 1389 } else { 1390 // Last callback on the queue 1391 if (app == mAppForAllowingBgActivityStartsByStart) { 1392 // The process we allowed is still running the service. We remove 1393 // the ability by start, but it may still be allowed via bound 1394 // connections. 1395 setAllowedBgActivityStartsByStart(BackgroundStartPrivileges.NONE); 1396 } else if (mAppForAllowingBgActivityStartsByStart != null) { 1397 // The process we allowed is not running the service. It therefore can't 1398 // be bound so we can unconditionally remove the ability. 1399 mAppForAllowingBgActivityStartsByStart 1400 .removeBackgroundStartPrivileges(ServiceRecord.this); 1401 } 1402 mAppForAllowingBgActivityStartsByStart = null; 1403 } 1404 } 1405 }; 1406 } 1407 1408 // Existing callbacks will only update the originating token, only when the last callback is 1409 // executed is the grant revoked. 1410 ams.mHandler.postDelayed(mCleanUpAllowBgActivityStartsByStartCallback, 1411 ams.mConstants.SERVICE_BG_ACTIVITY_START_TIMEOUT); 1412 } 1413 updateAllowUiJobScheduling(boolean allowUiJobScheduling)1414 void updateAllowUiJobScheduling(boolean allowUiJobScheduling) { 1415 if (mAllowUiJobScheduling == allowUiJobScheduling) { 1416 return; 1417 } 1418 mAllowUiJobScheduling = allowUiJobScheduling; 1419 } 1420 setAllowedBgActivityStartsByStart(BackgroundStartPrivileges newValue)1421 private void setAllowedBgActivityStartsByStart(BackgroundStartPrivileges newValue) { 1422 if (mBackgroundStartPrivilegesByStartMerged == newValue) { 1423 return; 1424 } 1425 mBackgroundStartPrivilegesByStartMerged = newValue; 1426 updateParentProcessBgActivityStartsToken(); 1427 } 1428 1429 /** 1430 * Whether the process this service runs in should be temporarily allowed to start 1431 * activities from background depends on the current state of both 1432 * {@code mIsAllowedBgActivityStartsByStart} and 1433 * {@code mIsAllowedBgActivityStartsByBinding}. If either is true, this ServiceRecord 1434 * should be contributing as a token in parent ProcessRecord. 1435 * 1436 * @see com.android.server.am.ProcessRecord#addOrUpdateBackgroundStartPrivileges(Binder, 1437 * BackgroundStartPrivileges) 1438 * @see com.android.server.am.ProcessRecord#removeBackgroundStartPrivileges(Binder) 1439 */ updateParentProcessBgActivityStartsToken()1440 private void updateParentProcessBgActivityStartsToken() { 1441 if (app == null) { 1442 return; 1443 } 1444 BackgroundStartPrivileges backgroundStartPrivileges = 1445 getBackgroundStartPrivilegesWithExclusiveToken(); 1446 if (backgroundStartPrivileges.allowsAny()) { 1447 // if the token is already there it's safe to "re-add it" - we're dealing with 1448 // a set of Binder objects 1449 app.addOrUpdateBackgroundStartPrivileges(this, 1450 backgroundStartPrivileges); 1451 } else { 1452 app.removeBackgroundStartPrivileges(this); 1453 } 1454 } 1455 1456 /** 1457 * Returns {@link BackgroundStartPrivileges} that represents the privileges a specific 1458 * originating token or a generic aggregate token. 1459 * 1460 * If all privileges are associated with the same token (i.e. the service is only allowed due 1461 * to starts) the token will be retained, otherwise (e.g. the privileges were granted by 1462 * bindings) the originating token will be empty. 1463 */ 1464 @Nullable getBackgroundStartPrivilegesWithExclusiveToken()1465 private BackgroundStartPrivileges getBackgroundStartPrivilegesWithExclusiveToken() { 1466 if (mIsAllowedBgActivityStartsByBinding) { 1467 return BackgroundStartPrivileges.ALLOW_BAL; 1468 } 1469 if (mBackgroundStartPrivilegesByStart.isEmpty()) { 1470 return BackgroundStartPrivileges.NONE; 1471 } 1472 return mBackgroundStartPrivilegesByStartMerged; 1473 } 1474 1475 @GuardedBy("ams") updateKeepWarmLocked()1476 void updateKeepWarmLocked() { 1477 mKeepWarming = ams.mConstants.KEEP_WARMING_SERVICES.contains(name) 1478 && (ams.mUserController.getCurrentUserId() == userId 1479 || ams.mUserController.isCurrentProfile(userId) 1480 || ams.isSingleton(processName, appInfo, instanceName.getClassName(), 1481 serviceInfo.flags)); 1482 } 1483 retrieveAppBindingLocked(Intent intent, ProcessRecord app, ProcessRecord attributedApp)1484 public AppBindRecord retrieveAppBindingLocked(Intent intent, 1485 ProcessRecord app, ProcessRecord attributedApp) { 1486 Intent.FilterComparison filter = new Intent.FilterComparison(intent); 1487 IntentBindRecord i = bindings.get(filter); 1488 if (i == null) { 1489 i = new IntentBindRecord(this, filter); 1490 bindings.put(filter, i); 1491 } 1492 AppBindRecord a = i.apps.get(app); 1493 if (a != null) { 1494 return a; 1495 } 1496 a = new AppBindRecord(this, i, app, attributedApp); 1497 i.apps.put(app, a); 1498 return a; 1499 } 1500 hasAutoCreateConnections()1501 public boolean hasAutoCreateConnections() { 1502 // XXX should probably keep a count of the number of auto-create 1503 // connections directly in the service. 1504 for (int conni=connections.size()-1; conni>=0; conni--) { 1505 ArrayList<ConnectionRecord> cr = connections.valueAt(conni); 1506 for (int i=0; i<cr.size(); i++) { 1507 if (cr.get(i).hasFlag(Context.BIND_AUTO_CREATE)) { 1508 return true; 1509 } 1510 } 1511 } 1512 return false; 1513 } 1514 updateAllowlistManager()1515 public void updateAllowlistManager() { 1516 allowlistManager = false; 1517 for (int conni=connections.size()-1; conni>=0; conni--) { 1518 ArrayList<ConnectionRecord> cr = connections.valueAt(conni); 1519 for (int i=0; i<cr.size(); i++) { 1520 if (cr.get(i).hasFlag(Context.BIND_ALLOW_WHITELIST_MANAGEMENT)) { 1521 allowlistManager = true; 1522 return; 1523 } 1524 } 1525 } 1526 } 1527 resetRestartCounter()1528 public void resetRestartCounter() { 1529 restartCount = 0; 1530 restartDelay = 0; 1531 restartTime = 0; 1532 mEarliestRestartTime = 0; 1533 mRestartSchedulingTime = 0; 1534 } 1535 findDeliveredStart(int id, boolean taskRemoved, boolean remove)1536 public StartItem findDeliveredStart(int id, boolean taskRemoved, boolean remove) { 1537 final int N = deliveredStarts.size(); 1538 for (int i=0; i<N; i++) { 1539 StartItem si = deliveredStarts.get(i); 1540 if (si.id == id && si.taskRemoved == taskRemoved) { 1541 if (remove) deliveredStarts.remove(i); 1542 return si; 1543 } 1544 } 1545 1546 return null; 1547 } 1548 getLastStartId()1549 public int getLastStartId() { 1550 return lastStartId; 1551 } 1552 makeNextStartId()1553 public int makeNextStartId() { 1554 lastStartId++; 1555 if (lastStartId < 1) { 1556 lastStartId = 1; 1557 } 1558 return lastStartId; 1559 } 1560 updateFgsHasNotificationPermission()1561 private void updateFgsHasNotificationPermission() { 1562 // Do asynchronous communication with notification manager to avoid deadlocks. 1563 final String localPackageName = packageName; 1564 final int appUid = appInfo.uid; 1565 1566 ams.mHandler.post(new Runnable() { 1567 public void run() { 1568 NotificationManagerInternal nm = LocalServices.getService( 1569 NotificationManagerInternal.class); 1570 if (nm == null) { 1571 return; 1572 } 1573 // Record whether the package has permission to notify the user 1574 mFgsHasNotificationPermission = nm.areNotificationsEnabledForPackage( 1575 localPackageName, appUid); 1576 } 1577 }); 1578 } 1579 postNotification(boolean byForegroundService)1580 public void postNotification(boolean byForegroundService) { 1581 if (isForeground && foregroundNoti != null && app != null) { 1582 final int appUid = appInfo.uid; 1583 final int appPid = app.getPid(); 1584 // Do asynchronous communication with notification manager to 1585 // avoid deadlocks. 1586 final String localPackageName = packageName; 1587 final int localForegroundId = foregroundId; 1588 final Notification _foregroundNoti = foregroundNoti; 1589 final ServiceRecord record = this; 1590 if (DEBUG_FOREGROUND_SERVICE) { 1591 Slog.d(TAG, "Posting notification " + _foregroundNoti 1592 + " for foreground service " + this); 1593 } 1594 ams.mHandler.post(new Runnable() { 1595 public void run() { 1596 NotificationManagerInternal nm = LocalServices.getService( 1597 NotificationManagerInternal.class); 1598 if (nm == null) { 1599 return; 1600 } 1601 // Record whether the package has permission to notify the user 1602 mFgsHasNotificationPermission = nm.areNotificationsEnabledForPackage( 1603 localPackageName, appUid); 1604 Notification localForegroundNoti = _foregroundNoti; 1605 try { 1606 if (localForegroundNoti.getSmallIcon() == null) { 1607 // It is not correct for the caller to not supply a notification 1608 // icon, but this used to be able to slip through, so for 1609 // those dirty apps we will create a notification clearly 1610 // blaming the app. 1611 Slog.v(TAG, "Attempted to start a foreground service (" 1612 + shortInstanceName 1613 + ") with a broken notification (no icon: " 1614 + localForegroundNoti 1615 + ")"); 1616 1617 CharSequence appName = appInfo.loadLabel( 1618 ams.mContext.getPackageManager()); 1619 if (appName == null) { 1620 appName = appInfo.packageName; 1621 } 1622 Context ctx = null; 1623 try { 1624 ctx = ams.mContext.createPackageContextAsUser( 1625 appInfo.packageName, 0, new UserHandle(userId)); 1626 1627 Notification.Builder notiBuilder = new Notification.Builder(ctx, 1628 localForegroundNoti.getChannelId()); 1629 1630 // it's ugly, but it clearly identifies the app 1631 notiBuilder.setSmallIcon(appInfo.icon); 1632 1633 // mark as foreground 1634 notiBuilder.setFlag(Notification.FLAG_FOREGROUND_SERVICE, true); 1635 1636 Intent runningIntent = new Intent( 1637 Settings.ACTION_APPLICATION_DETAILS_SETTINGS); 1638 runningIntent.setData(Uri.fromParts("package", 1639 appInfo.packageName, null)); 1640 PendingIntent pi = PendingIntent.getActivityAsUser(ams.mContext, 0, 1641 runningIntent, FLAG_UPDATE_CURRENT | FLAG_IMMUTABLE, null, 1642 UserHandle.of(userId)); 1643 notiBuilder.setColor(ams.mContext.getColor( 1644 com.android.internal 1645 .R.color.system_notification_accent_color)); 1646 notiBuilder.setContentTitle( 1647 ams.mContext.getString( 1648 com.android.internal.R.string 1649 .app_running_notification_title, 1650 appName)); 1651 notiBuilder.setContentText( 1652 ams.mContext.getString( 1653 com.android.internal.R.string 1654 .app_running_notification_text, 1655 appName)); 1656 notiBuilder.setContentIntent(pi); 1657 1658 localForegroundNoti = notiBuilder.build(); 1659 } catch (PackageManager.NameNotFoundException e) { 1660 } 1661 } 1662 if (nm.getNotificationChannel(localPackageName, appUid, 1663 localForegroundNoti.getChannelId()) == null) { 1664 int targetSdkVersion = Build.VERSION_CODES.O_MR1; 1665 try { 1666 final ApplicationInfo applicationInfo = 1667 ams.mContext.getPackageManager().getApplicationInfoAsUser( 1668 appInfo.packageName, 0, userId); 1669 targetSdkVersion = applicationInfo.targetSdkVersion; 1670 } catch (PackageManager.NameNotFoundException e) { 1671 } 1672 if (targetSdkVersion >= Build.VERSION_CODES.O_MR1) { 1673 throw new RuntimeException( 1674 "invalid channel for service notification: " 1675 + foregroundNoti); 1676 } 1677 } 1678 if (localForegroundNoti.getSmallIcon() == null) { 1679 // Notifications whose icon is 0 are defined to not show 1680 // a notification. We don't want to 1681 // just ignore it, we want to prevent the service from 1682 // being foreground. 1683 throw new RuntimeException("invalid service notification: " 1684 + foregroundNoti); 1685 } 1686 nm.enqueueNotification(localPackageName, localPackageName, 1687 appUid, appPid, null, localForegroundId, localForegroundNoti, 1688 userId, byForegroundService /* byForegroundService */); 1689 1690 foregroundNoti = localForegroundNoti; // save it for amending next time 1691 1692 signalForegroundServiceNotification(packageName, appInfo.uid, 1693 localForegroundId, false /* canceling */); 1694 1695 } catch (RuntimeException e) { 1696 Slog.w(TAG, "Error showing notification for service", e); 1697 // If it gave us a garbage notification, it doesn't 1698 // get to be foreground. 1699 ams.mServices.killMisbehavingService(record, 1700 appUid, appPid, localPackageName, 1701 CannotPostForegroundServiceNotificationException.TYPE_ID); 1702 } 1703 } 1704 }); 1705 } 1706 } 1707 cancelNotification()1708 public void cancelNotification() { 1709 // Do asynchronous communication with notification manager to 1710 // avoid deadlocks. 1711 final String localPackageName = packageName; 1712 final int localForegroundId = foregroundId; 1713 final int appUid = appInfo.uid; 1714 final int appPid = app != null ? app.getPid() : 0; 1715 ams.mHandler.post(new Runnable() { 1716 public void run() { 1717 NotificationManagerInternal nm = LocalServices.getService( 1718 NotificationManagerInternal.class); 1719 if (nm == null) { 1720 return; 1721 } 1722 try { 1723 nm.cancelNotification(localPackageName, localPackageName, appUid, appPid, 1724 null, localForegroundId, userId); 1725 } catch (RuntimeException e) { 1726 Slog.w(TAG, "Error canceling notification for service", e); 1727 } 1728 signalForegroundServiceNotification(packageName, appInfo.uid, localForegroundId, 1729 true /* canceling */); 1730 } 1731 }); 1732 } 1733 signalForegroundServiceNotification(String packageName, int uid, int foregroundId, boolean canceling)1734 private void signalForegroundServiceNotification(String packageName, int uid, 1735 int foregroundId, boolean canceling) { 1736 synchronized (ams) { 1737 for (int i = ams.mForegroundServiceStateListeners.size() - 1; i >= 0; i--) { 1738 ams.mForegroundServiceStateListeners.get(i).onForegroundServiceNotificationUpdated( 1739 packageName, appInfo.uid, foregroundId, canceling); 1740 } 1741 } 1742 } 1743 stripForegroundServiceFlagFromNotification()1744 public void stripForegroundServiceFlagFromNotification() { 1745 final int localForegroundId = foregroundId; 1746 final int localUserId = userId; 1747 final String localPackageName = packageName; 1748 1749 // Do asynchronous communication with notification manager to 1750 // avoid deadlocks. 1751 ams.mHandler.post(new Runnable() { 1752 @Override 1753 public void run() { 1754 NotificationManagerInternal nmi = LocalServices.getService( 1755 NotificationManagerInternal.class); 1756 if (nmi == null) { 1757 return; 1758 } 1759 nmi.removeForegroundServiceFlagFromNotification(localPackageName, localForegroundId, 1760 localUserId); 1761 } 1762 }); 1763 } 1764 clearDeliveredStartsLocked()1765 public void clearDeliveredStartsLocked() { 1766 for (int i=deliveredStarts.size()-1; i>=0; i--) { 1767 deliveredStarts.get(i).removeUriPermissionsLocked(); 1768 } 1769 deliveredStarts.clear(); 1770 } 1771 toString()1772 public String toString() { 1773 if (stringName != null) { 1774 return stringName; 1775 } 1776 StringBuilder sb = new StringBuilder(128); 1777 sb.append("ServiceRecord{") 1778 .append(Integer.toHexString(System.identityHashCode(this))) 1779 .append(" u").append(userId) 1780 .append(' ').append(shortInstanceName); 1781 if (mRecentCallingPackage != null) { 1782 sb.append(" c:").append(mRecentCallingPackage); 1783 } 1784 sb.append('}'); 1785 return stringName = sb.toString(); 1786 } 1787 getComponentName()1788 public ComponentName getComponentName() { 1789 return name; 1790 } 1791 1792 /** 1793 * @return true if it's a foreground service of the "short service" type and don't have 1794 * other fgs type bits set. 1795 */ isShortFgs()1796 public boolean isShortFgs() { 1797 // Note if the type contains FOREGROUND_SERVICE_TYPE_SHORT_SERVICE but also other bits 1798 // set, it's _not_ considered be a short service. (because we shouldn't apply 1799 // the short-service restrictions) 1800 // (But we should be preventing mixture of FOREGROUND_SERVICE_TYPE_SHORT_SERVICE 1801 // and other types in Service.startForeground().) 1802 return startRequested && isForeground 1803 && (foregroundServiceType == ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE); 1804 } 1805 getShortFgsInfo()1806 public ShortFgsInfo getShortFgsInfo() { 1807 return isShortFgs() ? mShortFgsInfo : null; 1808 } 1809 1810 /** 1811 * Call it when a short FGS starts. 1812 */ setShortFgsInfo(long uptimeNow)1813 public void setShortFgsInfo(long uptimeNow) { 1814 this.mShortFgsInfo = new ShortFgsInfo(uptimeNow); 1815 } 1816 1817 /** @return whether {@link #mShortFgsInfo} is set or not. */ hasShortFgsInfo()1818 public boolean hasShortFgsInfo() { 1819 return mShortFgsInfo != null; 1820 } 1821 1822 /** 1823 * Call it when a short FGS stops. 1824 */ clearShortFgsInfo()1825 public void clearShortFgsInfo() { 1826 this.mShortFgsInfo = null; 1827 } 1828 shouldTriggerShortFgsTimedEvent(long targetTime, long nowUptime)1829 private boolean shouldTriggerShortFgsTimedEvent(long targetTime, long nowUptime) { 1830 if (!isAppAlive()) { 1831 return false; 1832 } 1833 if (!this.startRequested || !isShortFgs() || mShortFgsInfo == null 1834 || !mShortFgsInfo.isCurrent()) { 1835 return false; 1836 } 1837 return targetTime <= nowUptime; 1838 } 1839 1840 /** 1841 * @return true if it's a short FGS that's still up and running, and should be timed out. 1842 */ shouldTriggerShortFgsTimeout(long nowUptime)1843 public boolean shouldTriggerShortFgsTimeout(long nowUptime) { 1844 return shouldTriggerShortFgsTimedEvent( 1845 (mShortFgsInfo == null ? 0 : mShortFgsInfo.getTimeoutTime()), 1846 nowUptime); 1847 } 1848 1849 /** 1850 * @return true if it's a short FGS's procstate should be demoted. 1851 */ shouldDemoteShortFgsProcState(long nowUptime)1852 public boolean shouldDemoteShortFgsProcState(long nowUptime) { 1853 return shouldTriggerShortFgsTimedEvent( 1854 (mShortFgsInfo == null ? 0 : mShortFgsInfo.getProcStateDemoteTime()), 1855 nowUptime); 1856 } 1857 1858 /** 1859 * @return true if it's a short FGS that's still up and running, and should be declared 1860 * an ANR. 1861 */ shouldTriggerShortFgsAnr(long nowUptime)1862 public boolean shouldTriggerShortFgsAnr(long nowUptime) { 1863 return shouldTriggerShortFgsTimedEvent( 1864 (mShortFgsInfo == null ? 0 : mShortFgsInfo.getAnrTime()), 1865 nowUptime); 1866 } 1867 1868 /** 1869 * Human readable description about short-FGS internal states. 1870 */ getShortFgsTimedEventDescription(long nowUptime)1871 public String getShortFgsTimedEventDescription(long nowUptime) { 1872 return "aa=" + isAppAlive() 1873 + " sreq=" + this.startRequested 1874 + " isfg=" + this.isForeground 1875 + " type=" + Integer.toHexString(this.foregroundServiceType) 1876 + " sfc=" + this.mStartForegroundCount 1877 + " now=" + nowUptime 1878 + " " + (mShortFgsInfo == null ? "" : mShortFgsInfo.getDescription()); 1879 } 1880 1881 /** 1882 * Called when a time-limited FGS starts. 1883 */ createTimeLimitedFgsInfo()1884 public TimeLimitedFgsInfo createTimeLimitedFgsInfo() { 1885 return new TimeLimitedFgsInfo(); 1886 } 1887 1888 /** 1889 * @return true if one of the types of this FGS has a time limit. 1890 */ isFgsTimeLimited()1891 public boolean isFgsTimeLimited() { 1892 return startRequested 1893 && isForeground 1894 && ams.mServices.getTimeLimitedFgsType(foregroundServiceType) 1895 != ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE; 1896 } 1897 isAppAlive()1898 private boolean isAppAlive() { 1899 if (app == null) { 1900 return false; 1901 } 1902 if (app.getThread() == null || app.isKilled() || app.isKilledByAm()) { 1903 return false; 1904 } 1905 return true; 1906 } 1907 1908 /** 1909 * @return {@code true} if the host process has updated its oom adj scores. 1910 */ wasOomAdjUpdated()1911 boolean wasOomAdjUpdated() { 1912 return app != null && app.mState.getAdjSeq() > mAdjSeq; 1913 } 1914 updateOomAdjSeq()1915 void updateOomAdjSeq() { 1916 if (app != null) { 1917 mAdjSeq = app.mState.getAdjSeq(); 1918 } 1919 } 1920 } 1921