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.app.ActivityManager.RESTRICTION_LEVEL_RESTRICTED_BUCKET; 20 import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY; 21 import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE; 22 import static android.text.TextUtils.formatSimple; 23 24 import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED; 25 import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__BOOT_COMPLETED; 26 import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__LOCKED_BOOT_COMPLETED; 27 import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED; 28 import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD; 29 import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM; 30 import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__MANIFEST; 31 import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME; 32 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST; 33 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_DEFERRAL; 34 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT; 35 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU; 36 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW; 37 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST; 38 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU; 39 import static com.android.server.am.OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER; 40 import static com.android.server.am.OomAdjuster.OOM_ADJ_REASON_START_RECEIVER; 41 42 43 import android.annotation.NonNull; 44 import android.annotation.Nullable; 45 import android.app.ActivityManager; 46 import android.app.AppGlobals; 47 import android.app.AppOpsManager; 48 import android.app.ApplicationExitInfo; 49 import android.app.BroadcastOptions; 50 import android.app.IApplicationThread; 51 import android.app.PendingIntent; 52 import android.app.usage.UsageEvents.Event; 53 import android.app.usage.UsageStatsManagerInternal; 54 import android.content.ComponentName; 55 import android.content.ContentResolver; 56 import android.content.IIntentReceiver; 57 import android.content.IIntentSender; 58 import android.content.Intent; 59 import android.content.IntentSender; 60 import android.content.pm.ActivityInfo; 61 import android.content.pm.ApplicationInfo; 62 import android.content.pm.PackageManager; 63 import android.content.pm.PermissionInfo; 64 import android.content.pm.ResolveInfo; 65 import android.content.pm.UserInfo; 66 import android.os.Bundle; 67 import android.os.Handler; 68 import android.os.IBinder; 69 import android.os.Looper; 70 import android.os.Message; 71 import android.os.PowerExemptionManager.ReasonCode; 72 import android.os.PowerExemptionManager.TempAllowListType; 73 import android.os.Process; 74 import android.os.RemoteException; 75 import android.os.SystemClock; 76 import android.os.Trace; 77 import android.os.UserHandle; 78 import android.os.UserManager; 79 import android.permission.IPermissionManager; 80 import android.text.TextUtils; 81 import android.util.EventLog; 82 import android.util.Slog; 83 import android.util.SparseIntArray; 84 import android.util.TimeUtils; 85 import android.util.proto.ProtoOutputStream; 86 87 import com.android.internal.util.ArrayUtils; 88 import com.android.internal.util.FrameworkStatsLog; 89 import com.android.server.LocalServices; 90 import com.android.server.pm.UserManagerInternal; 91 92 import java.io.FileDescriptor; 93 import java.io.PrintWriter; 94 import java.text.SimpleDateFormat; 95 import java.util.ArrayList; 96 import java.util.Date; 97 import java.util.Set; 98 99 /** 100 * BROADCASTS 101 * 102 * We keep three broadcast queues and associated bookkeeping, one for those at 103 * foreground priority, and one for normal (background-priority) broadcasts, and one to 104 * offload special broadcasts that we know take a long time, such as BOOT_COMPLETED. 105 */ 106 public final class BroadcastQueue { 107 private static final String TAG = "BroadcastQueue"; 108 private static final String TAG_MU = TAG + POSTFIX_MU; 109 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST; 110 111 static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50; 112 static final int MAX_BROADCAST_SUMMARY_HISTORY 113 = ActivityManager.isLowRamDeviceStatic() ? 25 : 300; 114 115 final ActivityManagerService mService; 116 117 /** 118 * Behavioral parameters such as timeouts and deferral policy, tracking Settings 119 * for runtime configurability 120 */ 121 final BroadcastConstants mConstants; 122 123 /** 124 * Recognizable moniker for this queue 125 */ 126 final String mQueueName; 127 128 /** 129 * If true, we can delay broadcasts while waiting services to finish in the previous 130 * receiver's process. 131 */ 132 final boolean mDelayBehindServices; 133 134 /** 135 * Lists of all active broadcasts that are to be executed immediately 136 * (without waiting for another broadcast to finish). Currently this only 137 * contains broadcasts to registered receivers, to avoid spinning up 138 * a bunch of processes to execute IntentReceiver components. Background- 139 * and foreground-priority broadcasts are queued separately. 140 */ 141 final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>(); 142 143 /** 144 * Tracking of the ordered broadcast queue, including deferral policy and alarm 145 * prioritization. 146 */ 147 final BroadcastDispatcher mDispatcher; 148 149 /** 150 * Refcounting for completion callbacks of split/deferred broadcasts. The key 151 * is an opaque integer token assigned lazily when a broadcast is first split 152 * into multiple BroadcastRecord objects. 153 */ 154 final SparseIntArray mSplitRefcounts = new SparseIntArray(); 155 private int mNextToken = 0; 156 157 /** 158 * Historical data of past broadcasts, for debugging. This is a ring buffer 159 * whose last element is at mHistoryNext. 160 */ 161 final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY]; 162 int mHistoryNext = 0; 163 164 /** 165 * Summary of historical data of past broadcasts, for debugging. This is a 166 * ring buffer whose last element is at mSummaryHistoryNext. 167 */ 168 final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY]; 169 int mSummaryHistoryNext = 0; 170 171 /** 172 * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring 173 * buffer, also tracked via the mSummaryHistoryNext index. These are all in wall 174 * clock time, not elapsed. 175 */ 176 final long[] mSummaryHistoryEnqueueTime = new long[MAX_BROADCAST_SUMMARY_HISTORY]; 177 final long[] mSummaryHistoryDispatchTime = new long[MAX_BROADCAST_SUMMARY_HISTORY]; 178 final long[] mSummaryHistoryFinishTime = new long[MAX_BROADCAST_SUMMARY_HISTORY]; 179 180 /** 181 * Set when we current have a BROADCAST_INTENT_MSG in flight. 182 */ 183 boolean mBroadcastsScheduled = false; 184 185 /** 186 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler. 187 */ 188 boolean mPendingBroadcastTimeoutMessage; 189 190 /** 191 * Intent broadcasts that we have tried to start, but are 192 * waiting for the application's process to be created. We only 193 * need one per scheduling class (instead of a list) because we always 194 * process broadcasts one at a time, so no others can be started while 195 * waiting for this one. 196 */ 197 BroadcastRecord mPendingBroadcast = null; 198 199 /** 200 * The receiver index that is pending, to restart the broadcast if needed. 201 */ 202 int mPendingBroadcastRecvIndex; 203 204 static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG; 205 static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1; 206 207 // log latency metrics for ordered broadcasts during BOOT_COMPLETED processing 208 boolean mLogLatencyMetrics = true; 209 210 final BroadcastHandler mHandler; 211 212 private final class BroadcastHandler extends Handler { BroadcastHandler(Looper looper)213 public BroadcastHandler(Looper looper) { 214 super(looper, null, true); 215 } 216 217 @Override handleMessage(Message msg)218 public void handleMessage(Message msg) { 219 switch (msg.what) { 220 case BROADCAST_INTENT_MSG: { 221 if (DEBUG_BROADCAST) Slog.v( 222 TAG_BROADCAST, "Received BROADCAST_INTENT_MSG [" 223 + mQueueName + "]"); 224 processNextBroadcast(true); 225 } break; 226 case BROADCAST_TIMEOUT_MSG: { 227 synchronized (mService) { 228 broadcastTimeoutLocked(true); 229 } 230 } break; 231 } 232 } 233 } 234 BroadcastQueue(ActivityManagerService service, Handler handler, String name, BroadcastConstants constants, boolean allowDelayBehindServices)235 BroadcastQueue(ActivityManagerService service, Handler handler, 236 String name, BroadcastConstants constants, boolean allowDelayBehindServices) { 237 mService = service; 238 mHandler = new BroadcastHandler(handler.getLooper()); 239 mQueueName = name; 240 mDelayBehindServices = allowDelayBehindServices; 241 242 mConstants = constants; 243 mDispatcher = new BroadcastDispatcher(this, mConstants, mHandler, mService); 244 } 245 start(ContentResolver resolver)246 void start(ContentResolver resolver) { 247 mDispatcher.start(); 248 mConstants.startObserving(mHandler, resolver); 249 } 250 251 @Override toString()252 public String toString() { 253 return mQueueName; 254 } 255 isPendingBroadcastProcessLocked(int pid)256 public boolean isPendingBroadcastProcessLocked(int pid) { 257 return mPendingBroadcast != null && mPendingBroadcast.curApp.getPid() == pid; 258 } 259 isPendingBroadcastProcessLocked(ProcessRecord app)260 boolean isPendingBroadcastProcessLocked(ProcessRecord app) { 261 return mPendingBroadcast != null && mPendingBroadcast.curApp == app; 262 } 263 enqueueParallelBroadcastLocked(BroadcastRecord r)264 public void enqueueParallelBroadcastLocked(BroadcastRecord r) { 265 r.enqueueClockTime = System.currentTimeMillis(); 266 r.enqueueTime = SystemClock.uptimeMillis(); 267 r.enqueueRealTime = SystemClock.elapsedRealtime(); 268 mParallelBroadcasts.add(r); 269 enqueueBroadcastHelper(r); 270 } 271 enqueueOrderedBroadcastLocked(BroadcastRecord r)272 public void enqueueOrderedBroadcastLocked(BroadcastRecord r) { 273 r.enqueueClockTime = System.currentTimeMillis(); 274 r.enqueueTime = SystemClock.uptimeMillis(); 275 r.enqueueRealTime = SystemClock.elapsedRealtime(); 276 mDispatcher.enqueueOrderedBroadcastLocked(r); 277 enqueueBroadcastHelper(r); 278 } 279 280 /** 281 * Don't call this method directly; call enqueueParallelBroadcastLocked or 282 * enqueueOrderedBroadcastLocked. 283 */ enqueueBroadcastHelper(BroadcastRecord r)284 private void enqueueBroadcastHelper(BroadcastRecord r) { 285 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 286 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, 287 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING), 288 System.identityHashCode(r)); 289 } 290 } 291 292 /** 293 * Find the same intent from queued parallel broadcast, replace with a new one and return 294 * the old one. 295 */ replaceParallelBroadcastLocked(BroadcastRecord r)296 public final BroadcastRecord replaceParallelBroadcastLocked(BroadcastRecord r) { 297 return replaceBroadcastLocked(mParallelBroadcasts, r, "PARALLEL"); 298 } 299 300 /** 301 * Find the same intent from queued ordered broadcast, replace with a new one and return 302 * the old one. 303 */ replaceOrderedBroadcastLocked(BroadcastRecord r)304 public final BroadcastRecord replaceOrderedBroadcastLocked(BroadcastRecord r) { 305 return mDispatcher.replaceBroadcastLocked(r, "ORDERED"); 306 } 307 replaceBroadcastLocked(ArrayList<BroadcastRecord> queue, BroadcastRecord r, String typeForLogging)308 private BroadcastRecord replaceBroadcastLocked(ArrayList<BroadcastRecord> queue, 309 BroadcastRecord r, String typeForLogging) { 310 final Intent intent = r.intent; 311 for (int i = queue.size() - 1; i > 0; i--) { 312 final BroadcastRecord old = queue.get(i); 313 if (old.userId == r.userId && intent.filterEquals(old.intent)) { 314 if (DEBUG_BROADCAST) { 315 Slog.v(TAG_BROADCAST, "***** DROPPING " 316 + typeForLogging + " [" + mQueueName + "]: " + intent); 317 } 318 queue.set(i, r); 319 return old; 320 } 321 } 322 return null; 323 } 324 processCurBroadcastLocked(BroadcastRecord r, ProcessRecord app)325 private final void processCurBroadcastLocked(BroadcastRecord r, 326 ProcessRecord app) throws RemoteException { 327 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 328 "Process cur broadcast " + r + " for app " + app); 329 final IApplicationThread thread = app.getThread(); 330 if (thread == null) { 331 throw new RemoteException(); 332 } 333 if (app.isInFullBackup()) { 334 skipReceiverLocked(r); 335 return; 336 } 337 338 r.receiver = thread.asBinder(); 339 r.curApp = app; 340 final ProcessReceiverRecord prr = app.mReceivers; 341 prr.addCurReceiver(r); 342 app.mState.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER); 343 // Don't bump its LRU position if it's in the background restricted. 344 if (mService.mInternal.getRestrictionLevel(app.info.packageName, app.userId) 345 < RESTRICTION_LEVEL_RESTRICTED_BUCKET) { 346 mService.updateLruProcessLocked(app, false, null); 347 } 348 // Make sure the oom adj score is updated before delivering the broadcast. 349 // Force an update, even if there are other pending requests, overall it still saves time, 350 // because time(updateOomAdj(N apps)) <= N * time(updateOomAdj(1 app)). 351 mService.enqueueOomAdjTargetLocked(app); 352 mService.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_START_RECEIVER); 353 354 // Tell the application to launch this receiver. 355 maybeReportBroadcastDispatchedEventLocked(r, r.curReceiver.applicationInfo.uid); 356 r.intent.setComponent(r.curComponent); 357 358 boolean started = false; 359 try { 360 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, 361 "Delivering to component " + r.curComponent 362 + ": " + r); 363 mService.notifyPackageUse(r.intent.getComponent().getPackageName(), 364 PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER); 365 thread.scheduleReceiver(new Intent(r.intent), r.curReceiver, 366 mService.compatibilityInfoForPackage(r.curReceiver.applicationInfo), 367 r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId, 368 app.mState.getReportedProcState()); 369 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 370 "Process cur broadcast " + r + " DELIVERED for app " + app); 371 started = true; 372 } finally { 373 if (!started) { 374 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 375 "Process cur broadcast " + r + ": NOT STARTED!"); 376 r.receiver = null; 377 r.curApp = null; 378 prr.removeCurReceiver(r); 379 } 380 } 381 382 // if something bad happens here, launch the app and try again 383 if (app.isKilled()) { 384 throw new RemoteException("app gets killed during broadcasting"); 385 } 386 } 387 388 /** 389 * Called by ActivityManagerService to notify that the uid has process started, if there is any 390 * deferred BOOT_COMPLETED broadcast, the BroadcastDispatcher can dispatch the broadcast now. 391 * @param uid 392 */ updateUidReadyForBootCompletedBroadcastLocked(int uid)393 public void updateUidReadyForBootCompletedBroadcastLocked(int uid) { 394 mDispatcher.updateUidReadyForBootCompletedBroadcastLocked(uid); 395 } 396 sendPendingBroadcastsLocked(ProcessRecord app)397 public boolean sendPendingBroadcastsLocked(ProcessRecord app) { 398 boolean didSomething = false; 399 final BroadcastRecord br = mPendingBroadcast; 400 if (br != null && br.curApp.getPid() > 0 && br.curApp.getPid() == app.getPid()) { 401 if (br.curApp != app) { 402 Slog.e(TAG, "App mismatch when sending pending broadcast to " 403 + app.processName + ", intended target is " + br.curApp.processName); 404 return false; 405 } 406 try { 407 mPendingBroadcast = null; 408 br.mIsReceiverAppRunning = false; 409 processCurBroadcastLocked(br, app); 410 didSomething = true; 411 } catch (Exception e) { 412 Slog.w(TAG, "Exception in new application when starting receiver " 413 + br.curComponent.flattenToShortString(), e); 414 logBroadcastReceiverDiscardLocked(br); 415 finishReceiverLocked(br, br.resultCode, br.resultData, 416 br.resultExtras, br.resultAbort, false); 417 scheduleBroadcastsLocked(); 418 // We need to reset the state if we failed to start the receiver. 419 br.state = BroadcastRecord.IDLE; 420 throw new RuntimeException(e.getMessage()); 421 } 422 } 423 return didSomething; 424 } 425 skipPendingBroadcastLocked(int pid)426 public void skipPendingBroadcastLocked(int pid) { 427 final BroadcastRecord br = mPendingBroadcast; 428 if (br != null && br.curApp.getPid() == pid) { 429 br.state = BroadcastRecord.IDLE; 430 br.nextReceiver = mPendingBroadcastRecvIndex; 431 mPendingBroadcast = null; 432 scheduleBroadcastsLocked(); 433 } 434 } 435 436 // Skip the current receiver, if any, that is in flight to the given process skipCurrentReceiverLocked(ProcessRecord app)437 public void skipCurrentReceiverLocked(ProcessRecord app) { 438 BroadcastRecord r = null; 439 final BroadcastRecord curActive = mDispatcher.getActiveBroadcastLocked(); 440 if (curActive != null && curActive.curApp == app) { 441 // confirmed: the current active broadcast is to the given app 442 r = curActive; 443 } 444 445 // If the current active broadcast isn't this BUT we're waiting for 446 // mPendingBroadcast to spin up the target app, that's what we use. 447 if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) { 448 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 449 "[" + mQueueName + "] skip & discard pending app " + r); 450 r = mPendingBroadcast; 451 } 452 453 if (r != null) { 454 skipReceiverLocked(r); 455 } 456 } 457 skipReceiverLocked(BroadcastRecord r)458 private void skipReceiverLocked(BroadcastRecord r) { 459 logBroadcastReceiverDiscardLocked(r); 460 finishReceiverLocked(r, r.resultCode, r.resultData, 461 r.resultExtras, r.resultAbort, false); 462 scheduleBroadcastsLocked(); 463 } 464 scheduleBroadcastsLocked()465 public void scheduleBroadcastsLocked() { 466 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts [" 467 + mQueueName + "]: current=" 468 + mBroadcastsScheduled); 469 470 if (mBroadcastsScheduled) { 471 return; 472 } 473 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this)); 474 mBroadcastsScheduled = true; 475 } 476 getMatchingOrderedReceiver(IBinder receiver)477 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) { 478 BroadcastRecord br = mDispatcher.getActiveBroadcastLocked(); 479 if (br != null && br.receiver == receiver) { 480 return br; 481 } 482 return null; 483 } 484 485 // > 0 only, no worry about "eventual" recycling nextSplitTokenLocked()486 private int nextSplitTokenLocked() { 487 int next = mNextToken + 1; 488 if (next <= 0) { 489 next = 1; 490 } 491 mNextToken = next; 492 return next; 493 } 494 postActivityStartTokenRemoval(ProcessRecord app, BroadcastRecord r)495 private void postActivityStartTokenRemoval(ProcessRecord app, BroadcastRecord r) { 496 // the receiver had run for less than allowed bg activity start timeout, 497 // so allow the process to still start activities from bg for some more time 498 String msgToken = (app.toShortString() + r.toString()).intern(); 499 // first, if there exists a past scheduled request to remove this token, drop 500 // that request - we don't want the token to be swept from under our feet... 501 mHandler.removeCallbacksAndMessages(msgToken); 502 // ...then schedule the removal of the token after the extended timeout 503 mHandler.postAtTime(() -> { 504 synchronized (mService) { 505 app.removeAllowBackgroundActivityStartsToken(r); 506 } 507 }, msgToken, (r.receiverTime + mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT)); 508 } 509 finishReceiverLocked(BroadcastRecord r, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices)510 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode, 511 String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) { 512 final int state = r.state; 513 final ActivityInfo receiver = r.curReceiver; 514 final long finishTime = SystemClock.uptimeMillis(); 515 final long elapsed = finishTime - r.receiverTime; 516 r.state = BroadcastRecord.IDLE; 517 final int curIndex = r.nextReceiver - 1; 518 if (curIndex >= 0 && curIndex < r.receivers.size() && r.curApp != null) { 519 final Object curReceiver = r.receivers.get(curIndex); 520 FrameworkStatsLog.write(BROADCAST_DELIVERY_EVENT_REPORTED, r.curApp.uid, 521 r.callingUid == -1 ? Process.SYSTEM_UID : r.callingUid, 522 r.intent.getAction(), 523 curReceiver instanceof BroadcastFilter 524 ? BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME 525 : BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__MANIFEST, 526 r.mIsReceiverAppRunning 527 ? BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM 528 : BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD, 529 r.dispatchTime - r.enqueueTime, 530 r.receiverTime - r.dispatchTime, 531 finishTime - r.receiverTime); 532 } 533 if (state == BroadcastRecord.IDLE) { 534 Slog.w(TAG_BROADCAST, "finishReceiver [" + mQueueName + "] called but state is IDLE"); 535 } 536 if (r.allowBackgroundActivityStarts && r.curApp != null) { 537 if (elapsed > mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT) { 538 // if the receiver has run for more than allowed bg activity start timeout, 539 // just remove the token for this process now and we're done 540 r.curApp.removeAllowBackgroundActivityStartsToken(r); 541 } else { 542 // It gets more time; post the removal to happen at the appropriate moment 543 postActivityStartTokenRemoval(r.curApp, r); 544 } 545 } 546 // If we're abandoning this broadcast before any receivers were actually spun up, 547 // nextReceiver is zero; in which case time-to-process bookkeeping doesn't apply. 548 if (r.nextReceiver > 0) { 549 r.duration[r.nextReceiver - 1] = elapsed; 550 } 551 552 // if this receiver was slow, impose deferral policy on the app. This will kick in 553 // when processNextBroadcastLocked() next finds this uid as a receiver identity. 554 if (!r.timeoutExempt) { 555 // r.curApp can be null if finish has raced with process death - benign 556 // edge case, and we just ignore it because we're already cleaning up 557 // as expected. 558 if (r.curApp != null 559 && mConstants.SLOW_TIME > 0 && elapsed > mConstants.SLOW_TIME) { 560 // Core system packages are exempt from deferral policy 561 if (!UserHandle.isCore(r.curApp.uid)) { 562 if (DEBUG_BROADCAST_DEFERRAL) { 563 Slog.i(TAG_BROADCAST, "Broadcast receiver " + (r.nextReceiver - 1) 564 + " was slow: " + receiver + " br=" + r); 565 } 566 mDispatcher.startDeferring(r.curApp.uid); 567 } else { 568 if (DEBUG_BROADCAST_DEFERRAL) { 569 Slog.i(TAG_BROADCAST, "Core uid " + r.curApp.uid 570 + " receiver was slow but not deferring: " 571 + receiver + " br=" + r); 572 } 573 } 574 } 575 } else { 576 if (DEBUG_BROADCAST_DEFERRAL) { 577 Slog.i(TAG_BROADCAST, "Finished broadcast " + r.intent.getAction() 578 + " is exempt from deferral policy"); 579 } 580 } 581 582 r.receiver = null; 583 r.intent.setComponent(null); 584 if (r.curApp != null && r.curApp.mReceivers.hasCurReceiver(r)) { 585 r.curApp.mReceivers.removeCurReceiver(r); 586 mService.enqueueOomAdjTargetLocked(r.curApp); 587 } 588 if (r.curFilter != null) { 589 r.curFilter.receiverList.curBroadcast = null; 590 } 591 r.curFilter = null; 592 r.curReceiver = null; 593 r.curApp = null; 594 mPendingBroadcast = null; 595 596 r.resultCode = resultCode; 597 r.resultData = resultData; 598 r.resultExtras = resultExtras; 599 if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) { 600 r.resultAbort = resultAbort; 601 } else { 602 r.resultAbort = false; 603 } 604 605 // If we want to wait behind services *AND* we're finishing the head/ 606 // active broadcast on its queue 607 if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices 608 && r.queue.mDispatcher.getActiveBroadcastLocked() == r) { 609 ActivityInfo nextReceiver; 610 if (r.nextReceiver < r.receivers.size()) { 611 Object obj = r.receivers.get(r.nextReceiver); 612 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null; 613 } else { 614 nextReceiver = null; 615 } 616 // Don't do this if the next receive is in the same process as the current one. 617 if (receiver == null || nextReceiver == null 618 || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid 619 || !receiver.processName.equals(nextReceiver.processName)) { 620 // In this case, we are ready to process the next receiver for the current broadcast, 621 // but are on a queue that would like to wait for services to finish before moving 622 // on. If there are background services currently starting, then we will go into a 623 // special state where we hold off on continuing this broadcast until they are done. 624 if (mService.mServices.hasBackgroundServicesLocked(r.userId)) { 625 Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString()); 626 r.state = BroadcastRecord.WAITING_SERVICES; 627 return false; 628 } 629 } 630 } 631 632 r.curComponent = null; 633 634 // We will process the next receiver right now if this is finishing 635 // an app receiver (which is always asynchronous) or after we have 636 // come back from calling a receiver. 637 return state == BroadcastRecord.APP_RECEIVE 638 || state == BroadcastRecord.CALL_DONE_RECEIVE; 639 } 640 backgroundServicesFinishedLocked(int userId)641 public void backgroundServicesFinishedLocked(int userId) { 642 BroadcastRecord br = mDispatcher.getActiveBroadcastLocked(); 643 if (br != null) { 644 if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) { 645 Slog.i(TAG, "Resuming delayed broadcast"); 646 br.curComponent = null; 647 br.state = BroadcastRecord.IDLE; 648 processNextBroadcastLocked(false, false); 649 } 650 } 651 } 652 performReceiveLocked(ProcessRecord app, IIntentReceiver receiver, Intent intent, int resultCode, String data, Bundle extras, boolean ordered, boolean sticky, int sendingUser, int receiverUid, int callingUid, long dispatchDelay, long receiveDelay)653 void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver, 654 Intent intent, int resultCode, String data, Bundle extras, 655 boolean ordered, boolean sticky, int sendingUser, 656 int receiverUid, int callingUid, long dispatchDelay, 657 long receiveDelay) throws RemoteException { 658 // Send the intent to the receiver asynchronously using one-way binder calls. 659 if (app != null) { 660 final IApplicationThread thread = app.getThread(); 661 if (thread != null) { 662 // If we have an app thread, do the call through that so it is 663 // correctly ordered with other one-way calls. 664 try { 665 thread.scheduleRegisteredReceiver(receiver, intent, resultCode, 666 data, extras, ordered, sticky, sendingUser, 667 app.mState.getReportedProcState()); 668 } catch (RemoteException ex) { 669 // Failed to call into the process. It's either dying or wedged. Kill it gently. 670 synchronized (mService) { 671 final String msg = "Failed to schedule " + intent + " to " + receiver 672 + " via " + app + ": " + ex; 673 Slog.w(TAG, msg); 674 app.killLocked("Can't deliver broadcast", ApplicationExitInfo.REASON_OTHER, 675 ApplicationExitInfo.SUBREASON_UNDELIVERED_BROADCAST, true); 676 } 677 throw ex; 678 } 679 } else { 680 // Application has died. Receiver doesn't exist. 681 throw new RemoteException("app.thread must not be null"); 682 } 683 } else { 684 receiver.performReceive(intent, resultCode, data, extras, ordered, 685 sticky, sendingUser); 686 } 687 if (!ordered) { 688 FrameworkStatsLog.write(BROADCAST_DELIVERY_EVENT_REPORTED, 689 receiverUid == -1 ? Process.SYSTEM_UID : receiverUid, 690 callingUid == -1 ? Process.SYSTEM_UID : callingUid, 691 intent.getAction(), 692 BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME, 693 BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM, 694 dispatchDelay, receiveDelay, 0 /* finish_delay */); 695 } 696 } 697 deliverToRegisteredReceiverLocked(BroadcastRecord r, BroadcastFilter filter, boolean ordered, int index)698 private void deliverToRegisteredReceiverLocked(BroadcastRecord r, 699 BroadcastFilter filter, boolean ordered, int index) { 700 boolean skip = false; 701 if (r.options != null && !r.options.testRequireCompatChange(filter.owningUid)) { 702 Slog.w(TAG, "Compat change filtered: broadcasting " + r.intent.toString() 703 + " to uid " + filter.owningUid + " due to compat change " 704 + r.options.getRequireCompatChangeId()); 705 skip = true; 706 } 707 if (!mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid, 708 filter.packageName, filter.owningUid)) { 709 Slog.w(TAG, "Association not allowed: broadcasting " 710 + r.intent.toString() 711 + " from " + r.callerPackage + " (pid=" + r.callingPid 712 + ", uid=" + r.callingUid + ") to " + filter.packageName + " through " 713 + filter); 714 skip = true; 715 } 716 if (!skip && !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid, 717 r.callingPid, r.resolvedType, filter.receiverList.uid)) { 718 Slog.w(TAG, "Firewall blocked: broadcasting " 719 + r.intent.toString() 720 + " from " + r.callerPackage + " (pid=" + r.callingPid 721 + ", uid=" + r.callingUid + ") to " + filter.packageName + " through " 722 + filter); 723 skip = true; 724 } 725 // Check that the sender has permission to send to this receiver 726 if (filter.requiredPermission != null) { 727 int perm = mService.checkComponentPermission(filter.requiredPermission, 728 r.callingPid, r.callingUid, -1, true); 729 if (perm != PackageManager.PERMISSION_GRANTED) { 730 Slog.w(TAG, "Permission Denial: broadcasting " 731 + r.intent.toString() 732 + " from " + r.callerPackage + " (pid=" 733 + r.callingPid + ", uid=" + r.callingUid + ")" 734 + " requires " + filter.requiredPermission 735 + " due to registered receiver " + filter); 736 skip = true; 737 } else { 738 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission); 739 if (opCode != AppOpsManager.OP_NONE 740 && mService.getAppOpsManager().noteOpNoThrow(opCode, r.callingUid, 741 r.callerPackage, r.callerFeatureId, "Broadcast sent to protected receiver") 742 != AppOpsManager.MODE_ALLOWED) { 743 Slog.w(TAG, "Appop Denial: broadcasting " 744 + r.intent.toString() 745 + " from " + r.callerPackage + " (pid=" 746 + r.callingPid + ", uid=" + r.callingUid + ")" 747 + " requires appop " + AppOpsManager.permissionToOp( 748 filter.requiredPermission) 749 + " due to registered receiver " + filter); 750 skip = true; 751 } 752 } 753 } 754 755 if (!skip && (filter.receiverList.app == null || filter.receiverList.app.isKilled() 756 || filter.receiverList.app.mErrorState.isCrashing())) { 757 Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r 758 + " to " + filter.receiverList + ": process gone or crashing"); 759 skip = true; 760 } 761 762 // Ensure that broadcasts are only sent to other Instant Apps if they are marked as 763 // visible to Instant Apps. 764 final boolean visibleToInstantApps = 765 (r.intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0; 766 767 if (!skip && !visibleToInstantApps && filter.instantApp 768 && filter.receiverList.uid != r.callingUid) { 769 Slog.w(TAG, "Instant App Denial: receiving " 770 + r.intent.toString() 771 + " to " + filter.receiverList.app 772 + " (pid=" + filter.receiverList.pid 773 + ", uid=" + filter.receiverList.uid + ")" 774 + " due to sender " + r.callerPackage 775 + " (uid " + r.callingUid + ")" 776 + " not specifying FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS"); 777 skip = true; 778 } 779 780 if (!skip && !filter.visibleToInstantApp && r.callerInstantApp 781 && filter.receiverList.uid != r.callingUid) { 782 Slog.w(TAG, "Instant App Denial: receiving " 783 + r.intent.toString() 784 + " to " + filter.receiverList.app 785 + " (pid=" + filter.receiverList.pid 786 + ", uid=" + filter.receiverList.uid + ")" 787 + " requires receiver be visible to instant apps" 788 + " due to sender " + r.callerPackage 789 + " (uid " + r.callingUid + ")"); 790 skip = true; 791 } 792 793 // Check that the receiver has the required permission(s) to receive this broadcast. 794 if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) { 795 for (int i = 0; i < r.requiredPermissions.length; i++) { 796 String requiredPermission = r.requiredPermissions[i]; 797 int perm = mService.checkComponentPermission(requiredPermission, 798 filter.receiverList.pid, filter.receiverList.uid, -1, true); 799 if (perm != PackageManager.PERMISSION_GRANTED) { 800 Slog.w(TAG, "Permission Denial: receiving " 801 + r.intent.toString() 802 + " to " + filter.receiverList.app 803 + " (pid=" + filter.receiverList.pid 804 + ", uid=" + filter.receiverList.uid + ")" 805 + " requires " + requiredPermission 806 + " due to sender " + r.callerPackage 807 + " (uid " + r.callingUid + ")"); 808 skip = true; 809 break; 810 } 811 int appOp = AppOpsManager.permissionToOpCode(requiredPermission); 812 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp 813 && mService.getAppOpsManager().noteOpNoThrow(appOp, 814 filter.receiverList.uid, filter.packageName, filter.featureId, 815 "Broadcast delivered to registered receiver " + filter.receiverId) 816 != AppOpsManager.MODE_ALLOWED) { 817 Slog.w(TAG, "Appop Denial: receiving " 818 + r.intent.toString() 819 + " to " + filter.receiverList.app 820 + " (pid=" + filter.receiverList.pid 821 + ", uid=" + filter.receiverList.uid + ")" 822 + " requires appop " + AppOpsManager.permissionToOp( 823 requiredPermission) 824 + " due to sender " + r.callerPackage 825 + " (uid " + r.callingUid + ")"); 826 skip = true; 827 break; 828 } 829 } 830 } 831 if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) { 832 int perm = mService.checkComponentPermission(null, 833 filter.receiverList.pid, filter.receiverList.uid, -1, true); 834 if (perm != PackageManager.PERMISSION_GRANTED) { 835 Slog.w(TAG, "Permission Denial: security check failed when receiving " 836 + r.intent.toString() 837 + " to " + filter.receiverList.app 838 + " (pid=" + filter.receiverList.pid 839 + ", uid=" + filter.receiverList.uid + ")" 840 + " due to sender " + r.callerPackage 841 + " (uid " + r.callingUid + ")"); 842 skip = true; 843 } 844 } 845 // Check that the receiver does *not* have any excluded permissions 846 if (!skip && r.excludedPermissions != null && r.excludedPermissions.length > 0) { 847 for (int i = 0; i < r.excludedPermissions.length; i++) { 848 String excludedPermission = r.excludedPermissions[i]; 849 final int perm = mService.checkComponentPermission(excludedPermission, 850 filter.receiverList.pid, filter.receiverList.uid, -1, true); 851 852 int appOp = AppOpsManager.permissionToOpCode(excludedPermission); 853 if (appOp != AppOpsManager.OP_NONE) { 854 // When there is an app op associated with the permission, 855 // skip when both the permission and the app op are 856 // granted. 857 if ((perm == PackageManager.PERMISSION_GRANTED) && ( 858 mService.getAppOpsManager().checkOpNoThrow(appOp, 859 filter.receiverList.uid, 860 filter.packageName) 861 == AppOpsManager.MODE_ALLOWED)) { 862 Slog.w(TAG, "Appop Denial: receiving " 863 + r.intent.toString() 864 + " to " + filter.receiverList.app 865 + " (pid=" + filter.receiverList.pid 866 + ", uid=" + filter.receiverList.uid + ")" 867 + " excludes appop " + AppOpsManager.permissionToOp( 868 excludedPermission) 869 + " due to sender " + r.callerPackage 870 + " (uid " + r.callingUid + ")"); 871 skip = true; 872 break; 873 } 874 } else { 875 // When there is no app op associated with the permission, 876 // skip when permission is granted. 877 if (perm == PackageManager.PERMISSION_GRANTED) { 878 Slog.w(TAG, "Permission Denial: receiving " 879 + r.intent.toString() 880 + " to " + filter.receiverList.app 881 + " (pid=" + filter.receiverList.pid 882 + ", uid=" + filter.receiverList.uid + ")" 883 + " excludes " + excludedPermission 884 + " due to sender " + r.callerPackage 885 + " (uid " + r.callingUid + ")"); 886 skip = true; 887 break; 888 } 889 } 890 } 891 } 892 893 // Check that the receiver does *not* belong to any of the excluded packages 894 if (!skip && r.excludedPackages != null && r.excludedPackages.length > 0) { 895 if (ArrayUtils.contains(r.excludedPackages, filter.packageName)) { 896 Slog.w(TAG, "Skipping delivery of excluded package " 897 + r.intent.toString() 898 + " to " + filter.receiverList.app 899 + " (pid=" + filter.receiverList.pid 900 + ", uid=" + filter.receiverList.uid + ")" 901 + " excludes package " + filter.packageName 902 + " due to sender " + r.callerPackage 903 + " (uid " + r.callingUid + ")"); 904 skip = true; 905 } 906 } 907 908 // If the broadcast also requires an app op check that as well. 909 if (!skip && r.appOp != AppOpsManager.OP_NONE 910 && mService.getAppOpsManager().noteOpNoThrow(r.appOp, 911 filter.receiverList.uid, filter.packageName, filter.featureId, 912 "Broadcast delivered to registered receiver " + filter.receiverId) 913 != AppOpsManager.MODE_ALLOWED) { 914 Slog.w(TAG, "Appop Denial: receiving " 915 + r.intent.toString() 916 + " to " + filter.receiverList.app 917 + " (pid=" + filter.receiverList.pid 918 + ", uid=" + filter.receiverList.uid + ")" 919 + " requires appop " + AppOpsManager.opToName(r.appOp) 920 + " due to sender " + r.callerPackage 921 + " (uid " + r.callingUid + ")"); 922 skip = true; 923 } 924 925 // Ensure that broadcasts are only sent to other apps if they are explicitly marked as 926 // exported, or are System level broadcasts 927 if (!skip && !filter.exported && mService.checkComponentPermission(null, r.callingPid, 928 r.callingUid, filter.receiverList.uid, filter.exported) 929 != PackageManager.PERMISSION_GRANTED) { 930 Slog.w(TAG, "Exported Denial: sending " 931 + r.intent.toString() 932 + ", action: " + r.intent.getAction() 933 + " from " + r.callerPackage 934 + " (uid=" + r.callingUid + ")" 935 + " due to receiver " + filter.receiverList.app 936 + " (uid " + filter.receiverList.uid + ")" 937 + " not specifying RECEIVER_EXPORTED"); 938 skip = true; 939 } 940 941 if (skip) { 942 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED; 943 return; 944 } 945 946 // If permissions need a review before any of the app components can run, we drop 947 // the broadcast and if the calling app is in the foreground and the broadcast is 948 // explicit we launch the review UI passing it a pending intent to send the skipped 949 // broadcast. 950 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName, 951 filter.owningUserId)) { 952 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED; 953 return; 954 } 955 956 r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED; 957 958 // If this is not being sent as an ordered broadcast, then we 959 // don't want to touch the fields that keep track of the current 960 // state of ordered broadcasts. 961 if (ordered) { 962 r.receiver = filter.receiverList.receiver.asBinder(); 963 r.curFilter = filter; 964 filter.receiverList.curBroadcast = r; 965 r.state = BroadcastRecord.CALL_IN_RECEIVE; 966 if (filter.receiverList.app != null) { 967 // Bump hosting application to no longer be in background 968 // scheduling class. Note that we can't do that if there 969 // isn't an app... but we can only be in that case for 970 // things that directly call the IActivityManager API, which 971 // are already core system stuff so don't matter for this. 972 r.curApp = filter.receiverList.app; 973 filter.receiverList.app.mReceivers.addCurReceiver(r); 974 mService.enqueueOomAdjTargetLocked(r.curApp); 975 mService.updateOomAdjPendingTargetsLocked( 976 OOM_ADJ_REASON_START_RECEIVER); 977 } 978 } else if (filter.receiverList.app != null) { 979 mService.mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily(filter.receiverList.app, 980 OOM_ADJ_REASON_START_RECEIVER); 981 } 982 983 try { 984 if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST, 985 "Delivering to " + filter + " : " + r); 986 if (filter.receiverList.app != null && filter.receiverList.app.isInFullBackup()) { 987 // Skip delivery if full backup in progress 988 // If it's an ordered broadcast, we need to continue to the next receiver. 989 if (ordered) { 990 skipReceiverLocked(r); 991 } 992 } else { 993 r.receiverTime = SystemClock.uptimeMillis(); 994 maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r); 995 maybeScheduleTempAllowlistLocked(filter.owningUid, r, r.options); 996 maybeReportBroadcastDispatchedEventLocked(r, filter.owningUid); 997 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver, 998 new Intent(r.intent), r.resultCode, r.resultData, 999 r.resultExtras, r.ordered, r.initialSticky, r.userId, 1000 filter.receiverList.uid, r.callingUid, 1001 r.dispatchTime - r.enqueueTime, 1002 r.receiverTime - r.dispatchTime); 1003 // parallel broadcasts are fire-and-forget, not bookended by a call to 1004 // finishReceiverLocked(), so we manage their activity-start token here 1005 if (filter.receiverList.app != null 1006 && r.allowBackgroundActivityStarts && !r.ordered) { 1007 postActivityStartTokenRemoval(filter.receiverList.app, r); 1008 } 1009 } 1010 if (ordered) { 1011 r.state = BroadcastRecord.CALL_DONE_RECEIVE; 1012 } 1013 } catch (RemoteException e) { 1014 Slog.w(TAG, "Failure sending broadcast " + r.intent, e); 1015 // Clean up ProcessRecord state related to this broadcast attempt 1016 if (filter.receiverList.app != null) { 1017 filter.receiverList.app.removeAllowBackgroundActivityStartsToken(r); 1018 if (ordered) { 1019 filter.receiverList.app.mReceivers.removeCurReceiver(r); 1020 // Something wrong, its oom adj could be downgraded, but not in a hurry. 1021 mService.enqueueOomAdjTargetLocked(r.curApp); 1022 } 1023 } 1024 // And BroadcastRecord state related to ordered delivery, if appropriate 1025 if (ordered) { 1026 r.receiver = null; 1027 r.curFilter = null; 1028 filter.receiverList.curBroadcast = null; 1029 } 1030 } 1031 } 1032 requestStartTargetPermissionsReviewIfNeededLocked( BroadcastRecord receiverRecord, String receivingPackageName, final int receivingUserId)1033 private boolean requestStartTargetPermissionsReviewIfNeededLocked( 1034 BroadcastRecord receiverRecord, String receivingPackageName, 1035 final int receivingUserId) { 1036 if (!mService.getPackageManagerInternal().isPermissionsReviewRequired( 1037 receivingPackageName, receivingUserId)) { 1038 return true; 1039 } 1040 1041 final boolean callerForeground = receiverRecord.callerApp != null 1042 ? receiverRecord.callerApp.mState.getSetSchedGroup() 1043 != ProcessList.SCHED_GROUP_BACKGROUND : true; 1044 1045 // Show a permission review UI only for explicit broadcast from a foreground app 1046 if (callerForeground && receiverRecord.intent.getComponent() != null) { 1047 IIntentSender target = mService.mPendingIntentController.getIntentSender( 1048 ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage, 1049 receiverRecord.callerFeatureId, receiverRecord.callingUid, 1050 receiverRecord.userId, null, null, 0, 1051 new Intent[]{receiverRecord.intent}, 1052 new String[]{receiverRecord.intent.resolveType(mService.mContext 1053 .getContentResolver())}, 1054 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT 1055 | PendingIntent.FLAG_IMMUTABLE, null); 1056 1057 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS); 1058 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 1059 | Intent.FLAG_ACTIVITY_MULTIPLE_TASK 1060 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 1061 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName); 1062 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target)); 1063 1064 if (DEBUG_PERMISSIONS_REVIEW) { 1065 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package " 1066 + receivingPackageName); 1067 } 1068 1069 mHandler.post(new Runnable() { 1070 @Override 1071 public void run() { 1072 mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId)); 1073 } 1074 }); 1075 } else { 1076 Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package" 1077 + receivingPackageName + " requires a permissions review"); 1078 } 1079 1080 return false; 1081 } 1082 maybeScheduleTempAllowlistLocked(int uid, BroadcastRecord r, @Nullable BroadcastOptions brOptions)1083 void maybeScheduleTempAllowlistLocked(int uid, BroadcastRecord r, 1084 @Nullable BroadcastOptions brOptions) { 1085 if (brOptions == null || brOptions.getTemporaryAppAllowlistDuration() <= 0) { 1086 return; 1087 } 1088 long duration = brOptions.getTemporaryAppAllowlistDuration(); 1089 final @TempAllowListType int type = brOptions.getTemporaryAppAllowlistType(); 1090 final @ReasonCode int reasonCode = brOptions.getTemporaryAppAllowlistReasonCode(); 1091 final String reason = brOptions.getTemporaryAppAllowlistReason(); 1092 1093 if (duration > Integer.MAX_VALUE) { 1094 duration = Integer.MAX_VALUE; 1095 } 1096 // XXX ideally we should pause the broadcast until everything behind this is done, 1097 // or else we will likely start dispatching the broadcast before we have opened 1098 // access to the app (there is a lot of asynchronicity behind this). It is probably 1099 // not that big a deal, however, because the main purpose here is to allow apps 1100 // to hold wake locks, and they will be able to acquire their wake lock immediately 1101 // it just won't be enabled until we get through this work. 1102 StringBuilder b = new StringBuilder(); 1103 b.append("broadcast:"); 1104 UserHandle.formatUid(b, r.callingUid); 1105 b.append(":"); 1106 if (r.intent.getAction() != null) { 1107 b.append(r.intent.getAction()); 1108 } else if (r.intent.getComponent() != null) { 1109 r.intent.getComponent().appendShortString(b); 1110 } else if (r.intent.getData() != null) { 1111 b.append(r.intent.getData()); 1112 } 1113 b.append(",reason:"); 1114 b.append(reason); 1115 if (DEBUG_BROADCAST) { 1116 Slog.v(TAG, "Broadcast temp allowlist uid=" + uid + " duration=" + duration 1117 + " type=" + type + " : " + b.toString()); 1118 } 1119 mService.tempAllowlistUidLocked(uid, duration, reasonCode, b.toString(), type, 1120 r.callingUid); 1121 } 1122 1123 /** 1124 * Return true if all given permissions are signature-only perms. 1125 */ isSignaturePerm(String[] perms)1126 final boolean isSignaturePerm(String[] perms) { 1127 if (perms == null) { 1128 return false; 1129 } 1130 IPermissionManager pm = AppGlobals.getPermissionManager(); 1131 for (int i = perms.length-1; i >= 0; i--) { 1132 try { 1133 PermissionInfo pi = pm.getPermissionInfo(perms[i], "android", 0); 1134 if (pi == null) { 1135 // a required permission that no package has actually 1136 // defined cannot be signature-required. 1137 return false; 1138 } 1139 if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE 1140 | PermissionInfo.PROTECTION_FLAG_PRIVILEGED)) 1141 != PermissionInfo.PROTECTION_SIGNATURE) { 1142 // If this a signature permission and NOT allowed for privileged apps, it 1143 // is okay... otherwise, nope! 1144 return false; 1145 } 1146 } catch (RemoteException e) { 1147 return false; 1148 } 1149 } 1150 return true; 1151 } 1152 processNextBroadcast(boolean fromMsg)1153 private void processNextBroadcast(boolean fromMsg) { 1154 synchronized (mService) { 1155 processNextBroadcastLocked(fromMsg, false); 1156 } 1157 } 1158 broadcastDescription(BroadcastRecord r, ComponentName component)1159 static String broadcastDescription(BroadcastRecord r, ComponentName component) { 1160 return r.intent.toString() 1161 + " from " + r.callerPackage + " (pid=" + r.callingPid 1162 + ", uid=" + r.callingUid + ") to " + component.flattenToShortString(); 1163 } 1164 processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj)1165 final void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj) { 1166 BroadcastRecord r; 1167 1168 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast [" 1169 + mQueueName + "]: " 1170 + mParallelBroadcasts.size() + " parallel broadcasts; " 1171 + mDispatcher.describeStateLocked()); 1172 1173 mService.updateCpuStats(); 1174 1175 if (fromMsg) { 1176 mBroadcastsScheduled = false; 1177 } 1178 1179 // First, deliver any non-serialized broadcasts right away. 1180 while (mParallelBroadcasts.size() > 0) { 1181 r = mParallelBroadcasts.remove(0); 1182 r.dispatchTime = SystemClock.uptimeMillis(); 1183 r.dispatchRealTime = SystemClock.elapsedRealtime(); 1184 r.dispatchClockTime = System.currentTimeMillis(); 1185 r.mIsReceiverAppRunning = true; 1186 1187 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 1188 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, 1189 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING), 1190 System.identityHashCode(r)); 1191 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, 1192 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED), 1193 System.identityHashCode(r)); 1194 } 1195 1196 final int N = r.receivers.size(); 1197 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast [" 1198 + mQueueName + "] " + r); 1199 for (int i=0; i<N; i++) { 1200 Object target = r.receivers.get(i); 1201 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 1202 "Delivering non-ordered on [" + mQueueName + "] to registered " 1203 + target + ": " + r); 1204 deliverToRegisteredReceiverLocked(r, 1205 (BroadcastFilter) target, false, i); 1206 } 1207 addBroadcastToHistoryLocked(r); 1208 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast [" 1209 + mQueueName + "] " + r); 1210 } 1211 1212 // Now take care of the next serialized one... 1213 1214 // If we are waiting for a process to come up to handle the next 1215 // broadcast, then do nothing at this point. Just in case, we 1216 // check that the process we're waiting for still exists. 1217 if (mPendingBroadcast != null) { 1218 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, 1219 "processNextBroadcast [" + mQueueName + "]: waiting for " 1220 + mPendingBroadcast.curApp); 1221 1222 boolean isDead; 1223 if (mPendingBroadcast.curApp.getPid() > 0) { 1224 synchronized (mService.mPidsSelfLocked) { 1225 ProcessRecord proc = mService.mPidsSelfLocked.get( 1226 mPendingBroadcast.curApp.getPid()); 1227 isDead = proc == null || proc.mErrorState.isCrashing(); 1228 } 1229 } else { 1230 final ProcessRecord proc = mService.mProcessList.getProcessNamesLOSP().get( 1231 mPendingBroadcast.curApp.processName, mPendingBroadcast.curApp.uid); 1232 isDead = proc == null || !proc.isPendingStart(); 1233 } 1234 if (!isDead) { 1235 // It's still alive, so keep waiting 1236 return; 1237 } else { 1238 Slog.w(TAG, "pending app [" 1239 + mQueueName + "]" + mPendingBroadcast.curApp 1240 + " died before responding to broadcast"); 1241 mPendingBroadcast.state = BroadcastRecord.IDLE; 1242 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex; 1243 mPendingBroadcast = null; 1244 } 1245 } 1246 1247 boolean looped = false; 1248 1249 do { 1250 final long now = SystemClock.uptimeMillis(); 1251 r = mDispatcher.getNextBroadcastLocked(now); 1252 1253 if (r == null) { 1254 // No more broadcasts are deliverable right now, so all done! 1255 mDispatcher.scheduleDeferralCheckLocked(false); 1256 synchronized (mService.mAppProfiler.mProfilerLock) { 1257 mService.mAppProfiler.scheduleAppGcsLPf(); 1258 } 1259 if (looped && !skipOomAdj) { 1260 // If we had finished the last ordered broadcast, then 1261 // make sure all processes have correct oom and sched 1262 // adjustments. 1263 mService.updateOomAdjPendingTargetsLocked( 1264 OOM_ADJ_REASON_START_RECEIVER); 1265 } 1266 1267 // when we have no more ordered broadcast on this queue, stop logging 1268 if (mService.mUserController.mBootCompleted && mLogLatencyMetrics) { 1269 mLogLatencyMetrics = false; 1270 } 1271 1272 return; 1273 } 1274 1275 boolean forceReceive = false; 1276 1277 // Ensure that even if something goes awry with the timeout 1278 // detection, we catch "hung" broadcasts here, discard them, 1279 // and continue to make progress. 1280 // 1281 // This is only done if the system is ready so that early-stage receivers 1282 // don't get executed with timeouts; and of course other timeout- 1283 // exempt broadcasts are ignored. 1284 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0; 1285 if (mService.mProcessesReady && !r.timeoutExempt && r.dispatchTime > 0) { 1286 if ((numReceivers > 0) && 1287 (now > r.dispatchTime + (2 * mConstants.TIMEOUT * numReceivers))) { 1288 Slog.w(TAG, "Hung broadcast [" 1289 + mQueueName + "] discarded after timeout failure:" 1290 + " now=" + now 1291 + " dispatchTime=" + r.dispatchTime 1292 + " startTime=" + r.receiverTime 1293 + " intent=" + r.intent 1294 + " numReceivers=" + numReceivers 1295 + " nextReceiver=" + r.nextReceiver 1296 + " state=" + r.state); 1297 broadcastTimeoutLocked(false); // forcibly finish this broadcast 1298 forceReceive = true; 1299 r.state = BroadcastRecord.IDLE; 1300 } 1301 } 1302 1303 if (r.state != BroadcastRecord.IDLE) { 1304 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST, 1305 "processNextBroadcast(" 1306 + mQueueName + ") called when not idle (state=" 1307 + r.state + ")"); 1308 return; 1309 } 1310 1311 // Is the current broadcast is done for any reason? 1312 if (r.receivers == null || r.nextReceiver >= numReceivers 1313 || r.resultAbort || forceReceive) { 1314 // Send the final result if requested 1315 if (r.resultTo != null) { 1316 boolean sendResult = true; 1317 1318 // if this was part of a split/deferral complex, update the refcount and only 1319 // send the completion when we clear all of them 1320 if (r.splitToken != 0) { 1321 int newCount = mSplitRefcounts.get(r.splitToken) - 1; 1322 if (newCount == 0) { 1323 // done! clear out this record's bookkeeping and deliver 1324 if (DEBUG_BROADCAST_DEFERRAL) { 1325 Slog.i(TAG_BROADCAST, 1326 "Sending broadcast completion for split token " 1327 + r.splitToken + " : " + r.intent.getAction()); 1328 } 1329 mSplitRefcounts.delete(r.splitToken); 1330 } else { 1331 // still have some split broadcast records in flight; update refcount 1332 // and hold off on the callback 1333 if (DEBUG_BROADCAST_DEFERRAL) { 1334 Slog.i(TAG_BROADCAST, 1335 "Result refcount now " + newCount + " for split token " 1336 + r.splitToken + " : " + r.intent.getAction() 1337 + " - not sending completion yet"); 1338 } 1339 sendResult = false; 1340 mSplitRefcounts.put(r.splitToken, newCount); 1341 } 1342 } 1343 if (sendResult) { 1344 if (r.callerApp != null) { 1345 mService.mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily( 1346 r.callerApp, OOM_ADJ_REASON_FINISH_RECEIVER); 1347 } 1348 try { 1349 if (DEBUG_BROADCAST) { 1350 Slog.i(TAG_BROADCAST, "Finishing broadcast [" + mQueueName + "] " 1351 + r.intent.getAction() + " app=" + r.callerApp); 1352 } 1353 if (r.dispatchTime == 0) { 1354 // The dispatch time here could be 0, in case it's a parallel 1355 // broadcast but it has a result receiver. Set it to now. 1356 r.dispatchTime = now; 1357 } 1358 r.mIsReceiverAppRunning = true; 1359 performReceiveLocked(r.callerApp, r.resultTo, 1360 new Intent(r.intent), r.resultCode, 1361 r.resultData, r.resultExtras, false, false, r.userId, 1362 r.callingUid, r.callingUid, 1363 r.dispatchTime - r.enqueueTime, 1364 now - r.dispatchTime); 1365 logBootCompletedBroadcastCompletionLatencyIfPossible(r); 1366 // Set this to null so that the reference 1367 // (local and remote) isn't kept in the mBroadcastHistory. 1368 r.resultTo = null; 1369 } catch (RemoteException e) { 1370 r.resultTo = null; 1371 Slog.w(TAG, "Failure [" 1372 + mQueueName + "] sending broadcast result of " 1373 + r.intent, e); 1374 } 1375 } 1376 } 1377 1378 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG"); 1379 cancelBroadcastTimeoutLocked(); 1380 1381 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, 1382 "Finished with ordered broadcast " + r); 1383 1384 // ... and on to the next... 1385 addBroadcastToHistoryLocked(r); 1386 if (r.intent.getComponent() == null && r.intent.getPackage() == null 1387 && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 1388 // This was an implicit broadcast... let's record it for posterity. 1389 mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage, 1390 r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime); 1391 } 1392 mDispatcher.retireBroadcastLocked(r); 1393 r = null; 1394 looped = true; 1395 continue; 1396 } 1397 1398 // Check whether the next receiver is under deferral policy, and handle that 1399 // accordingly. If the current broadcast was already part of deferred-delivery 1400 // tracking, we know that it must now be deliverable as-is without re-deferral. 1401 if (!r.deferred) { 1402 final int receiverUid = r.getReceiverUid(r.receivers.get(r.nextReceiver)); 1403 if (mDispatcher.isDeferringLocked(receiverUid)) { 1404 if (DEBUG_BROADCAST_DEFERRAL) { 1405 Slog.i(TAG_BROADCAST, "Next receiver in " + r + " uid " + receiverUid 1406 + " at " + r.nextReceiver + " is under deferral"); 1407 } 1408 // If this is the only (remaining) receiver in the broadcast, "splitting" 1409 // doesn't make sense -- just defer it as-is and retire it as the 1410 // currently active outgoing broadcast. 1411 BroadcastRecord defer; 1412 if (r.nextReceiver + 1 == numReceivers) { 1413 if (DEBUG_BROADCAST_DEFERRAL) { 1414 Slog.i(TAG_BROADCAST, "Sole receiver of " + r 1415 + " is under deferral; setting aside and proceeding"); 1416 } 1417 defer = r; 1418 mDispatcher.retireBroadcastLocked(r); 1419 } else { 1420 // Nontrivial case; split out 'uid's receivers to a new broadcast record 1421 // and defer that, then loop and pick up continuing delivery of the current 1422 // record (now absent those receivers). 1423 1424 // The split operation is guaranteed to match at least at 'nextReceiver' 1425 defer = r.splitRecipientsLocked(receiverUid, r.nextReceiver); 1426 if (DEBUG_BROADCAST_DEFERRAL) { 1427 Slog.i(TAG_BROADCAST, "Post split:"); 1428 Slog.i(TAG_BROADCAST, "Original broadcast receivers:"); 1429 for (int i = 0; i < r.receivers.size(); i++) { 1430 Slog.i(TAG_BROADCAST, " " + r.receivers.get(i)); 1431 } 1432 Slog.i(TAG_BROADCAST, "Split receivers:"); 1433 for (int i = 0; i < defer.receivers.size(); i++) { 1434 Slog.i(TAG_BROADCAST, " " + defer.receivers.get(i)); 1435 } 1436 } 1437 // Track completion refcount as well if relevant 1438 if (r.resultTo != null) { 1439 int token = r.splitToken; 1440 if (token == 0) { 1441 // first split of this record; refcount for 'r' and 'deferred' 1442 r.splitToken = defer.splitToken = nextSplitTokenLocked(); 1443 mSplitRefcounts.put(r.splitToken, 2); 1444 if (DEBUG_BROADCAST_DEFERRAL) { 1445 Slog.i(TAG_BROADCAST, 1446 "Broadcast needs split refcount; using new token " 1447 + r.splitToken); 1448 } 1449 } else { 1450 // new split from an already-refcounted situation; increment count 1451 final int curCount = mSplitRefcounts.get(token); 1452 if (DEBUG_BROADCAST_DEFERRAL) { 1453 if (curCount == 0) { 1454 Slog.wtf(TAG_BROADCAST, 1455 "Split refcount is zero with token for " + r); 1456 } 1457 } 1458 mSplitRefcounts.put(token, curCount + 1); 1459 if (DEBUG_BROADCAST_DEFERRAL) { 1460 Slog.i(TAG_BROADCAST, "New split count for token " + token 1461 + " is " + (curCount + 1)); 1462 } 1463 } 1464 } 1465 } 1466 mDispatcher.addDeferredBroadcast(receiverUid, defer); 1467 r = null; 1468 looped = true; 1469 continue; 1470 } 1471 } 1472 } while (r == null); 1473 1474 // Get the next receiver... 1475 int recIdx = r.nextReceiver++; 1476 1477 // Keep track of when this receiver started, and make sure there 1478 // is a timeout message pending to kill it if need be. 1479 r.receiverTime = SystemClock.uptimeMillis(); 1480 if (recIdx == 0) { 1481 r.dispatchTime = r.receiverTime; 1482 r.dispatchRealTime = SystemClock.elapsedRealtime(); 1483 r.dispatchClockTime = System.currentTimeMillis(); 1484 1485 if (mLogLatencyMetrics) { 1486 FrameworkStatsLog.write( 1487 FrameworkStatsLog.BROADCAST_DISPATCH_LATENCY_REPORTED, 1488 r.dispatchClockTime - r.enqueueClockTime); 1489 } 1490 1491 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 1492 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, 1493 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING), 1494 System.identityHashCode(r)); 1495 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, 1496 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED), 1497 System.identityHashCode(r)); 1498 } 1499 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast [" 1500 + mQueueName + "] " + r); 1501 } 1502 if (! mPendingBroadcastTimeoutMessage) { 1503 long timeoutTime = r.receiverTime + mConstants.TIMEOUT; 1504 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 1505 "Submitting BROADCAST_TIMEOUT_MSG [" 1506 + mQueueName + "] for " + r + " at " + timeoutTime); 1507 setBroadcastTimeoutLocked(timeoutTime); 1508 } 1509 1510 final BroadcastOptions brOptions = r.options; 1511 final Object nextReceiver = r.receivers.get(recIdx); 1512 1513 if (nextReceiver instanceof BroadcastFilter) { 1514 // Simple case: this is a registered receiver who gets 1515 // a direct call. 1516 BroadcastFilter filter = (BroadcastFilter)nextReceiver; 1517 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 1518 "Delivering ordered [" 1519 + mQueueName + "] to registered " 1520 + filter + ": " + r); 1521 r.mIsReceiverAppRunning = true; 1522 deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx); 1523 if (r.receiver == null || !r.ordered) { 1524 // The receiver has already finished, so schedule to 1525 // process the next one. 1526 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing [" 1527 + mQueueName + "]: ordered=" 1528 + r.ordered + " receiver=" + r.receiver); 1529 r.state = BroadcastRecord.IDLE; 1530 scheduleBroadcastsLocked(); 1531 } else { 1532 if (filter.receiverList != null) { 1533 maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r); 1534 // r is guaranteed ordered at this point, so we know finishReceiverLocked() 1535 // will get a callback and handle the activity start token lifecycle. 1536 } 1537 } 1538 return; 1539 } 1540 1541 // Hard case: need to instantiate the receiver, possibly 1542 // starting its application process to host it. 1543 1544 ResolveInfo info = 1545 (ResolveInfo)nextReceiver; 1546 ComponentName component = new ComponentName( 1547 info.activityInfo.applicationInfo.packageName, 1548 info.activityInfo.name); 1549 1550 boolean skip = false; 1551 if (brOptions != null && 1552 (info.activityInfo.applicationInfo.targetSdkVersion 1553 < brOptions.getMinManifestReceiverApiLevel() || 1554 info.activityInfo.applicationInfo.targetSdkVersion 1555 > brOptions.getMaxManifestReceiverApiLevel())) { 1556 Slog.w(TAG, "Target SDK mismatch: receiver " + info.activityInfo 1557 + " targets " + info.activityInfo.applicationInfo.targetSdkVersion 1558 + " but delivery restricted to [" 1559 + brOptions.getMinManifestReceiverApiLevel() + ", " 1560 + brOptions.getMaxManifestReceiverApiLevel() 1561 + "] broadcasting " + broadcastDescription(r, component)); 1562 skip = true; 1563 } 1564 if (brOptions != null && 1565 !brOptions.testRequireCompatChange(info.activityInfo.applicationInfo.uid)) { 1566 Slog.w(TAG, "Compat change filtered: broadcasting " + broadcastDescription(r, component) 1567 + " to uid " + info.activityInfo.applicationInfo.uid + " due to compat change " 1568 + r.options.getRequireCompatChangeId()); 1569 skip = true; 1570 } 1571 if (!skip && !mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid, 1572 component.getPackageName(), info.activityInfo.applicationInfo.uid)) { 1573 Slog.w(TAG, "Association not allowed: broadcasting " 1574 + broadcastDescription(r, component)); 1575 skip = true; 1576 } 1577 if (!skip) { 1578 skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid, 1579 r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid); 1580 if (skip) { 1581 Slog.w(TAG, "Firewall blocked: broadcasting " 1582 + broadcastDescription(r, component)); 1583 } 1584 } 1585 int perm = mService.checkComponentPermission(info.activityInfo.permission, 1586 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid, 1587 info.activityInfo.exported); 1588 if (!skip && perm != PackageManager.PERMISSION_GRANTED) { 1589 if (!info.activityInfo.exported) { 1590 Slog.w(TAG, "Permission Denial: broadcasting " 1591 + broadcastDescription(r, component) 1592 + " is not exported from uid " + info.activityInfo.applicationInfo.uid); 1593 } else { 1594 Slog.w(TAG, "Permission Denial: broadcasting " 1595 + broadcastDescription(r, component) 1596 + " requires " + info.activityInfo.permission); 1597 } 1598 skip = true; 1599 } else if (!skip && info.activityInfo.permission != null) { 1600 final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission); 1601 if (opCode != AppOpsManager.OP_NONE && mService.getAppOpsManager().noteOpNoThrow(opCode, 1602 r.callingUid, r.callerPackage, r.callerFeatureId, 1603 "Broadcast delivered to " + info.activityInfo.name) 1604 != AppOpsManager.MODE_ALLOWED) { 1605 Slog.w(TAG, "Appop Denial: broadcasting " 1606 + broadcastDescription(r, component) 1607 + " requires appop " + AppOpsManager.permissionToOp( 1608 info.activityInfo.permission)); 1609 skip = true; 1610 } 1611 } 1612 1613 boolean isSingleton = false; 1614 try { 1615 isSingleton = mService.isSingleton(info.activityInfo.processName, 1616 info.activityInfo.applicationInfo, 1617 info.activityInfo.name, info.activityInfo.flags); 1618 } catch (SecurityException e) { 1619 Slog.w(TAG, e.getMessage()); 1620 skip = true; 1621 } 1622 if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { 1623 if (ActivityManager.checkUidPermission( 1624 android.Manifest.permission.INTERACT_ACROSS_USERS, 1625 info.activityInfo.applicationInfo.uid) 1626 != PackageManager.PERMISSION_GRANTED) { 1627 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString() 1628 + " requests FLAG_SINGLE_USER, but app does not hold " 1629 + android.Manifest.permission.INTERACT_ACROSS_USERS); 1630 skip = true; 1631 } 1632 } 1633 if (!skip && info.activityInfo.applicationInfo.isInstantApp() 1634 && r.callingUid != info.activityInfo.applicationInfo.uid) { 1635 Slog.w(TAG, "Instant App Denial: receiving " 1636 + r.intent 1637 + " to " + component.flattenToShortString() 1638 + " due to sender " + r.callerPackage 1639 + " (uid " + r.callingUid + ")" 1640 + " Instant Apps do not support manifest receivers"); 1641 skip = true; 1642 } 1643 if (!skip && r.callerInstantApp 1644 && (info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0 1645 && r.callingUid != info.activityInfo.applicationInfo.uid) { 1646 Slog.w(TAG, "Instant App Denial: receiving " 1647 + r.intent 1648 + " to " + component.flattenToShortString() 1649 + " requires receiver have visibleToInstantApps set" 1650 + " due to sender " + r.callerPackage 1651 + " (uid " + r.callingUid + ")"); 1652 skip = true; 1653 } 1654 if (r.curApp != null && r.curApp.mErrorState.isCrashing()) { 1655 // If the target process is crashing, just skip it. 1656 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r 1657 + " to " + r.curApp + ": process crashing"); 1658 skip = true; 1659 } 1660 if (!skip) { 1661 boolean isAvailable = false; 1662 try { 1663 isAvailable = AppGlobals.getPackageManager().isPackageAvailable( 1664 info.activityInfo.packageName, 1665 UserHandle.getUserId(info.activityInfo.applicationInfo.uid)); 1666 } catch (Exception e) { 1667 // all such failures mean we skip this receiver 1668 Slog.w(TAG, "Exception getting recipient info for " 1669 + info.activityInfo.packageName, e); 1670 } 1671 if (!isAvailable) { 1672 Slog.w(TAG_BROADCAST, 1673 "Skipping delivery to " + info.activityInfo.packageName + " / " 1674 + info.activityInfo.applicationInfo.uid 1675 + " : package no longer available"); 1676 skip = true; 1677 } 1678 } 1679 1680 // If permissions need a review before any of the app components can run, we drop 1681 // the broadcast and if the calling app is in the foreground and the broadcast is 1682 // explicit we launch the review UI passing it a pending intent to send the skipped 1683 // broadcast. 1684 if (!skip) { 1685 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, 1686 info.activityInfo.packageName, UserHandle.getUserId( 1687 info.activityInfo.applicationInfo.uid))) { 1688 Slog.w(TAG_BROADCAST, 1689 "Skipping delivery: permission review required for " 1690 + broadcastDescription(r, component)); 1691 skip = true; 1692 } 1693 } 1694 1695 // This is safe to do even if we are skipping the broadcast, and we need 1696 // this information now to evaluate whether it is going to be allowed to run. 1697 final int receiverUid = info.activityInfo.applicationInfo.uid; 1698 // If it's a singleton, it needs to be the same app or a special app 1699 if (r.callingUid != Process.SYSTEM_UID && isSingleton 1700 && mService.isValidSingletonCall(r.callingUid, receiverUid)) { 1701 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0); 1702 } 1703 String targetProcess = info.activityInfo.processName; 1704 ProcessRecord app = mService.getProcessRecordLocked(targetProcess, 1705 info.activityInfo.applicationInfo.uid); 1706 1707 if (!skip) { 1708 final int allowed = mService.getAppStartModeLOSP( 1709 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName, 1710 info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false, false); 1711 if (allowed != ActivityManager.APP_START_MODE_NORMAL) { 1712 // We won't allow this receiver to be launched if the app has been 1713 // completely disabled from launches, or it was not explicitly sent 1714 // to it and the app is in a state that should not receive it 1715 // (depending on how getAppStartModeLOSP has determined that). 1716 if (allowed == ActivityManager.APP_START_MODE_DISABLED) { 1717 Slog.w(TAG, "Background execution disabled: receiving " 1718 + r.intent + " to " 1719 + component.flattenToShortString()); 1720 skip = true; 1721 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0) 1722 || (r.intent.getComponent() == null 1723 && r.intent.getPackage() == null 1724 && ((r.intent.getFlags() 1725 & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0) 1726 && !isSignaturePerm(r.requiredPermissions))) { 1727 mService.addBackgroundCheckViolationLocked(r.intent.getAction(), 1728 component.getPackageName()); 1729 Slog.w(TAG, "Background execution not allowed: receiving " 1730 + r.intent + " to " 1731 + component.flattenToShortString()); 1732 skip = true; 1733 } 1734 } 1735 } 1736 1737 if (!skip && !Intent.ACTION_SHUTDOWN.equals(r.intent.getAction()) 1738 && !mService.mUserController 1739 .isUserRunning(UserHandle.getUserId(info.activityInfo.applicationInfo.uid), 1740 0 /* flags */)) { 1741 skip = true; 1742 Slog.w(TAG, 1743 "Skipping delivery to " + info.activityInfo.packageName + " / " 1744 + info.activityInfo.applicationInfo.uid + " : user is not running"); 1745 } 1746 1747 if (!skip && r.excludedPermissions != null && r.excludedPermissions.length > 0) { 1748 for (int i = 0; i < r.excludedPermissions.length; i++) { 1749 String excludedPermission = r.excludedPermissions[i]; 1750 try { 1751 perm = AppGlobals.getPackageManager() 1752 .checkPermission(excludedPermission, 1753 info.activityInfo.applicationInfo.packageName, 1754 UserHandle 1755 .getUserId(info.activityInfo.applicationInfo.uid)); 1756 } catch (RemoteException e) { 1757 perm = PackageManager.PERMISSION_DENIED; 1758 } 1759 1760 int appOp = AppOpsManager.permissionToOpCode(excludedPermission); 1761 if (appOp != AppOpsManager.OP_NONE) { 1762 // When there is an app op associated with the permission, 1763 // skip when both the permission and the app op are 1764 // granted. 1765 if ((perm == PackageManager.PERMISSION_GRANTED) && ( 1766 mService.getAppOpsManager().checkOpNoThrow(appOp, 1767 info.activityInfo.applicationInfo.uid, 1768 info.activityInfo.packageName) 1769 == AppOpsManager.MODE_ALLOWED)) { 1770 skip = true; 1771 break; 1772 } 1773 } else { 1774 // When there is no app op associated with the permission, 1775 // skip when permission is granted. 1776 if (perm == PackageManager.PERMISSION_GRANTED) { 1777 skip = true; 1778 break; 1779 } 1780 } 1781 } 1782 } 1783 1784 // Check that the receiver does *not* belong to any of the excluded packages 1785 if (!skip && r.excludedPackages != null && r.excludedPackages.length > 0) { 1786 if (ArrayUtils.contains(r.excludedPackages, component.getPackageName())) { 1787 Slog.w(TAG, "Skipping delivery of excluded package " 1788 + r.intent + " to " 1789 + component.flattenToShortString() 1790 + " excludes package " + component.getPackageName() 1791 + " due to sender " + r.callerPackage 1792 + " (uid " + r.callingUid + ")"); 1793 skip = true; 1794 } 1795 } 1796 1797 if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID && 1798 r.requiredPermissions != null && r.requiredPermissions.length > 0) { 1799 for (int i = 0; i < r.requiredPermissions.length; i++) { 1800 String requiredPermission = r.requiredPermissions[i]; 1801 try { 1802 perm = AppGlobals.getPackageManager(). 1803 checkPermission(requiredPermission, 1804 info.activityInfo.applicationInfo.packageName, 1805 UserHandle 1806 .getUserId(info.activityInfo.applicationInfo.uid)); 1807 } catch (RemoteException e) { 1808 perm = PackageManager.PERMISSION_DENIED; 1809 } 1810 if (perm != PackageManager.PERMISSION_GRANTED) { 1811 Slog.w(TAG, "Permission Denial: receiving " 1812 + r.intent + " to " 1813 + component.flattenToShortString() 1814 + " requires " + requiredPermission 1815 + " due to sender " + r.callerPackage 1816 + " (uid " + r.callingUid + ")"); 1817 skip = true; 1818 break; 1819 } 1820 int appOp = AppOpsManager.permissionToOpCode(requiredPermission); 1821 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp) { 1822 if (!noteOpForManifestReceiver(appOp, r, info, component)) { 1823 skip = true; 1824 break; 1825 } 1826 } 1827 } 1828 } 1829 if (!skip && r.appOp != AppOpsManager.OP_NONE) { 1830 if (!noteOpForManifestReceiver(r.appOp, r, info, component)) { 1831 skip = true; 1832 } 1833 } 1834 1835 if (skip) { 1836 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 1837 "Skipping delivery of ordered [" + mQueueName + "] " 1838 + r + " for reason described above"); 1839 r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED; 1840 r.receiver = null; 1841 r.curFilter = null; 1842 r.state = BroadcastRecord.IDLE; 1843 r.manifestSkipCount++; 1844 scheduleBroadcastsLocked(); 1845 return; 1846 } 1847 r.manifestCount++; 1848 1849 r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED; 1850 r.state = BroadcastRecord.APP_RECEIVE; 1851 r.curComponent = component; 1852 r.curReceiver = info.activityInfo; 1853 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) { 1854 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, " 1855 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = " 1856 + receiverUid); 1857 } 1858 final boolean isActivityCapable = 1859 (brOptions != null && brOptions.getTemporaryAppAllowlistDuration() > 0); 1860 maybeScheduleTempAllowlistLocked(receiverUid, r, brOptions); 1861 1862 // Report that a component is used for explicit broadcasts. 1863 if (r.intent.getComponent() != null && r.curComponent != null 1864 && !TextUtils.equals(r.curComponent.getPackageName(), r.callerPackage)) { 1865 mService.mUsageStatsService.reportEvent( 1866 r.curComponent.getPackageName(), r.userId, Event.APP_COMPONENT_USED); 1867 } 1868 1869 // Broadcast is being executed, its package can't be stopped. 1870 try { 1871 AppGlobals.getPackageManager().setPackageStoppedState( 1872 r.curComponent.getPackageName(), false, r.userId); 1873 } catch (RemoteException e) { 1874 } catch (IllegalArgumentException e) { 1875 Slog.w(TAG, "Failed trying to unstop package " 1876 + r.curComponent.getPackageName() + ": " + e); 1877 } 1878 1879 // Is this receiver's application already running? 1880 if (app != null && app.getThread() != null && !app.isKilled()) { 1881 try { 1882 app.addPackage(info.activityInfo.packageName, 1883 info.activityInfo.applicationInfo.longVersionCode, mService.mProcessStats); 1884 maybeAddAllowBackgroundActivityStartsToken(app, r); 1885 r.mIsReceiverAppRunning = true; 1886 processCurBroadcastLocked(r, app); 1887 return; 1888 } catch (RemoteException e) { 1889 final String msg = "Failed to schedule " + r.intent + " to " + info 1890 + " via " + app + ": " + e; 1891 Slog.w(TAG, msg); 1892 app.killLocked("Can't deliver broadcast", ApplicationExitInfo.REASON_OTHER, 1893 ApplicationExitInfo.SUBREASON_UNDELIVERED_BROADCAST, true); 1894 } catch (RuntimeException e) { 1895 Slog.wtf(TAG, "Failed sending broadcast to " 1896 + r.curComponent + " with " + r.intent, e); 1897 // If some unexpected exception happened, just skip 1898 // this broadcast. At this point we are not in the call 1899 // from a client, so throwing an exception out from here 1900 // will crash the entire system instead of just whoever 1901 // sent the broadcast. 1902 logBroadcastReceiverDiscardLocked(r); 1903 finishReceiverLocked(r, r.resultCode, r.resultData, 1904 r.resultExtras, r.resultAbort, false); 1905 scheduleBroadcastsLocked(); 1906 // We need to reset the state if we failed to start the receiver. 1907 r.state = BroadcastRecord.IDLE; 1908 return; 1909 } 1910 1911 // If a dead object exception was thrown -- fall through to 1912 // restart the application. 1913 } 1914 1915 // Not running -- get it started, to be executed when the app comes up. 1916 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 1917 "Need to start app [" 1918 + mQueueName + "] " + targetProcess + " for broadcast " + r); 1919 r.curApp = mService.startProcessLocked(targetProcess, 1920 info.activityInfo.applicationInfo, true, 1921 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND, 1922 new HostingRecord(HostingRecord.HOSTING_TYPE_BROADCAST, r.curComponent, 1923 r.intent.getAction(), getHostingRecordTriggerType(r)), 1924 isActivityCapable ? ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE : ZYGOTE_POLICY_FLAG_EMPTY, 1925 (r.intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false); 1926 if (r.curApp == null) { 1927 // Ah, this recipient is unavailable. Finish it if necessary, 1928 // and mark the broadcast record as ready for the next. 1929 Slog.w(TAG, "Unable to launch app " 1930 + info.activityInfo.applicationInfo.packageName + "/" 1931 + receiverUid + " for broadcast " 1932 + r.intent + ": process is bad"); 1933 logBroadcastReceiverDiscardLocked(r); 1934 finishReceiverLocked(r, r.resultCode, r.resultData, 1935 r.resultExtras, r.resultAbort, false); 1936 scheduleBroadcastsLocked(); 1937 r.state = BroadcastRecord.IDLE; 1938 return; 1939 } 1940 1941 maybeAddAllowBackgroundActivityStartsToken(r.curApp, r); 1942 mPendingBroadcast = r; 1943 mPendingBroadcastRecvIndex = recIdx; 1944 } 1945 getHostingRecordTriggerType(BroadcastRecord r)1946 private String getHostingRecordTriggerType(BroadcastRecord r) { 1947 if (r.alarm) { 1948 return HostingRecord.TRIGGER_TYPE_ALARM; 1949 } else if (r.pushMessage) { 1950 return HostingRecord.TRIGGER_TYPE_PUSH_MESSAGE; 1951 } else if (r.pushMessageOverQuota) { 1952 return HostingRecord.TRIGGER_TYPE_PUSH_MESSAGE_OVER_QUOTA; 1953 } 1954 return HostingRecord.TRIGGER_TYPE_UNKNOWN; 1955 } 1956 1957 @Nullable getTargetPackage(BroadcastRecord r)1958 private String getTargetPackage(BroadcastRecord r) { 1959 if (r.intent == null) { 1960 return null; 1961 } 1962 if (r.intent.getPackage() != null) { 1963 return r.intent.getPackage(); 1964 } else if (r.intent.getComponent() != null) { 1965 return r.intent.getComponent().getPackageName(); 1966 } 1967 return null; 1968 } 1969 logBootCompletedBroadcastCompletionLatencyIfPossible(BroadcastRecord r)1970 private void logBootCompletedBroadcastCompletionLatencyIfPossible(BroadcastRecord r) { 1971 // Only log after last receiver. 1972 // In case of split BOOT_COMPLETED broadcast, make sure only call this method on the 1973 // last BroadcastRecord of the split broadcast which has non-null resultTo. 1974 final int numReceivers = (r.receivers != null) ? r.receivers.size() : 0; 1975 if (r.nextReceiver < numReceivers) { 1976 return; 1977 } 1978 final String action = r.intent.getAction(); 1979 int event = 0; 1980 if (Intent.ACTION_LOCKED_BOOT_COMPLETED.equals(action)) { 1981 event = BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__LOCKED_BOOT_COMPLETED; 1982 } else if (Intent.ACTION_BOOT_COMPLETED.equals(action)) { 1983 event = BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__BOOT_COMPLETED; 1984 } 1985 if (event != 0) { 1986 final int dispatchLatency = (int)(r.dispatchTime - r.enqueueTime); 1987 final int completeLatency = (int) 1988 (SystemClock.uptimeMillis() - r.enqueueTime); 1989 final int dispatchRealLatency = (int)(r.dispatchRealTime - r.enqueueRealTime); 1990 final int completeRealLatency = (int) 1991 (SystemClock.elapsedRealtime() - r.enqueueRealTime); 1992 int userType = FrameworkStatsLog.USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__TYPE_UNKNOWN; 1993 // This method is called very infrequently, no performance issue we call 1994 // LocalServices.getService() here. 1995 final UserManagerInternal umInternal = LocalServices.getService( 1996 UserManagerInternal.class); 1997 final UserInfo userInfo = umInternal.getUserInfo(r.userId); 1998 if (userInfo != null) { 1999 userType = UserManager.getUserTypeForStatsd(userInfo.userType); 2000 } 2001 Slog.i(TAG_BROADCAST, 2002 "BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED action:" 2003 + action 2004 + " dispatchLatency:" + dispatchLatency 2005 + " completeLatency:" + completeLatency 2006 + " dispatchRealLatency:" + dispatchRealLatency 2007 + " completeRealLatency:" + completeRealLatency 2008 + " receiversSize:" + numReceivers 2009 + " userId:" + r.userId 2010 + " userType:" + (userInfo != null? userInfo.userType : null)); 2011 FrameworkStatsLog.write( 2012 BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED, 2013 event, 2014 dispatchLatency, 2015 completeLatency, 2016 dispatchRealLatency, 2017 completeRealLatency, 2018 r.userId, 2019 userType); 2020 } 2021 } 2022 maybeReportBroadcastDispatchedEventLocked(BroadcastRecord r, int targetUid)2023 private void maybeReportBroadcastDispatchedEventLocked(BroadcastRecord r, int targetUid) { 2024 if (r.options == null || r.options.getIdForResponseEvent() <= 0) { 2025 return; 2026 } 2027 final String targetPackage = getTargetPackage(r); 2028 // Ignore non-explicit broadcasts 2029 if (targetPackage == null) { 2030 return; 2031 } 2032 getUsageStatsManagerInternal().reportBroadcastDispatched( 2033 r.callingUid, targetPackage, UserHandle.of(r.userId), 2034 r.options.getIdForResponseEvent(), SystemClock.elapsedRealtime(), 2035 mService.getUidStateLocked(targetUid)); 2036 } 2037 2038 @NonNull getUsageStatsManagerInternal()2039 private UsageStatsManagerInternal getUsageStatsManagerInternal() { 2040 final UsageStatsManagerInternal usageStatsManagerInternal = 2041 LocalServices.getService(UsageStatsManagerInternal.class); 2042 return usageStatsManagerInternal; 2043 } 2044 noteOpForManifestReceiver(int appOp, BroadcastRecord r, ResolveInfo info, ComponentName component)2045 private boolean noteOpForManifestReceiver(int appOp, BroadcastRecord r, ResolveInfo info, 2046 ComponentName component) { 2047 if (ArrayUtils.isEmpty(info.activityInfo.attributionTags)) { 2048 return noteOpForManifestReceiverInner(appOp, r, info, component, null); 2049 } else { 2050 // Attribution tags provided, noteOp each tag 2051 for (String tag : info.activityInfo.attributionTags) { 2052 if (!noteOpForManifestReceiverInner(appOp, r, info, component, tag)) { 2053 return false; 2054 } 2055 } 2056 return true; 2057 } 2058 } 2059 noteOpForManifestReceiverInner(int appOp, BroadcastRecord r, ResolveInfo info, ComponentName component, String tag)2060 private boolean noteOpForManifestReceiverInner(int appOp, BroadcastRecord r, ResolveInfo info, 2061 ComponentName component, String tag) { 2062 if (mService.getAppOpsManager().noteOpNoThrow(appOp, 2063 info.activityInfo.applicationInfo.uid, 2064 info.activityInfo.packageName, 2065 tag, 2066 "Broadcast delivered to " + info.activityInfo.name) 2067 != AppOpsManager.MODE_ALLOWED) { 2068 Slog.w(TAG, "Appop Denial: receiving " 2069 + r.intent + " to " 2070 + component.flattenToShortString() 2071 + " requires appop " + AppOpsManager.opToName(appOp) 2072 + " due to sender " + r.callerPackage 2073 + " (uid " + r.callingUid + ")"); 2074 return false; 2075 } 2076 return true; 2077 } 2078 maybeAddAllowBackgroundActivityStartsToken(ProcessRecord proc, BroadcastRecord r)2079 private void maybeAddAllowBackgroundActivityStartsToken(ProcessRecord proc, BroadcastRecord r) { 2080 if (r == null || proc == null || !r.allowBackgroundActivityStarts) { 2081 return; 2082 } 2083 String msgToken = (proc.toShortString() + r.toString()).intern(); 2084 // first, if there exists a past scheduled request to remove this token, drop 2085 // that request - we don't want the token to be swept from under our feet... 2086 mHandler.removeCallbacksAndMessages(msgToken); 2087 // ...then add the token 2088 proc.addOrUpdateAllowBackgroundActivityStartsToken(r, r.mBackgroundActivityStartsToken); 2089 } 2090 setBroadcastTimeoutLocked(long timeoutTime)2091 final void setBroadcastTimeoutLocked(long timeoutTime) { 2092 if (! mPendingBroadcastTimeoutMessage) { 2093 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this); 2094 mHandler.sendMessageAtTime(msg, timeoutTime); 2095 mPendingBroadcastTimeoutMessage = true; 2096 } 2097 } 2098 cancelBroadcastTimeoutLocked()2099 final void cancelBroadcastTimeoutLocked() { 2100 if (mPendingBroadcastTimeoutMessage) { 2101 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this); 2102 mPendingBroadcastTimeoutMessage = false; 2103 } 2104 } 2105 broadcastTimeoutLocked(boolean fromMsg)2106 final void broadcastTimeoutLocked(boolean fromMsg) { 2107 if (fromMsg) { 2108 mPendingBroadcastTimeoutMessage = false; 2109 } 2110 2111 if (mDispatcher.isEmpty() || mDispatcher.getActiveBroadcastLocked() == null) { 2112 return; 2113 } 2114 2115 long now = SystemClock.uptimeMillis(); 2116 BroadcastRecord r = mDispatcher.getActiveBroadcastLocked(); 2117 if (fromMsg) { 2118 if (!mService.mProcessesReady) { 2119 // Only process broadcast timeouts if the system is ready; some early 2120 // broadcasts do heavy work setting up system facilities 2121 return; 2122 } 2123 2124 // If the broadcast is generally exempt from timeout tracking, we're done 2125 if (r.timeoutExempt) { 2126 if (DEBUG_BROADCAST) { 2127 Slog.i(TAG_BROADCAST, "Broadcast timeout but it's exempt: " 2128 + r.intent.getAction()); 2129 } 2130 return; 2131 } 2132 2133 long timeoutTime = r.receiverTime + mConstants.TIMEOUT; 2134 if (timeoutTime > now) { 2135 // We can observe premature timeouts because we do not cancel and reset the 2136 // broadcast timeout message after each receiver finishes. Instead, we set up 2137 // an initial timeout then kick it down the road a little further as needed 2138 // when it expires. 2139 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 2140 "Premature timeout [" 2141 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for " 2142 + timeoutTime); 2143 setBroadcastTimeoutLocked(timeoutTime); 2144 return; 2145 } 2146 } 2147 2148 if (r.state == BroadcastRecord.WAITING_SERVICES) { 2149 // In this case the broadcast had already finished, but we had decided to wait 2150 // for started services to finish as well before going on. So if we have actually 2151 // waited long enough time timeout the broadcast, let's give up on the whole thing 2152 // and just move on to the next. 2153 Slog.i(TAG, "Waited long enough for: " + (r.curComponent != null 2154 ? r.curComponent.flattenToShortString() : "(null)")); 2155 r.curComponent = null; 2156 r.state = BroadcastRecord.IDLE; 2157 processNextBroadcastLocked(false, false); 2158 return; 2159 } 2160 2161 // If the receiver app is being debugged we quietly ignore unresponsiveness, just 2162 // tidying up and moving on to the next broadcast without crashing or ANRing this 2163 // app just because it's stopped at a breakpoint. 2164 final boolean debugging = (r.curApp != null && r.curApp.isDebugging()); 2165 2166 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver 2167 + ", started " + (now - r.receiverTime) + "ms ago"); 2168 r.receiverTime = now; 2169 if (!debugging) { 2170 r.anrCount++; 2171 } 2172 2173 ProcessRecord app = null; 2174 String anrMessage = null; 2175 2176 Object curReceiver; 2177 if (r.nextReceiver > 0) { 2178 curReceiver = r.receivers.get(r.nextReceiver-1); 2179 r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT; 2180 } else { 2181 curReceiver = r.curReceiver; 2182 } 2183 Slog.w(TAG, "Receiver during timeout of " + r + " : " + curReceiver); 2184 logBroadcastReceiverDiscardLocked(r); 2185 if (curReceiver != null && curReceiver instanceof BroadcastFilter) { 2186 BroadcastFilter bf = (BroadcastFilter)curReceiver; 2187 if (bf.receiverList.pid != 0 2188 && bf.receiverList.pid != ActivityManagerService.MY_PID) { 2189 synchronized (mService.mPidsSelfLocked) { 2190 app = mService.mPidsSelfLocked.get( 2191 bf.receiverList.pid); 2192 } 2193 } 2194 } else { 2195 app = r.curApp; 2196 } 2197 2198 if (app != null) { 2199 anrMessage = "Broadcast of " + r.intent.toString(); 2200 } 2201 2202 if (mPendingBroadcast == r) { 2203 mPendingBroadcast = null; 2204 } 2205 2206 // Move on to the next receiver. 2207 finishReceiverLocked(r, r.resultCode, r.resultData, 2208 r.resultExtras, r.resultAbort, false); 2209 scheduleBroadcastsLocked(); 2210 2211 if (!debugging && anrMessage != null) { 2212 mService.mAnrHelper.appNotResponding(app, anrMessage); 2213 } 2214 } 2215 ringAdvance(int x, final int increment, final int ringSize)2216 private final int ringAdvance(int x, final int increment, final int ringSize) { 2217 x += increment; 2218 if (x < 0) return (ringSize - 1); 2219 else if (x >= ringSize) return 0; 2220 else return x; 2221 } 2222 addBroadcastToHistoryLocked(BroadcastRecord original)2223 private final void addBroadcastToHistoryLocked(BroadcastRecord original) { 2224 if (original.callingUid < 0) { 2225 // This was from a registerReceiver() call; ignore it. 2226 return; 2227 } 2228 original.finishTime = SystemClock.uptimeMillis(); 2229 2230 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 2231 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, 2232 createBroadcastTraceTitle(original, BroadcastRecord.DELIVERY_DELIVERED), 2233 System.identityHashCode(original)); 2234 } 2235 2236 final ApplicationInfo info = original.callerApp != null ? original.callerApp.info : null; 2237 final String callerPackage = info != null ? info.packageName : original.callerPackage; 2238 if (callerPackage != null) { 2239 mService.mHandler.obtainMessage(ActivityManagerService.DISPATCH_SENDING_BROADCAST_EVENT, 2240 original.callingUid, 0, callerPackage).sendToTarget(); 2241 } 2242 2243 // Note sometimes (only for sticky broadcasts?) we reuse BroadcastRecords, 2244 // So don't change the incoming record directly. 2245 final BroadcastRecord historyRecord = original.maybeStripForHistory(); 2246 2247 mBroadcastHistory[mHistoryNext] = historyRecord; 2248 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY); 2249 2250 mBroadcastSummaryHistory[mSummaryHistoryNext] = historyRecord.intent; 2251 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = historyRecord.enqueueClockTime; 2252 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = historyRecord.dispatchClockTime; 2253 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis(); 2254 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY); 2255 } 2256 cleanupDisabledPackageReceiversLocked( String packageName, Set<String> filterByClasses, int userId, boolean doit)2257 boolean cleanupDisabledPackageReceiversLocked( 2258 String packageName, Set<String> filterByClasses, int userId, boolean doit) { 2259 boolean didSomething = false; 2260 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) { 2261 didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked( 2262 packageName, filterByClasses, userId, doit); 2263 if (!doit && didSomething) { 2264 return true; 2265 } 2266 } 2267 2268 didSomething |= mDispatcher.cleanupDisabledPackageReceiversLocked(packageName, 2269 filterByClasses, userId, doit); 2270 2271 return didSomething; 2272 } 2273 logBroadcastReceiverDiscardLocked(BroadcastRecord r)2274 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) { 2275 final int logIndex = r.nextReceiver - 1; 2276 if (logIndex >= 0 && logIndex < r.receivers.size()) { 2277 Object curReceiver = r.receivers.get(logIndex); 2278 if (curReceiver instanceof BroadcastFilter) { 2279 BroadcastFilter bf = (BroadcastFilter) curReceiver; 2280 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER, 2281 bf.owningUserId, System.identityHashCode(r), 2282 r.intent.getAction(), logIndex, System.identityHashCode(bf)); 2283 } else { 2284 ResolveInfo ri = (ResolveInfo) curReceiver; 2285 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP, 2286 UserHandle.getUserId(ri.activityInfo.applicationInfo.uid), 2287 System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString()); 2288 } 2289 } else { 2290 if (logIndex < 0) Slog.w(TAG, 2291 "Discarding broadcast before first receiver is invoked: " + r); 2292 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP, 2293 -1, System.identityHashCode(r), 2294 r.intent.getAction(), 2295 r.nextReceiver, 2296 "NONE"); 2297 } 2298 } 2299 createBroadcastTraceTitle(BroadcastRecord record, int state)2300 private String createBroadcastTraceTitle(BroadcastRecord record, int state) { 2301 return formatSimple("Broadcast %s from %s (%s) %s", 2302 state == BroadcastRecord.DELIVERY_PENDING ? "in queue" : "dispatched", 2303 record.callerPackage == null ? "" : record.callerPackage, 2304 record.callerApp == null ? "process unknown" : record.callerApp.toShortString(), 2305 record.intent == null ? "" : record.intent.getAction()); 2306 } 2307 isIdle()2308 boolean isIdle() { 2309 return mParallelBroadcasts.isEmpty() && mDispatcher.isIdle() 2310 && (mPendingBroadcast == null); 2311 } 2312 2313 // Used by wait-for-broadcast-idle : fast-forward all current deferrals to 2314 // be immediately deliverable. cancelDeferrals()2315 void cancelDeferrals() { 2316 synchronized (mService) { 2317 mDispatcher.cancelDeferralsLocked(); 2318 scheduleBroadcastsLocked(); 2319 } 2320 } 2321 describeState()2322 String describeState() { 2323 synchronized (mService) { 2324 return mParallelBroadcasts.size() + " parallel; " 2325 + mDispatcher.describeStateLocked(); 2326 } 2327 } 2328 dumpDebug(ProtoOutputStream proto, long fieldId)2329 void dumpDebug(ProtoOutputStream proto, long fieldId) { 2330 long token = proto.start(fieldId); 2331 proto.write(BroadcastQueueProto.QUEUE_NAME, mQueueName); 2332 int N; 2333 N = mParallelBroadcasts.size(); 2334 for (int i = N - 1; i >= 0; i--) { 2335 mParallelBroadcasts.get(i).dumpDebug(proto, BroadcastQueueProto.PARALLEL_BROADCASTS); 2336 } 2337 mDispatcher.dumpDebug(proto, BroadcastQueueProto.ORDERED_BROADCASTS); 2338 if (mPendingBroadcast != null) { 2339 mPendingBroadcast.dumpDebug(proto, BroadcastQueueProto.PENDING_BROADCAST); 2340 } 2341 2342 int lastIndex = mHistoryNext; 2343 int ringIndex = lastIndex; 2344 do { 2345 // increasing index = more recent entry, and we want to print the most 2346 // recent first and work backwards, so we roll through the ring backwards. 2347 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY); 2348 BroadcastRecord r = mBroadcastHistory[ringIndex]; 2349 if (r != null) { 2350 r.dumpDebug(proto, BroadcastQueueProto.HISTORICAL_BROADCASTS); 2351 } 2352 } while (ringIndex != lastIndex); 2353 2354 lastIndex = ringIndex = mSummaryHistoryNext; 2355 do { 2356 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY); 2357 Intent intent = mBroadcastSummaryHistory[ringIndex]; 2358 if (intent == null) { 2359 continue; 2360 } 2361 long summaryToken = proto.start(BroadcastQueueProto.HISTORICAL_BROADCASTS_SUMMARY); 2362 intent.dumpDebug(proto, BroadcastQueueProto.BroadcastSummary.INTENT, 2363 false, true, true, false); 2364 proto.write(BroadcastQueueProto.BroadcastSummary.ENQUEUE_CLOCK_TIME_MS, 2365 mSummaryHistoryEnqueueTime[ringIndex]); 2366 proto.write(BroadcastQueueProto.BroadcastSummary.DISPATCH_CLOCK_TIME_MS, 2367 mSummaryHistoryDispatchTime[ringIndex]); 2368 proto.write(BroadcastQueueProto.BroadcastSummary.FINISH_CLOCK_TIME_MS, 2369 mSummaryHistoryFinishTime[ringIndex]); 2370 proto.end(summaryToken); 2371 } while (ringIndex != lastIndex); 2372 proto.end(token); 2373 } 2374 dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, boolean needSep)2375 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args, 2376 int opti, boolean dumpAll, String dumpPackage, boolean needSep) { 2377 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); 2378 if (!mParallelBroadcasts.isEmpty() || !mDispatcher.isEmpty() 2379 || mPendingBroadcast != null) { 2380 boolean printed = false; 2381 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) { 2382 BroadcastRecord br = mParallelBroadcasts.get(i); 2383 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) { 2384 continue; 2385 } 2386 if (!printed) { 2387 if (needSep) { 2388 pw.println(); 2389 } 2390 needSep = true; 2391 printed = true; 2392 pw.println(" Active broadcasts [" + mQueueName + "]:"); 2393 } 2394 pw.println(" Active Broadcast " + mQueueName + " #" + i + ":"); 2395 br.dump(pw, " ", sdf); 2396 } 2397 2398 mDispatcher.dumpLocked(pw, dumpPackage, mQueueName, sdf); 2399 2400 if (dumpPackage == null || (mPendingBroadcast != null 2401 && dumpPackage.equals(mPendingBroadcast.callerPackage))) { 2402 pw.println(); 2403 pw.println(" Pending broadcast [" + mQueueName + "]:"); 2404 if (mPendingBroadcast != null) { 2405 mPendingBroadcast.dump(pw, " ", sdf); 2406 } else { 2407 pw.println(" (null)"); 2408 } 2409 needSep = true; 2410 } 2411 } 2412 2413 mConstants.dump(pw); 2414 2415 int i; 2416 boolean printed = false; 2417 2418 i = -1; 2419 int lastIndex = mHistoryNext; 2420 int ringIndex = lastIndex; 2421 do { 2422 // increasing index = more recent entry, and we want to print the most 2423 // recent first and work backwards, so we roll through the ring backwards. 2424 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY); 2425 BroadcastRecord r = mBroadcastHistory[ringIndex]; 2426 if (r == null) { 2427 continue; 2428 } 2429 2430 i++; // genuine record of some sort even if we're filtering it out 2431 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) { 2432 continue; 2433 } 2434 if (!printed) { 2435 if (needSep) { 2436 pw.println(); 2437 } 2438 needSep = true; 2439 pw.println(" Historical broadcasts [" + mQueueName + "]:"); 2440 printed = true; 2441 } 2442 if (dumpAll) { 2443 pw.print(" Historical Broadcast " + mQueueName + " #"); 2444 pw.print(i); pw.println(":"); 2445 r.dump(pw, " ", sdf); 2446 } else { 2447 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r); 2448 pw.print(" "); 2449 pw.println(r.intent.toShortString(false, true, true, false)); 2450 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) { 2451 pw.print(" targetComp: "); pw.println(r.targetComp.toShortString()); 2452 } 2453 Bundle bundle = r.intent.getExtras(); 2454 if (bundle != null) { 2455 pw.print(" extras: "); pw.println(bundle.toString()); 2456 } 2457 } 2458 } while (ringIndex != lastIndex); 2459 2460 if (dumpPackage == null) { 2461 lastIndex = ringIndex = mSummaryHistoryNext; 2462 if (dumpAll) { 2463 printed = false; 2464 i = -1; 2465 } else { 2466 // roll over the 'i' full dumps that have already been issued 2467 for (int j = i; 2468 j > 0 && ringIndex != lastIndex;) { 2469 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY); 2470 BroadcastRecord r = mBroadcastHistory[ringIndex]; 2471 if (r == null) { 2472 continue; 2473 } 2474 j--; 2475 } 2476 } 2477 // done skipping; dump the remainder of the ring. 'i' is still the ordinal within 2478 // the overall broadcast history. 2479 do { 2480 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY); 2481 Intent intent = mBroadcastSummaryHistory[ringIndex]; 2482 if (intent == null) { 2483 continue; 2484 } 2485 if (!printed) { 2486 if (needSep) { 2487 pw.println(); 2488 } 2489 needSep = true; 2490 pw.println(" Historical broadcasts summary [" + mQueueName + "]:"); 2491 printed = true; 2492 } 2493 if (!dumpAll && i >= 50) { 2494 pw.println(" ..."); 2495 break; 2496 } 2497 i++; 2498 pw.print(" #"); pw.print(i); pw.print(": "); 2499 pw.println(intent.toShortString(false, true, true, false)); 2500 pw.print(" "); 2501 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex] 2502 - mSummaryHistoryEnqueueTime[ringIndex], pw); 2503 pw.print(" dispatch "); 2504 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex] 2505 - mSummaryHistoryDispatchTime[ringIndex], pw); 2506 pw.println(" finish"); 2507 pw.print(" enq="); 2508 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex]))); 2509 pw.print(" disp="); 2510 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex]))); 2511 pw.print(" fin="); 2512 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex]))); 2513 Bundle bundle = intent.getExtras(); 2514 if (bundle != null) { 2515 pw.print(" extras: "); pw.println(bundle.toString()); 2516 } 2517 } while (ringIndex != lastIndex); 2518 } 2519 2520 return needSep; 2521 } 2522 } 2523