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