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