blob: 39b63db08c6b22b9e86e13406a30550401763e0c [file] [log] [blame]
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001/*
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 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, UserId
723 .getUserId(r.callingUid));
724 }
725 r.curReceiver = info.activityInfo;
726 if (DEBUG_MU && r.callingUid > UserId.PER_USER_RANGE) {
727 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
728 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
729 + info.activityInfo.applicationInfo.uid);
730 }
731
732 // Broadcast is being executed, its package can't be stopped.
733 try {
734 AppGlobals.getPackageManager().setPackageStoppedState(
735 r.curComponent.getPackageName(), false);
736 } catch (RemoteException e) {
737 } catch (IllegalArgumentException e) {
738 Slog.w(TAG, "Failed trying to unstop package "
739 + r.curComponent.getPackageName() + ": " + e);
740 }
741
742 // Is this receiver's application already running?
743 ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
744 info.activityInfo.applicationInfo.uid);
745 if (app != null && app.thread != null) {
746 try {
747 app.addPackage(info.activityInfo.packageName);
748 processCurBroadcastLocked(r, app);
749 return;
750 } catch (RemoteException e) {
751 Slog.w(TAG, "Exception when sending broadcast to "
752 + r.curComponent, e);
753 }
754
755 // If a dead object exception was thrown -- fall through to
756 // restart the application.
757 }
758
759 // Not running -- get it started, to be executed when the app comes up.
760 if (DEBUG_BROADCAST) Slog.v(TAG,
761 "Need to start app ["
762 + mQueueName + "] " + targetProcess + " for broadcast " + r);
763 if ((r.curApp=mService.startProcessLocked(targetProcess,
764 info.activityInfo.applicationInfo, true,
765 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
766 "broadcast", r.curComponent,
767 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false))
768 == null) {
769 // Ah, this recipient is unavailable. Finish it if necessary,
770 // and mark the broadcast record as ready for the next.
771 Slog.w(TAG, "Unable to launch app "
772 + info.activityInfo.applicationInfo.packageName + "/"
773 + info.activityInfo.applicationInfo.uid + " for broadcast "
774 + r.intent + ": process is bad");
775 logBroadcastReceiverDiscardLocked(r);
776 finishReceiverLocked(r, r.resultCode, r.resultData,
777 r.resultExtras, r.resultAbort, true);
778 scheduleBroadcastsLocked();
779 r.state = BroadcastRecord.IDLE;
780 return;
781 }
782
783 mPendingBroadcast = r;
784 mPendingBroadcastRecvIndex = recIdx;
785 }
786 }
787
788 final void setBroadcastTimeoutLocked(long timeoutTime) {
789 if (! mPendingBroadcastTimeoutMessage) {
790 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
791 mHandler.sendMessageAtTime(msg, timeoutTime);
792 mPendingBroadcastTimeoutMessage = true;
793 }
794 }
795
796 final void cancelBroadcastTimeoutLocked() {
797 if (mPendingBroadcastTimeoutMessage) {
798 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
799 mPendingBroadcastTimeoutMessage = false;
800 }
801 }
802
803 final void broadcastTimeoutLocked(boolean fromMsg) {
804 if (fromMsg) {
805 mPendingBroadcastTimeoutMessage = false;
806 }
807
808 if (mOrderedBroadcasts.size() == 0) {
809 return;
810 }
811
812 long now = SystemClock.uptimeMillis();
813 BroadcastRecord r = mOrderedBroadcasts.get(0);
814 if (fromMsg) {
815 if (mService.mDidDexOpt) {
816 // Delay timeouts until dexopt finishes.
817 mService.mDidDexOpt = false;
818 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
819 setBroadcastTimeoutLocked(timeoutTime);
820 return;
821 }
822 if (!mService.mProcessesReady) {
823 // Only process broadcast timeouts if the system is ready. That way
824 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
825 // to do heavy lifting for system up.
826 return;
827 }
828
829 long timeoutTime = r.receiverTime + mTimeoutPeriod;
830 if (timeoutTime > now) {
831 // We can observe premature timeouts because we do not cancel and reset the
832 // broadcast timeout message after each receiver finishes. Instead, we set up
833 // an initial timeout then kick it down the road a little further as needed
834 // when it expires.
835 if (DEBUG_BROADCAST) Slog.v(TAG,
836 "Premature timeout ["
837 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
838 + timeoutTime);
839 setBroadcastTimeoutLocked(timeoutTime);
840 return;
841 }
842 }
843
844 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
845 + ", started " + (now - r.receiverTime) + "ms ago");
846 r.receiverTime = now;
847 r.anrCount++;
848
849 // Current receiver has passed its expiration date.
850 if (r.nextReceiver <= 0) {
851 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
852 return;
853 }
854
855 ProcessRecord app = null;
856 String anrMessage = null;
857
858 Object curReceiver = r.receivers.get(r.nextReceiver-1);
859 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
860 logBroadcastReceiverDiscardLocked(r);
861 if (curReceiver instanceof BroadcastFilter) {
862 BroadcastFilter bf = (BroadcastFilter)curReceiver;
863 if (bf.receiverList.pid != 0
864 && bf.receiverList.pid != ActivityManagerService.MY_PID) {
865 synchronized (mService.mPidsSelfLocked) {
866 app = mService.mPidsSelfLocked.get(
867 bf.receiverList.pid);
868 }
869 }
870 } else {
871 app = r.curApp;
872 }
873
874 if (app != null) {
875 anrMessage = "Broadcast of " + r.intent.toString();
876 }
877
878 if (mPendingBroadcast == r) {
879 mPendingBroadcast = null;
880 }
881
882 // Move on to the next receiver.
883 finishReceiverLocked(r, r.resultCode, r.resultData,
884 r.resultExtras, r.resultAbort, true);
885 scheduleBroadcastsLocked();
886
887 if (anrMessage != null) {
888 // Post the ANR to the handler since we do not want to process ANRs while
889 // potentially holding our lock.
890 mHandler.post(new AppNotResponding(app, anrMessage));
891 }
892 }
893
894 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
895 if (r.callingUid < 0) {
896 // This was from a registerReceiver() call; ignore it.
897 return;
898 }
899 System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
900 MAX_BROADCAST_HISTORY-1);
901 r.finishTime = SystemClock.uptimeMillis();
902 mBroadcastHistory[0] = r;
903 }
904
905 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
906 if (r.nextReceiver > 0) {
907 Object curReceiver = r.receivers.get(r.nextReceiver-1);
908 if (curReceiver instanceof BroadcastFilter) {
909 BroadcastFilter bf = (BroadcastFilter) curReceiver;
910 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
911 System.identityHashCode(r),
912 r.intent.getAction(),
913 r.nextReceiver - 1,
914 System.identityHashCode(bf));
915 } else {
916 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
917 System.identityHashCode(r),
918 r.intent.getAction(),
919 r.nextReceiver - 1,
920 ((ResolveInfo)curReceiver).toString());
921 }
922 } else {
923 Slog.w(TAG, "Discarding broadcast before first receiver is invoked: "
924 + r);
925 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
926 System.identityHashCode(r),
927 r.intent.getAction(),
928 r.nextReceiver,
929 "NONE");
930 }
931 }
932
933 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
934 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
935 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
936 || mPendingBroadcast != null) {
937 boolean printed = false;
938 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
939 BroadcastRecord br = mParallelBroadcasts.get(i);
940 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
941 continue;
942 }
943 if (!printed) {
944 if (needSep) {
945 pw.println();
946 needSep = false;
947 }
948 printed = true;
949 pw.println(" Active broadcasts [" + mQueueName + "]:");
950 }
951 pw.println(" Broadcast #" + i + ":");
952 br.dump(pw, " ");
953 }
954 printed = false;
955 needSep = true;
956 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
957 BroadcastRecord br = mOrderedBroadcasts.get(i);
958 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
959 continue;
960 }
961 if (!printed) {
962 if (needSep) {
963 pw.println();
964 }
965 needSep = true;
966 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
967 }
968 pw.println(" Ordered Broadcast #" + i + ":");
969 mOrderedBroadcasts.get(i).dump(pw, " ");
970 }
971 if (dumpPackage == null || (mPendingBroadcast != null
972 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
973 if (needSep) {
974 pw.println();
975 }
976 pw.println(" Pending broadcast [" + mQueueName + "]:");
977 if (mPendingBroadcast != null) {
978 mPendingBroadcast.dump(pw, " ");
979 } else {
980 pw.println(" (null)");
981 }
982 needSep = true;
983 }
984 }
985
986 boolean printed = false;
987 for (int i=0; i<MAX_BROADCAST_HISTORY; i++) {
988 BroadcastRecord r = mBroadcastHistory[i];
989 if (r == null) {
990 break;
991 }
992 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
993 continue;
994 }
995 if (!printed) {
996 if (needSep) {
997 pw.println();
998 }
999 needSep = true;
1000 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1001 printed = true;
1002 }
1003 if (dumpAll) {
1004 pw.print(" Historical Broadcast #"); pw.print(i); pw.println(":");
1005 r.dump(pw, " ");
1006 } else {
1007 if (i >= 50) {
1008 pw.println(" ...");
1009 break;
1010 }
1011 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1012 }
1013 }
1014
1015 return needSep;
1016 }
1017}