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