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