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