BroadcastQueue.java revision 27c073796978106746e4a51f2100b29068ab37f6
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 560 if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid, 561 r.callingPid, r.resolvedType, filter.receiverList.uid)) { 562 return; 563 } 564 565 if (filter.receiverList.app == null || filter.receiverList.app.crashing) { 566 Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r 567 + " to " + filter.receiverList + ": process crashing"); 568 skip = true; 569 } 570 571 if (!skip) { 572 // If this is not being sent as an ordered broadcast, then we 573 // don't want to touch the fields that keep track of the current 574 // state of ordered broadcasts. 575 if (ordered) { 576 r.receiver = filter.receiverList.receiver.asBinder(); 577 r.curFilter = filter; 578 filter.receiverList.curBroadcast = r; 579 r.state = BroadcastRecord.CALL_IN_RECEIVE; 580 if (filter.receiverList.app != null) { 581 // Bump hosting application to no longer be in background 582 // scheduling class. Note that we can't do that if there 583 // isn't an app... but we can only be in that case for 584 // things that directly call the IActivityManager API, which 585 // are already core system stuff so don't matter for this. 586 r.curApp = filter.receiverList.app; 587 filter.receiverList.app.curReceiver = r; 588 mService.updateOomAdjLocked(r.curApp); 589 } 590 } 591 try { 592 if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST, 593 "Delivering to " + filter + " : " + r); 594 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver, 595 new Intent(r.intent), r.resultCode, r.resultData, 596 r.resultExtras, r.ordered, r.initialSticky, r.userId); 597 if (ordered) { 598 r.state = BroadcastRecord.CALL_DONE_RECEIVE; 599 } 600 } catch (RemoteException e) { 601 Slog.w(TAG, "Failure sending broadcast " + r.intent, e); 602 if (ordered) { 603 r.receiver = null; 604 r.curFilter = null; 605 filter.receiverList.curBroadcast = null; 606 if (filter.receiverList.app != null) { 607 filter.receiverList.app.curReceiver = null; 608 } 609 } 610 } 611 } 612 } 613 614 final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) { 615 if (duration > Integer.MAX_VALUE) { 616 duration = Integer.MAX_VALUE; 617 } 618 // XXX ideally we should pause the broadcast until everything behind this is done, 619 // or else we will likely start dispatching the broadcast before we have opened 620 // access to the app (there is a lot of asynchronicity behind this). It is probably 621 // not that big a deal, however, because the main purpose here is to allow apps 622 // to hold wake locks, and they will be able to acquire their wake lock immediately 623 // it just won't be enabled until we get through this work. 624 StringBuilder b = new StringBuilder(); 625 b.append("broadcast:"); 626 UserHandle.formatUid(b, r.callingUid); 627 b.append(":"); 628 if (r.intent.getAction() != null) { 629 b.append(r.intent.getAction()); 630 } else if (r.intent.getComponent() != null) { 631 b.append(r.intent.getComponent().flattenToShortString()); 632 } else if (r.intent.getData() != null) { 633 b.append(r.intent.getData()); 634 } 635 mHandler.obtainMessage(SCHEDULE_TEMP_WHITELIST_MSG, uid, (int)duration, b.toString()) 636 .sendToTarget(); 637 } 638 639 final void processNextBroadcast(boolean fromMsg) { 640 synchronized(mService) { 641 BroadcastRecord r; 642 643 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast [" 644 + mQueueName + "]: " 645 + mParallelBroadcasts.size() + " broadcasts, " 646 + mOrderedBroadcasts.size() + " ordered broadcasts"); 647 648 mService.updateCpuStats(); 649 650 if (fromMsg) { 651 mBroadcastsScheduled = false; 652 } 653 654 // First, deliver any non-serialized broadcasts right away. 655 while (mParallelBroadcasts.size() > 0) { 656 r = mParallelBroadcasts.remove(0); 657 r.dispatchTime = SystemClock.uptimeMillis(); 658 r.dispatchClockTime = System.currentTimeMillis(); 659 final int N = r.receivers.size(); 660 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast [" 661 + mQueueName + "] " + r); 662 for (int i=0; i<N; i++) { 663 Object target = r.receivers.get(i); 664 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 665 "Delivering non-ordered on [" + mQueueName + "] to registered " 666 + target + ": " + r); 667 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false); 668 } 669 addBroadcastToHistoryLocked(r); 670 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast [" 671 + mQueueName + "] " + r); 672 } 673 674 // Now take care of the next serialized one... 675 676 // If we are waiting for a process to come up to handle the next 677 // broadcast, then do nothing at this point. Just in case, we 678 // check that the process we're waiting for still exists. 679 if (mPendingBroadcast != null) { 680 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, 681 "processNextBroadcast [" + mQueueName + "]: waiting for " 682 + mPendingBroadcast.curApp); 683 684 boolean isDead; 685 synchronized (mService.mPidsSelfLocked) { 686 ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid); 687 isDead = proc == null || proc.crashing; 688 } 689 if (!isDead) { 690 // It's still alive, so keep waiting 691 return; 692 } else { 693 Slog.w(TAG, "pending app [" 694 + mQueueName + "]" + mPendingBroadcast.curApp 695 + " died before responding to broadcast"); 696 mPendingBroadcast.state = BroadcastRecord.IDLE; 697 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex; 698 mPendingBroadcast = null; 699 } 700 } 701 702 boolean looped = false; 703 704 do { 705 if (mOrderedBroadcasts.size() == 0) { 706 // No more broadcasts pending, so all done! 707 mService.scheduleAppGcsLocked(); 708 if (looped) { 709 // If we had finished the last ordered broadcast, then 710 // make sure all processes have correct oom and sched 711 // adjustments. 712 mService.updateOomAdjLocked(); 713 } 714 return; 715 } 716 r = mOrderedBroadcasts.get(0); 717 boolean forceReceive = false; 718 719 // Ensure that even if something goes awry with the timeout 720 // detection, we catch "hung" broadcasts here, discard them, 721 // and continue to make progress. 722 // 723 // This is only done if the system is ready so that PRE_BOOT_COMPLETED 724 // receivers don't get executed with timeouts. They're intended for 725 // one time heavy lifting after system upgrades and can take 726 // significant amounts of time. 727 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0; 728 if (mService.mProcessesReady && r.dispatchTime > 0) { 729 long now = SystemClock.uptimeMillis(); 730 if ((numReceivers > 0) && 731 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) { 732 Slog.w(TAG, "Hung broadcast [" 733 + mQueueName + "] discarded after timeout failure:" 734 + " now=" + now 735 + " dispatchTime=" + r.dispatchTime 736 + " startTime=" + r.receiverTime 737 + " intent=" + r.intent 738 + " numReceivers=" + numReceivers 739 + " nextReceiver=" + r.nextReceiver 740 + " state=" + r.state); 741 broadcastTimeoutLocked(false); // forcibly finish this broadcast 742 forceReceive = true; 743 r.state = BroadcastRecord.IDLE; 744 } 745 } 746 747 if (r.state != BroadcastRecord.IDLE) { 748 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST, 749 "processNextBroadcast(" 750 + mQueueName + ") called when not idle (state=" 751 + r.state + ")"); 752 return; 753 } 754 755 if (r.receivers == null || r.nextReceiver >= numReceivers 756 || r.resultAbort || forceReceive) { 757 // No more receivers for this broadcast! Send the final 758 // result if requested... 759 if (r.resultTo != null) { 760 try { 761 if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST, 762 "Finishing broadcast [" + mQueueName + "] " 763 + r.intent.getAction() + " app=" + r.callerApp); 764 performReceiveLocked(r.callerApp, r.resultTo, 765 new Intent(r.intent), r.resultCode, 766 r.resultData, r.resultExtras, false, false, r.userId); 767 // Set this to null so that the reference 768 // (local and remote) isn't kept in the mBroadcastHistory. 769 r.resultTo = null; 770 } catch (RemoteException e) { 771 r.resultTo = null; 772 Slog.w(TAG, "Failure [" 773 + mQueueName + "] sending broadcast result of " 774 + r.intent, e); 775 } 776 } 777 778 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG"); 779 cancelBroadcastTimeoutLocked(); 780 781 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, 782 "Finished with ordered broadcast " + r); 783 784 // ... and on to the next... 785 addBroadcastToHistoryLocked(r); 786 mOrderedBroadcasts.remove(0); 787 r = null; 788 looped = true; 789 continue; 790 } 791 } while (r == null); 792 793 // Get the next receiver... 794 int recIdx = r.nextReceiver++; 795 796 // Keep track of when this receiver started, and make sure there 797 // is a timeout message pending to kill it if need be. 798 r.receiverTime = SystemClock.uptimeMillis(); 799 if (recIdx == 0) { 800 r.dispatchTime = r.receiverTime; 801 r.dispatchClockTime = System.currentTimeMillis(); 802 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast [" 803 + mQueueName + "] " + r); 804 } 805 if (! mPendingBroadcastTimeoutMessage) { 806 long timeoutTime = r.receiverTime + mTimeoutPeriod; 807 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 808 "Submitting BROADCAST_TIMEOUT_MSG [" 809 + mQueueName + "] for " + r + " at " + timeoutTime); 810 setBroadcastTimeoutLocked(timeoutTime); 811 } 812 813 final BroadcastOptions brOptions = r.options; 814 final Object nextReceiver = r.receivers.get(recIdx); 815 816 if (nextReceiver instanceof BroadcastFilter) { 817 // Simple case: this is a registered receiver who gets 818 // a direct call. 819 BroadcastFilter filter = (BroadcastFilter)nextReceiver; 820 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 821 "Delivering ordered [" 822 + mQueueName + "] to registered " 823 + filter + ": " + r); 824 deliverToRegisteredReceiverLocked(r, filter, r.ordered); 825 if (r.receiver == null || !r.ordered) { 826 // The receiver has already finished, so schedule to 827 // process the next one. 828 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing [" 829 + mQueueName + "]: ordered=" 830 + r.ordered + " receiver=" + r.receiver); 831 r.state = BroadcastRecord.IDLE; 832 scheduleBroadcastsLocked(); 833 } else { 834 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) { 835 scheduleTempWhitelistLocked(filter.owningUid, 836 brOptions.getTemporaryAppWhitelistDuration(), r); 837 } 838 } 839 return; 840 } 841 842 // Hard case: need to instantiate the receiver, possibly 843 // starting its application process to host it. 844 845 ResolveInfo info = 846 (ResolveInfo)nextReceiver; 847 ComponentName component = new ComponentName( 848 info.activityInfo.applicationInfo.packageName, 849 info.activityInfo.name); 850 851 boolean skip = false; 852 int perm = mService.checkComponentPermission(info.activityInfo.permission, 853 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid, 854 info.activityInfo.exported); 855 if (perm != PackageManager.PERMISSION_GRANTED) { 856 if (!info.activityInfo.exported) { 857 Slog.w(TAG, "Permission Denial: broadcasting " 858 + r.intent.toString() 859 + " from " + r.callerPackage + " (pid=" + r.callingPid 860 + ", uid=" + r.callingUid + ")" 861 + " is not exported from uid " + info.activityInfo.applicationInfo.uid 862 + " due to receiver " + component.flattenToShortString()); 863 } else { 864 Slog.w(TAG, "Permission Denial: broadcasting " 865 + r.intent.toString() 866 + " from " + r.callerPackage + " (pid=" + r.callingPid 867 + ", uid=" + r.callingUid + ")" 868 + " requires " + info.activityInfo.permission 869 + " due to receiver " + component.flattenToShortString()); 870 } 871 skip = true; 872 } else if (info.activityInfo.permission != null) { 873 final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission); 874 if (opCode != AppOpsManager.OP_NONE 875 && mService.mAppOpsService.noteOperation(opCode, r.callingUid, 876 r.callerPackage) != AppOpsManager.MODE_ALLOWED) { 877 Slog.w(TAG, "Appop Denial: broadcasting " 878 + r.intent.toString() 879 + " from " + r.callerPackage + " (pid=" 880 + r.callingPid + ", uid=" + r.callingUid + ")" 881 + " requires appop " + AppOpsManager.permissionToOp( 882 info.activityInfo.permission) 883 + " due to registered receiver " 884 + component.flattenToShortString()); 885 skip = true; 886 } 887 } 888 if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID && 889 r.requiredPermissions != null && r.requiredPermissions.length > 0) { 890 for (int i = 0; i < r.requiredPermissions.length; i++) { 891 String requiredPermission = r.requiredPermissions[i]; 892 try { 893 perm = AppGlobals.getPackageManager(). 894 checkPermission(requiredPermission, 895 info.activityInfo.applicationInfo.packageName, 896 UserHandle 897 .getUserId(info.activityInfo.applicationInfo.uid)); 898 } catch (RemoteException e) { 899 perm = PackageManager.PERMISSION_DENIED; 900 } 901 if (perm != PackageManager.PERMISSION_GRANTED) { 902 Slog.w(TAG, "Permission Denial: receiving " 903 + r.intent + " to " 904 + component.flattenToShortString() 905 + " requires " + requiredPermission 906 + " due to sender " + r.callerPackage 907 + " (uid " + r.callingUid + ")"); 908 skip = true; 909 break; 910 } 911 int appOp = AppOpsManager.permissionToOpCode(requiredPermission); 912 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp 913 && mService.mAppOpsService.noteOperation(appOp, 914 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName) 915 != AppOpsManager.MODE_ALLOWED) { 916 Slog.w(TAG, "Appop Denial: receiving " 917 + r.intent + " to " 918 + component.flattenToShortString() 919 + " requires appop " + AppOpsManager.permissionToOp( 920 requiredPermission) 921 + " due to sender " + r.callerPackage 922 + " (uid " + r.callingUid + ")"); 923 skip = true; 924 break; 925 } 926 } 927 } 928 if (!skip && r.appOp != AppOpsManager.OP_NONE 929 && mService.mAppOpsService.noteOperation(r.appOp, 930 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName) 931 != AppOpsManager.MODE_ALLOWED) { 932 Slog.w(TAG, "Appop Denial: receiving " 933 + r.intent + " to " 934 + component.flattenToShortString() 935 + " requires appop " + AppOpsManager.opToName(r.appOp) 936 + " due to sender " + r.callerPackage 937 + " (uid " + r.callingUid + ")"); 938 skip = true; 939 } 940 if (!skip) { 941 skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid, 942 r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid); 943 } 944 boolean isSingleton = false; 945 try { 946 isSingleton = mService.isSingleton(info.activityInfo.processName, 947 info.activityInfo.applicationInfo, 948 info.activityInfo.name, info.activityInfo.flags); 949 } catch (SecurityException e) { 950 Slog.w(TAG, e.getMessage()); 951 skip = true; 952 } 953 if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { 954 if (ActivityManager.checkUidPermission( 955 android.Manifest.permission.INTERACT_ACROSS_USERS, 956 info.activityInfo.applicationInfo.uid) 957 != PackageManager.PERMISSION_GRANTED) { 958 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString() 959 + " requests FLAG_SINGLE_USER, but app does not hold " 960 + android.Manifest.permission.INTERACT_ACROSS_USERS); 961 skip = true; 962 } 963 } 964 if (r.curApp != null && r.curApp.crashing) { 965 // If the target process is crashing, just skip it. 966 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r 967 + " to " + r.curApp + ": process crashing"); 968 skip = true; 969 } 970 if (!skip) { 971 boolean isAvailable = false; 972 try { 973 isAvailable = AppGlobals.getPackageManager().isPackageAvailable( 974 info.activityInfo.packageName, 975 UserHandle.getUserId(info.activityInfo.applicationInfo.uid)); 976 } catch (Exception e) { 977 // all such failures mean we skip this receiver 978 Slog.w(TAG, "Exception getting recipient info for " 979 + info.activityInfo.packageName, e); 980 } 981 if (!isAvailable) { 982 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 983 "Skipping delivery to " + info.activityInfo.packageName + " / " 984 + info.activityInfo.applicationInfo.uid 985 + " : package no longer available"); 986 skip = true; 987 } 988 } 989 990 if (skip) { 991 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 992 "Skipping delivery of ordered [" + mQueueName + "] " 993 + r + " for whatever reason"); 994 r.receiver = null; 995 r.curFilter = null; 996 r.state = BroadcastRecord.IDLE; 997 scheduleBroadcastsLocked(); 998 return; 999 } 1000 1001 r.state = BroadcastRecord.APP_RECEIVE; 1002 String targetProcess = info.activityInfo.processName; 1003 r.curComponent = component; 1004 final int receiverUid = info.activityInfo.applicationInfo.uid; 1005 // If it's a singleton, it needs to be the same app or a special app 1006 if (r.callingUid != Process.SYSTEM_UID && isSingleton 1007 && mService.isValidSingletonCall(r.callingUid, receiverUid)) { 1008 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0); 1009 } 1010 r.curReceiver = info.activityInfo; 1011 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) { 1012 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, " 1013 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = " 1014 + info.activityInfo.applicationInfo.uid); 1015 } 1016 1017 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) { 1018 scheduleTempWhitelistLocked(receiverUid, 1019 brOptions.getTemporaryAppWhitelistDuration(), r); 1020 } 1021 1022 // Broadcast is being executed, its package can't be stopped. 1023 try { 1024 AppGlobals.getPackageManager().setPackageStoppedState( 1025 r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid)); 1026 } catch (RemoteException e) { 1027 } catch (IllegalArgumentException e) { 1028 Slog.w(TAG, "Failed trying to unstop package " 1029 + r.curComponent.getPackageName() + ": " + e); 1030 } 1031 1032 // Is this receiver's application already running? 1033 ProcessRecord app = mService.getProcessRecordLocked(targetProcess, 1034 info.activityInfo.applicationInfo.uid, false); 1035 if (app != null && app.thread != null) { 1036 try { 1037 app.addPackage(info.activityInfo.packageName, 1038 info.activityInfo.applicationInfo.versionCode, mService.mProcessStats); 1039 processCurBroadcastLocked(r, app); 1040 return; 1041 } catch (RemoteException e) { 1042 Slog.w(TAG, "Exception when sending broadcast to " 1043 + r.curComponent, e); 1044 } catch (RuntimeException e) { 1045 Slog.wtf(TAG, "Failed sending broadcast to " 1046 + r.curComponent + " with " + r.intent, e); 1047 // If some unexpected exception happened, just skip 1048 // this broadcast. At this point we are not in the call 1049 // from a client, so throwing an exception out from here 1050 // will crash the entire system instead of just whoever 1051 // sent the broadcast. 1052 logBroadcastReceiverDiscardLocked(r); 1053 finishReceiverLocked(r, r.resultCode, r.resultData, 1054 r.resultExtras, r.resultAbort, false); 1055 scheduleBroadcastsLocked(); 1056 // We need to reset the state if we failed to start the receiver. 1057 r.state = BroadcastRecord.IDLE; 1058 return; 1059 } 1060 1061 // If a dead object exception was thrown -- fall through to 1062 // restart the application. 1063 } 1064 1065 // Not running -- get it started, to be executed when the app comes up. 1066 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 1067 "Need to start app [" 1068 + mQueueName + "] " + targetProcess + " for broadcast " + r); 1069 if ((r.curApp=mService.startProcessLocked(targetProcess, 1070 info.activityInfo.applicationInfo, true, 1071 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND, 1072 "broadcast", r.curComponent, 1073 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false)) 1074 == null) { 1075 // Ah, this recipient is unavailable. Finish it if necessary, 1076 // and mark the broadcast record as ready for the next. 1077 Slog.w(TAG, "Unable to launch app " 1078 + info.activityInfo.applicationInfo.packageName + "/" 1079 + info.activityInfo.applicationInfo.uid + " for broadcast " 1080 + r.intent + ": process is bad"); 1081 logBroadcastReceiverDiscardLocked(r); 1082 finishReceiverLocked(r, r.resultCode, r.resultData, 1083 r.resultExtras, r.resultAbort, false); 1084 scheduleBroadcastsLocked(); 1085 r.state = BroadcastRecord.IDLE; 1086 return; 1087 } 1088 1089 mPendingBroadcast = r; 1090 mPendingBroadcastRecvIndex = recIdx; 1091 } 1092 } 1093 1094 final void setBroadcastTimeoutLocked(long timeoutTime) { 1095 if (! mPendingBroadcastTimeoutMessage) { 1096 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this); 1097 mHandler.sendMessageAtTime(msg, timeoutTime); 1098 mPendingBroadcastTimeoutMessage = true; 1099 } 1100 } 1101 1102 final void cancelBroadcastTimeoutLocked() { 1103 if (mPendingBroadcastTimeoutMessage) { 1104 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this); 1105 mPendingBroadcastTimeoutMessage = false; 1106 } 1107 } 1108 1109 final void broadcastTimeoutLocked(boolean fromMsg) { 1110 if (fromMsg) { 1111 mPendingBroadcastTimeoutMessage = false; 1112 } 1113 1114 if (mOrderedBroadcasts.size() == 0) { 1115 return; 1116 } 1117 1118 long now = SystemClock.uptimeMillis(); 1119 BroadcastRecord r = mOrderedBroadcasts.get(0); 1120 if (fromMsg) { 1121 if (mService.mDidDexOpt) { 1122 // Delay timeouts until dexopt finishes. 1123 mService.mDidDexOpt = false; 1124 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod; 1125 setBroadcastTimeoutLocked(timeoutTime); 1126 return; 1127 } 1128 if (!mService.mProcessesReady) { 1129 // Only process broadcast timeouts if the system is ready. That way 1130 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended 1131 // to do heavy lifting for system up. 1132 return; 1133 } 1134 1135 long timeoutTime = r.receiverTime + mTimeoutPeriod; 1136 if (timeoutTime > now) { 1137 // We can observe premature timeouts because we do not cancel and reset the 1138 // broadcast timeout message after each receiver finishes. Instead, we set up 1139 // an initial timeout then kick it down the road a little further as needed 1140 // when it expires. 1141 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, 1142 "Premature timeout [" 1143 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for " 1144 + timeoutTime); 1145 setBroadcastTimeoutLocked(timeoutTime); 1146 return; 1147 } 1148 } 1149 1150 BroadcastRecord br = mOrderedBroadcasts.get(0); 1151 if (br.state == BroadcastRecord.WAITING_SERVICES) { 1152 // In this case the broadcast had already finished, but we had decided to wait 1153 // for started services to finish as well before going on. So if we have actually 1154 // waited long enough time timeout the broadcast, let's give up on the whole thing 1155 // and just move on to the next. 1156 Slog.i(TAG, "Waited long enough for: " + (br.curComponent != null 1157 ? br.curComponent.flattenToShortString() : "(null)")); 1158 br.curComponent = null; 1159 br.state = BroadcastRecord.IDLE; 1160 processNextBroadcast(false); 1161 return; 1162 } 1163 1164 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver 1165 + ", started " + (now - r.receiverTime) + "ms ago"); 1166 r.receiverTime = now; 1167 r.anrCount++; 1168 1169 // Current receiver has passed its expiration date. 1170 if (r.nextReceiver <= 0) { 1171 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0"); 1172 return; 1173 } 1174 1175 ProcessRecord app = null; 1176 String anrMessage = null; 1177 1178 Object curReceiver = r.receivers.get(r.nextReceiver-1); 1179 Slog.w(TAG, "Receiver during timeout: " + curReceiver); 1180 logBroadcastReceiverDiscardLocked(r); 1181 if (curReceiver instanceof BroadcastFilter) { 1182 BroadcastFilter bf = (BroadcastFilter)curReceiver; 1183 if (bf.receiverList.pid != 0 1184 && bf.receiverList.pid != ActivityManagerService.MY_PID) { 1185 synchronized (mService.mPidsSelfLocked) { 1186 app = mService.mPidsSelfLocked.get( 1187 bf.receiverList.pid); 1188 } 1189 } 1190 } else { 1191 app = r.curApp; 1192 } 1193 1194 if (app != null) { 1195 anrMessage = "Broadcast of " + r.intent.toString(); 1196 } 1197 1198 if (mPendingBroadcast == r) { 1199 mPendingBroadcast = null; 1200 } 1201 1202 // Move on to the next receiver. 1203 finishReceiverLocked(r, r.resultCode, r.resultData, 1204 r.resultExtras, r.resultAbort, false); 1205 scheduleBroadcastsLocked(); 1206 1207 if (anrMessage != null) { 1208 // Post the ANR to the handler since we do not want to process ANRs while 1209 // potentially holding our lock. 1210 mHandler.post(new AppNotResponding(app, anrMessage)); 1211 } 1212 } 1213 1214 private final int ringAdvance(int x, final int increment, final int ringSize) { 1215 x += increment; 1216 if (x < 0) return (ringSize - 1); 1217 else if (x >= ringSize) return 0; 1218 else return x; 1219 } 1220 1221 private final void addBroadcastToHistoryLocked(BroadcastRecord r) { 1222 if (r.callingUid < 0) { 1223 // This was from a registerReceiver() call; ignore it. 1224 return; 1225 } 1226 r.finishTime = SystemClock.uptimeMillis(); 1227 1228 mBroadcastHistory[mHistoryNext] = r; 1229 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY); 1230 1231 mBroadcastSummaryHistory[mSummaryHistoryNext] = r.intent; 1232 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = r.enqueueClockTime; 1233 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = r.dispatchClockTime; 1234 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis(); 1235 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY); 1236 } 1237 1238 boolean cleanupDisabledPackageReceiversLocked( 1239 String packageName, Set<String> filterByClasses, int userId, boolean doit) { 1240 boolean didSomething = false; 1241 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) { 1242 didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked( 1243 packageName, filterByClasses, userId, doit); 1244 if (!doit && didSomething) { 1245 return true; 1246 } 1247 } 1248 1249 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) { 1250 didSomething |= mOrderedBroadcasts.get(i).cleanupDisabledPackageReceiversLocked( 1251 packageName, filterByClasses, userId, doit); 1252 if (!doit && didSomething) { 1253 return true; 1254 } 1255 } 1256 1257 return didSomething; 1258 } 1259 1260 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) { 1261 final int logIndex = r.nextReceiver - 1; 1262 if (logIndex >= 0 && logIndex < r.receivers.size()) { 1263 Object curReceiver = r.receivers.get(logIndex); 1264 if (curReceiver instanceof BroadcastFilter) { 1265 BroadcastFilter bf = (BroadcastFilter) curReceiver; 1266 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER, 1267 bf.owningUserId, System.identityHashCode(r), 1268 r.intent.getAction(), logIndex, System.identityHashCode(bf)); 1269 } else { 1270 ResolveInfo ri = (ResolveInfo) curReceiver; 1271 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP, 1272 UserHandle.getUserId(ri.activityInfo.applicationInfo.uid), 1273 System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString()); 1274 } 1275 } else { 1276 if (logIndex < 0) Slog.w(TAG, 1277 "Discarding broadcast before first receiver is invoked: " + r); 1278 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP, 1279 -1, System.identityHashCode(r), 1280 r.intent.getAction(), 1281 r.nextReceiver, 1282 "NONE"); 1283 } 1284 } 1285 1286 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args, 1287 int opti, boolean dumpAll, String dumpPackage, boolean needSep) { 1288 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 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, " ", sdf); 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, " ", sdf); 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, " ", sdf); 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, " ", sdf); 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 do { 1406 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY); 1407 Intent intent = mBroadcastSummaryHistory[ringIndex]; 1408 if (intent == null) { 1409 continue; 1410 } 1411 if (!printed) { 1412 if (needSep) { 1413 pw.println(); 1414 } 1415 needSep = true; 1416 pw.println(" Historical broadcasts summary [" + mQueueName + "]:"); 1417 printed = true; 1418 } 1419 if (!dumpAll && i >= 50) { 1420 pw.println(" ..."); 1421 break; 1422 } 1423 i++; 1424 pw.print(" #"); pw.print(i); pw.print(": "); 1425 pw.println(intent.toShortString(false, true, true, false)); 1426 pw.print(" "); 1427 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex] 1428 - mSummaryHistoryEnqueueTime[ringIndex], pw); 1429 pw.print(" dispatch "); 1430 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex] 1431 - mSummaryHistoryDispatchTime[ringIndex], pw); 1432 pw.println(" finish"); 1433 pw.print(" enq="); 1434 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex]))); 1435 pw.print(" disp="); 1436 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex]))); 1437 pw.print(" fin="); 1438 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex]))); 1439 Bundle bundle = intent.getExtras(); 1440 if (bundle != null) { 1441 pw.print(" extras: "); pw.println(bundle.toString()); 1442 } 1443 } while (ringIndex != lastIndex); 1444 } 1445 1446 return needSep; 1447 } 1448} 1449