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