BroadcastQueue.java revision f7097a5b697fedb6976774e55a51471405a23c0e
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    }
191
192    public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
193        mOrderedBroadcasts.add(r);
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,
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,
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,
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,
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,
250                    "Process cur broadcast " + r + " DELIVERED for app " + app);
251            started = true;
252        } finally {
253            if (!started) {
254                if (DEBUG_BROADCAST)  Slog.v(TAG,
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) {
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
309        r = mPendingBroadcast;
310        if (r != null && r.curApp == app) {
311            if (DEBUG_BROADCAST) Slog.v(TAG,
312                    "[" + mQueueName + "] skip & discard pending app " + r);
313            logBroadcastReceiverDiscardLocked(r);
314            finishReceiverLocked(r, r.resultCode, r.resultData,
315                    r.resultExtras, r.resultAbort, false);
316            reschedule = true;
317        }
318        if (reschedule) {
319            scheduleBroadcastsLocked();
320        }
321    }
322
323    public void scheduleBroadcastsLocked() {
324        if (DEBUG_BROADCAST) Slog.v(TAG, "Schedule broadcasts ["
325                + mQueueName + "]: current="
326                + mBroadcastsScheduled);
327
328        if (mBroadcastsScheduled) {
329            return;
330        }
331        mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
332        mBroadcastsScheduled = true;
333    }
334
335    public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
336        if (mOrderedBroadcasts.size() > 0) {
337            final BroadcastRecord r = mOrderedBroadcasts.get(0);
338            if (r != null && r.receiver == receiver) {
339                return r;
340            }
341        }
342        return null;
343    }
344
345    public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
346            String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
347        final int state = r.state;
348        final ActivityInfo receiver = r.curReceiver;
349        r.state = BroadcastRecord.IDLE;
350        if (state == BroadcastRecord.IDLE) {
351            Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
352        }
353        r.receiver = null;
354        r.intent.setComponent(null);
355        if (r.curApp != null) {
356            r.curApp.curReceiver = null;
357        }
358        if (r.curFilter != null) {
359            r.curFilter.receiverList.curBroadcast = null;
360        }
361        r.curFilter = null;
362        r.curReceiver = null;
363        r.curApp = null;
364        mPendingBroadcast = null;
365
366        r.resultCode = resultCode;
367        r.resultData = resultData;
368        r.resultExtras = resultExtras;
369        if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
370            r.resultAbort = resultAbort;
371        } else {
372            r.resultAbort = false;
373        }
374
375        if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
376                && r.queue.mOrderedBroadcasts.size() > 0
377                && r.queue.mOrderedBroadcasts.get(0) == r) {
378            ActivityInfo nextReceiver;
379            if (r.nextReceiver < r.receivers.size()) {
380                Object obj = r.receivers.get(r.nextReceiver);
381                nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
382            } else {
383                nextReceiver = null;
384            }
385            // Don't do this if the next receive is in the same process as the current one.
386            if (receiver == null || nextReceiver == null
387                    || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
388                    || !receiver.processName.equals(nextReceiver.processName)) {
389                // In this case, we are ready to process the next receiver for the current broadcast,
390                // but are on a queue that would like to wait for services to finish before moving
391                // on.  If there are background services currently starting, then we will go into a
392                // special state where we hold off on continuing this broadcast until they are done.
393                if (mService.mServices.hasBackgroundServices(r.userId)) {
394                    Slog.i(ActivityManagerService.TAG, "Delay finish: "
395                            + r.curComponent.flattenToShortString());
396                    r.state = BroadcastRecord.WAITING_SERVICES;
397                    return false;
398                }
399            }
400        }
401
402        r.curComponent = null;
403
404        // We will process the next receiver right now if this is finishing
405        // an app receiver (which is always asynchronous) or after we have
406        // come back from calling a receiver.
407        return state == BroadcastRecord.APP_RECEIVE
408                || state == BroadcastRecord.CALL_DONE_RECEIVE;
409    }
410
411    public void backgroundServicesFinishedLocked(int userId) {
412        if (mOrderedBroadcasts.size() > 0) {
413            BroadcastRecord br = mOrderedBroadcasts.get(0);
414            if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
415                Slog.i(ActivityManagerService.TAG, "Resuming delayed broadcast");
416                br.curComponent = null;
417                br.state = BroadcastRecord.IDLE;
418                processNextBroadcast(false);
419            }
420        }
421    }
422
423    private static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
424            Intent intent, int resultCode, String data, Bundle extras,
425            boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
426        // Send the intent to the receiver asynchronously using one-way binder calls.
427        if (app != null && app.thread != null) {
428            // If we have an app thread, do the call through that so it is
429            // correctly ordered with other one-way calls.
430            app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
431                    data, extras, ordered, sticky, sendingUser, app.repProcState);
432        } else {
433            receiver.performReceive(intent, resultCode, data, extras, ordered,
434                    sticky, sendingUser);
435        }
436    }
437
438    private final void deliverToRegisteredReceiverLocked(BroadcastRecord r,
439            BroadcastFilter filter, boolean ordered) {
440        boolean skip = false;
441        if (filter.requiredPermission != null) {
442            int perm = mService.checkComponentPermission(filter.requiredPermission,
443                    r.callingPid, r.callingUid, -1, true);
444            if (perm != PackageManager.PERMISSION_GRANTED) {
445                Slog.w(TAG, "Permission Denial: broadcasting "
446                        + r.intent.toString()
447                        + " from " + r.callerPackage + " (pid="
448                        + r.callingPid + ", uid=" + r.callingUid + ")"
449                        + " requires " + filter.requiredPermission
450                        + " due to registered receiver " + filter);
451                skip = true;
452            }
453        }
454        if (!skip && r.requiredPermission != null) {
455            int perm = mService.checkComponentPermission(r.requiredPermission,
456                    filter.receiverList.pid, filter.receiverList.uid, -1, true);
457            if (perm != PackageManager.PERMISSION_GRANTED) {
458                Slog.w(TAG, "Permission Denial: receiving "
459                        + r.intent.toString()
460                        + " to " + filter.receiverList.app
461                        + " (pid=" + filter.receiverList.pid
462                        + ", uid=" + filter.receiverList.uid + ")"
463                        + " requires " + r.requiredPermission
464                        + " due to sender " + r.callerPackage
465                        + " (uid " + r.callingUid + ")");
466                skip = true;
467            }
468        }
469        if (r.appOp != AppOpsManager.OP_NONE) {
470            int mode = mService.mAppOpsService.noteOperation(r.appOp,
471                    filter.receiverList.uid, filter.packageName);
472            if (mode != AppOpsManager.MODE_ALLOWED) {
473                if (DEBUG_BROADCAST)  Slog.v(TAG,
474                        "App op " + r.appOp + " not allowed for broadcast to uid "
475                        + filter.receiverList.uid + " pkg " + filter.packageName);
476                skip = true;
477            }
478        }
479        if (!skip) {
480            skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
481                    r.callingPid, r.resolvedType, filter.receiverList.uid);
482        }
483
484        if (filter.receiverList.app == null || filter.receiverList.app.crashing) {
485            Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
486                    + " to " + filter.receiverList + ": process crashing");
487            skip = true;
488        }
489
490        if (!skip) {
491            // If this is not being sent as an ordered broadcast, then we
492            // don't want to touch the fields that keep track of the current
493            // state of ordered broadcasts.
494            if (ordered) {
495                r.receiver = filter.receiverList.receiver.asBinder();
496                r.curFilter = filter;
497                filter.receiverList.curBroadcast = r;
498                r.state = BroadcastRecord.CALL_IN_RECEIVE;
499                if (filter.receiverList.app != null) {
500                    // Bump hosting application to no longer be in background
501                    // scheduling class.  Note that we can't do that if there
502                    // isn't an app...  but we can only be in that case for
503                    // things that directly call the IActivityManager API, which
504                    // are already core system stuff so don't matter for this.
505                    r.curApp = filter.receiverList.app;
506                    filter.receiverList.app.curReceiver = r;
507                    mService.updateOomAdjLocked(r.curApp);
508                }
509            }
510            try {
511                if (DEBUG_BROADCAST_LIGHT) {
512                    int seq = r.intent.getIntExtra("seq", -1);
513                    Slog.i(TAG, "Delivering to " + filter
514                            + " (seq=" + seq + "): " + r);
515                }
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, "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, "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,
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, "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) {
578                    Slog.v(TAG, "processNextBroadcast ["
579                            + mQueueName + "]: waiting for "
580                            + mPendingBroadcast.curApp);
581                }
582
583                boolean isDead;
584                synchronized (mService.mPidsSelfLocked) {
585                    ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
586                    isDead = proc == null || proc.crashing;
587                }
588                if (!isDead) {
589                    // It's still alive, so keep waiting
590                    return;
591                } else {
592                    Slog.w(TAG, "pending app  ["
593                            + mQueueName + "]" + mPendingBroadcast.curApp
594                            + " died before responding to broadcast");
595                    mPendingBroadcast.state = BroadcastRecord.IDLE;
596                    mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
597                    mPendingBroadcast = null;
598                }
599            }
600
601            boolean looped = false;
602
603            do {
604                if (mOrderedBroadcasts.size() == 0) {
605                    // No more broadcasts pending, so all done!
606                    mService.scheduleAppGcsLocked();
607                    if (looped) {
608                        // If we had finished the last ordered broadcast, then
609                        // make sure all processes have correct oom and sched
610                        // adjustments.
611                        mService.updateOomAdjLocked();
612                    }
613                    return;
614                }
615                r = mOrderedBroadcasts.get(0);
616                boolean forceReceive = false;
617
618                // Ensure that even if something goes awry with the timeout
619                // detection, we catch "hung" broadcasts here, discard them,
620                // and continue to make progress.
621                //
622                // This is only done if the system is ready so that PRE_BOOT_COMPLETED
623                // receivers don't get executed with timeouts. They're intended for
624                // one time heavy lifting after system upgrades and can take
625                // significant amounts of time.
626                int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
627                if (mService.mProcessesReady && r.dispatchTime > 0) {
628                    long now = SystemClock.uptimeMillis();
629                    if ((numReceivers > 0) &&
630                            (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
631                        Slog.w(TAG, "Hung broadcast ["
632                                + mQueueName + "] discarded after timeout failure:"
633                                + " now=" + now
634                                + " dispatchTime=" + r.dispatchTime
635                                + " startTime=" + r.receiverTime
636                                + " intent=" + r.intent
637                                + " numReceivers=" + numReceivers
638                                + " nextReceiver=" + r.nextReceiver
639                                + " state=" + r.state);
640                        broadcastTimeoutLocked(false); // forcibly finish this broadcast
641                        forceReceive = true;
642                        r.state = BroadcastRecord.IDLE;
643                    }
644                }
645
646                if (r.state != BroadcastRecord.IDLE) {
647                    if (DEBUG_BROADCAST) Slog.d(TAG,
648                            "processNextBroadcast("
649                            + mQueueName + ") called when not idle (state="
650                            + r.state + ")");
651                    return;
652                }
653
654                if (r.receivers == null || r.nextReceiver >= numReceivers
655                        || r.resultAbort || forceReceive) {
656                    // No more receivers for this broadcast!  Send the final
657                    // result if requested...
658                    if (r.resultTo != null) {
659                        try {
660                            if (DEBUG_BROADCAST) {
661                                int seq = r.intent.getIntExtra("seq", -1);
662                                Slog.i(TAG, "Finishing broadcast ["
663                                        + mQueueName + "] " + r.intent.getAction()
664                                        + " seq=" + seq + " app=" + r.callerApp);
665                            }
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                            Slog.w(TAG, "Failure ["
674                                    + mQueueName + "] sending broadcast result of "
675                                    + r.intent, e);
676                        }
677                    }
678
679                    if (DEBUG_BROADCAST) Slog.v(TAG, "Cancelling BROADCAST_TIMEOUT_MSG");
680                    cancelBroadcastTimeoutLocked();
681
682                    if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Finished with ordered broadcast "
683                            + r);
684
685                    // ... and on to the next...
686                    addBroadcastToHistoryLocked(r);
687                    mOrderedBroadcasts.remove(0);
688                    r = null;
689                    looped = true;
690                    continue;
691                }
692            } while (r == null);
693
694            // Get the next receiver...
695            int recIdx = r.nextReceiver++;
696
697            // Keep track of when this receiver started, and make sure there
698            // is a timeout message pending to kill it if need be.
699            r.receiverTime = SystemClock.uptimeMillis();
700            if (recIdx == 0) {
701                r.dispatchTime = r.receiverTime;
702                r.dispatchClockTime = System.currentTimeMillis();
703                if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing ordered broadcast ["
704                        + mQueueName + "] " + r);
705            }
706            if (! mPendingBroadcastTimeoutMessage) {
707                long timeoutTime = r.receiverTime + mTimeoutPeriod;
708                if (DEBUG_BROADCAST) Slog.v(TAG,
709                        "Submitting BROADCAST_TIMEOUT_MSG ["
710                        + mQueueName + "] for " + r + " at " + timeoutTime);
711                setBroadcastTimeoutLocked(timeoutTime);
712            }
713
714            Object nextReceiver = r.receivers.get(recIdx);
715            if (nextReceiver instanceof BroadcastFilter) {
716                // Simple case: this is a registered receiver who gets
717                // a direct call.
718                BroadcastFilter filter = (BroadcastFilter)nextReceiver;
719                if (DEBUG_BROADCAST)  Slog.v(TAG,
720                        "Delivering ordered ["
721                        + mQueueName + "] to registered "
722                        + filter + ": " + r);
723                deliverToRegisteredReceiverLocked(r, filter, r.ordered);
724                if (r.receiver == null || !r.ordered) {
725                    // The receiver has already finished, so schedule to
726                    // process the next one.
727                    if (DEBUG_BROADCAST) Slog.v(TAG, "Quick finishing ["
728                            + mQueueName + "]: ordered="
729                            + r.ordered + " receiver=" + r.receiver);
730                    r.state = BroadcastRecord.IDLE;
731                    scheduleBroadcastsLocked();
732                }
733                return;
734            }
735
736            // Hard case: need to instantiate the receiver, possibly
737            // starting its application process to host it.
738
739            ResolveInfo info =
740                (ResolveInfo)nextReceiver;
741            ComponentName component = new ComponentName(
742                    info.activityInfo.applicationInfo.packageName,
743                    info.activityInfo.name);
744
745            boolean skip = false;
746            int perm = mService.checkComponentPermission(info.activityInfo.permission,
747                    r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
748                    info.activityInfo.exported);
749            if (perm != PackageManager.PERMISSION_GRANTED) {
750                if (!info.activityInfo.exported) {
751                    Slog.w(TAG, "Permission Denial: broadcasting "
752                            + r.intent.toString()
753                            + " from " + r.callerPackage + " (pid=" + r.callingPid
754                            + ", uid=" + r.callingUid + ")"
755                            + " is not exported from uid " + info.activityInfo.applicationInfo.uid
756                            + " due to receiver " + component.flattenToShortString());
757                } else {
758                    Slog.w(TAG, "Permission Denial: broadcasting "
759                            + r.intent.toString()
760                            + " from " + r.callerPackage + " (pid=" + r.callingPid
761                            + ", uid=" + r.callingUid + ")"
762                            + " requires " + info.activityInfo.permission
763                            + " due to receiver " + component.flattenToShortString());
764                }
765                skip = true;
766            }
767            if (info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
768                r.requiredPermission != null) {
769                try {
770                    perm = AppGlobals.getPackageManager().
771                            checkPermission(r.requiredPermission,
772                                    info.activityInfo.applicationInfo.packageName);
773                } catch (RemoteException e) {
774                    perm = PackageManager.PERMISSION_DENIED;
775                }
776                if (perm != PackageManager.PERMISSION_GRANTED) {
777                    Slog.w(TAG, "Permission Denial: receiving "
778                            + r.intent + " to "
779                            + component.flattenToShortString()
780                            + " requires " + r.requiredPermission
781                            + " due to sender " + r.callerPackage
782                            + " (uid " + r.callingUid + ")");
783                    skip = true;
784                }
785            }
786            if (r.appOp != AppOpsManager.OP_NONE) {
787                int mode = mService.mAppOpsService.noteOperation(r.appOp,
788                        info.activityInfo.applicationInfo.uid, info.activityInfo.packageName);
789                if (mode != AppOpsManager.MODE_ALLOWED) {
790                    if (DEBUG_BROADCAST)  Slog.v(TAG,
791                            "App op " + r.appOp + " not allowed for broadcast to uid "
792                            + info.activityInfo.applicationInfo.uid + " pkg "
793                            + info.activityInfo.packageName);
794                    skip = true;
795                }
796            }
797            if (!skip) {
798                skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
799                        r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
800            }
801            boolean isSingleton = false;
802            try {
803                isSingleton = mService.isSingleton(info.activityInfo.processName,
804                        info.activityInfo.applicationInfo,
805                        info.activityInfo.name, info.activityInfo.flags);
806            } catch (SecurityException e) {
807                Slog.w(TAG, e.getMessage());
808                skip = true;
809            }
810            if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
811                if (ActivityManager.checkUidPermission(
812                        android.Manifest.permission.INTERACT_ACROSS_USERS,
813                        info.activityInfo.applicationInfo.uid)
814                                != PackageManager.PERMISSION_GRANTED) {
815                    Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
816                            + " requests FLAG_SINGLE_USER, but app does not hold "
817                            + android.Manifest.permission.INTERACT_ACROSS_USERS);
818                    skip = true;
819                }
820            }
821            if (r.curApp != null && r.curApp.crashing) {
822                // If the target process is crashing, just skip it.
823                Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
824                        + " to " + r.curApp + ": process crashing");
825                skip = true;
826            }
827            if (!skip) {
828                boolean isAvailable = false;
829                try {
830                    isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
831                            info.activityInfo.packageName,
832                            UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
833                } catch (Exception e) {
834                    // all such failures mean we skip this receiver
835                    Slog.w(TAG, "Exception getting recipient info for "
836                            + info.activityInfo.packageName, e);
837                }
838                if (!isAvailable) {
839                    if (DEBUG_BROADCAST) {
840                        Slog.v(TAG, "Skipping delivery to " + info.activityInfo.packageName
841                                + " / " + info.activityInfo.applicationInfo.uid
842                                + " : package no longer available");
843                    }
844                    skip = true;
845                }
846            }
847
848            if (skip) {
849                if (DEBUG_BROADCAST)  Slog.v(TAG,
850                        "Skipping delivery of ordered ["
851                        + mQueueName + "] " + r + " for whatever reason");
852                r.receiver = null;
853                r.curFilter = null;
854                r.state = BroadcastRecord.IDLE;
855                scheduleBroadcastsLocked();
856                return;
857            }
858
859            r.state = BroadcastRecord.APP_RECEIVE;
860            String targetProcess = info.activityInfo.processName;
861            r.curComponent = component;
862            final int receiverUid = info.activityInfo.applicationInfo.uid;
863            // If it's a singleton, it needs to be the same app or a special app
864            if (r.callingUid != Process.SYSTEM_UID && isSingleton
865                    && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
866                info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
867            }
868            r.curReceiver = info.activityInfo;
869            if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
870                Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
871                        + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
872                        + info.activityInfo.applicationInfo.uid);
873            }
874
875            // Broadcast is being executed, its package can't be stopped.
876            try {
877                AppGlobals.getPackageManager().setPackageStoppedState(
878                        r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
879            } catch (RemoteException e) {
880            } catch (IllegalArgumentException e) {
881                Slog.w(TAG, "Failed trying to unstop package "
882                        + r.curComponent.getPackageName() + ": " + e);
883            }
884
885            // Is this receiver's application already running?
886            ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
887                    info.activityInfo.applicationInfo.uid, false);
888            if (app != null && app.thread != null) {
889                try {
890                    app.addPackage(info.activityInfo.packageName,
891                            info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
892                    processCurBroadcastLocked(r, app);
893                    return;
894                } catch (RemoteException e) {
895                    Slog.w(TAG, "Exception when sending broadcast to "
896                          + r.curComponent, e);
897                } catch (RuntimeException e) {
898                    Log.wtf(TAG, "Failed sending broadcast to "
899                            + r.curComponent + " with " + r.intent, e);
900                    // If some unexpected exception happened, just skip
901                    // this broadcast.  At this point we are not in the call
902                    // from a client, so throwing an exception out from here
903                    // will crash the entire system instead of just whoever
904                    // sent the broadcast.
905                    logBroadcastReceiverDiscardLocked(r);
906                    finishReceiverLocked(r, r.resultCode, r.resultData,
907                            r.resultExtras, r.resultAbort, false);
908                    scheduleBroadcastsLocked();
909                    // We need to reset the state if we failed to start the receiver.
910                    r.state = BroadcastRecord.IDLE;
911                    return;
912                }
913
914                // If a dead object exception was thrown -- fall through to
915                // restart the application.
916            }
917
918            // Not running -- get it started, to be executed when the app comes up.
919            if (DEBUG_BROADCAST)  Slog.v(TAG,
920                    "Need to start app ["
921                    + mQueueName + "] " + targetProcess + " for broadcast " + r);
922            if ((r.curApp=mService.startProcessLocked(targetProcess,
923                    info.activityInfo.applicationInfo, true,
924                    r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
925                    "broadcast", r.curComponent,
926                    (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
927                            == null) {
928                // Ah, this recipient is unavailable.  Finish it if necessary,
929                // and mark the broadcast record as ready for the next.
930                Slog.w(TAG, "Unable to launch app "
931                        + info.activityInfo.applicationInfo.packageName + "/"
932                        + info.activityInfo.applicationInfo.uid + " for broadcast "
933                        + r.intent + ": process is bad");
934                logBroadcastReceiverDiscardLocked(r);
935                finishReceiverLocked(r, r.resultCode, r.resultData,
936                        r.resultExtras, r.resultAbort, false);
937                scheduleBroadcastsLocked();
938                r.state = BroadcastRecord.IDLE;
939                return;
940            }
941
942            mPendingBroadcast = r;
943            mPendingBroadcastRecvIndex = recIdx;
944        }
945    }
946
947    final void setBroadcastTimeoutLocked(long timeoutTime) {
948        if (! mPendingBroadcastTimeoutMessage) {
949            Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
950            mHandler.sendMessageAtTime(msg, timeoutTime);
951            mPendingBroadcastTimeoutMessage = true;
952        }
953    }
954
955    final void cancelBroadcastTimeoutLocked() {
956        if (mPendingBroadcastTimeoutMessage) {
957            mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
958            mPendingBroadcastTimeoutMessage = false;
959        }
960    }
961
962    final void broadcastTimeoutLocked(boolean fromMsg) {
963        if (fromMsg) {
964            mPendingBroadcastTimeoutMessage = false;
965        }
966
967        if (mOrderedBroadcasts.size() == 0) {
968            return;
969        }
970
971        long now = SystemClock.uptimeMillis();
972        BroadcastRecord r = mOrderedBroadcasts.get(0);
973        if (fromMsg) {
974            if (mService.mDidDexOpt) {
975                // Delay timeouts until dexopt finishes.
976                mService.mDidDexOpt = false;
977                long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
978                setBroadcastTimeoutLocked(timeoutTime);
979                return;
980            }
981            if (!mService.mProcessesReady) {
982                // Only process broadcast timeouts if the system is ready. That way
983                // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
984                // to do heavy lifting for system up.
985                return;
986            }
987
988            long timeoutTime = r.receiverTime + mTimeoutPeriod;
989            if (timeoutTime > now) {
990                // We can observe premature timeouts because we do not cancel and reset the
991                // broadcast timeout message after each receiver finishes.  Instead, we set up
992                // an initial timeout then kick it down the road a little further as needed
993                // when it expires.
994                if (DEBUG_BROADCAST) Slog.v(TAG,
995                        "Premature timeout ["
996                        + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
997                        + timeoutTime);
998                setBroadcastTimeoutLocked(timeoutTime);
999                return;
1000            }
1001        }
1002
1003        BroadcastRecord br = mOrderedBroadcasts.get(0);
1004        if (br.state == BroadcastRecord.WAITING_SERVICES) {
1005            // In this case the broadcast had already finished, but we had decided to wait
1006            // for started services to finish as well before going on.  So if we have actually
1007            // waited long enough time timeout the broadcast, let's give up on the whole thing
1008            // and just move on to the next.
1009            Slog.i(ActivityManagerService.TAG, "Waited long enough for: " + (br.curComponent != null
1010                    ? br.curComponent.flattenToShortString() : "(null)"));
1011            br.curComponent = null;
1012            br.state = BroadcastRecord.IDLE;
1013            processNextBroadcast(false);
1014            return;
1015        }
1016
1017        Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver
1018                + ", started " + (now - r.receiverTime) + "ms ago");
1019        r.receiverTime = now;
1020        r.anrCount++;
1021
1022        // Current receiver has passed its expiration date.
1023        if (r.nextReceiver <= 0) {
1024            Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
1025            return;
1026        }
1027
1028        ProcessRecord app = null;
1029        String anrMessage = null;
1030
1031        Object curReceiver = r.receivers.get(r.nextReceiver-1);
1032        Slog.w(TAG, "Receiver during timeout: " + curReceiver);
1033        logBroadcastReceiverDiscardLocked(r);
1034        if (curReceiver instanceof BroadcastFilter) {
1035            BroadcastFilter bf = (BroadcastFilter)curReceiver;
1036            if (bf.receiverList.pid != 0
1037                    && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1038                synchronized (mService.mPidsSelfLocked) {
1039                    app = mService.mPidsSelfLocked.get(
1040                            bf.receiverList.pid);
1041                }
1042            }
1043        } else {
1044            app = r.curApp;
1045        }
1046
1047        if (app != null) {
1048            anrMessage = "Broadcast of " + r.intent.toString();
1049        }
1050
1051        if (mPendingBroadcast == r) {
1052            mPendingBroadcast = null;
1053        }
1054
1055        // Move on to the next receiver.
1056        finishReceiverLocked(r, r.resultCode, r.resultData,
1057                r.resultExtras, r.resultAbort, false);
1058        scheduleBroadcastsLocked();
1059
1060        if (anrMessage != null) {
1061            // Post the ANR to the handler since we do not want to process ANRs while
1062            // potentially holding our lock.
1063            mHandler.post(new AppNotResponding(app, anrMessage));
1064        }
1065    }
1066
1067    private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
1068        if (r.callingUid < 0) {
1069            // This was from a registerReceiver() call; ignore it.
1070            return;
1071        }
1072        System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
1073                MAX_BROADCAST_HISTORY-1);
1074        r.finishTime = SystemClock.uptimeMillis();
1075        mBroadcastHistory[0] = r;
1076        System.arraycopy(mBroadcastSummaryHistory, 0, mBroadcastSummaryHistory, 1,
1077                MAX_BROADCAST_SUMMARY_HISTORY-1);
1078        mBroadcastSummaryHistory[0] = r.intent;
1079    }
1080
1081    final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
1082        if (r.nextReceiver > 0) {
1083            Object curReceiver = r.receivers.get(r.nextReceiver-1);
1084            if (curReceiver instanceof BroadcastFilter) {
1085                BroadcastFilter bf = (BroadcastFilter) curReceiver;
1086                EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
1087                        bf.owningUserId, System.identityHashCode(r),
1088                        r.intent.getAction(),
1089                        r.nextReceiver - 1,
1090                        System.identityHashCode(bf));
1091            } else {
1092                ResolveInfo ri = (ResolveInfo)curReceiver;
1093                EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1094                        UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
1095                        System.identityHashCode(r), r.intent.getAction(),
1096                        r.nextReceiver - 1, ri.toString());
1097            }
1098        } else {
1099            Slog.w(TAG, "Discarding broadcast before first receiver is invoked: "
1100                    + r);
1101            EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1102                    -1, System.identityHashCode(r),
1103                    r.intent.getAction(),
1104                    r.nextReceiver,
1105                    "NONE");
1106        }
1107    }
1108
1109    final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1110            int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
1111        if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1112                || mPendingBroadcast != null) {
1113            boolean printed = false;
1114            for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
1115                BroadcastRecord br = mParallelBroadcasts.get(i);
1116                if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1117                    continue;
1118                }
1119                if (!printed) {
1120                    if (needSep) {
1121                        pw.println();
1122                    }
1123                    needSep = true;
1124                    printed = true;
1125                    pw.println("  Active broadcasts [" + mQueueName + "]:");
1126                }
1127                pw.println("  Active Broadcast " + mQueueName + " #" + i + ":");
1128                br.dump(pw, "    ");
1129            }
1130            printed = false;
1131            needSep = true;
1132            for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
1133                BroadcastRecord br = mOrderedBroadcasts.get(i);
1134                if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1135                    continue;
1136                }
1137                if (!printed) {
1138                    if (needSep) {
1139                        pw.println();
1140                    }
1141                    needSep = true;
1142                    printed = true;
1143                    pw.println("  Active ordered broadcasts [" + mQueueName + "]:");
1144                }
1145                pw.println("  Active Ordered Broadcast " + mQueueName + " #" + i + ":");
1146                mOrderedBroadcasts.get(i).dump(pw, "    ");
1147            }
1148            if (dumpPackage == null || (mPendingBroadcast != null
1149                    && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1150                if (needSep) {
1151                    pw.println();
1152                }
1153                pw.println("  Pending broadcast [" + mQueueName + "]:");
1154                if (mPendingBroadcast != null) {
1155                    mPendingBroadcast.dump(pw, "    ");
1156                } else {
1157                    pw.println("    (null)");
1158                }
1159                needSep = true;
1160            }
1161        }
1162
1163        int i;
1164        boolean printed = false;
1165        for (i=0; i<MAX_BROADCAST_HISTORY; i++) {
1166            BroadcastRecord r = mBroadcastHistory[i];
1167            if (r == null) {
1168                break;
1169            }
1170            if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1171                continue;
1172            }
1173            if (!printed) {
1174                if (needSep) {
1175                    pw.println();
1176                }
1177                needSep = true;
1178                pw.println("  Historical broadcasts [" + mQueueName + "]:");
1179                printed = true;
1180            }
1181            if (dumpAll) {
1182                pw.print("  Historical Broadcast " + mQueueName + " #");
1183                        pw.print(i); pw.println(":");
1184                r.dump(pw, "    ");
1185            } else {
1186                pw.print("  #"); pw.print(i); pw.print(": "); pw.println(r);
1187                pw.print("    ");
1188                pw.println(r.intent.toShortString(false, true, true, false));
1189                if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1190                    pw.print("    targetComp: "); pw.println(r.targetComp.toShortString());
1191                }
1192                Bundle bundle = r.intent.getExtras();
1193                if (bundle != null) {
1194                    pw.print("    extras: "); pw.println(bundle.toString());
1195                }
1196            }
1197        }
1198
1199        if (dumpPackage == null) {
1200            if (dumpAll) {
1201                i = 0;
1202                printed = false;
1203            }
1204            for (; i<MAX_BROADCAST_SUMMARY_HISTORY; i++) {
1205                Intent intent = mBroadcastSummaryHistory[i];
1206                if (intent == null) {
1207                    break;
1208                }
1209                if (!printed) {
1210                    if (needSep) {
1211                        pw.println();
1212                    }
1213                    needSep = true;
1214                    pw.println("  Historical broadcasts summary [" + mQueueName + "]:");
1215                    printed = true;
1216                }
1217                if (!dumpAll && i >= 50) {
1218                    pw.println("  ...");
1219                    break;
1220                }
1221                pw.print("  #"); pw.print(i); pw.print(": ");
1222                pw.println(intent.toShortString(false, true, true, false));
1223                Bundle bundle = intent.getExtras();
1224                if (bundle != null) {
1225                    pw.print("    extras: "); pw.println(bundle.toString());
1226                }
1227            }
1228        }
1229
1230        return needSep;
1231    }
1232}
1233