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