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