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