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