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