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