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