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