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