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