BroadcastQueue.java revision b4e7283c9afd9fb15ebd63f6ce9b75c9c1af658b
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.text.SimpleDateFormat;
22import java.util.ArrayList;
23import java.util.Date;
24import java.util.Set;
25
26import android.app.ActivityManager;
27import android.app.AppGlobals;
28import android.app.AppOpsManager;
29import android.app.BroadcastOptions;
30import android.content.ComponentName;
31import android.content.IIntentReceiver;
32import android.content.Intent;
33import android.content.pm.ActivityInfo;
34import android.content.pm.PackageManager;
35import android.content.pm.ResolveInfo;
36import android.os.Bundle;
37import android.os.Handler;
38import android.os.IBinder;
39import android.os.Looper;
40import android.os.Message;
41import android.os.Process;
42import android.os.RemoteException;
43import android.os.SystemClock;
44import android.os.UserHandle;
45import android.util.EventLog;
46import android.util.Slog;
47import com.android.server.DeviceIdleController;
48
49import static com.android.server.am.ActivityManagerDebugConfig.*;
50
51/**
52 * BROADCASTS
53 *
54 * We keep two broadcast queues and associated bookkeeping, one for those at
55 * foreground priority, and one for normal (background-priority) broadcasts.
56 */
57public final class BroadcastQueue {
58    private static final String TAG = "BroadcastQueue";
59    private static final String TAG_MU = TAG + POSTFIX_MU;
60    private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
61
62    static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50;
63    static final int MAX_BROADCAST_SUMMARY_HISTORY
64            = ActivityManager.isLowRamDeviceStatic() ? 25 : 300;
65
66    final ActivityManagerService mService;
67
68    /**
69     * Recognizable moniker for this queue
70     */
71    final String mQueueName;
72
73    /**
74     * Timeout period for this queue's broadcasts
75     */
76    final long mTimeoutPeriod;
77
78    /**
79     * If true, we can delay broadcasts while waiting services to finish in the previous
80     * receiver's process.
81     */
82    final boolean mDelayBehindServices;
83
84    /**
85     * Lists of all active broadcasts that are to be executed immediately
86     * (without waiting for another broadcast to finish).  Currently this only
87     * contains broadcasts to registered receivers, to avoid spinning up
88     * a bunch of processes to execute IntentReceiver components.  Background-
89     * and foreground-priority broadcasts are queued separately.
90     */
91    final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
92
93    /**
94     * List of all active broadcasts that are to be executed one at a time.
95     * The object at the top of the list is the currently activity broadcasts;
96     * those after it are waiting for the top to finish.  As with parallel
97     * broadcasts, separate background- and foreground-priority queues are
98     * maintained.
99     */
100    final ArrayList<BroadcastRecord> mOrderedBroadcasts = new ArrayList<>();
101
102    /**
103     * Historical data of past broadcasts, for debugging.  This is a ring buffer
104     * whose last element is at mHistoryNext.
105     */
106    final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY];
107    int mHistoryNext = 0;
108
109    /**
110     * Summary of historical data of past broadcasts, for debugging.  This is a
111     * ring buffer whose last element is at mSummaryHistoryNext.
112     */
113    final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
114    int mSummaryHistoryNext = 0;
115
116    /**
117     * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring
118     * buffer, also tracked via the mSummaryHistoryNext index.  These are all in wall
119     * clock time, not elapsed.
120     */
121    final long[] mSummaryHistoryEnqueueTime = new  long[MAX_BROADCAST_SUMMARY_HISTORY];
122    final long[] mSummaryHistoryDispatchTime = new  long[MAX_BROADCAST_SUMMARY_HISTORY];
123    final long[] mSummaryHistoryFinishTime = new  long[MAX_BROADCAST_SUMMARY_HISTORY];
124
125    /**
126     * Set when we current have a BROADCAST_INTENT_MSG in flight.
127     */
128    boolean mBroadcastsScheduled = false;
129
130    /**
131     * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
132     */
133    boolean mPendingBroadcastTimeoutMessage;
134
135    /**
136     * Intent broadcasts that we have tried to start, but are
137     * waiting for the application's process to be created.  We only
138     * need one per scheduling class (instead of a list) because we always
139     * process broadcasts one at a time, so no others can be started while
140     * waiting for this one.
141     */
142    BroadcastRecord mPendingBroadcast = null;
143
144    /**
145     * The receiver index that is pending, to restart the broadcast if needed.
146     */
147    int mPendingBroadcastRecvIndex;
148
149    static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
150    static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
151    static final int SCHEDULE_TEMP_WHITELIST_MSG
152            = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 2;
153
154    final BroadcastHandler mHandler;
155
156    private final class BroadcastHandler extends Handler {
157        public BroadcastHandler(Looper looper) {
158            super(looper, null, true);
159        }
160
161        @Override
162        public void handleMessage(Message msg) {
163            switch (msg.what) {
164                case BROADCAST_INTENT_MSG: {
165                    if (DEBUG_BROADCAST) Slog.v(
166                            TAG_BROADCAST, "Received BROADCAST_INTENT_MSG");
167                    processNextBroadcast(true);
168                } break;
169                case BROADCAST_TIMEOUT_MSG: {
170                    synchronized (mService) {
171                        broadcastTimeoutLocked(true);
172                    }
173                } break;
174                case SCHEDULE_TEMP_WHITELIST_MSG: {
175                    DeviceIdleController.LocalService dic = mService.mLocalDeviceIdleController;
176                    if (dic != null) {
177                        dic.addPowerSaveTempWhitelistAppDirect(UserHandle.getAppId(msg.arg1),
178                                msg.arg2);
179                    }
180                } break;
181            }
182        }
183    };
184
185    private final class AppNotResponding implements Runnable {
186        private final ProcessRecord mApp;
187        private final String mAnnotation;
188
189        public AppNotResponding(ProcessRecord app, String annotation) {
190            mApp = app;
191            mAnnotation = annotation;
192        }
193
194        @Override
195        public void run() {
196            mService.appNotResponding(mApp, null, null, false, mAnnotation);
197        }
198    }
199
200    BroadcastQueue(ActivityManagerService service, Handler handler,
201            String name, long timeoutPeriod, boolean allowDelayBehindServices) {
202        mService = service;
203        mHandler = new BroadcastHandler(handler.getLooper());
204        mQueueName = name;
205        mTimeoutPeriod = timeoutPeriod;
206        mDelayBehindServices = allowDelayBehindServices;
207    }
208
209    public boolean isPendingBroadcastProcessLocked(int pid) {
210        return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
211    }
212
213    public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
214        mParallelBroadcasts.add(r);
215        r.enqueueClockTime = System.currentTimeMillis();
216    }
217
218    public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
219        mOrderedBroadcasts.add(r);
220        r.enqueueClockTime = System.currentTimeMillis();
221    }
222
223    public final boolean replaceParallelBroadcastLocked(BroadcastRecord r) {
224        for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
225            if (r.intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
226                if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
227                        "***** DROPPING PARALLEL ["
228                + mQueueName + "]: " + r.intent);
229                mParallelBroadcasts.set(i, r);
230                return true;
231            }
232        }
233        return false;
234    }
235
236    public final boolean replaceOrderedBroadcastLocked(BroadcastRecord r) {
237        for (int i = mOrderedBroadcasts.size() - 1; i > 0; i--) {
238            if (r.intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
239                if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
240                        "***** DROPPING ORDERED ["
241                        + mQueueName + "]: " + r.intent);
242                mOrderedBroadcasts.set(i, r);
243                return true;
244            }
245        }
246        return false;
247    }
248
249    private final void processCurBroadcastLocked(BroadcastRecord r,
250            ProcessRecord app) throws RemoteException {
251        if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
252                "Process cur broadcast " + r + " for app " + app);
253        if (app.thread == null) {
254            throw new RemoteException();
255        }
256        r.receiver = app.thread.asBinder();
257        r.curApp = app;
258        app.curReceiver = r;
259        app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
260        mService.updateLruProcessLocked(app, false, null);
261        mService.updateOomAdjLocked();
262
263        // Tell the application to launch this receiver.
264        r.intent.setComponent(r.curComponent);
265
266        boolean started = false;
267        try {
268            if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
269                    "Delivering to component " + r.curComponent
270                    + ": " + r);
271            mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
272            app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
273                    mService.compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
274                    r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
275                    app.repProcState);
276            if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
277                    "Process cur broadcast " + r + " DELIVERED for app " + app);
278            started = true;
279        } finally {
280            if (!started) {
281                if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
282                        "Process cur broadcast " + r + ": NOT STARTED!");
283                r.receiver = null;
284                r.curApp = null;
285                app.curReceiver = null;
286            }
287        }
288    }
289
290    public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
291        boolean didSomething = false;
292        final BroadcastRecord br = mPendingBroadcast;
293        if (br != null && br.curApp.pid == app.pid) {
294            try {
295                mPendingBroadcast = null;
296                processCurBroadcastLocked(br, app);
297                didSomething = true;
298            } catch (Exception e) {
299                Slog.w(TAG, "Exception in new application when starting receiver "
300                        + br.curComponent.flattenToShortString(), e);
301                logBroadcastReceiverDiscardLocked(br);
302                finishReceiverLocked(br, br.resultCode, br.resultData,
303                        br.resultExtras, br.resultAbort, false);
304                scheduleBroadcastsLocked();
305                // We need to reset the state if we failed to start the receiver.
306                br.state = BroadcastRecord.IDLE;
307                throw new RuntimeException(e.getMessage());
308            }
309        }
310        return didSomething;
311    }
312
313    public void skipPendingBroadcastLocked(int pid) {
314        final BroadcastRecord br = mPendingBroadcast;
315        if (br != null && br.curApp.pid == pid) {
316            br.state = BroadcastRecord.IDLE;
317            br.nextReceiver = mPendingBroadcastRecvIndex;
318            mPendingBroadcast = null;
319            scheduleBroadcastsLocked();
320        }
321    }
322
323    public void skipCurrentReceiverLocked(ProcessRecord app) {
324        BroadcastRecord r = app.curReceiver;
325        if (r != null && r.queue == this) {
326            // The current broadcast is waiting for this app's receiver
327            // to be finished.  Looks like that's not going to happen, so
328            // let the broadcast continue.
329            logBroadcastReceiverDiscardLocked(r);
330            finishReceiverLocked(r, r.resultCode, r.resultData,
331                    r.resultExtras, r.resultAbort, false);
332        }
333        if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
334            if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
335                    "[" + mQueueName + "] skip & discard pending app " + r);
336            r = mPendingBroadcast;
337        }
338
339        if (r != null) {
340            logBroadcastReceiverDiscardLocked(r);
341            finishReceiverLocked(r, r.resultCode, r.resultData,
342                    r.resultExtras, r.resultAbort, false);
343            scheduleBroadcastsLocked();
344        }
345    }
346
347    public void scheduleBroadcastsLocked() {
348        if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
349                + mQueueName + "]: current="
350                + mBroadcastsScheduled);
351
352        if (mBroadcastsScheduled) {
353            return;
354        }
355        mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
356        mBroadcastsScheduled = true;
357    }
358
359    public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
360        if (mOrderedBroadcasts.size() > 0) {
361            final BroadcastRecord r = mOrderedBroadcasts.get(0);
362            if (r != null && r.receiver == receiver) {
363                return r;
364            }
365        }
366        return null;
367    }
368
369    public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
370            String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
371        final int state = r.state;
372        final ActivityInfo receiver = r.curReceiver;
373        r.state = BroadcastRecord.IDLE;
374        if (state == BroadcastRecord.IDLE) {
375            Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
376        }
377        r.receiver = null;
378        r.intent.setComponent(null);
379        if (r.curApp != null && r.curApp.curReceiver == r) {
380            r.curApp.curReceiver = null;
381        }
382        if (r.curFilter != null) {
383            r.curFilter.receiverList.curBroadcast = null;
384        }
385        r.curFilter = null;
386        r.curReceiver = null;
387        r.curApp = null;
388        mPendingBroadcast = null;
389
390        r.resultCode = resultCode;
391        r.resultData = resultData;
392        r.resultExtras = resultExtras;
393        if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
394            r.resultAbort = resultAbort;
395        } else {
396            r.resultAbort = false;
397        }
398
399        if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
400                && r.queue.mOrderedBroadcasts.size() > 0
401                && r.queue.mOrderedBroadcasts.get(0) == r) {
402            ActivityInfo nextReceiver;
403            if (r.nextReceiver < r.receivers.size()) {
404                Object obj = r.receivers.get(r.nextReceiver);
405                nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
406            } else {
407                nextReceiver = null;
408            }
409            // Don't do this if the next receive is in the same process as the current one.
410            if (receiver == null || nextReceiver == null
411                    || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
412                    || !receiver.processName.equals(nextReceiver.processName)) {
413                // In this case, we are ready to process the next receiver for the current broadcast,
414                // but are on a queue that would like to wait for services to finish before moving
415                // on.  If there are background services currently starting, then we will go into a
416                // special state where we hold off on continuing this broadcast until they are done.
417                if (mService.mServices.hasBackgroundServices(r.userId)) {
418                    Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
419                    r.state = BroadcastRecord.WAITING_SERVICES;
420                    return false;
421                }
422            }
423        }
424
425        r.curComponent = null;
426
427        // We will process the next receiver right now if this is finishing
428        // an app receiver (which is always asynchronous) or after we have
429        // come back from calling a receiver.
430        return state == BroadcastRecord.APP_RECEIVE
431                || state == BroadcastRecord.CALL_DONE_RECEIVE;
432    }
433
434    public void backgroundServicesFinishedLocked(int userId) {
435        if (mOrderedBroadcasts.size() > 0) {
436            BroadcastRecord br = mOrderedBroadcasts.get(0);
437            if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
438                Slog.i(TAG, "Resuming delayed broadcast");
439                br.curComponent = null;
440                br.state = BroadcastRecord.IDLE;
441                processNextBroadcast(false);
442            }
443        }
444    }
445
446    private static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
447            Intent intent, int resultCode, String data, Bundle extras,
448            boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
449        // Send the intent to the receiver asynchronously using one-way binder calls.
450        if (app != null) {
451            if (app.thread != null) {
452                // If we have an app thread, do the call through that so it is
453                // correctly ordered with other one-way calls.
454                app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
455                        data, extras, ordered, sticky, sendingUser, app.repProcState);
456            } else {
457                // Application has died. Receiver doesn't exist.
458                throw new RemoteException("app.thread must not be null");
459            }
460        } else {
461            receiver.performReceive(intent, resultCode, data, extras, ordered,
462                    sticky, sendingUser);
463        }
464    }
465
466    private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
467            BroadcastFilter filter, boolean ordered) {
468        boolean skip = false;
469        if (filter.requiredPermission != null) {
470            int perm = mService.checkComponentPermission(filter.requiredPermission,
471                    r.callingPid, r.callingUid, -1, true);
472            if (perm != PackageManager.PERMISSION_GRANTED) {
473                Slog.w(TAG, "Permission Denial: broadcasting "
474                        + r.intent.toString()
475                        + " from " + r.callerPackage + " (pid="
476                        + r.callingPid + ", uid=" + r.callingUid + ")"
477                        + " requires " + filter.requiredPermission
478                        + " due to registered receiver " + filter);
479                skip = true;
480            } else {
481                final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
482                if (opCode != AppOpsManager.OP_NONE
483                        && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
484                                r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
485                    Slog.w(TAG, "Appop Denial: broadcasting "
486                            + r.intent.toString()
487                            + " from " + r.callerPackage + " (pid="
488                            + r.callingPid + ", uid=" + r.callingUid + ")"
489                            + " requires appop " + AppOpsManager.permissionToOp(
490                                    filter.requiredPermission)
491                            + " due to registered receiver " + filter);
492                    skip = true;
493                }
494            }
495        }
496        if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
497            for (int i = 0; i < r.requiredPermissions.length; i++) {
498                String requiredPermission = r.requiredPermissions[i];
499                int perm = mService.checkComponentPermission(requiredPermission,
500                        filter.receiverList.pid, filter.receiverList.uid, -1, true);
501                if (perm != PackageManager.PERMISSION_GRANTED) {
502                    Slog.w(TAG, "Permission Denial: receiving "
503                            + r.intent.toString()
504                            + " to " + filter.receiverList.app
505                            + " (pid=" + filter.receiverList.pid
506                            + ", uid=" + filter.receiverList.uid + ")"
507                            + " requires " + requiredPermission
508                            + " due to sender " + r.callerPackage
509                            + " (uid " + r.callingUid + ")");
510                    skip = true;
511                    break;
512                }
513                int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
514                if (appOp != r.appOp
515                        && mService.mAppOpsService.noteOperation(appOp,
516                        filter.receiverList.uid, filter.packageName)
517                        != AppOpsManager.MODE_ALLOWED) {
518                    Slog.w(TAG, "Appop Denial: receiving "
519                            + r.intent.toString()
520                            + " to " + filter.receiverList.app
521                            + " (pid=" + filter.receiverList.pid
522                            + ", uid=" + filter.receiverList.uid + ")"
523                            + " requires appop " + AppOpsManager.permissionToOp(
524                            requiredPermission)
525                            + " due to sender " + r.callerPackage
526                            + " (uid " + r.callingUid + ")");
527                    skip = true;
528                    break;
529                }
530            }
531        }
532        if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
533            int perm = mService.checkComponentPermission(null,
534                    filter.receiverList.pid, filter.receiverList.uid, -1, true);
535            if (perm != PackageManager.PERMISSION_GRANTED) {
536                Slog.w(TAG, "Permission Denial: security check failed when receiving "
537                        + r.intent.toString()
538                        + " to " + filter.receiverList.app
539                        + " (pid=" + filter.receiverList.pid
540                        + ", uid=" + filter.receiverList.uid + ")"
541                        + " due to sender " + r.callerPackage
542                        + " (uid " + r.callingUid + ")");
543                skip = true;
544            }
545        }
546        if (!skip && r.appOp != AppOpsManager.OP_NONE
547                && mService.mAppOpsService.noteOperation(r.appOp,
548                filter.receiverList.uid, filter.packageName)
549                != AppOpsManager.MODE_ALLOWED) {
550            Slog.w(TAG, "Appop Denial: receiving "
551                    + r.intent.toString()
552                    + " to " + filter.receiverList.app
553                    + " (pid=" + filter.receiverList.pid
554                    + ", uid=" + filter.receiverList.uid + ")"
555                    + " requires appop " + AppOpsManager.opToName(r.appOp)
556                    + " due to sender " + r.callerPackage
557                    + " (uid " + r.callingUid + ")");
558            skip = true;
559        }
560
561        if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
562                r.callingPid, r.resolvedType, filter.receiverList.uid)) {
563            return;
564        }
565
566        if (filter.receiverList.app == null || filter.receiverList.app.crashing) {
567            Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
568                    + " to " + filter.receiverList + ": process crashing");
569            skip = true;
570        }
571
572        if (!skip) {
573            // If this is not being sent as an ordered broadcast, then we
574            // don't want to touch the fields that keep track of the current
575            // state of ordered broadcasts.
576            if (ordered) {
577                r.receiver = filter.receiverList.receiver.asBinder();
578                r.curFilter = filter;
579                filter.receiverList.curBroadcast = r;
580                r.state = BroadcastRecord.CALL_IN_RECEIVE;
581                if (filter.receiverList.app != null) {
582                    // Bump hosting application to no longer be in background
583                    // scheduling class.  Note that we can't do that if there
584                    // isn't an app...  but we can only be in that case for
585                    // things that directly call the IActivityManager API, which
586                    // are already core system stuff so don't matter for this.
587                    r.curApp = filter.receiverList.app;
588                    filter.receiverList.app.curReceiver = r;
589                    mService.updateOomAdjLocked(r.curApp);
590                }
591            }
592            try {
593                if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
594                        "Delivering to " + filter + " : " + r);
595                performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
596                        new Intent(r.intent), r.resultCode, r.resultData,
597                        r.resultExtras, r.ordered, r.initialSticky, r.userId);
598                if (ordered) {
599                    r.state = BroadcastRecord.CALL_DONE_RECEIVE;
600                }
601            } catch (RemoteException e) {
602                Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
603                if (ordered) {
604                    r.receiver = null;
605                    r.curFilter = null;
606                    filter.receiverList.curBroadcast = null;
607                    if (filter.receiverList.app != null) {
608                        filter.receiverList.app.curReceiver = null;
609                    }
610                }
611            }
612        }
613    }
614
615    final void scheduleTempWhitelistLocked(int uid, long duration) {
616        if (duration > Integer.MAX_VALUE) {
617            duration = Integer.MAX_VALUE;
618        }
619        // XXX ideally we should pause the broadcast until everything behind this is done,
620        // or else we will likely start dispatching the broadcast before we have opened
621        // access to the app (there is a lot of asynchronicity behind this).  It is probably
622        // not that big a deal, however, because the main purpose here is to allow apps
623        // to hold wake locks, and they will be able to acquire their wake lock immediately
624        // it just won't be enabled until we get through this work.
625        mHandler.obtainMessage(SCHEDULE_TEMP_WHITELIST_MSG, uid, (int)duration).sendToTarget();
626    }
627
628    final void processNextBroadcast(boolean fromMsg) {
629        synchronized(mService) {
630            BroadcastRecord r;
631
632            if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
633                    + mQueueName + "]: "
634                    + mParallelBroadcasts.size() + " broadcasts, "
635                    + mOrderedBroadcasts.size() + " ordered broadcasts");
636
637            mService.updateCpuStats();
638
639            if (fromMsg) {
640                mBroadcastsScheduled = false;
641            }
642
643            // First, deliver any non-serialized broadcasts right away.
644            while (mParallelBroadcasts.size() > 0) {
645                r = mParallelBroadcasts.remove(0);
646                r.dispatchTime = SystemClock.uptimeMillis();
647                r.dispatchClockTime = System.currentTimeMillis();
648                final int N = r.receivers.size();
649                if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
650                        + mQueueName + "] " + r);
651                for (int i=0; i<N; i++) {
652                    Object target = r.receivers.get(i);
653                    if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
654                            "Delivering non-ordered on [" + mQueueName + "] to registered "
655                            + target + ": " + r);
656                    deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
657                }
658                addBroadcastToHistoryLocked(r);
659                if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
660                        + mQueueName + "] " + r);
661            }
662
663            // Now take care of the next serialized one...
664
665            // If we are waiting for a process to come up to handle the next
666            // broadcast, then do nothing at this point.  Just in case, we
667            // check that the process we're waiting for still exists.
668            if (mPendingBroadcast != null) {
669                if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
670                        "processNextBroadcast [" + mQueueName + "]: waiting for "
671                        + mPendingBroadcast.curApp);
672
673                boolean isDead;
674                synchronized (mService.mPidsSelfLocked) {
675                    ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
676                    isDead = proc == null || proc.crashing;
677                }
678                if (!isDead) {
679                    // It's still alive, so keep waiting
680                    return;
681                } else {
682                    Slog.w(TAG, "pending app  ["
683                            + mQueueName + "]" + mPendingBroadcast.curApp
684                            + " died before responding to broadcast");
685                    mPendingBroadcast.state = BroadcastRecord.IDLE;
686                    mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
687                    mPendingBroadcast = null;
688                }
689            }
690
691            boolean looped = false;
692
693            do {
694                if (mOrderedBroadcasts.size() == 0) {
695                    // No more broadcasts pending, so all done!
696                    mService.scheduleAppGcsLocked();
697                    if (looped) {
698                        // If we had finished the last ordered broadcast, then
699                        // make sure all processes have correct oom and sched
700                        // adjustments.
701                        mService.updateOomAdjLocked();
702                    }
703                    return;
704                }
705                r = mOrderedBroadcasts.get(0);
706                boolean forceReceive = false;
707
708                // Ensure that even if something goes awry with the timeout
709                // detection, we catch "hung" broadcasts here, discard them,
710                // and continue to make progress.
711                //
712                // This is only done if the system is ready so that PRE_BOOT_COMPLETED
713                // receivers don't get executed with timeouts. They're intended for
714                // one time heavy lifting after system upgrades and can take
715                // significant amounts of time.
716                int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
717                if (mService.mProcessesReady && r.dispatchTime > 0) {
718                    long now = SystemClock.uptimeMillis();
719                    if ((numReceivers > 0) &&
720                            (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
721                        Slog.w(TAG, "Hung broadcast ["
722                                + mQueueName + "] discarded after timeout failure:"
723                                + " now=" + now
724                                + " dispatchTime=" + r.dispatchTime
725                                + " startTime=" + r.receiverTime
726                                + " intent=" + r.intent
727                                + " numReceivers=" + numReceivers
728                                + " nextReceiver=" + r.nextReceiver
729                                + " state=" + r.state);
730                        broadcastTimeoutLocked(false); // forcibly finish this broadcast
731                        forceReceive = true;
732                        r.state = BroadcastRecord.IDLE;
733                    }
734                }
735
736                if (r.state != BroadcastRecord.IDLE) {
737                    if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
738                            "processNextBroadcast("
739                            + mQueueName + ") called when not idle (state="
740                            + r.state + ")");
741                    return;
742                }
743
744                if (r.receivers == null || r.nextReceiver >= numReceivers
745                        || r.resultAbort || forceReceive) {
746                    // No more receivers for this broadcast!  Send the final
747                    // result if requested...
748                    if (r.resultTo != null) {
749                        try {
750                            if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,
751                                    "Finishing broadcast [" + mQueueName + "] "
752                                    + r.intent.getAction() + " app=" + r.callerApp);
753                            performReceiveLocked(r.callerApp, r.resultTo,
754                                new Intent(r.intent), r.resultCode,
755                                r.resultData, r.resultExtras, false, false, r.userId);
756                            // Set this to null so that the reference
757                            // (local and remote) isn't kept in the mBroadcastHistory.
758                            r.resultTo = null;
759                        } catch (RemoteException e) {
760                            r.resultTo = null;
761                            Slog.w(TAG, "Failure ["
762                                    + mQueueName + "] sending broadcast result of "
763                                    + r.intent, e);
764                        }
765                    }
766
767                    if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
768                    cancelBroadcastTimeoutLocked();
769
770                    if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
771                            "Finished with ordered broadcast " + r);
772
773                    // ... and on to the next...
774                    addBroadcastToHistoryLocked(r);
775                    mOrderedBroadcasts.remove(0);
776                    r = null;
777                    looped = true;
778                    continue;
779                }
780            } while (r == null);
781
782            // Get the next receiver...
783            int recIdx = r.nextReceiver++;
784
785            // Keep track of when this receiver started, and make sure there
786            // is a timeout message pending to kill it if need be.
787            r.receiverTime = SystemClock.uptimeMillis();
788            if (recIdx == 0) {
789                r.dispatchTime = r.receiverTime;
790                r.dispatchClockTime = System.currentTimeMillis();
791                if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
792                        + mQueueName + "] " + r);
793            }
794            if (! mPendingBroadcastTimeoutMessage) {
795                long timeoutTime = r.receiverTime + mTimeoutPeriod;
796                if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
797                        "Submitting BROADCAST_TIMEOUT_MSG ["
798                        + mQueueName + "] for " + r + " at " + timeoutTime);
799                setBroadcastTimeoutLocked(timeoutTime);
800            }
801
802            final BroadcastOptions brOptions = r.options;
803            final Object nextReceiver = r.receivers.get(recIdx);
804
805            if (nextReceiver instanceof BroadcastFilter) {
806                // Simple case: this is a registered receiver who gets
807                // a direct call.
808                BroadcastFilter filter = (BroadcastFilter)nextReceiver;
809                if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
810                        "Delivering ordered ["
811                        + mQueueName + "] to registered "
812                        + filter + ": " + r);
813                deliverToRegisteredReceiverLocked(r, filter, r.ordered);
814                if (r.receiver == null || !r.ordered) {
815                    // The receiver has already finished, so schedule to
816                    // process the next one.
817                    if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
818                            + mQueueName + "]: ordered="
819                            + r.ordered + " receiver=" + r.receiver);
820                    r.state = BroadcastRecord.IDLE;
821                    scheduleBroadcastsLocked();
822                } else {
823                    if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
824                        scheduleTempWhitelistLocked(filter.owningUid,
825                                brOptions.getTemporaryAppWhitelistDuration());
826                    }
827                }
828                return;
829            }
830
831            // Hard case: need to instantiate the receiver, possibly
832            // starting its application process to host it.
833
834            ResolveInfo info =
835                (ResolveInfo)nextReceiver;
836            ComponentName component = new ComponentName(
837                    info.activityInfo.applicationInfo.packageName,
838                    info.activityInfo.name);
839
840            boolean skip = false;
841            int perm = mService.checkComponentPermission(info.activityInfo.permission,
842                    r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
843                    info.activityInfo.exported);
844            if (perm != PackageManager.PERMISSION_GRANTED) {
845                if (!info.activityInfo.exported) {
846                    Slog.w(TAG, "Permission Denial: broadcasting "
847                            + r.intent.toString()
848                            + " from " + r.callerPackage + " (pid=" + r.callingPid
849                            + ", uid=" + r.callingUid + ")"
850                            + " is not exported from uid " + info.activityInfo.applicationInfo.uid
851                            + " due to receiver " + component.flattenToShortString());
852                } else {
853                    Slog.w(TAG, "Permission Denial: broadcasting "
854                            + r.intent.toString()
855                            + " from " + r.callerPackage + " (pid=" + r.callingPid
856                            + ", uid=" + r.callingUid + ")"
857                            + " requires " + info.activityInfo.permission
858                            + " due to receiver " + component.flattenToShortString());
859                }
860                skip = true;
861            } else if (info.activityInfo.permission != null) {
862                final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
863                if (opCode != AppOpsManager.OP_NONE
864                        && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
865                                r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
866                    Slog.w(TAG, "Appop Denial: broadcasting "
867                            + r.intent.toString()
868                            + " from " + r.callerPackage + " (pid="
869                            + r.callingPid + ", uid=" + r.callingUid + ")"
870                            + " requires appop " + AppOpsManager.permissionToOp(
871                                    info.activityInfo.permission)
872                            + " due to registered receiver "
873                            + component.flattenToShortString());
874                    skip = true;
875                }
876            }
877            if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
878                r.requiredPermissions != null && r.requiredPermissions.length > 0) {
879                for (int i = 0; i < r.requiredPermissions.length; i++) {
880                    String requiredPermission = r.requiredPermissions[i];
881                    try {
882                        perm = AppGlobals.getPackageManager().
883                                checkPermission(requiredPermission,
884                                        info.activityInfo.applicationInfo.packageName,
885                                        UserHandle
886                                                .getUserId(info.activityInfo.applicationInfo.uid));
887                    } catch (RemoteException e) {
888                        perm = PackageManager.PERMISSION_DENIED;
889                    }
890                    if (perm != PackageManager.PERMISSION_GRANTED) {
891                        Slog.w(TAG, "Permission Denial: receiving "
892                                + r.intent + " to "
893                                + component.flattenToShortString()
894                                + " requires " + requiredPermission
895                                + " due to sender " + r.callerPackage
896                                + " (uid " + r.callingUid + ")");
897                        skip = true;
898                        break;
899                    }
900                    int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
901                    if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
902                            && mService.mAppOpsService.noteOperation(appOp,
903                            info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
904                            != AppOpsManager.MODE_ALLOWED) {
905                        Slog.w(TAG, "Appop Denial: receiving "
906                                + r.intent + " to "
907                                + component.flattenToShortString()
908                                + " requires appop " + AppOpsManager.permissionToOp(
909                                requiredPermission)
910                                + " due to sender " + r.callerPackage
911                                + " (uid " + r.callingUid + ")");
912                        skip = true;
913                        break;
914                    }
915                }
916            }
917            if (!skip && r.appOp != AppOpsManager.OP_NONE
918                    && mService.mAppOpsService.noteOperation(r.appOp,
919                    info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
920                    != AppOpsManager.MODE_ALLOWED) {
921                Slog.w(TAG, "Appop Denial: receiving "
922                        + r.intent + " to "
923                        + component.flattenToShortString()
924                        + " requires appop " + AppOpsManager.opToName(r.appOp)
925                        + " due to sender " + r.callerPackage
926                        + " (uid " + r.callingUid + ")");
927                skip = true;
928            }
929            if (!skip) {
930                skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
931                        r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
932            }
933            boolean isSingleton = false;
934            try {
935                isSingleton = mService.isSingleton(info.activityInfo.processName,
936                        info.activityInfo.applicationInfo,
937                        info.activityInfo.name, info.activityInfo.flags);
938            } catch (SecurityException e) {
939                Slog.w(TAG, e.getMessage());
940                skip = true;
941            }
942            if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
943                if (ActivityManager.checkUidPermission(
944                        android.Manifest.permission.INTERACT_ACROSS_USERS,
945                        info.activityInfo.applicationInfo.uid)
946                                != PackageManager.PERMISSION_GRANTED) {
947                    Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
948                            + " requests FLAG_SINGLE_USER, but app does not hold "
949                            + android.Manifest.permission.INTERACT_ACROSS_USERS);
950                    skip = true;
951                }
952            }
953            if (r.curApp != null && r.curApp.crashing) {
954                // If the target process is crashing, just skip it.
955                Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
956                        + " to " + r.curApp + ": process crashing");
957                skip = true;
958            }
959            if (!skip) {
960                boolean isAvailable = false;
961                try {
962                    isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
963                            info.activityInfo.packageName,
964                            UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
965                } catch (Exception e) {
966                    // all such failures mean we skip this receiver
967                    Slog.w(TAG, "Exception getting recipient info for "
968                            + info.activityInfo.packageName, e);
969                }
970                if (!isAvailable) {
971                    if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
972                            "Skipping delivery to " + info.activityInfo.packageName + " / "
973                            + info.activityInfo.applicationInfo.uid
974                            + " : package no longer available");
975                    skip = true;
976                }
977            }
978
979            if (skip) {
980                if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
981                        "Skipping delivery of ordered [" + mQueueName + "] "
982                        + r + " for whatever reason");
983                r.receiver = null;
984                r.curFilter = null;
985                r.state = BroadcastRecord.IDLE;
986                scheduleBroadcastsLocked();
987                return;
988            }
989
990            r.state = BroadcastRecord.APP_RECEIVE;
991            String targetProcess = info.activityInfo.processName;
992            r.curComponent = component;
993            final int receiverUid = info.activityInfo.applicationInfo.uid;
994            // If it's a singleton, it needs to be the same app or a special app
995            if (r.callingUid != Process.SYSTEM_UID && isSingleton
996                    && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
997                info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
998            }
999            r.curReceiver = info.activityInfo;
1000            if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
1001                Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1002                        + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1003                        + info.activityInfo.applicationInfo.uid);
1004            }
1005
1006            if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1007                scheduleTempWhitelistLocked(receiverUid,
1008                        brOptions.getTemporaryAppWhitelistDuration());
1009            }
1010
1011            // Broadcast is being executed, its package can't be stopped.
1012            try {
1013                AppGlobals.getPackageManager().setPackageStoppedState(
1014                        r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
1015            } catch (RemoteException e) {
1016            } catch (IllegalArgumentException e) {
1017                Slog.w(TAG, "Failed trying to unstop package "
1018                        + r.curComponent.getPackageName() + ": " + e);
1019            }
1020
1021            // Is this receiver's application already running?
1022            ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1023                    info.activityInfo.applicationInfo.uid, false);
1024            if (app != null && app.thread != null) {
1025                try {
1026                    app.addPackage(info.activityInfo.packageName,
1027                            info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
1028                    processCurBroadcastLocked(r, app);
1029                    return;
1030                } catch (RemoteException e) {
1031                    Slog.w(TAG, "Exception when sending broadcast to "
1032                          + r.curComponent, e);
1033                } catch (RuntimeException e) {
1034                    Slog.wtf(TAG, "Failed sending broadcast to "
1035                            + r.curComponent + " with " + r.intent, e);
1036                    // If some unexpected exception happened, just skip
1037                    // this broadcast.  At this point we are not in the call
1038                    // from a client, so throwing an exception out from here
1039                    // will crash the entire system instead of just whoever
1040                    // sent the broadcast.
1041                    logBroadcastReceiverDiscardLocked(r);
1042                    finishReceiverLocked(r, r.resultCode, r.resultData,
1043                            r.resultExtras, r.resultAbort, false);
1044                    scheduleBroadcastsLocked();
1045                    // We need to reset the state if we failed to start the receiver.
1046                    r.state = BroadcastRecord.IDLE;
1047                    return;
1048                }
1049
1050                // If a dead object exception was thrown -- fall through to
1051                // restart the application.
1052            }
1053
1054            // Not running -- get it started, to be executed when the app comes up.
1055            if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1056                    "Need to start app ["
1057                    + mQueueName + "] " + targetProcess + " for broadcast " + r);
1058            if ((r.curApp=mService.startProcessLocked(targetProcess,
1059                    info.activityInfo.applicationInfo, true,
1060                    r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1061                    "broadcast", r.curComponent,
1062                    (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
1063                            == null) {
1064                // Ah, this recipient is unavailable.  Finish it if necessary,
1065                // and mark the broadcast record as ready for the next.
1066                Slog.w(TAG, "Unable to launch app "
1067                        + info.activityInfo.applicationInfo.packageName + "/"
1068                        + info.activityInfo.applicationInfo.uid + " for broadcast "
1069                        + r.intent + ": process is bad");
1070                logBroadcastReceiverDiscardLocked(r);
1071                finishReceiverLocked(r, r.resultCode, r.resultData,
1072                        r.resultExtras, r.resultAbort, false);
1073                scheduleBroadcastsLocked();
1074                r.state = BroadcastRecord.IDLE;
1075                return;
1076            }
1077
1078            mPendingBroadcast = r;
1079            mPendingBroadcastRecvIndex = recIdx;
1080        }
1081    }
1082
1083    final void setBroadcastTimeoutLocked(long timeoutTime) {
1084        if (! mPendingBroadcastTimeoutMessage) {
1085            Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1086            mHandler.sendMessageAtTime(msg, timeoutTime);
1087            mPendingBroadcastTimeoutMessage = true;
1088        }
1089    }
1090
1091    final void cancelBroadcastTimeoutLocked() {
1092        if (mPendingBroadcastTimeoutMessage) {
1093            mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1094            mPendingBroadcastTimeoutMessage = false;
1095        }
1096    }
1097
1098    final void broadcastTimeoutLocked(boolean fromMsg) {
1099        if (fromMsg) {
1100            mPendingBroadcastTimeoutMessage = false;
1101        }
1102
1103        if (mOrderedBroadcasts.size() == 0) {
1104            return;
1105        }
1106
1107        long now = SystemClock.uptimeMillis();
1108        BroadcastRecord r = mOrderedBroadcasts.get(0);
1109        if (fromMsg) {
1110            if (mService.mDidDexOpt) {
1111                // Delay timeouts until dexopt finishes.
1112                mService.mDidDexOpt = false;
1113                long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
1114                setBroadcastTimeoutLocked(timeoutTime);
1115                return;
1116            }
1117            if (!mService.mProcessesReady) {
1118                // Only process broadcast timeouts if the system is ready. That way
1119                // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1120                // to do heavy lifting for system up.
1121                return;
1122            }
1123
1124            long timeoutTime = r.receiverTime + mTimeoutPeriod;
1125            if (timeoutTime > now) {
1126                // We can observe premature timeouts because we do not cancel and reset the
1127                // broadcast timeout message after each receiver finishes.  Instead, we set up
1128                // an initial timeout then kick it down the road a little further as needed
1129                // when it expires.
1130                if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1131                        "Premature timeout ["
1132                        + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1133                        + timeoutTime);
1134                setBroadcastTimeoutLocked(timeoutTime);
1135                return;
1136            }
1137        }
1138
1139        BroadcastRecord br = mOrderedBroadcasts.get(0);
1140        if (br.state == BroadcastRecord.WAITING_SERVICES) {
1141            // In this case the broadcast had already finished, but we had decided to wait
1142            // for started services to finish as well before going on.  So if we have actually
1143            // waited long enough time timeout the broadcast, let's give up on the whole thing
1144            // and just move on to the next.
1145            Slog.i(TAG, "Waited long enough for: " + (br.curComponent != null
1146                    ? br.curComponent.flattenToShortString() : "(null)"));
1147            br.curComponent = null;
1148            br.state = BroadcastRecord.IDLE;
1149            processNextBroadcast(false);
1150            return;
1151        }
1152
1153        Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver
1154                + ", started " + (now - r.receiverTime) + "ms ago");
1155        r.receiverTime = now;
1156        r.anrCount++;
1157
1158        // Current receiver has passed its expiration date.
1159        if (r.nextReceiver <= 0) {
1160            Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
1161            return;
1162        }
1163
1164        ProcessRecord app = null;
1165        String anrMessage = null;
1166
1167        Object curReceiver = r.receivers.get(r.nextReceiver-1);
1168        Slog.w(TAG, "Receiver during timeout: " + curReceiver);
1169        logBroadcastReceiverDiscardLocked(r);
1170        if (curReceiver instanceof BroadcastFilter) {
1171            BroadcastFilter bf = (BroadcastFilter)curReceiver;
1172            if (bf.receiverList.pid != 0
1173                    && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1174                synchronized (mService.mPidsSelfLocked) {
1175                    app = mService.mPidsSelfLocked.get(
1176                            bf.receiverList.pid);
1177                }
1178            }
1179        } else {
1180            app = r.curApp;
1181        }
1182
1183        if (app != null) {
1184            anrMessage = "Broadcast of " + r.intent.toString();
1185        }
1186
1187        if (mPendingBroadcast == r) {
1188            mPendingBroadcast = null;
1189        }
1190
1191        // Move on to the next receiver.
1192        finishReceiverLocked(r, r.resultCode, r.resultData,
1193                r.resultExtras, r.resultAbort, false);
1194        scheduleBroadcastsLocked();
1195
1196        if (anrMessage != null) {
1197            // Post the ANR to the handler since we do not want to process ANRs while
1198            // potentially holding our lock.
1199            mHandler.post(new AppNotResponding(app, anrMessage));
1200        }
1201    }
1202
1203    private final int ringAdvance(int x, final int increment, final int ringSize) {
1204        x += increment;
1205        if (x < 0) return (ringSize - 1);
1206        else if (x >= ringSize) return 0;
1207        else return x;
1208    }
1209
1210    private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
1211        if (r.callingUid < 0) {
1212            // This was from a registerReceiver() call; ignore it.
1213            return;
1214        }
1215        r.finishTime = SystemClock.uptimeMillis();
1216
1217        mBroadcastHistory[mHistoryNext] = r;
1218        mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1219
1220        mBroadcastSummaryHistory[mSummaryHistoryNext] = r.intent;
1221        mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = r.enqueueClockTime;
1222        mSummaryHistoryDispatchTime[mSummaryHistoryNext] = r.dispatchClockTime;
1223        mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1224        mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
1225    }
1226
1227    boolean cleanupDisabledPackageReceiversLocked(
1228            String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1229        boolean didSomething = false;
1230        for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1231            didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1232                    packageName, filterByClasses, userId, doit);
1233            if (!doit && didSomething) {
1234                return true;
1235            }
1236        }
1237
1238        for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1239            didSomething |= mOrderedBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1240                    packageName, filterByClasses, userId, doit);
1241            if (!doit && didSomething) {
1242                return true;
1243            }
1244        }
1245
1246        return didSomething;
1247    }
1248
1249    final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
1250        final int logIndex = r.nextReceiver - 1;
1251        if (logIndex >= 0 && logIndex < r.receivers.size()) {
1252            Object curReceiver = r.receivers.get(logIndex);
1253            if (curReceiver instanceof BroadcastFilter) {
1254                BroadcastFilter bf = (BroadcastFilter) curReceiver;
1255                EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
1256                        bf.owningUserId, System.identityHashCode(r),
1257                        r.intent.getAction(), logIndex, System.identityHashCode(bf));
1258            } else {
1259                ResolveInfo ri = (ResolveInfo) curReceiver;
1260                EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1261                        UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
1262                        System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
1263            }
1264        } else {
1265            if (logIndex < 0) Slog.w(TAG,
1266                    "Discarding broadcast before first receiver is invoked: " + r);
1267            EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1268                    -1, System.identityHashCode(r),
1269                    r.intent.getAction(),
1270                    r.nextReceiver,
1271                    "NONE");
1272        }
1273    }
1274
1275    final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1276            int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
1277        if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1278                || mPendingBroadcast != null) {
1279            boolean printed = false;
1280            for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1281                BroadcastRecord br = mParallelBroadcasts.get(i);
1282                if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1283                    continue;
1284                }
1285                if (!printed) {
1286                    if (needSep) {
1287                        pw.println();
1288                    }
1289                    needSep = true;
1290                    printed = true;
1291                    pw.println("  Active broadcasts [" + mQueueName + "]:");
1292                }
1293                pw.println("  Active Broadcast " + mQueueName + " #" + i + ":");
1294                br.dump(pw, "    ");
1295            }
1296            printed = false;
1297            needSep = true;
1298            for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1299                BroadcastRecord br = mOrderedBroadcasts.get(i);
1300                if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1301                    continue;
1302                }
1303                if (!printed) {
1304                    if (needSep) {
1305                        pw.println();
1306                    }
1307                    needSep = true;
1308                    printed = true;
1309                    pw.println("  Active ordered broadcasts [" + mQueueName + "]:");
1310                }
1311                pw.println("  Active Ordered Broadcast " + mQueueName + " #" + i + ":");
1312                mOrderedBroadcasts.get(i).dump(pw, "    ");
1313            }
1314            if (dumpPackage == null || (mPendingBroadcast != null
1315                    && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1316                if (needSep) {
1317                    pw.println();
1318                }
1319                pw.println("  Pending broadcast [" + mQueueName + "]:");
1320                if (mPendingBroadcast != null) {
1321                    mPendingBroadcast.dump(pw, "    ");
1322                } else {
1323                    pw.println("    (null)");
1324                }
1325                needSep = true;
1326            }
1327        }
1328
1329        int i;
1330        boolean printed = false;
1331
1332        i = -1;
1333        int lastIndex = mHistoryNext;
1334        int ringIndex = lastIndex;
1335        do {
1336            // increasing index = more recent entry, and we want to print the most
1337            // recent first and work backwards, so we roll through the ring backwards.
1338            ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1339            BroadcastRecord r = mBroadcastHistory[ringIndex];
1340            if (r == null) {
1341                continue;
1342            }
1343
1344            i++; // genuine record of some sort even if we're filtering it out
1345            if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1346                continue;
1347            }
1348            if (!printed) {
1349                if (needSep) {
1350                    pw.println();
1351                }
1352                needSep = true;
1353                pw.println("  Historical broadcasts [" + mQueueName + "]:");
1354                printed = true;
1355            }
1356            if (dumpAll) {
1357                pw.print("  Historical Broadcast " + mQueueName + " #");
1358                        pw.print(i); pw.println(":");
1359                r.dump(pw, "    ");
1360            } else {
1361                pw.print("  #"); pw.print(i); pw.print(": "); pw.println(r);
1362                pw.print("    ");
1363                pw.println(r.intent.toShortString(false, true, true, false));
1364                if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1365                    pw.print("    targetComp: "); pw.println(r.targetComp.toShortString());
1366                }
1367                Bundle bundle = r.intent.getExtras();
1368                if (bundle != null) {
1369                    pw.print("    extras: "); pw.println(bundle.toString());
1370                }
1371            }
1372        } while (ringIndex != lastIndex);
1373
1374        if (dumpPackage == null) {
1375            lastIndex = ringIndex = mSummaryHistoryNext;
1376            if (dumpAll) {
1377                printed = false;
1378                i = -1;
1379            } else {
1380                // roll over the 'i' full dumps that have already been issued
1381                for (int j = i;
1382                        j > 0 && ringIndex != lastIndex;) {
1383                    ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1384                    BroadcastRecord r = mBroadcastHistory[ringIndex];
1385                    if (r == null) {
1386                        continue;
1387                    }
1388                    j--;
1389                }
1390            }
1391            // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
1392            // the overall broadcast history.
1393            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1394            do {
1395                ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1396                Intent intent = mBroadcastSummaryHistory[ringIndex];
1397                if (intent == null) {
1398                    continue;
1399                }
1400                if (!printed) {
1401                    if (needSep) {
1402                        pw.println();
1403                    }
1404                    needSep = true;
1405                    pw.println("  Historical broadcasts summary [" + mQueueName + "]:");
1406                    printed = true;
1407                }
1408                if (!dumpAll && i >= 50) {
1409                    pw.println("  ...");
1410                    break;
1411                }
1412                i++;
1413                pw.print("  #"); pw.print(i); pw.print(": ");
1414                pw.println(intent.toShortString(false, true, true, false));
1415                pw.print("    enq="); pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
1416                pw.print(" disp="); pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
1417                pw.print(" fin="); pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
1418                Bundle bundle = intent.getExtras();
1419                if (bundle != null) {
1420                    pw.print("    extras: "); pw.println(bundle.toString());
1421                }
1422            } while (ringIndex != lastIndex);
1423        }
1424
1425        return needSep;
1426    }
1427}
1428