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