BroadcastQueue.java revision 99b6043dad9d215cf15810b885b6b8c215dd5b5a
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) {
497            int perm = mService.checkComponentPermission(r.requiredPermission,
498                    filter.receiverList.pid, filter.receiverList.uid, -1, true);
499            if (perm != PackageManager.PERMISSION_GRANTED) {
500                Slog.w(TAG, "Permission Denial: receiving "
501                        + r.intent.toString()
502                        + " to " + filter.receiverList.app
503                        + " (pid=" + filter.receiverList.pid
504                        + ", uid=" + filter.receiverList.uid + ")"
505                        + " requires " + r.requiredPermission
506                        + " due to sender " + r.callerPackage
507                        + " (uid " + r.callingUid + ")");
508                skip = true;
509            }
510            int appOp = AppOpsManager.OP_NONE;
511            if (r.requiredPermission != null) {
512                appOp = AppOpsManager.permissionToOpCode(r.requiredPermission);
513                if (appOp != AppOpsManager.OP_NONE
514                        && mService.mAppOpsService.noteOperation(appOp,
515                            filter.receiverList.uid, filter.packageName)
516                                != AppOpsManager.MODE_ALLOWED) {
517                    Slog.w(TAG, "Appop Denial: receiving "
518                            + r.intent.toString()
519                            + " to " + filter.receiverList.app
520                            + " (pid=" + filter.receiverList.pid
521                            + ", uid=" + filter.receiverList.uid + ")"
522                            + " requires appop " + AppOpsManager.permissionToOp(
523                                    r.requiredPermission)
524                            + " due to sender " + r.callerPackage
525                            + " (uid " + r.callingUid + ")");
526                    skip = true;
527                }
528            }
529            if (!skip && r.appOp != appOp && r.appOp != AppOpsManager.OP_NONE
530                    && mService.mAppOpsService.noteOperation(r.appOp,
531                            filter.receiverList.uid, filter.packageName)
532                                    != AppOpsManager.MODE_ALLOWED) {
533                    Slog.w(TAG, "Appop Denial: receiving "
534                            + r.intent.toString()
535                            + " to " + filter.receiverList.app
536                            + " (pid=" + filter.receiverList.pid
537                            + ", uid=" + filter.receiverList.uid + ")"
538                            + " requires appop " + AppOpsManager.permissionToOp(
539                            r.requiredPermission)
540                            + " due to sender " + r.callerPackage
541                            + " (uid " + r.callingUid + ")");
542                    skip = true;
543            }
544        }
545
546        if (!skip) {
547            skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
548                    r.callingPid, r.resolvedType, filter.receiverList.uid);
549        }
550
551        if (filter.receiverList.app == null || filter.receiverList.app.crashing) {
552            Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
553                    + " to " + filter.receiverList + ": process crashing");
554            skip = true;
555        }
556
557        if (!skip) {
558            // If this is not being sent as an ordered broadcast, then we
559            // don't want to touch the fields that keep track of the current
560            // state of ordered broadcasts.
561            if (ordered) {
562                r.receiver = filter.receiverList.receiver.asBinder();
563                r.curFilter = filter;
564                filter.receiverList.curBroadcast = r;
565                r.state = BroadcastRecord.CALL_IN_RECEIVE;
566                if (filter.receiverList.app != null) {
567                    // Bump hosting application to no longer be in background
568                    // scheduling class.  Note that we can't do that if there
569                    // isn't an app...  but we can only be in that case for
570                    // things that directly call the IActivityManager API, which
571                    // are already core system stuff so don't matter for this.
572                    r.curApp = filter.receiverList.app;
573                    filter.receiverList.app.curReceiver = r;
574                    mService.updateOomAdjLocked(r.curApp);
575                }
576            }
577            try {
578                if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
579                        "Delivering to " + filter + " : " + r);
580                performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
581                        new Intent(r.intent), r.resultCode, r.resultData,
582                        r.resultExtras, r.ordered, r.initialSticky, r.userId);
583                if (ordered) {
584                    r.state = BroadcastRecord.CALL_DONE_RECEIVE;
585                }
586            } catch (RemoteException e) {
587                Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
588                if (ordered) {
589                    r.receiver = null;
590                    r.curFilter = null;
591                    filter.receiverList.curBroadcast = null;
592                    if (filter.receiverList.app != null) {
593                        filter.receiverList.app.curReceiver = null;
594                    }
595                }
596            }
597        }
598    }
599
600    final void scheduleTempWhitelistLocked(int uid, long duration) {
601        if (duration > Integer.MAX_VALUE) {
602            duration = Integer.MAX_VALUE;
603        }
604        // XXX ideally we should pause the broadcast until everything behind this is done,
605        // or else we will likely start dispatching the broadcast before we have opened
606        // access to the app (there is a lot of asynchronicity behind this).  It is probably
607        // not that big a deal, however, because the main purpose here is to allow apps
608        // to hold wake locks, and they will be able to acquire their wake lock immediately
609        // it just won't be enabled until we get through this work.
610        mHandler.obtainMessage(SCHEDULE_TEMP_WHITELIST_MSG, uid, (int)duration).sendToTarget();
611    }
612
613    final void processNextBroadcast(boolean fromMsg) {
614        synchronized(mService) {
615            BroadcastRecord r;
616
617            if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
618                    + mQueueName + "]: "
619                    + mParallelBroadcasts.size() + " broadcasts, "
620                    + mOrderedBroadcasts.size() + " ordered broadcasts");
621
622            mService.updateCpuStats();
623
624            if (fromMsg) {
625                mBroadcastsScheduled = false;
626            }
627
628            // First, deliver any non-serialized broadcasts right away.
629            while (mParallelBroadcasts.size() > 0) {
630                r = mParallelBroadcasts.remove(0);
631                r.dispatchTime = SystemClock.uptimeMillis();
632                r.dispatchClockTime = System.currentTimeMillis();
633                final int N = r.receivers.size();
634                if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
635                        + mQueueName + "] " + r);
636                for (int i=0; i<N; i++) {
637                    Object target = r.receivers.get(i);
638                    if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
639                            "Delivering non-ordered on [" + mQueueName + "] to registered "
640                            + target + ": " + r);
641                    deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
642                }
643                addBroadcastToHistoryLocked(r);
644                if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
645                        + mQueueName + "] " + r);
646            }
647
648            // Now take care of the next serialized one...
649
650            // If we are waiting for a process to come up to handle the next
651            // broadcast, then do nothing at this point.  Just in case, we
652            // check that the process we're waiting for still exists.
653            if (mPendingBroadcast != null) {
654                if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
655                        "processNextBroadcast [" + mQueueName + "]: waiting for "
656                        + mPendingBroadcast.curApp);
657
658                boolean isDead;
659                synchronized (mService.mPidsSelfLocked) {
660                    ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
661                    isDead = proc == null || proc.crashing;
662                }
663                if (!isDead) {
664                    // It's still alive, so keep waiting
665                    return;
666                } else {
667                    Slog.w(TAG, "pending app  ["
668                            + mQueueName + "]" + mPendingBroadcast.curApp
669                            + " died before responding to broadcast");
670                    mPendingBroadcast.state = BroadcastRecord.IDLE;
671                    mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
672                    mPendingBroadcast = null;
673                }
674            }
675
676            boolean looped = false;
677
678            do {
679                if (mOrderedBroadcasts.size() == 0) {
680                    // No more broadcasts pending, so all done!
681                    mService.scheduleAppGcsLocked();
682                    if (looped) {
683                        // If we had finished the last ordered broadcast, then
684                        // make sure all processes have correct oom and sched
685                        // adjustments.
686                        mService.updateOomAdjLocked();
687                    }
688                    return;
689                }
690                r = mOrderedBroadcasts.get(0);
691                boolean forceReceive = false;
692
693                // Ensure that even if something goes awry with the timeout
694                // detection, we catch "hung" broadcasts here, discard them,
695                // and continue to make progress.
696                //
697                // This is only done if the system is ready so that PRE_BOOT_COMPLETED
698                // receivers don't get executed with timeouts. They're intended for
699                // one time heavy lifting after system upgrades and can take
700                // significant amounts of time.
701                int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
702                if (mService.mProcessesReady && r.dispatchTime > 0) {
703                    long now = SystemClock.uptimeMillis();
704                    if ((numReceivers > 0) &&
705                            (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
706                        Slog.w(TAG, "Hung broadcast ["
707                                + mQueueName + "] discarded after timeout failure:"
708                                + " now=" + now
709                                + " dispatchTime=" + r.dispatchTime
710                                + " startTime=" + r.receiverTime
711                                + " intent=" + r.intent
712                                + " numReceivers=" + numReceivers
713                                + " nextReceiver=" + r.nextReceiver
714                                + " state=" + r.state);
715                        broadcastTimeoutLocked(false); // forcibly finish this broadcast
716                        forceReceive = true;
717                        r.state = BroadcastRecord.IDLE;
718                    }
719                }
720
721                if (r.state != BroadcastRecord.IDLE) {
722                    if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
723                            "processNextBroadcast("
724                            + mQueueName + ") called when not idle (state="
725                            + r.state + ")");
726                    return;
727                }
728
729                if (r.receivers == null || r.nextReceiver >= numReceivers
730                        || r.resultAbort || forceReceive) {
731                    // No more receivers for this broadcast!  Send the final
732                    // result if requested...
733                    if (r.resultTo != null) {
734                        try {
735                            if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,
736                                    "Finishing broadcast [" + mQueueName + "] "
737                                    + r.intent.getAction() + " app=" + r.callerApp);
738                            performReceiveLocked(r.callerApp, r.resultTo,
739                                new Intent(r.intent), r.resultCode,
740                                r.resultData, r.resultExtras, false, false, r.userId);
741                            // Set this to null so that the reference
742                            // (local and remote) isn't kept in the mBroadcastHistory.
743                            r.resultTo = null;
744                        } catch (RemoteException e) {
745                            r.resultTo = null;
746                            Slog.w(TAG, "Failure ["
747                                    + mQueueName + "] sending broadcast result of "
748                                    + r.intent, e);
749                        }
750                    }
751
752                    if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
753                    cancelBroadcastTimeoutLocked();
754
755                    if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
756                            "Finished with ordered broadcast " + r);
757
758                    // ... and on to the next...
759                    addBroadcastToHistoryLocked(r);
760                    mOrderedBroadcasts.remove(0);
761                    r = null;
762                    looped = true;
763                    continue;
764                }
765            } while (r == null);
766
767            // Get the next receiver...
768            int recIdx = r.nextReceiver++;
769
770            // Keep track of when this receiver started, and make sure there
771            // is a timeout message pending to kill it if need be.
772            r.receiverTime = SystemClock.uptimeMillis();
773            if (recIdx == 0) {
774                r.dispatchTime = r.receiverTime;
775                r.dispatchClockTime = System.currentTimeMillis();
776                if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
777                        + mQueueName + "] " + r);
778            }
779            if (! mPendingBroadcastTimeoutMessage) {
780                long timeoutTime = r.receiverTime + mTimeoutPeriod;
781                if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
782                        "Submitting BROADCAST_TIMEOUT_MSG ["
783                        + mQueueName + "] for " + r + " at " + timeoutTime);
784                setBroadcastTimeoutLocked(timeoutTime);
785            }
786
787            final BroadcastOptions brOptions = r.options;
788            final Object nextReceiver = r.receivers.get(recIdx);
789
790            if (nextReceiver instanceof BroadcastFilter) {
791                // Simple case: this is a registered receiver who gets
792                // a direct call.
793                BroadcastFilter filter = (BroadcastFilter)nextReceiver;
794                if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
795                        "Delivering ordered ["
796                        + mQueueName + "] to registered "
797                        + filter + ": " + r);
798                deliverToRegisteredReceiverLocked(r, filter, r.ordered);
799                if (r.receiver == null || !r.ordered) {
800                    // The receiver has already finished, so schedule to
801                    // process the next one.
802                    if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
803                            + mQueueName + "]: ordered="
804                            + r.ordered + " receiver=" + r.receiver);
805                    r.state = BroadcastRecord.IDLE;
806                    scheduleBroadcastsLocked();
807                } else {
808                    if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
809                        scheduleTempWhitelistLocked(filter.owningUid,
810                                brOptions.getTemporaryAppWhitelistDuration());
811                    }
812                }
813                return;
814            }
815
816            // Hard case: need to instantiate the receiver, possibly
817            // starting its application process to host it.
818
819            ResolveInfo info =
820                (ResolveInfo)nextReceiver;
821            ComponentName component = new ComponentName(
822                    info.activityInfo.applicationInfo.packageName,
823                    info.activityInfo.name);
824
825            boolean skip = false;
826            int perm = mService.checkComponentPermission(info.activityInfo.permission,
827                    r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
828                    info.activityInfo.exported);
829            if (perm != PackageManager.PERMISSION_GRANTED) {
830                if (!info.activityInfo.exported) {
831                    Slog.w(TAG, "Permission Denial: broadcasting "
832                            + r.intent.toString()
833                            + " from " + r.callerPackage + " (pid=" + r.callingPid
834                            + ", uid=" + r.callingUid + ")"
835                            + " is not exported from uid " + info.activityInfo.applicationInfo.uid
836                            + " due to receiver " + component.flattenToShortString());
837                } else {
838                    Slog.w(TAG, "Permission Denial: broadcasting "
839                            + r.intent.toString()
840                            + " from " + r.callerPackage + " (pid=" + r.callingPid
841                            + ", uid=" + r.callingUid + ")"
842                            + " requires " + info.activityInfo.permission
843                            + " due to receiver " + component.flattenToShortString());
844                }
845                skip = true;
846            } else if (info.activityInfo.permission != null) {
847                final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
848                if (opCode != AppOpsManager.OP_NONE
849                        && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
850                                r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
851                    Slog.w(TAG, "Appop Denial: broadcasting "
852                            + r.intent.toString()
853                            + " from " + r.callerPackage + " (pid="
854                            + r.callingPid + ", uid=" + r.callingUid + ")"
855                            + " requires appop " + AppOpsManager.permissionToOp(
856                                    info.activityInfo.permission)
857                            + " due to registered receiver "
858                            + component.flattenToShortString());
859                    skip = true;
860                }
861            }
862            if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
863                r.requiredPermission != null) {
864                try {
865                    perm = AppGlobals.getPackageManager().
866                            checkPermission(r.requiredPermission,
867                                    info.activityInfo.applicationInfo.packageName,
868                                    UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
869                } catch (RemoteException e) {
870                    perm = PackageManager.PERMISSION_DENIED;
871                }
872                if (perm != PackageManager.PERMISSION_GRANTED) {
873                    Slog.w(TAG, "Permission Denial: receiving "
874                            + r.intent + " to "
875                            + component.flattenToShortString()
876                            + " requires " + r.requiredPermission
877                            + " due to sender " + r.callerPackage
878                            + " (uid " + r.callingUid + ")");
879                    skip = true;
880                }
881            }
882            int appOp = AppOpsManager.OP_NONE;
883            if (!skip && r.requiredPermission != null) {
884                appOp = AppOpsManager.permissionToOpCode(r.requiredPermission);
885                if (appOp != AppOpsManager.OP_NONE
886                        && mService.mAppOpsService.noteOperation(appOp,
887                               info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
888                                        != AppOpsManager.MODE_ALLOWED) {
889                    Slog.w(TAG, "Appop Denial: receiving "
890                            + r.intent + " to "
891                            + component.flattenToShortString()
892                            + " requires appop " + AppOpsManager.permissionToOp(
893                            r.requiredPermission)
894                            + " due to sender " + r.callerPackage
895                            + " (uid " + r.callingUid + ")");
896                    skip = true;
897                }
898            }
899            if (!skip && r.appOp != appOp && r.appOp != AppOpsManager.OP_NONE
900                    && mService.mAppOpsService.noteOperation(r.appOp,
901                            info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
902                                    != AppOpsManager.MODE_ALLOWED) {
903                Slog.w(TAG, "Appop Denial: receiving "
904                        + r.intent + " to "
905                        + component.flattenToShortString()
906                        + " requires appop " + AppOpsManager.permissionToOp(
907                        r.requiredPermission)
908                        + " due to sender " + r.callerPackage
909                        + " (uid " + r.callingUid + ")");
910                skip = true;
911            }
912            if (!skip) {
913                skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
914                        r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
915            }
916            boolean isSingleton = false;
917            try {
918                isSingleton = mService.isSingleton(info.activityInfo.processName,
919                        info.activityInfo.applicationInfo,
920                        info.activityInfo.name, info.activityInfo.flags);
921            } catch (SecurityException e) {
922                Slog.w(TAG, e.getMessage());
923                skip = true;
924            }
925            if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
926                if (ActivityManager.checkUidPermission(
927                        android.Manifest.permission.INTERACT_ACROSS_USERS,
928                        info.activityInfo.applicationInfo.uid)
929                                != PackageManager.PERMISSION_GRANTED) {
930                    Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
931                            + " requests FLAG_SINGLE_USER, but app does not hold "
932                            + android.Manifest.permission.INTERACT_ACROSS_USERS);
933                    skip = true;
934                }
935            }
936            if (r.curApp != null && r.curApp.crashing) {
937                // If the target process is crashing, just skip it.
938                Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
939                        + " to " + r.curApp + ": process crashing");
940                skip = true;
941            }
942            if (!skip) {
943                boolean isAvailable = false;
944                try {
945                    isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
946                            info.activityInfo.packageName,
947                            UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
948                } catch (Exception e) {
949                    // all such failures mean we skip this receiver
950                    Slog.w(TAG, "Exception getting recipient info for "
951                            + info.activityInfo.packageName, e);
952                }
953                if (!isAvailable) {
954                    if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
955                            "Skipping delivery to " + info.activityInfo.packageName + " / "
956                            + info.activityInfo.applicationInfo.uid
957                            + " : package no longer available");
958                    skip = true;
959                }
960            }
961
962            if (skip) {
963                if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
964                        "Skipping delivery of ordered [" + mQueueName + "] "
965                        + r + " for whatever reason");
966                r.receiver = null;
967                r.curFilter = null;
968                r.state = BroadcastRecord.IDLE;
969                scheduleBroadcastsLocked();
970                return;
971            }
972
973            r.state = BroadcastRecord.APP_RECEIVE;
974            String targetProcess = info.activityInfo.processName;
975            r.curComponent = component;
976            final int receiverUid = info.activityInfo.applicationInfo.uid;
977            // If it's a singleton, it needs to be the same app or a special app
978            if (r.callingUid != Process.SYSTEM_UID && isSingleton
979                    && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
980                info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
981            }
982            r.curReceiver = info.activityInfo;
983            if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
984                Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
985                        + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
986                        + info.activityInfo.applicationInfo.uid);
987            }
988
989            if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
990                scheduleTempWhitelistLocked(receiverUid,
991                        brOptions.getTemporaryAppWhitelistDuration());
992            }
993
994            // Broadcast is being executed, its package can't be stopped.
995            try {
996                AppGlobals.getPackageManager().setPackageStoppedState(
997                        r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
998            } catch (RemoteException e) {
999            } catch (IllegalArgumentException e) {
1000                Slog.w(TAG, "Failed trying to unstop package "
1001                        + r.curComponent.getPackageName() + ": " + e);
1002            }
1003
1004            // Is this receiver's application already running?
1005            ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1006                    info.activityInfo.applicationInfo.uid, false);
1007            if (app != null && app.thread != null) {
1008                try {
1009                    app.addPackage(info.activityInfo.packageName,
1010                            info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
1011                    processCurBroadcastLocked(r, app);
1012                    return;
1013                } catch (RemoteException e) {
1014                    Slog.w(TAG, "Exception when sending broadcast to "
1015                          + r.curComponent, e);
1016                } catch (RuntimeException e) {
1017                    Slog.wtf(TAG, "Failed sending broadcast to "
1018                            + r.curComponent + " with " + r.intent, e);
1019                    // If some unexpected exception happened, just skip
1020                    // this broadcast.  At this point we are not in the call
1021                    // from a client, so throwing an exception out from here
1022                    // will crash the entire system instead of just whoever
1023                    // sent the broadcast.
1024                    logBroadcastReceiverDiscardLocked(r);
1025                    finishReceiverLocked(r, r.resultCode, r.resultData,
1026                            r.resultExtras, r.resultAbort, false);
1027                    scheduleBroadcastsLocked();
1028                    // We need to reset the state if we failed to start the receiver.
1029                    r.state = BroadcastRecord.IDLE;
1030                    return;
1031                }
1032
1033                // If a dead object exception was thrown -- fall through to
1034                // restart the application.
1035            }
1036
1037            // Not running -- get it started, to be executed when the app comes up.
1038            if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1039                    "Need to start app ["
1040                    + mQueueName + "] " + targetProcess + " for broadcast " + r);
1041            if ((r.curApp=mService.startProcessLocked(targetProcess,
1042                    info.activityInfo.applicationInfo, true,
1043                    r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1044                    "broadcast", r.curComponent,
1045                    (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
1046                            == null) {
1047                // Ah, this recipient is unavailable.  Finish it if necessary,
1048                // and mark the broadcast record as ready for the next.
1049                Slog.w(TAG, "Unable to launch app "
1050                        + info.activityInfo.applicationInfo.packageName + "/"
1051                        + info.activityInfo.applicationInfo.uid + " for broadcast "
1052                        + r.intent + ": process is bad");
1053                logBroadcastReceiverDiscardLocked(r);
1054                finishReceiverLocked(r, r.resultCode, r.resultData,
1055                        r.resultExtras, r.resultAbort, false);
1056                scheduleBroadcastsLocked();
1057                r.state = BroadcastRecord.IDLE;
1058                return;
1059            }
1060
1061            mPendingBroadcast = r;
1062            mPendingBroadcastRecvIndex = recIdx;
1063        }
1064    }
1065
1066    final void setBroadcastTimeoutLocked(long timeoutTime) {
1067        if (! mPendingBroadcastTimeoutMessage) {
1068            Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1069            mHandler.sendMessageAtTime(msg, timeoutTime);
1070            mPendingBroadcastTimeoutMessage = true;
1071        }
1072    }
1073
1074    final void cancelBroadcastTimeoutLocked() {
1075        if (mPendingBroadcastTimeoutMessage) {
1076            mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1077            mPendingBroadcastTimeoutMessage = false;
1078        }
1079    }
1080
1081    final void broadcastTimeoutLocked(boolean fromMsg) {
1082        if (fromMsg) {
1083            mPendingBroadcastTimeoutMessage = false;
1084        }
1085
1086        if (mOrderedBroadcasts.size() == 0) {
1087            return;
1088        }
1089
1090        long now = SystemClock.uptimeMillis();
1091        BroadcastRecord r = mOrderedBroadcasts.get(0);
1092        if (fromMsg) {
1093            if (mService.mDidDexOpt) {
1094                // Delay timeouts until dexopt finishes.
1095                mService.mDidDexOpt = false;
1096                long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
1097                setBroadcastTimeoutLocked(timeoutTime);
1098                return;
1099            }
1100            if (!mService.mProcessesReady) {
1101                // Only process broadcast timeouts if the system is ready. That way
1102                // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1103                // to do heavy lifting for system up.
1104                return;
1105            }
1106
1107            long timeoutTime = r.receiverTime + mTimeoutPeriod;
1108            if (timeoutTime > now) {
1109                // We can observe premature timeouts because we do not cancel and reset the
1110                // broadcast timeout message after each receiver finishes.  Instead, we set up
1111                // an initial timeout then kick it down the road a little further as needed
1112                // when it expires.
1113                if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1114                        "Premature timeout ["
1115                        + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1116                        + timeoutTime);
1117                setBroadcastTimeoutLocked(timeoutTime);
1118                return;
1119            }
1120        }
1121
1122        BroadcastRecord br = mOrderedBroadcasts.get(0);
1123        if (br.state == BroadcastRecord.WAITING_SERVICES) {
1124            // In this case the broadcast had already finished, but we had decided to wait
1125            // for started services to finish as well before going on.  So if we have actually
1126            // waited long enough time timeout the broadcast, let's give up on the whole thing
1127            // and just move on to the next.
1128            Slog.i(TAG, "Waited long enough for: " + (br.curComponent != null
1129                    ? br.curComponent.flattenToShortString() : "(null)"));
1130            br.curComponent = null;
1131            br.state = BroadcastRecord.IDLE;
1132            processNextBroadcast(false);
1133            return;
1134        }
1135
1136        Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver
1137                + ", started " + (now - r.receiverTime) + "ms ago");
1138        r.receiverTime = now;
1139        r.anrCount++;
1140
1141        // Current receiver has passed its expiration date.
1142        if (r.nextReceiver <= 0) {
1143            Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
1144            return;
1145        }
1146
1147        ProcessRecord app = null;
1148        String anrMessage = null;
1149
1150        Object curReceiver = r.receivers.get(r.nextReceiver-1);
1151        Slog.w(TAG, "Receiver during timeout: " + curReceiver);
1152        logBroadcastReceiverDiscardLocked(r);
1153        if (curReceiver instanceof BroadcastFilter) {
1154            BroadcastFilter bf = (BroadcastFilter)curReceiver;
1155            if (bf.receiverList.pid != 0
1156                    && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1157                synchronized (mService.mPidsSelfLocked) {
1158                    app = mService.mPidsSelfLocked.get(
1159                            bf.receiverList.pid);
1160                }
1161            }
1162        } else {
1163            app = r.curApp;
1164        }
1165
1166        if (app != null) {
1167            anrMessage = "Broadcast of " + r.intent.toString();
1168        }
1169
1170        if (mPendingBroadcast == r) {
1171            mPendingBroadcast = null;
1172        }
1173
1174        // Move on to the next receiver.
1175        finishReceiverLocked(r, r.resultCode, r.resultData,
1176                r.resultExtras, r.resultAbort, false);
1177        scheduleBroadcastsLocked();
1178
1179        if (anrMessage != null) {
1180            // Post the ANR to the handler since we do not want to process ANRs while
1181            // potentially holding our lock.
1182            mHandler.post(new AppNotResponding(app, anrMessage));
1183        }
1184    }
1185
1186    private final int ringAdvance(int x, final int increment, final int ringSize) {
1187        x += increment;
1188        if (x < 0) return (ringSize - 1);
1189        else if (x >= ringSize) return 0;
1190        else return x;
1191    }
1192
1193    private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
1194        if (r.callingUid < 0) {
1195            // This was from a registerReceiver() call; ignore it.
1196            return;
1197        }
1198        r.finishTime = SystemClock.uptimeMillis();
1199
1200        mBroadcastHistory[mHistoryNext] = r;
1201        mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1202
1203        mBroadcastSummaryHistory[mSummaryHistoryNext] = r.intent;
1204        mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = r.enqueueClockTime;
1205        mSummaryHistoryDispatchTime[mSummaryHistoryNext] = r.dispatchClockTime;
1206        mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1207        mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
1208    }
1209
1210    boolean cleanupDisabledPackageReceiversLocked(
1211            String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1212        boolean didSomething = false;
1213        for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1214            didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1215                    packageName, filterByClasses, userId, doit);
1216            if (!doit && didSomething) {
1217                return true;
1218            }
1219        }
1220
1221        for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1222            didSomething |= mOrderedBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1223                    packageName, filterByClasses, userId, doit);
1224            if (!doit && didSomething) {
1225                return true;
1226            }
1227        }
1228
1229        return didSomething;
1230    }
1231
1232    final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
1233        final int logIndex = r.nextReceiver - 1;
1234        if (logIndex >= 0 && logIndex < r.receivers.size()) {
1235            Object curReceiver = r.receivers.get(logIndex);
1236            if (curReceiver instanceof BroadcastFilter) {
1237                BroadcastFilter bf = (BroadcastFilter) curReceiver;
1238                EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
1239                        bf.owningUserId, System.identityHashCode(r),
1240                        r.intent.getAction(), logIndex, System.identityHashCode(bf));
1241            } else {
1242                ResolveInfo ri = (ResolveInfo) curReceiver;
1243                EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1244                        UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
1245                        System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
1246            }
1247        } else {
1248            if (logIndex < 0) Slog.w(TAG,
1249                    "Discarding broadcast before first receiver is invoked: " + r);
1250            EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1251                    -1, System.identityHashCode(r),
1252                    r.intent.getAction(),
1253                    r.nextReceiver,
1254                    "NONE");
1255        }
1256    }
1257
1258    final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1259            int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
1260        if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1261                || mPendingBroadcast != null) {
1262            boolean printed = false;
1263            for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1264                BroadcastRecord br = mParallelBroadcasts.get(i);
1265                if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1266                    continue;
1267                }
1268                if (!printed) {
1269                    if (needSep) {
1270                        pw.println();
1271                    }
1272                    needSep = true;
1273                    printed = true;
1274                    pw.println("  Active broadcasts [" + mQueueName + "]:");
1275                }
1276                pw.println("  Active Broadcast " + mQueueName + " #" + i + ":");
1277                br.dump(pw, "    ");
1278            }
1279            printed = false;
1280            needSep = true;
1281            for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1282                BroadcastRecord br = mOrderedBroadcasts.get(i);
1283                if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1284                    continue;
1285                }
1286                if (!printed) {
1287                    if (needSep) {
1288                        pw.println();
1289                    }
1290                    needSep = true;
1291                    printed = true;
1292                    pw.println("  Active ordered broadcasts [" + mQueueName + "]:");
1293                }
1294                pw.println("  Active Ordered Broadcast " + mQueueName + " #" + i + ":");
1295                mOrderedBroadcasts.get(i).dump(pw, "    ");
1296            }
1297            if (dumpPackage == null || (mPendingBroadcast != null
1298                    && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1299                if (needSep) {
1300                    pw.println();
1301                }
1302                pw.println("  Pending broadcast [" + mQueueName + "]:");
1303                if (mPendingBroadcast != null) {
1304                    mPendingBroadcast.dump(pw, "    ");
1305                } else {
1306                    pw.println("    (null)");
1307                }
1308                needSep = true;
1309            }
1310        }
1311
1312        int i;
1313        boolean printed = false;
1314
1315        i = -1;
1316        int lastIndex = mHistoryNext;
1317        int ringIndex = lastIndex;
1318        do {
1319            // increasing index = more recent entry, and we want to print the most
1320            // recent first and work backwards, so we roll through the ring backwards.
1321            ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1322            BroadcastRecord r = mBroadcastHistory[ringIndex];
1323            if (r == null) {
1324                continue;
1325            }
1326
1327            i++; // genuine record of some sort even if we're filtering it out
1328            if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1329                continue;
1330            }
1331            if (!printed) {
1332                if (needSep) {
1333                    pw.println();
1334                }
1335                needSep = true;
1336                pw.println("  Historical broadcasts [" + mQueueName + "]:");
1337                printed = true;
1338            }
1339            if (dumpAll) {
1340                pw.print("  Historical Broadcast " + mQueueName + " #");
1341                        pw.print(i); pw.println(":");
1342                r.dump(pw, "    ");
1343            } else {
1344                pw.print("  #"); pw.print(i); pw.print(": "); pw.println(r);
1345                pw.print("    ");
1346                pw.println(r.intent.toShortString(false, true, true, false));
1347                if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1348                    pw.print("    targetComp: "); pw.println(r.targetComp.toShortString());
1349                }
1350                Bundle bundle = r.intent.getExtras();
1351                if (bundle != null) {
1352                    pw.print("    extras: "); pw.println(bundle.toString());
1353                }
1354            }
1355        } while (ringIndex != lastIndex);
1356
1357        if (dumpPackage == null) {
1358            lastIndex = ringIndex = mSummaryHistoryNext;
1359            if (dumpAll) {
1360                printed = false;
1361                i = -1;
1362            } else {
1363                // roll over the 'i' full dumps that have already been issued
1364                for (int j = i;
1365                        j > 0 && ringIndex != lastIndex;) {
1366                    ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1367                    BroadcastRecord r = mBroadcastHistory[ringIndex];
1368                    if (r == null) {
1369                        continue;
1370                    }
1371                    j--;
1372                }
1373            }
1374            // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
1375            // the overall broadcast history.
1376            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1377            do {
1378                ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1379                Intent intent = mBroadcastSummaryHistory[ringIndex];
1380                if (intent == null) {
1381                    continue;
1382                }
1383                if (!printed) {
1384                    if (needSep) {
1385                        pw.println();
1386                    }
1387                    needSep = true;
1388                    pw.println("  Historical broadcasts summary [" + mQueueName + "]:");
1389                    printed = true;
1390                }
1391                if (!dumpAll && i >= 50) {
1392                    pw.println("  ...");
1393                    break;
1394                }
1395                i++;
1396                pw.print("  #"); pw.print(i); pw.print(": ");
1397                pw.println(intent.toShortString(false, true, true, false));
1398                pw.print("    enq="); pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
1399                pw.print(" disp="); pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
1400                pw.print(" fin="); pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
1401                Bundle bundle = intent.getExtras();
1402                if (bundle != null) {
1403                    pw.print("    extras: "); pw.println(bundle.toString());
1404                }
1405            } while (ringIndex != lastIndex);
1406        }
1407
1408        return needSep;
1409    }
1410}
1411