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