blob: 7873dd82f39cbf8e7d399d502cf20959ddaffe94 [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;
Dianne Hackbornb4163a62012-08-02 18:31:26 -0700375 if (r.onlySendToCaller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700376 if (!UserHandle.isSameApp(r.callingUid, filter.owningUid)) {
Dianne Hackbornb4163a62012-08-02 18:31:26 -0700377 Slog.w(TAG, "Permission Denial: broadcasting "
378 + r.intent.toString()
379 + " from " + r.callerPackage + " (pid="
380 + r.callingPid + ", uid=" + r.callingUid + ")"
381 + " not allowed to go to different app " + filter.owningUid);
382 skip = true;
383 }
384 }
385 if (!skip && filter.requiredPermission != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800386 int perm = mService.checkComponentPermission(filter.requiredPermission,
387 r.callingPid, r.callingUid, -1, true);
388 if (perm != PackageManager.PERMISSION_GRANTED) {
389 Slog.w(TAG, "Permission Denial: broadcasting "
390 + r.intent.toString()
391 + " from " + r.callerPackage + " (pid="
392 + r.callingPid + ", uid=" + r.callingUid + ")"
393 + " requires " + filter.requiredPermission
394 + " due to registered receiver " + filter);
395 skip = true;
396 }
397 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -0700398 if (!skip && r.requiredPermission != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800399 int perm = mService.checkComponentPermission(r.requiredPermission,
400 filter.receiverList.pid, filter.receiverList.uid, -1, true);
401 if (perm != PackageManager.PERMISSION_GRANTED) {
402 Slog.w(TAG, "Permission Denial: receiving "
403 + r.intent.toString()
404 + " to " + filter.receiverList.app
405 + " (pid=" + filter.receiverList.pid
406 + ", uid=" + filter.receiverList.uid + ")"
407 + " requires " + r.requiredPermission
408 + " due to sender " + r.callerPackage
409 + " (uid " + r.callingUid + ")");
410 skip = true;
411 }
412 }
413
414 if (!skip) {
415 // If this is not being sent as an ordered broadcast, then we
416 // don't want to touch the fields that keep track of the current
417 // state of ordered broadcasts.
418 if (ordered) {
419 r.receiver = filter.receiverList.receiver.asBinder();
420 r.curFilter = filter;
421 filter.receiverList.curBroadcast = r;
422 r.state = BroadcastRecord.CALL_IN_RECEIVE;
423 if (filter.receiverList.app != null) {
424 // Bump hosting application to no longer be in background
425 // scheduling class. Note that we can't do that if there
426 // isn't an app... but we can only be in that case for
427 // things that directly call the IActivityManager API, which
428 // are already core system stuff so don't matter for this.
429 r.curApp = filter.receiverList.app;
430 filter.receiverList.app.curReceiver = r;
431 mService.updateOomAdjLocked();
432 }
433 }
434 try {
435 if (DEBUG_BROADCAST_LIGHT) {
436 int seq = r.intent.getIntExtra("seq", -1);
437 Slog.i(TAG, "Delivering to " + filter
438 + " (seq=" + seq + "): " + r);
439 }
440 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
441 new Intent(r.intent), r.resultCode,
442 r.resultData, r.resultExtras, r.ordered, r.initialSticky);
443 if (ordered) {
444 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
445 }
446 } catch (RemoteException e) {
447 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
448 if (ordered) {
449 r.receiver = null;
450 r.curFilter = null;
451 filter.receiverList.curBroadcast = null;
452 if (filter.receiverList.app != null) {
453 filter.receiverList.app.curReceiver = null;
454 }
455 }
456 }
457 }
458 }
459
460 final void processNextBroadcast(boolean fromMsg) {
461 synchronized(mService) {
462 BroadcastRecord r;
463
464 if (DEBUG_BROADCAST) Slog.v(TAG, "processNextBroadcast ["
465 + mQueueName + "]: "
466 + mParallelBroadcasts.size() + " broadcasts, "
467 + mOrderedBroadcasts.size() + " ordered broadcasts");
468
469 mService.updateCpuStats();
470
471 if (fromMsg) {
472 mBroadcastsScheduled = false;
473 }
474
475 // First, deliver any non-serialized broadcasts right away.
476 while (mParallelBroadcasts.size() > 0) {
477 r = mParallelBroadcasts.remove(0);
478 r.dispatchTime = SystemClock.uptimeMillis();
479 r.dispatchClockTime = System.currentTimeMillis();
480 final int N = r.receivers.size();
481 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing parallel broadcast ["
482 + mQueueName + "] " + r);
483 for (int i=0; i<N; i++) {
484 Object target = r.receivers.get(i);
485 if (DEBUG_BROADCAST) Slog.v(TAG,
486 "Delivering non-ordered on [" + mQueueName + "] to registered "
487 + target + ": " + r);
488 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
489 }
490 addBroadcastToHistoryLocked(r);
491 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Done with parallel broadcast ["
492 + mQueueName + "] " + r);
493 }
494
495 // Now take care of the next serialized one...
496
497 // If we are waiting for a process to come up to handle the next
498 // broadcast, then do nothing at this point. Just in case, we
499 // check that the process we're waiting for still exists.
500 if (mPendingBroadcast != null) {
501 if (DEBUG_BROADCAST_LIGHT) {
502 Slog.v(TAG, "processNextBroadcast ["
503 + mQueueName + "]: waiting for "
504 + mPendingBroadcast.curApp);
505 }
506
507 boolean isDead;
508 synchronized (mService.mPidsSelfLocked) {
509 isDead = (mService.mPidsSelfLocked.get(
510 mPendingBroadcast.curApp.pid) == null);
511 }
512 if (!isDead) {
513 // It's still alive, so keep waiting
514 return;
515 } else {
516 Slog.w(TAG, "pending app ["
517 + mQueueName + "]" + mPendingBroadcast.curApp
518 + " died before responding to broadcast");
519 mPendingBroadcast.state = BroadcastRecord.IDLE;
520 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
521 mPendingBroadcast = null;
522 }
523 }
524
525 boolean looped = false;
526
527 do {
528 if (mOrderedBroadcasts.size() == 0) {
529 // No more broadcasts pending, so all done!
530 mService.scheduleAppGcsLocked();
531 if (looped) {
532 // If we had finished the last ordered broadcast, then
533 // make sure all processes have correct oom and sched
534 // adjustments.
535 mService.updateOomAdjLocked();
536 }
537 return;
538 }
539 r = mOrderedBroadcasts.get(0);
540 boolean forceReceive = false;
541
542 // Ensure that even if something goes awry with the timeout
543 // detection, we catch "hung" broadcasts here, discard them,
544 // and continue to make progress.
545 //
546 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
547 // receivers don't get executed with timeouts. They're intended for
548 // one time heavy lifting after system upgrades and can take
549 // significant amounts of time.
550 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
551 if (mService.mProcessesReady && r.dispatchTime > 0) {
552 long now = SystemClock.uptimeMillis();
553 if ((numReceivers > 0) &&
554 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
555 Slog.w(TAG, "Hung broadcast ["
556 + mQueueName + "] discarded after timeout failure:"
557 + " now=" + now
558 + " dispatchTime=" + r.dispatchTime
559 + " startTime=" + r.receiverTime
560 + " intent=" + r.intent
561 + " numReceivers=" + numReceivers
562 + " nextReceiver=" + r.nextReceiver
563 + " state=" + r.state);
564 broadcastTimeoutLocked(false); // forcibly finish this broadcast
565 forceReceive = true;
566 r.state = BroadcastRecord.IDLE;
567 }
568 }
569
570 if (r.state != BroadcastRecord.IDLE) {
571 if (DEBUG_BROADCAST) Slog.d(TAG,
572 "processNextBroadcast("
573 + mQueueName + ") called when not idle (state="
574 + r.state + ")");
575 return;
576 }
577
578 if (r.receivers == null || r.nextReceiver >= numReceivers
579 || r.resultAbort || forceReceive) {
580 // No more receivers for this broadcast! Send the final
581 // result if requested...
582 if (r.resultTo != null) {
583 try {
584 if (DEBUG_BROADCAST) {
585 int seq = r.intent.getIntExtra("seq", -1);
586 Slog.i(TAG, "Finishing broadcast ["
587 + mQueueName + "] " + r.intent.getAction()
588 + " seq=" + seq + " app=" + r.callerApp);
589 }
590 performReceiveLocked(r.callerApp, r.resultTo,
591 new Intent(r.intent), r.resultCode,
592 r.resultData, r.resultExtras, false, false);
593 // Set this to null so that the reference
594 // (local and remote) isnt kept in the mBroadcastHistory.
595 r.resultTo = null;
596 } catch (RemoteException e) {
597 Slog.w(TAG, "Failure ["
598 + mQueueName + "] sending broadcast result of "
599 + r.intent, e);
600 }
601 }
602
603 if (DEBUG_BROADCAST) Slog.v(TAG, "Cancelling BROADCAST_TIMEOUT_MSG");
604 cancelBroadcastTimeoutLocked();
605
606 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Finished with ordered broadcast "
607 + r);
608
609 // ... and on to the next...
610 addBroadcastToHistoryLocked(r);
611 mOrderedBroadcasts.remove(0);
612 r = null;
613 looped = true;
614 continue;
615 }
616 } while (r == null);
617
618 // Get the next receiver...
619 int recIdx = r.nextReceiver++;
620
621 // Keep track of when this receiver started, and make sure there
622 // is a timeout message pending to kill it if need be.
623 r.receiverTime = SystemClock.uptimeMillis();
624 if (recIdx == 0) {
625 r.dispatchTime = r.receiverTime;
626 r.dispatchClockTime = System.currentTimeMillis();
627 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing ordered broadcast ["
628 + mQueueName + "] " + r);
629 }
630 if (! mPendingBroadcastTimeoutMessage) {
631 long timeoutTime = r.receiverTime + mTimeoutPeriod;
632 if (DEBUG_BROADCAST) Slog.v(TAG,
633 "Submitting BROADCAST_TIMEOUT_MSG ["
634 + mQueueName + "] for " + r + " at " + timeoutTime);
635 setBroadcastTimeoutLocked(timeoutTime);
636 }
637
638 Object nextReceiver = r.receivers.get(recIdx);
639 if (nextReceiver instanceof BroadcastFilter) {
640 // Simple case: this is a registered receiver who gets
641 // a direct call.
642 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
643 if (DEBUG_BROADCAST) Slog.v(TAG,
644 "Delivering ordered ["
645 + mQueueName + "] to registered "
646 + filter + ": " + r);
647 deliverToRegisteredReceiverLocked(r, filter, r.ordered);
648 if (r.receiver == null || !r.ordered) {
649 // The receiver has already finished, so schedule to
650 // process the next one.
651 if (DEBUG_BROADCAST) Slog.v(TAG, "Quick finishing ["
652 + mQueueName + "]: ordered="
653 + r.ordered + " receiver=" + r.receiver);
654 r.state = BroadcastRecord.IDLE;
655 scheduleBroadcastsLocked();
656 }
657 return;
658 }
659
660 // Hard case: need to instantiate the receiver, possibly
661 // starting its application process to host it.
662
663 ResolveInfo info =
664 (ResolveInfo)nextReceiver;
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700665 ComponentName component = new ComponentName(
666 info.activityInfo.applicationInfo.packageName,
667 info.activityInfo.name);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800668
669 boolean skip = false;
Dianne Hackbornb4163a62012-08-02 18:31:26 -0700670 if (r.onlySendToCaller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700671 if (!UserHandle.isSameApp(r.callingUid, info.activityInfo.applicationInfo.uid)) {
Dianne Hackbornb4163a62012-08-02 18:31:26 -0700672 Slog.w(TAG, "Permission Denial: broadcasting "
673 + r.intent.toString()
674 + " from " + r.callerPackage + " (pid="
675 + r.callingPid + ", uid=" + r.callingUid + ")"
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700676 + " to " + component.flattenToShortString()
Dianne Hackbornb4163a62012-08-02 18:31:26 -0700677 + " not allowed to go to different app "
678 + info.activityInfo.applicationInfo.uid);
679 skip = true;
680 }
681 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800682 int perm = mService.checkComponentPermission(info.activityInfo.permission,
683 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
684 info.activityInfo.exported);
685 if (perm != PackageManager.PERMISSION_GRANTED) {
686 if (!info.activityInfo.exported) {
687 Slog.w(TAG, "Permission Denial: broadcasting "
688 + r.intent.toString()
689 + " from " + r.callerPackage + " (pid=" + r.callingPid
690 + ", uid=" + r.callingUid + ")"
691 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700692 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800693 } else {
694 Slog.w(TAG, "Permission Denial: broadcasting "
695 + r.intent.toString()
696 + " from " + r.callerPackage + " (pid=" + r.callingPid
697 + ", uid=" + r.callingUid + ")"
698 + " requires " + info.activityInfo.permission
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700699 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800700 }
701 skip = true;
702 }
703 if (info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
704 r.requiredPermission != null) {
705 try {
706 perm = AppGlobals.getPackageManager().
707 checkPermission(r.requiredPermission,
708 info.activityInfo.applicationInfo.packageName);
709 } catch (RemoteException e) {
710 perm = PackageManager.PERMISSION_DENIED;
711 }
712 if (perm != PackageManager.PERMISSION_GRANTED) {
713 Slog.w(TAG, "Permission Denial: receiving "
714 + r.intent + " to "
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700715 + component.flattenToShortString()
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800716 + " requires " + r.requiredPermission
717 + " due to sender " + r.callerPackage
718 + " (uid " + r.callingUid + ")");
719 skip = true;
720 }
721 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700722 boolean isSingleton = false;
723 try {
724 isSingleton = mService.isSingleton(info.activityInfo.processName,
725 info.activityInfo.applicationInfo,
726 info.activityInfo.name, info.activityInfo.flags);
727 } catch (SecurityException e) {
728 Slog.w(TAG, e.getMessage());
729 skip = true;
730 }
731 if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
732 if (ActivityManager.checkUidPermission(
733 android.Manifest.permission.INTERACT_ACROSS_USERS,
734 info.activityInfo.applicationInfo.uid)
735 != PackageManager.PERMISSION_GRANTED) {
736 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
737 + " requests FLAG_SINGLE_USER, but app does not hold "
738 + android.Manifest.permission.INTERACT_ACROSS_USERS);
739 skip = true;
740 }
741 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800742 if (r.curApp != null && r.curApp.crashing) {
743 // If the target process is crashing, just skip it.
744 if (DEBUG_BROADCAST) Slog.v(TAG,
745 "Skipping deliver ordered ["
746 + mQueueName + "] " + r + " to " + r.curApp
747 + ": process crashing");
748 skip = true;
749 }
750
751 if (skip) {
752 if (DEBUG_BROADCAST) Slog.v(TAG,
753 "Skipping delivery of ordered ["
754 + mQueueName + "] " + r + " for whatever reason");
755 r.receiver = null;
756 r.curFilter = null;
757 r.state = BroadcastRecord.IDLE;
758 scheduleBroadcastsLocked();
759 return;
760 }
761
762 r.state = BroadcastRecord.APP_RECEIVE;
763 String targetProcess = info.activityInfo.processName;
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700764 r.curComponent = component;
765 if (r.callingUid != Process.SYSTEM_UID && isSingleton) {
766 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800767 }
768 r.curReceiver = info.activityInfo;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700769 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800770 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
771 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
772 + info.activityInfo.applicationInfo.uid);
773 }
774
775 // Broadcast is being executed, its package can't be stopped.
776 try {
777 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700778 r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800779 } catch (RemoteException e) {
780 } catch (IllegalArgumentException e) {
781 Slog.w(TAG, "Failed trying to unstop package "
782 + r.curComponent.getPackageName() + ": " + e);
783 }
784
785 // Is this receiver's application already running?
786 ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
787 info.activityInfo.applicationInfo.uid);
788 if (app != null && app.thread != null) {
789 try {
790 app.addPackage(info.activityInfo.packageName);
791 processCurBroadcastLocked(r, app);
792 return;
793 } catch (RemoteException e) {
794 Slog.w(TAG, "Exception when sending broadcast to "
795 + r.curComponent, e);
796 }
797
798 // If a dead object exception was thrown -- fall through to
799 // restart the application.
800 }
801
802 // Not running -- get it started, to be executed when the app comes up.
803 if (DEBUG_BROADCAST) Slog.v(TAG,
804 "Need to start app ["
805 + mQueueName + "] " + targetProcess + " for broadcast " + r);
806 if ((r.curApp=mService.startProcessLocked(targetProcess,
807 info.activityInfo.applicationInfo, true,
808 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
809 "broadcast", r.curComponent,
810 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false))
811 == null) {
812 // Ah, this recipient is unavailable. Finish it if necessary,
813 // and mark the broadcast record as ready for the next.
814 Slog.w(TAG, "Unable to launch app "
815 + info.activityInfo.applicationInfo.packageName + "/"
816 + info.activityInfo.applicationInfo.uid + " for broadcast "
817 + r.intent + ": process is bad");
818 logBroadcastReceiverDiscardLocked(r);
819 finishReceiverLocked(r, r.resultCode, r.resultData,
820 r.resultExtras, r.resultAbort, true);
821 scheduleBroadcastsLocked();
822 r.state = BroadcastRecord.IDLE;
823 return;
824 }
825
826 mPendingBroadcast = r;
827 mPendingBroadcastRecvIndex = recIdx;
828 }
829 }
830
831 final void setBroadcastTimeoutLocked(long timeoutTime) {
832 if (! mPendingBroadcastTimeoutMessage) {
833 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
834 mHandler.sendMessageAtTime(msg, timeoutTime);
835 mPendingBroadcastTimeoutMessage = true;
836 }
837 }
838
839 final void cancelBroadcastTimeoutLocked() {
840 if (mPendingBroadcastTimeoutMessage) {
841 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
842 mPendingBroadcastTimeoutMessage = false;
843 }
844 }
845
846 final void broadcastTimeoutLocked(boolean fromMsg) {
847 if (fromMsg) {
848 mPendingBroadcastTimeoutMessage = false;
849 }
850
851 if (mOrderedBroadcasts.size() == 0) {
852 return;
853 }
854
855 long now = SystemClock.uptimeMillis();
856 BroadcastRecord r = mOrderedBroadcasts.get(0);
857 if (fromMsg) {
858 if (mService.mDidDexOpt) {
859 // Delay timeouts until dexopt finishes.
860 mService.mDidDexOpt = false;
861 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
862 setBroadcastTimeoutLocked(timeoutTime);
863 return;
864 }
865 if (!mService.mProcessesReady) {
866 // Only process broadcast timeouts if the system is ready. That way
867 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
868 // to do heavy lifting for system up.
869 return;
870 }
871
872 long timeoutTime = r.receiverTime + mTimeoutPeriod;
873 if (timeoutTime > now) {
874 // We can observe premature timeouts because we do not cancel and reset the
875 // broadcast timeout message after each receiver finishes. Instead, we set up
876 // an initial timeout then kick it down the road a little further as needed
877 // when it expires.
878 if (DEBUG_BROADCAST) Slog.v(TAG,
879 "Premature timeout ["
880 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
881 + timeoutTime);
882 setBroadcastTimeoutLocked(timeoutTime);
883 return;
884 }
885 }
886
887 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
888 + ", started " + (now - r.receiverTime) + "ms ago");
889 r.receiverTime = now;
890 r.anrCount++;
891
892 // Current receiver has passed its expiration date.
893 if (r.nextReceiver <= 0) {
894 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
895 return;
896 }
897
898 ProcessRecord app = null;
899 String anrMessage = null;
900
901 Object curReceiver = r.receivers.get(r.nextReceiver-1);
902 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
903 logBroadcastReceiverDiscardLocked(r);
904 if (curReceiver instanceof BroadcastFilter) {
905 BroadcastFilter bf = (BroadcastFilter)curReceiver;
906 if (bf.receiverList.pid != 0
907 && bf.receiverList.pid != ActivityManagerService.MY_PID) {
908 synchronized (mService.mPidsSelfLocked) {
909 app = mService.mPidsSelfLocked.get(
910 bf.receiverList.pid);
911 }
912 }
913 } else {
914 app = r.curApp;
915 }
916
917 if (app != null) {
918 anrMessage = "Broadcast of " + r.intent.toString();
919 }
920
921 if (mPendingBroadcast == r) {
922 mPendingBroadcast = null;
923 }
924
925 // Move on to the next receiver.
926 finishReceiverLocked(r, r.resultCode, r.resultData,
927 r.resultExtras, r.resultAbort, true);
928 scheduleBroadcastsLocked();
929
930 if (anrMessage != null) {
931 // Post the ANR to the handler since we do not want to process ANRs while
932 // potentially holding our lock.
933 mHandler.post(new AppNotResponding(app, anrMessage));
934 }
935 }
936
937 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
938 if (r.callingUid < 0) {
939 // This was from a registerReceiver() call; ignore it.
940 return;
941 }
942 System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
943 MAX_BROADCAST_HISTORY-1);
944 r.finishTime = SystemClock.uptimeMillis();
945 mBroadcastHistory[0] = r;
946 }
947
948 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
949 if (r.nextReceiver > 0) {
950 Object curReceiver = r.receivers.get(r.nextReceiver-1);
951 if (curReceiver instanceof BroadcastFilter) {
952 BroadcastFilter bf = (BroadcastFilter) curReceiver;
953 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
954 System.identityHashCode(r),
955 r.intent.getAction(),
956 r.nextReceiver - 1,
957 System.identityHashCode(bf));
958 } else {
959 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
960 System.identityHashCode(r),
961 r.intent.getAction(),
962 r.nextReceiver - 1,
963 ((ResolveInfo)curReceiver).toString());
964 }
965 } else {
966 Slog.w(TAG, "Discarding broadcast before first receiver is invoked: "
967 + r);
968 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
969 System.identityHashCode(r),
970 r.intent.getAction(),
971 r.nextReceiver,
972 "NONE");
973 }
974 }
975
976 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
977 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
978 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
979 || mPendingBroadcast != null) {
980 boolean printed = false;
981 for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
982 BroadcastRecord br = mParallelBroadcasts.get(i);
983 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
984 continue;
985 }
986 if (!printed) {
987 if (needSep) {
988 pw.println();
989 needSep = false;
990 }
991 printed = true;
992 pw.println(" Active broadcasts [" + mQueueName + "]:");
993 }
994 pw.println(" Broadcast #" + i + ":");
995 br.dump(pw, " ");
996 }
997 printed = false;
998 needSep = true;
999 for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
1000 BroadcastRecord br = mOrderedBroadcasts.get(i);
1001 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1002 continue;
1003 }
1004 if (!printed) {
1005 if (needSep) {
1006 pw.println();
1007 }
1008 needSep = true;
1009 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1010 }
1011 pw.println(" Ordered Broadcast #" + i + ":");
1012 mOrderedBroadcasts.get(i).dump(pw, " ");
1013 }
1014 if (dumpPackage == null || (mPendingBroadcast != null
1015 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1016 if (needSep) {
1017 pw.println();
1018 }
1019 pw.println(" Pending broadcast [" + mQueueName + "]:");
1020 if (mPendingBroadcast != null) {
1021 mPendingBroadcast.dump(pw, " ");
1022 } else {
1023 pw.println(" (null)");
1024 }
1025 needSep = true;
1026 }
1027 }
1028
1029 boolean printed = false;
1030 for (int i=0; i<MAX_BROADCAST_HISTORY; i++) {
1031 BroadcastRecord r = mBroadcastHistory[i];
1032 if (r == null) {
1033 break;
1034 }
1035 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1036 continue;
1037 }
1038 if (!printed) {
1039 if (needSep) {
1040 pw.println();
1041 }
1042 needSep = true;
1043 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1044 printed = true;
1045 }
1046 if (dumpAll) {
1047 pw.print(" Historical Broadcast #"); pw.print(i); pw.println(":");
1048 r.dump(pw, " ");
1049 } else {
1050 if (i >= 50) {
1051 pw.println(" ...");
1052 break;
1053 }
1054 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1055 }
1056 }
1057
1058 return needSep;
1059 }
1060}