• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 package com.android.server.am;
18 
19 import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY;
20 import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE;
21 
22 import static com.android.server.am.ActivityManagerDebugConfig.*;
23 
24 import android.app.ActivityManager;
25 import android.app.AppGlobals;
26 import android.app.AppOpsManager;
27 import android.app.BroadcastOptions;
28 import android.app.PendingIntent;
29 import android.content.ComponentName;
30 import android.content.ContentResolver;
31 import android.content.IIntentReceiver;
32 import android.content.IIntentSender;
33 import android.content.Intent;
34 import android.content.IntentSender;
35 import android.content.pm.ActivityInfo;
36 import android.content.pm.PackageManager;
37 import android.content.pm.PermissionInfo;
38 import android.content.pm.ResolveInfo;
39 import android.os.Bundle;
40 import android.os.Handler;
41 import android.os.IBinder;
42 import android.os.Looper;
43 import android.os.Message;
44 import android.os.Process;
45 import android.os.RemoteException;
46 import android.os.SystemClock;
47 import android.os.Trace;
48 import android.os.UserHandle;
49 import android.permission.IPermissionManager;
50 import android.util.EventLog;
51 import android.util.Slog;
52 import android.util.SparseIntArray;
53 import android.util.TimeUtils;
54 import android.util.proto.ProtoOutputStream;
55 
56 import com.android.internal.util.FrameworkStatsLog;
57 
58 import java.io.FileDescriptor;
59 import java.io.PrintWriter;
60 import java.text.SimpleDateFormat;
61 import java.util.ArrayList;
62 import java.util.Date;
63 import java.util.Set;
64 
65 /**
66  * BROADCASTS
67  *
68  * We keep three broadcast queues and associated bookkeeping, one for those at
69  * foreground priority, and one for normal (background-priority) broadcasts, and one to
70  * offload special broadcasts that we know take a long time, such as BOOT_COMPLETED.
71  */
72 public final class BroadcastQueue {
73     private static final String TAG = "BroadcastQueue";
74     private static final String TAG_MU = TAG + POSTFIX_MU;
75     private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
76 
77     static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50;
78     static final int MAX_BROADCAST_SUMMARY_HISTORY
79             = ActivityManager.isLowRamDeviceStatic() ? 25 : 300;
80 
81     final ActivityManagerService mService;
82 
83     /**
84      * Behavioral parameters such as timeouts and deferral policy, tracking Settings
85      * for runtime configurability
86      */
87     final BroadcastConstants mConstants;
88 
89     /**
90      * Recognizable moniker for this queue
91      */
92     final String mQueueName;
93 
94     /**
95      * If true, we can delay broadcasts while waiting services to finish in the previous
96      * receiver's process.
97      */
98     final boolean mDelayBehindServices;
99 
100     /**
101      * Lists of all active broadcasts that are to be executed immediately
102      * (without waiting for another broadcast to finish).  Currently this only
103      * contains broadcasts to registered receivers, to avoid spinning up
104      * a bunch of processes to execute IntentReceiver components.  Background-
105      * and foreground-priority broadcasts are queued separately.
106      */
107     final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
108 
109     /**
110      * Tracking of the ordered broadcast queue, including deferral policy and alarm
111      * prioritization.
112      */
113     final BroadcastDispatcher mDispatcher;
114 
115     /**
116      * Refcounting for completion callbacks of split/deferred broadcasts.  The key
117      * is an opaque integer token assigned lazily when a broadcast is first split
118      * into multiple BroadcastRecord objects.
119      */
120     final SparseIntArray mSplitRefcounts = new SparseIntArray();
121     private int mNextToken = 0;
122 
123     /**
124      * Historical data of past broadcasts, for debugging.  This is a ring buffer
125      * whose last element is at mHistoryNext.
126      */
127     final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY];
128     int mHistoryNext = 0;
129 
130     /**
131      * Summary of historical data of past broadcasts, for debugging.  This is a
132      * ring buffer whose last element is at mSummaryHistoryNext.
133      */
134     final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
135     int mSummaryHistoryNext = 0;
136 
137     /**
138      * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring
139      * buffer, also tracked via the mSummaryHistoryNext index.  These are all in wall
140      * clock time, not elapsed.
141      */
142     final long[] mSummaryHistoryEnqueueTime = new  long[MAX_BROADCAST_SUMMARY_HISTORY];
143     final long[] mSummaryHistoryDispatchTime = new  long[MAX_BROADCAST_SUMMARY_HISTORY];
144     final long[] mSummaryHistoryFinishTime = new  long[MAX_BROADCAST_SUMMARY_HISTORY];
145 
146     /**
147      * Set when we current have a BROADCAST_INTENT_MSG in flight.
148      */
149     boolean mBroadcastsScheduled = false;
150 
151     /**
152      * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
153      */
154     boolean mPendingBroadcastTimeoutMessage;
155 
156     /**
157      * Intent broadcasts that we have tried to start, but are
158      * waiting for the application's process to be created.  We only
159      * need one per scheduling class (instead of a list) because we always
160      * process broadcasts one at a time, so no others can be started while
161      * waiting for this one.
162      */
163     BroadcastRecord mPendingBroadcast = null;
164 
165     /**
166      * The receiver index that is pending, to restart the broadcast if needed.
167      */
168     int mPendingBroadcastRecvIndex;
169 
170     static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
171     static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
172 
173     // log latency metrics for ordered broadcasts during BOOT_COMPLETED processing
174     boolean mLogLatencyMetrics = true;
175 
176     final BroadcastHandler mHandler;
177 
178     private final class BroadcastHandler extends Handler {
BroadcastHandler(Looper looper)179         public BroadcastHandler(Looper looper) {
180             super(looper, null, true);
181         }
182 
183         @Override
handleMessage(Message msg)184         public void handleMessage(Message msg) {
185             switch (msg.what) {
186                 case BROADCAST_INTENT_MSG: {
187                     if (DEBUG_BROADCAST) Slog.v(
188                             TAG_BROADCAST, "Received BROADCAST_INTENT_MSG ["
189                             + mQueueName + "]");
190                     processNextBroadcast(true);
191                 } break;
192                 case BROADCAST_TIMEOUT_MSG: {
193                     synchronized (mService) {
194                         broadcastTimeoutLocked(true);
195                     }
196                 } break;
197             }
198         }
199     }
200 
BroadcastQueue(ActivityManagerService service, Handler handler, String name, BroadcastConstants constants, boolean allowDelayBehindServices)201     BroadcastQueue(ActivityManagerService service, Handler handler,
202             String name, BroadcastConstants constants, boolean allowDelayBehindServices) {
203         mService = service;
204         mHandler = new BroadcastHandler(handler.getLooper());
205         mQueueName = name;
206         mDelayBehindServices = allowDelayBehindServices;
207 
208         mConstants = constants;
209         mDispatcher = new BroadcastDispatcher(this, mConstants, mHandler, mService);
210     }
211 
start(ContentResolver resolver)212     void start(ContentResolver resolver) {
213         mDispatcher.start();
214         mConstants.startObserving(mHandler, resolver);
215     }
216 
217     @Override
toString()218     public String toString() {
219         return mQueueName;
220     }
221 
isPendingBroadcastProcessLocked(int pid)222     public boolean isPendingBroadcastProcessLocked(int pid) {
223         return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
224     }
225 
enqueueParallelBroadcastLocked(BroadcastRecord r)226     public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
227         mParallelBroadcasts.add(r);
228         enqueueBroadcastHelper(r);
229     }
230 
enqueueOrderedBroadcastLocked(BroadcastRecord r)231     public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
232         mDispatcher.enqueueOrderedBroadcastLocked(r);
233         enqueueBroadcastHelper(r);
234     }
235 
236     /**
237      * Don't call this method directly; call enqueueParallelBroadcastLocked or
238      * enqueueOrderedBroadcastLocked.
239      */
enqueueBroadcastHelper(BroadcastRecord r)240     private void enqueueBroadcastHelper(BroadcastRecord r) {
241         r.enqueueClockTime = System.currentTimeMillis();
242 
243         if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
244             Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
245                 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
246                 System.identityHashCode(r));
247         }
248     }
249 
250     /**
251      * Find the same intent from queued parallel broadcast, replace with a new one and return
252      * the old one.
253      */
replaceParallelBroadcastLocked(BroadcastRecord r)254     public final BroadcastRecord replaceParallelBroadcastLocked(BroadcastRecord r) {
255         return replaceBroadcastLocked(mParallelBroadcasts, r, "PARALLEL");
256     }
257 
258     /**
259      * Find the same intent from queued ordered broadcast, replace with a new one and return
260      * the old one.
261      */
replaceOrderedBroadcastLocked(BroadcastRecord r)262     public final BroadcastRecord replaceOrderedBroadcastLocked(BroadcastRecord r) {
263         return mDispatcher.replaceBroadcastLocked(r, "ORDERED");
264     }
265 
replaceBroadcastLocked(ArrayList<BroadcastRecord> queue, BroadcastRecord r, String typeForLogging)266     private BroadcastRecord replaceBroadcastLocked(ArrayList<BroadcastRecord> queue,
267             BroadcastRecord r, String typeForLogging) {
268         final Intent intent = r.intent;
269         for (int i = queue.size() - 1; i > 0; i--) {
270             final BroadcastRecord old = queue.get(i);
271             if (old.userId == r.userId && intent.filterEquals(old.intent)) {
272                 if (DEBUG_BROADCAST) {
273                     Slog.v(TAG_BROADCAST, "***** DROPPING "
274                             + typeForLogging + " [" + mQueueName + "]: " + intent);
275                 }
276                 queue.set(i, r);
277                 return old;
278             }
279         }
280         return null;
281     }
282 
processCurBroadcastLocked(BroadcastRecord r, ProcessRecord app, boolean skipOomAdj)283     private final void processCurBroadcastLocked(BroadcastRecord r,
284             ProcessRecord app, boolean skipOomAdj) throws RemoteException {
285         if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
286                 "Process cur broadcast " + r + " for app " + app);
287         if (app.thread == null) {
288             throw new RemoteException();
289         }
290         if (app.inFullBackup) {
291             skipReceiverLocked(r);
292             return;
293         }
294 
295         r.receiver = app.thread.asBinder();
296         r.curApp = app;
297         app.curReceivers.add(r);
298         app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
299         mService.mProcessList.updateLruProcessLocked(app, false, null);
300         if (!skipOomAdj) {
301             mService.updateOomAdjLocked(app, OomAdjuster.OOM_ADJ_REASON_NONE);
302         }
303 
304         // Tell the application to launch this receiver.
305         r.intent.setComponent(r.curComponent);
306 
307         boolean started = false;
308         try {
309             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
310                     "Delivering to component " + r.curComponent
311                     + ": " + r);
312             mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
313                                       PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER);
314             app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
315                     mService.compatibilityInfoForPackage(r.curReceiver.applicationInfo),
316                     r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
317                     app.getReportedProcState());
318             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
319                     "Process cur broadcast " + r + " DELIVERED for app " + app);
320             started = true;
321         } finally {
322             if (!started) {
323                 if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
324                         "Process cur broadcast " + r + ": NOT STARTED!");
325                 r.receiver = null;
326                 r.curApp = null;
327                 app.curReceivers.remove(r);
328             }
329         }
330     }
331 
sendPendingBroadcastsLocked(ProcessRecord app)332     public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
333         boolean didSomething = false;
334         final BroadcastRecord br = mPendingBroadcast;
335         if (br != null && br.curApp.pid > 0 && br.curApp.pid == app.pid) {
336             if (br.curApp != app) {
337                 Slog.e(TAG, "App mismatch when sending pending broadcast to "
338                         + app.processName + ", intended target is " + br.curApp.processName);
339                 return false;
340             }
341             try {
342                 mPendingBroadcast = null;
343                 processCurBroadcastLocked(br, app, false);
344                 didSomething = true;
345             } catch (Exception e) {
346                 Slog.w(TAG, "Exception in new application when starting receiver "
347                         + br.curComponent.flattenToShortString(), e);
348                 logBroadcastReceiverDiscardLocked(br);
349                 finishReceiverLocked(br, br.resultCode, br.resultData,
350                         br.resultExtras, br.resultAbort, false);
351                 scheduleBroadcastsLocked();
352                 // We need to reset the state if we failed to start the receiver.
353                 br.state = BroadcastRecord.IDLE;
354                 throw new RuntimeException(e.getMessage());
355             }
356         }
357         return didSomething;
358     }
359 
skipPendingBroadcastLocked(int pid)360     public void skipPendingBroadcastLocked(int pid) {
361         final BroadcastRecord br = mPendingBroadcast;
362         if (br != null && br.curApp.pid == pid) {
363             br.state = BroadcastRecord.IDLE;
364             br.nextReceiver = mPendingBroadcastRecvIndex;
365             mPendingBroadcast = null;
366             scheduleBroadcastsLocked();
367         }
368     }
369 
370     // Skip the current receiver, if any, that is in flight to the given process
skipCurrentReceiverLocked(ProcessRecord app)371     public void skipCurrentReceiverLocked(ProcessRecord app) {
372         BroadcastRecord r = null;
373         final BroadcastRecord curActive = mDispatcher.getActiveBroadcastLocked();
374         if (curActive != null && curActive.curApp == app) {
375             // confirmed: the current active broadcast is to the given app
376             r = curActive;
377         }
378 
379         // If the current active broadcast isn't this BUT we're waiting for
380         // mPendingBroadcast to spin up the target app, that's what we use.
381         if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
382             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
383                     "[" + mQueueName + "] skip & discard pending app " + r);
384             r = mPendingBroadcast;
385         }
386 
387         if (r != null) {
388             skipReceiverLocked(r);
389         }
390     }
391 
skipReceiverLocked(BroadcastRecord r)392     private void skipReceiverLocked(BroadcastRecord r) {
393         logBroadcastReceiverDiscardLocked(r);
394         finishReceiverLocked(r, r.resultCode, r.resultData,
395                 r.resultExtras, r.resultAbort, false);
396         scheduleBroadcastsLocked();
397     }
398 
scheduleBroadcastsLocked()399     public void scheduleBroadcastsLocked() {
400         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
401                 + mQueueName + "]: current="
402                 + mBroadcastsScheduled);
403 
404         if (mBroadcastsScheduled) {
405             return;
406         }
407         mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
408         mBroadcastsScheduled = true;
409     }
410 
getMatchingOrderedReceiver(IBinder receiver)411     public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
412         BroadcastRecord br = mDispatcher.getActiveBroadcastLocked();
413         if (br != null && br.receiver == receiver) {
414             return br;
415         }
416         return null;
417     }
418 
419     // > 0 only, no worry about "eventual" recycling
nextSplitTokenLocked()420     private int nextSplitTokenLocked() {
421         int next = mNextToken + 1;
422         if (next <= 0) {
423             next = 1;
424         }
425         mNextToken = next;
426         return next;
427     }
428 
postActivityStartTokenRemoval(ProcessRecord app, BroadcastRecord r)429     private void postActivityStartTokenRemoval(ProcessRecord app, BroadcastRecord r) {
430         // the receiver had run for less than allowed bg activity start timeout,
431         // so allow the process to still start activities from bg for some more time
432         String msgToken = (app.toShortString() + r.toString()).intern();
433         // first, if there exists a past scheduled request to remove this token, drop
434         // that request - we don't want the token to be swept from under our feet...
435         mHandler.removeCallbacksAndMessages(msgToken);
436         // ...then schedule the removal of the token after the extended timeout
437         mHandler.postAtTime(() -> {
438             synchronized (mService) {
439                 app.removeAllowBackgroundActivityStartsToken(r);
440             }
441         }, msgToken, (r.receiverTime + mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT));
442     }
443 
finishReceiverLocked(BroadcastRecord r, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices)444     public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
445             String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
446         final int state = r.state;
447         final ActivityInfo receiver = r.curReceiver;
448         final long finishTime = SystemClock.uptimeMillis();
449         final long elapsed = finishTime - r.receiverTime;
450         r.state = BroadcastRecord.IDLE;
451         if (state == BroadcastRecord.IDLE) {
452             Slog.w(TAG_BROADCAST, "finishReceiver [" + mQueueName + "] called but state is IDLE");
453         }
454         if (r.allowBackgroundActivityStarts && r.curApp != null) {
455             if (elapsed > mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT) {
456                 // if the receiver has run for more than allowed bg activity start timeout,
457                 // just remove the token for this process now and we're done
458                 r.curApp.removeAllowBackgroundActivityStartsToken(r);
459             } else {
460                 // It gets more time; post the removal to happen at the appropriate moment
461                 postActivityStartTokenRemoval(r.curApp, r);
462             }
463         }
464         // If we're abandoning this broadcast before any receivers were actually spun up,
465         // nextReceiver is zero; in which case time-to-process bookkeeping doesn't apply.
466         if (r.nextReceiver > 0) {
467             r.duration[r.nextReceiver - 1] = elapsed;
468         }
469 
470         // if this receiver was slow, impose deferral policy on the app.  This will kick in
471         // when processNextBroadcastLocked() next finds this uid as a receiver identity.
472         if (!r.timeoutExempt) {
473             // r.curApp can be null if finish has raced with process death - benign
474             // edge case, and we just ignore it because we're already cleaning up
475             // as expected.
476             if (r.curApp != null
477                     && mConstants.SLOW_TIME > 0 && elapsed > mConstants.SLOW_TIME) {
478                 // Core system packages are exempt from deferral policy
479                 if (!UserHandle.isCore(r.curApp.uid)) {
480                     if (DEBUG_BROADCAST_DEFERRAL) {
481                         Slog.i(TAG_BROADCAST, "Broadcast receiver " + (r.nextReceiver - 1)
482                                 + " was slow: " + receiver + " br=" + r);
483                     }
484                     mDispatcher.startDeferring(r.curApp.uid);
485                 } else {
486                     if (DEBUG_BROADCAST_DEFERRAL) {
487                         Slog.i(TAG_BROADCAST, "Core uid " + r.curApp.uid
488                                 + " receiver was slow but not deferring: "
489                                 + receiver + " br=" + r);
490                     }
491                 }
492             }
493         } else {
494             if (DEBUG_BROADCAST_DEFERRAL) {
495                 Slog.i(TAG_BROADCAST, "Finished broadcast " + r.intent.getAction()
496                         + " is exempt from deferral policy");
497             }
498         }
499 
500         r.receiver = null;
501         r.intent.setComponent(null);
502         if (r.curApp != null && r.curApp.curReceivers.contains(r)) {
503             r.curApp.curReceivers.remove(r);
504         }
505         if (r.curFilter != null) {
506             r.curFilter.receiverList.curBroadcast = null;
507         }
508         r.curFilter = null;
509         r.curReceiver = null;
510         r.curApp = null;
511         mPendingBroadcast = null;
512 
513         r.resultCode = resultCode;
514         r.resultData = resultData;
515         r.resultExtras = resultExtras;
516         if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
517             r.resultAbort = resultAbort;
518         } else {
519             r.resultAbort = false;
520         }
521 
522         // If we want to wait behind services *AND* we're finishing the head/
523         // active broadcast on its queue
524         if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
525                 && r.queue.mDispatcher.getActiveBroadcastLocked() == r) {
526             ActivityInfo nextReceiver;
527             if (r.nextReceiver < r.receivers.size()) {
528                 Object obj = r.receivers.get(r.nextReceiver);
529                 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
530             } else {
531                 nextReceiver = null;
532             }
533             // Don't do this if the next receive is in the same process as the current one.
534             if (receiver == null || nextReceiver == null
535                     || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
536                     || !receiver.processName.equals(nextReceiver.processName)) {
537                 // In this case, we are ready to process the next receiver for the current broadcast,
538                 // but are on a queue that would like to wait for services to finish before moving
539                 // on.  If there are background services currently starting, then we will go into a
540                 // special state where we hold off on continuing this broadcast until they are done.
541                 if (mService.mServices.hasBackgroundServicesLocked(r.userId)) {
542                     Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
543                     r.state = BroadcastRecord.WAITING_SERVICES;
544                     return false;
545                 }
546             }
547         }
548 
549         r.curComponent = null;
550 
551         // We will process the next receiver right now if this is finishing
552         // an app receiver (which is always asynchronous) or after we have
553         // come back from calling a receiver.
554         return state == BroadcastRecord.APP_RECEIVE
555                 || state == BroadcastRecord.CALL_DONE_RECEIVE;
556     }
557 
backgroundServicesFinishedLocked(int userId)558     public void backgroundServicesFinishedLocked(int userId) {
559         BroadcastRecord br = mDispatcher.getActiveBroadcastLocked();
560         if (br != null) {
561             if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
562                 Slog.i(TAG, "Resuming delayed broadcast");
563                 br.curComponent = null;
564                 br.state = BroadcastRecord.IDLE;
565                 processNextBroadcast(false);
566             }
567         }
568     }
569 
performReceiveLocked(ProcessRecord app, IIntentReceiver receiver, Intent intent, int resultCode, String data, Bundle extras, boolean ordered, boolean sticky, int sendingUser)570     void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
571             Intent intent, int resultCode, String data, Bundle extras,
572             boolean ordered, boolean sticky, int sendingUser)
573             throws RemoteException {
574         // Send the intent to the receiver asynchronously using one-way binder calls.
575         if (app != null) {
576             if (app.thread != null) {
577                 // If we have an app thread, do the call through that so it is
578                 // correctly ordered with other one-way calls.
579                 try {
580                     app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
581                             data, extras, ordered, sticky, sendingUser, app.getReportedProcState());
582                 // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting
583                 // DeadObjectException when the process isn't actually dead.
584                 //} catch (DeadObjectException ex) {
585                 // Failed to call into the process.  It's dying so just let it die and move on.
586                 //    throw ex;
587                 } catch (RemoteException ex) {
588                     // Failed to call into the process. It's either dying or wedged. Kill it gently.
589                     synchronized (mService) {
590                         Slog.w(TAG, "Can't deliver broadcast to " + app.processName
591                                 + " (pid " + app.pid + "). Crashing it.");
592                         app.scheduleCrash("can't deliver broadcast");
593                     }
594                     throw ex;
595                 }
596             } else {
597                 // Application has died. Receiver doesn't exist.
598                 throw new RemoteException("app.thread must not be null");
599             }
600         } else {
601             receiver.performReceive(intent, resultCode, data, extras, ordered,
602                     sticky, sendingUser);
603         }
604     }
605 
deliverToRegisteredReceiverLocked(BroadcastRecord r, BroadcastFilter filter, boolean ordered, int index)606     private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
607             BroadcastFilter filter, boolean ordered, int index) {
608         boolean skip = false;
609         if (!mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid,
610                 filter.packageName, filter.owningUid)) {
611             Slog.w(TAG, "Association not allowed: broadcasting "
612                     + r.intent.toString()
613                     + " from " + r.callerPackage + " (pid=" + r.callingPid
614                     + ", uid=" + r.callingUid + ") to " + filter.packageName + " through "
615                     + filter);
616             skip = true;
617         }
618         if (!skip && !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
619                 r.callingPid, r.resolvedType, filter.receiverList.uid)) {
620             Slog.w(TAG, "Firewall blocked: broadcasting "
621                     + r.intent.toString()
622                     + " from " + r.callerPackage + " (pid=" + r.callingPid
623                     + ", uid=" + r.callingUid + ") to " + filter.packageName + " through "
624                     + filter);
625             skip = true;
626         }
627         if (filter.requiredPermission != null) {
628             int perm = mService.checkComponentPermission(filter.requiredPermission,
629                     r.callingPid, r.callingUid, -1, true);
630             if (perm != PackageManager.PERMISSION_GRANTED) {
631                 Slog.w(TAG, "Permission Denial: broadcasting "
632                         + r.intent.toString()
633                         + " from " + r.callerPackage + " (pid="
634                         + r.callingPid + ", uid=" + r.callingUid + ")"
635                         + " requires " + filter.requiredPermission
636                         + " due to registered receiver " + filter);
637                 skip = true;
638             } else {
639                 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
640                 if (opCode != AppOpsManager.OP_NONE
641                         && mService.getAppOpsManager().noteOpNoThrow(opCode, r.callingUid,
642                         r.callerPackage, r.callerFeatureId, "")
643                         != AppOpsManager.MODE_ALLOWED) {
644                     Slog.w(TAG, "Appop Denial: broadcasting "
645                             + r.intent.toString()
646                             + " from " + r.callerPackage + " (pid="
647                             + r.callingPid + ", uid=" + r.callingUid + ")"
648                             + " requires appop " + AppOpsManager.permissionToOp(
649                                     filter.requiredPermission)
650                             + " due to registered receiver " + filter);
651                     skip = true;
652                 }
653             }
654         }
655         if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
656             for (int i = 0; i < r.requiredPermissions.length; i++) {
657                 String requiredPermission = r.requiredPermissions[i];
658                 int perm = mService.checkComponentPermission(requiredPermission,
659                         filter.receiverList.pid, filter.receiverList.uid, -1, true);
660                 if (perm != PackageManager.PERMISSION_GRANTED) {
661                     Slog.w(TAG, "Permission Denial: receiving "
662                             + r.intent.toString()
663                             + " to " + filter.receiverList.app
664                             + " (pid=" + filter.receiverList.pid
665                             + ", uid=" + filter.receiverList.uid + ")"
666                             + " requires " + requiredPermission
667                             + " due to sender " + r.callerPackage
668                             + " (uid " + r.callingUid + ")");
669                     skip = true;
670                     break;
671                 }
672                 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
673                 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
674                         && mService.getAppOpsManager().noteOpNoThrow(appOp,
675                         filter.receiverList.uid, filter.packageName, filter.featureId, "")
676                         != AppOpsManager.MODE_ALLOWED) {
677                     Slog.w(TAG, "Appop Denial: receiving "
678                             + r.intent.toString()
679                             + " to " + filter.receiverList.app
680                             + " (pid=" + filter.receiverList.pid
681                             + ", uid=" + filter.receiverList.uid + ")"
682                             + " requires appop " + AppOpsManager.permissionToOp(
683                             requiredPermission)
684                             + " due to sender " + r.callerPackage
685                             + " (uid " + r.callingUid + ")");
686                     skip = true;
687                     break;
688                 }
689             }
690         }
691         if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
692             int perm = mService.checkComponentPermission(null,
693                     filter.receiverList.pid, filter.receiverList.uid, -1, true);
694             if (perm != PackageManager.PERMISSION_GRANTED) {
695                 Slog.w(TAG, "Permission Denial: security check failed when receiving "
696                         + r.intent.toString()
697                         + " to " + filter.receiverList.app
698                         + " (pid=" + filter.receiverList.pid
699                         + ", uid=" + filter.receiverList.uid + ")"
700                         + " due to sender " + r.callerPackage
701                         + " (uid " + r.callingUid + ")");
702                 skip = true;
703             }
704         }
705         if (!skip && r.appOp != AppOpsManager.OP_NONE
706                 && mService.getAppOpsManager().noteOpNoThrow(r.appOp,
707                 filter.receiverList.uid, filter.packageName, filter.featureId, "")
708                 != AppOpsManager.MODE_ALLOWED) {
709             Slog.w(TAG, "Appop Denial: receiving "
710                     + r.intent.toString()
711                     + " to " + filter.receiverList.app
712                     + " (pid=" + filter.receiverList.pid
713                     + ", uid=" + filter.receiverList.uid + ")"
714                     + " requires appop " + AppOpsManager.opToName(r.appOp)
715                     + " due to sender " + r.callerPackage
716                     + " (uid " + r.callingUid + ")");
717             skip = true;
718         }
719 
720         if (!skip && (filter.receiverList.app == null || filter.receiverList.app.killed
721                 || filter.receiverList.app.isCrashing())) {
722             Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
723                     + " to " + filter.receiverList + ": process gone or crashing");
724             skip = true;
725         }
726 
727         // Ensure that broadcasts are only sent to other Instant Apps if they are marked as
728         // visible to Instant Apps.
729         final boolean visibleToInstantApps =
730                 (r.intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0;
731 
732         if (!skip && !visibleToInstantApps && filter.instantApp
733                 && filter.receiverList.uid != r.callingUid) {
734             Slog.w(TAG, "Instant App Denial: receiving "
735                     + r.intent.toString()
736                     + " to " + filter.receiverList.app
737                     + " (pid=" + filter.receiverList.pid
738                     + ", uid=" + filter.receiverList.uid + ")"
739                     + " due to sender " + r.callerPackage
740                     + " (uid " + r.callingUid + ")"
741                     + " not specifying FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS");
742             skip = true;
743         }
744 
745         if (!skip && !filter.visibleToInstantApp && r.callerInstantApp
746                 && filter.receiverList.uid != r.callingUid) {
747             Slog.w(TAG, "Instant App Denial: receiving "
748                     + r.intent.toString()
749                     + " to " + filter.receiverList.app
750                     + " (pid=" + filter.receiverList.pid
751                     + ", uid=" + filter.receiverList.uid + ")"
752                     + " requires receiver be visible to instant apps"
753                     + " due to sender " + r.callerPackage
754                     + " (uid " + r.callingUid + ")");
755             skip = true;
756         }
757 
758         if (skip) {
759             r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
760             return;
761         }
762 
763         // If permissions need a review before any of the app components can run, we drop
764         // the broadcast and if the calling app is in the foreground and the broadcast is
765         // explicit we launch the review UI passing it a pending intent to send the skipped
766         // broadcast.
767         if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
768                 filter.owningUserId)) {
769             r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
770             return;
771         }
772 
773         r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
774 
775         // If this is not being sent as an ordered broadcast, then we
776         // don't want to touch the fields that keep track of the current
777         // state of ordered broadcasts.
778         if (ordered) {
779             r.receiver = filter.receiverList.receiver.asBinder();
780             r.curFilter = filter;
781             filter.receiverList.curBroadcast = r;
782             r.state = BroadcastRecord.CALL_IN_RECEIVE;
783             if (filter.receiverList.app != null) {
784                 // Bump hosting application to no longer be in background
785                 // scheduling class.  Note that we can't do that if there
786                 // isn't an app...  but we can only be in that case for
787                 // things that directly call the IActivityManager API, which
788                 // are already core system stuff so don't matter for this.
789                 r.curApp = filter.receiverList.app;
790                 filter.receiverList.app.curReceivers.add(r);
791                 mService.updateOomAdjLocked(r.curApp, true,
792                         OomAdjuster.OOM_ADJ_REASON_START_RECEIVER);
793             }
794         } else if (filter.receiverList.app != null) {
795             mService.mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily(filter.receiverList.app);
796         }
797 
798         try {
799             if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
800                     "Delivering to " + filter + " : " + r);
801             if (filter.receiverList.app != null && filter.receiverList.app.inFullBackup) {
802                 // Skip delivery if full backup in progress
803                 // If it's an ordered broadcast, we need to continue to the next receiver.
804                 if (ordered) {
805                     skipReceiverLocked(r);
806                 }
807             } else {
808                 r.receiverTime = SystemClock.uptimeMillis();
809                 maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
810                 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
811                         new Intent(r.intent), r.resultCode, r.resultData,
812                         r.resultExtras, r.ordered, r.initialSticky, r.userId);
813                 // parallel broadcasts are fire-and-forget, not bookended by a call to
814                 // finishReceiverLocked(), so we manage their activity-start token here
815                 if (r.allowBackgroundActivityStarts && !r.ordered) {
816                     postActivityStartTokenRemoval(filter.receiverList.app, r);
817                 }
818             }
819             if (ordered) {
820                 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
821             }
822         } catch (RemoteException e) {
823             Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
824             // Clean up ProcessRecord state related to this broadcast attempt
825             if (filter.receiverList.app != null) {
826                 filter.receiverList.app.removeAllowBackgroundActivityStartsToken(r);
827                 if (ordered) {
828                     filter.receiverList.app.curReceivers.remove(r);
829                 }
830             }
831             // And BroadcastRecord state related to ordered delivery, if appropriate
832             if (ordered) {
833                 r.receiver = null;
834                 r.curFilter = null;
835                 filter.receiverList.curBroadcast = null;
836             }
837         }
838     }
839 
requestStartTargetPermissionsReviewIfNeededLocked( BroadcastRecord receiverRecord, String receivingPackageName, final int receivingUserId)840     private boolean requestStartTargetPermissionsReviewIfNeededLocked(
841             BroadcastRecord receiverRecord, String receivingPackageName,
842             final int receivingUserId) {
843         if (!mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
844                 receivingPackageName, receivingUserId)) {
845             return true;
846         }
847 
848         final boolean callerForeground = receiverRecord.callerApp != null
849                 ? receiverRecord.callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND
850                 : true;
851 
852         // Show a permission review UI only for explicit broadcast from a foreground app
853         if (callerForeground && receiverRecord.intent.getComponent() != null) {
854             IIntentSender target = mService.mPendingIntentController.getIntentSender(
855                     ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
856                     receiverRecord.callerFeatureId, receiverRecord.callingUid,
857                     receiverRecord.userId, null, null, 0,
858                     new Intent[]{receiverRecord.intent},
859                     new String[]{receiverRecord.intent.resolveType(mService.mContext
860                             .getContentResolver())},
861                     PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
862                             | PendingIntent.FLAG_IMMUTABLE, null);
863 
864             final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
865             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
866                     | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
867                     | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
868             intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
869             intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
870 
871             if (DEBUG_PERMISSIONS_REVIEW) {
872                 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
873                         + receivingPackageName);
874             }
875 
876             mHandler.post(new Runnable() {
877                 @Override
878                 public void run() {
879                     mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
880                 }
881             });
882         } else {
883             Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
884                     + receivingPackageName + " requires a permissions review");
885         }
886 
887         return false;
888     }
889 
scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r)890     final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
891         if (duration > Integer.MAX_VALUE) {
892             duration = Integer.MAX_VALUE;
893         }
894         // XXX ideally we should pause the broadcast until everything behind this is done,
895         // or else we will likely start dispatching the broadcast before we have opened
896         // access to the app (there is a lot of asynchronicity behind this).  It is probably
897         // not that big a deal, however, because the main purpose here is to allow apps
898         // to hold wake locks, and they will be able to acquire their wake lock immediately
899         // it just won't be enabled until we get through this work.
900         StringBuilder b = new StringBuilder();
901         b.append("broadcast:");
902         UserHandle.formatUid(b, r.callingUid);
903         b.append(":");
904         if (r.intent.getAction() != null) {
905             b.append(r.intent.getAction());
906         } else if (r.intent.getComponent() != null) {
907             r.intent.getComponent().appendShortString(b);
908         } else if (r.intent.getData() != null) {
909             b.append(r.intent.getData());
910         }
911         if (DEBUG_BROADCAST) {
912             Slog.v(TAG, "Broadcast temp whitelist uid=" + uid + " duration=" + duration
913                     + " : " + b.toString());
914         }
915         mService.tempWhitelistUidLocked(uid, duration, b.toString());
916     }
917 
918     /**
919      * Return true if all given permissions are signature-only perms.
920      */
isSignaturePerm(String[] perms)921     final boolean isSignaturePerm(String[] perms) {
922         if (perms == null) {
923             return false;
924         }
925         IPermissionManager pm = AppGlobals.getPermissionManager();
926         for (int i = perms.length-1; i >= 0; i--) {
927             try {
928                 PermissionInfo pi = pm.getPermissionInfo(perms[i], "android", 0);
929                 if (pi == null) {
930                     // a required permission that no package has actually
931                     // defined cannot be signature-required.
932                     return false;
933                 }
934                 if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE
935                         | PermissionInfo.PROTECTION_FLAG_PRIVILEGED))
936                         != PermissionInfo.PROTECTION_SIGNATURE) {
937                     // If this a signature permission and NOT allowed for privileged apps, it
938                     // is okay...  otherwise, nope!
939                     return false;
940                 }
941             } catch (RemoteException e) {
942                 return false;
943             }
944         }
945         return true;
946     }
947 
processNextBroadcast(boolean fromMsg)948     final void processNextBroadcast(boolean fromMsg) {
949         synchronized (mService) {
950             processNextBroadcastLocked(fromMsg, false);
951         }
952     }
953 
processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj)954     final void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj) {
955         BroadcastRecord r;
956 
957         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
958                 + mQueueName + "]: "
959                 + mParallelBroadcasts.size() + " parallel broadcasts; "
960                 + mDispatcher.describeStateLocked());
961 
962         mService.updateCpuStats();
963 
964         if (fromMsg) {
965             mBroadcastsScheduled = false;
966         }
967 
968         // First, deliver any non-serialized broadcasts right away.
969         while (mParallelBroadcasts.size() > 0) {
970             r = mParallelBroadcasts.remove(0);
971             r.dispatchTime = SystemClock.uptimeMillis();
972             r.dispatchClockTime = System.currentTimeMillis();
973 
974             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
975                 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
976                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
977                     System.identityHashCode(r));
978                 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
979                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
980                     System.identityHashCode(r));
981             }
982 
983             final int N = r.receivers.size();
984             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
985                     + mQueueName + "] " + r);
986             for (int i=0; i<N; i++) {
987                 Object target = r.receivers.get(i);
988                 if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
989                         "Delivering non-ordered on [" + mQueueName + "] to registered "
990                         + target + ": " + r);
991                 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
992             }
993             addBroadcastToHistoryLocked(r);
994             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
995                     + mQueueName + "] " + r);
996         }
997 
998         // Now take care of the next serialized one...
999 
1000         // If we are waiting for a process to come up to handle the next
1001         // broadcast, then do nothing at this point.  Just in case, we
1002         // check that the process we're waiting for still exists.
1003         if (mPendingBroadcast != null) {
1004             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
1005                     "processNextBroadcast [" + mQueueName + "]: waiting for "
1006                     + mPendingBroadcast.curApp);
1007 
1008             boolean isDead;
1009             if (mPendingBroadcast.curApp.pid > 0) {
1010                 synchronized (mService.mPidsSelfLocked) {
1011                     ProcessRecord proc = mService.mPidsSelfLocked.get(
1012                             mPendingBroadcast.curApp.pid);
1013                     isDead = proc == null || proc.isCrashing();
1014                 }
1015             } else {
1016                 final ProcessRecord proc = mService.mProcessList.mProcessNames.get(
1017                         mPendingBroadcast.curApp.processName, mPendingBroadcast.curApp.uid);
1018                 isDead = proc == null || !proc.pendingStart;
1019             }
1020             if (!isDead) {
1021                 // It's still alive, so keep waiting
1022                 return;
1023             } else {
1024                 Slog.w(TAG, "pending app  ["
1025                         + mQueueName + "]" + mPendingBroadcast.curApp
1026                         + " died before responding to broadcast");
1027                 mPendingBroadcast.state = BroadcastRecord.IDLE;
1028                 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
1029                 mPendingBroadcast = null;
1030             }
1031         }
1032 
1033         boolean looped = false;
1034 
1035         do {
1036             final long now = SystemClock.uptimeMillis();
1037             r = mDispatcher.getNextBroadcastLocked(now);
1038 
1039             if (r == null) {
1040                 // No more broadcasts are deliverable right now, so all done!
1041                 mDispatcher.scheduleDeferralCheckLocked(false);
1042                 mService.scheduleAppGcsLocked();
1043                 if (looped) {
1044                     // If we had finished the last ordered broadcast, then
1045                     // make sure all processes have correct oom and sched
1046                     // adjustments.
1047                     mService.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_START_RECEIVER);
1048                 }
1049 
1050                 // when we have no more ordered broadcast on this queue, stop logging
1051                 if (mService.mUserController.mBootCompleted && mLogLatencyMetrics) {
1052                     mLogLatencyMetrics = false;
1053                 }
1054 
1055                 return;
1056             }
1057 
1058             boolean forceReceive = false;
1059 
1060             // Ensure that even if something goes awry with the timeout
1061             // detection, we catch "hung" broadcasts here, discard them,
1062             // and continue to make progress.
1063             //
1064             // This is only done if the system is ready so that early-stage receivers
1065             // don't get executed with timeouts; and of course other timeout-
1066             // exempt broadcasts are ignored.
1067             int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
1068             if (mService.mProcessesReady && !r.timeoutExempt && r.dispatchTime > 0) {
1069                 if ((numReceivers > 0) &&
1070                         (now > r.dispatchTime + (2 * mConstants.TIMEOUT * numReceivers))) {
1071                     Slog.w(TAG, "Hung broadcast ["
1072                             + mQueueName + "] discarded after timeout failure:"
1073                             + " now=" + now
1074                             + " dispatchTime=" + r.dispatchTime
1075                             + " startTime=" + r.receiverTime
1076                             + " intent=" + r.intent
1077                             + " numReceivers=" + numReceivers
1078                             + " nextReceiver=" + r.nextReceiver
1079                             + " state=" + r.state);
1080                     broadcastTimeoutLocked(false); // forcibly finish this broadcast
1081                     forceReceive = true;
1082                     r.state = BroadcastRecord.IDLE;
1083                 }
1084             }
1085 
1086             if (r.state != BroadcastRecord.IDLE) {
1087                 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
1088                         "processNextBroadcast("
1089                         + mQueueName + ") called when not idle (state="
1090                         + r.state + ")");
1091                 return;
1092             }
1093 
1094             // Is the current broadcast is done for any reason?
1095             if (r.receivers == null || r.nextReceiver >= numReceivers
1096                     || r.resultAbort || forceReceive) {
1097                 // Send the final result if requested
1098                 if (r.resultTo != null) {
1099                     boolean sendResult = true;
1100 
1101                     // if this was part of a split/deferral complex, update the refcount and only
1102                     // send the completion when we clear all of them
1103                     if (r.splitToken != 0) {
1104                         int newCount = mSplitRefcounts.get(r.splitToken) - 1;
1105                         if (newCount == 0) {
1106                             // done!  clear out this record's bookkeeping and deliver
1107                             if (DEBUG_BROADCAST_DEFERRAL) {
1108                                 Slog.i(TAG_BROADCAST,
1109                                         "Sending broadcast completion for split token "
1110                                         + r.splitToken + " : " + r.intent.getAction());
1111                             }
1112                             mSplitRefcounts.delete(r.splitToken);
1113                         } else {
1114                             // still have some split broadcast records in flight; update refcount
1115                             // and hold off on the callback
1116                             if (DEBUG_BROADCAST_DEFERRAL) {
1117                                 Slog.i(TAG_BROADCAST,
1118                                         "Result refcount now " + newCount + " for split token "
1119                                         + r.splitToken + " : " + r.intent.getAction()
1120                                         + " - not sending completion yet");
1121                             }
1122                             sendResult = false;
1123                             mSplitRefcounts.put(r.splitToken, newCount);
1124                         }
1125                     }
1126                     if (sendResult) {
1127                         if (r.callerApp != null) {
1128                             mService.mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily(
1129                                     r.callerApp);
1130                         }
1131                         try {
1132                             if (DEBUG_BROADCAST) {
1133                                 Slog.i(TAG_BROADCAST, "Finishing broadcast [" + mQueueName + "] "
1134                                         + r.intent.getAction() + " app=" + r.callerApp);
1135                             }
1136                             performReceiveLocked(r.callerApp, r.resultTo,
1137                                     new Intent(r.intent), r.resultCode,
1138                                     r.resultData, r.resultExtras, false, false, r.userId);
1139                             // Set this to null so that the reference
1140                             // (local and remote) isn't kept in the mBroadcastHistory.
1141                             r.resultTo = null;
1142                         } catch (RemoteException e) {
1143                             r.resultTo = null;
1144                             Slog.w(TAG, "Failure ["
1145                                     + mQueueName + "] sending broadcast result of "
1146                                     + r.intent, e);
1147                         }
1148                     }
1149                 }
1150 
1151                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
1152                 cancelBroadcastTimeoutLocked();
1153 
1154                 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
1155                         "Finished with ordered broadcast " + r);
1156 
1157                 // ... and on to the next...
1158                 addBroadcastToHistoryLocked(r);
1159                 if (r.intent.getComponent() == null && r.intent.getPackage() == null
1160                         && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
1161                     // This was an implicit broadcast... let's record it for posterity.
1162                     mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
1163                             r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
1164                 }
1165                 mDispatcher.retireBroadcastLocked(r);
1166                 r = null;
1167                 looped = true;
1168                 continue;
1169             }
1170 
1171             // Check whether the next receiver is under deferral policy, and handle that
1172             // accordingly.  If the current broadcast was already part of deferred-delivery
1173             // tracking, we know that it must now be deliverable as-is without re-deferral.
1174             if (!r.deferred) {
1175                 final int receiverUid = r.getReceiverUid(r.receivers.get(r.nextReceiver));
1176                 if (mDispatcher.isDeferringLocked(receiverUid)) {
1177                     if (DEBUG_BROADCAST_DEFERRAL) {
1178                         Slog.i(TAG_BROADCAST, "Next receiver in " + r + " uid " + receiverUid
1179                                 + " at " + r.nextReceiver + " is under deferral");
1180                     }
1181                     // If this is the only (remaining) receiver in the broadcast, "splitting"
1182                     // doesn't make sense -- just defer it as-is and retire it as the
1183                     // currently active outgoing broadcast.
1184                     BroadcastRecord defer;
1185                     if (r.nextReceiver + 1 == numReceivers) {
1186                         if (DEBUG_BROADCAST_DEFERRAL) {
1187                             Slog.i(TAG_BROADCAST, "Sole receiver of " + r
1188                                     + " is under deferral; setting aside and proceeding");
1189                         }
1190                         defer = r;
1191                         mDispatcher.retireBroadcastLocked(r);
1192                     } else {
1193                         // Nontrivial case; split out 'uid's receivers to a new broadcast record
1194                         // and defer that, then loop and pick up continuing delivery of the current
1195                         // record (now absent those receivers).
1196 
1197                         // The split operation is guaranteed to match at least at 'nextReceiver'
1198                         defer = r.splitRecipientsLocked(receiverUid, r.nextReceiver);
1199                         if (DEBUG_BROADCAST_DEFERRAL) {
1200                             Slog.i(TAG_BROADCAST, "Post split:");
1201                             Slog.i(TAG_BROADCAST, "Original broadcast receivers:");
1202                             for (int i = 0; i < r.receivers.size(); i++) {
1203                                 Slog.i(TAG_BROADCAST, "  " + r.receivers.get(i));
1204                             }
1205                             Slog.i(TAG_BROADCAST, "Split receivers:");
1206                             for (int i = 0; i < defer.receivers.size(); i++) {
1207                                 Slog.i(TAG_BROADCAST, "  " + defer.receivers.get(i));
1208                             }
1209                         }
1210                         // Track completion refcount as well if relevant
1211                         if (r.resultTo != null) {
1212                             int token = r.splitToken;
1213                             if (token == 0) {
1214                                 // first split of this record; refcount for 'r' and 'deferred'
1215                                 r.splitToken = defer.splitToken = nextSplitTokenLocked();
1216                                 mSplitRefcounts.put(r.splitToken, 2);
1217                                 if (DEBUG_BROADCAST_DEFERRAL) {
1218                                     Slog.i(TAG_BROADCAST,
1219                                             "Broadcast needs split refcount; using new token "
1220                                             + r.splitToken);
1221                                 }
1222                             } else {
1223                                 // new split from an already-refcounted situation; increment count
1224                                 final int curCount = mSplitRefcounts.get(token);
1225                                 if (DEBUG_BROADCAST_DEFERRAL) {
1226                                     if (curCount == 0) {
1227                                         Slog.wtf(TAG_BROADCAST,
1228                                                 "Split refcount is zero with token for " + r);
1229                                     }
1230                                 }
1231                                 mSplitRefcounts.put(token, curCount + 1);
1232                                 if (DEBUG_BROADCAST_DEFERRAL) {
1233                                     Slog.i(TAG_BROADCAST, "New split count for token " + token
1234                                             + " is " + (curCount + 1));
1235                                 }
1236                             }
1237                         }
1238                     }
1239                     mDispatcher.addDeferredBroadcast(receiverUid, defer);
1240                     r = null;
1241                     looped = true;
1242                     continue;
1243                 }
1244             }
1245         } while (r == null);
1246 
1247         // Get the next receiver...
1248         int recIdx = r.nextReceiver++;
1249 
1250         // Keep track of when this receiver started, and make sure there
1251         // is a timeout message pending to kill it if need be.
1252         r.receiverTime = SystemClock.uptimeMillis();
1253         if (recIdx == 0) {
1254             r.dispatchTime = r.receiverTime;
1255             r.dispatchClockTime = System.currentTimeMillis();
1256 
1257             if (mLogLatencyMetrics) {
1258                 FrameworkStatsLog.write(
1259                         FrameworkStatsLog.BROADCAST_DISPATCH_LATENCY_REPORTED,
1260                         r.dispatchClockTime - r.enqueueClockTime);
1261             }
1262 
1263             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1264                 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1265                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
1266                     System.identityHashCode(r));
1267                 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1268                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
1269                     System.identityHashCode(r));
1270             }
1271             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
1272                     + mQueueName + "] " + r);
1273         }
1274         if (! mPendingBroadcastTimeoutMessage) {
1275             long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
1276             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1277                     "Submitting BROADCAST_TIMEOUT_MSG ["
1278                     + mQueueName + "] for " + r + " at " + timeoutTime);
1279             setBroadcastTimeoutLocked(timeoutTime);
1280         }
1281 
1282         final BroadcastOptions brOptions = r.options;
1283         final Object nextReceiver = r.receivers.get(recIdx);
1284 
1285         if (nextReceiver instanceof BroadcastFilter) {
1286             // Simple case: this is a registered receiver who gets
1287             // a direct call.
1288             BroadcastFilter filter = (BroadcastFilter)nextReceiver;
1289             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1290                     "Delivering ordered ["
1291                     + mQueueName + "] to registered "
1292                     + filter + ": " + r);
1293             deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
1294             if (r.receiver == null || !r.ordered) {
1295                 // The receiver has already finished, so schedule to
1296                 // process the next one.
1297                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
1298                         + mQueueName + "]: ordered="
1299                         + r.ordered + " receiver=" + r.receiver);
1300                 r.state = BroadcastRecord.IDLE;
1301                 scheduleBroadcastsLocked();
1302             } else {
1303                 if (filter.receiverList != null) {
1304                     maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
1305                     // r is guaranteed ordered at this point, so we know finishReceiverLocked()
1306                     // will get a callback and handle the activity start token lifecycle.
1307                 }
1308                 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1309                     scheduleTempWhitelistLocked(filter.owningUid,
1310                             brOptions.getTemporaryAppWhitelistDuration(), r);
1311                 }
1312             }
1313             return;
1314         }
1315 
1316         // Hard case: need to instantiate the receiver, possibly
1317         // starting its application process to host it.
1318 
1319         ResolveInfo info =
1320             (ResolveInfo)nextReceiver;
1321         ComponentName component = new ComponentName(
1322                 info.activityInfo.applicationInfo.packageName,
1323                 info.activityInfo.name);
1324 
1325         boolean skip = false;
1326         if (brOptions != null &&
1327                 (info.activityInfo.applicationInfo.targetSdkVersion
1328                         < brOptions.getMinManifestReceiverApiLevel() ||
1329                 info.activityInfo.applicationInfo.targetSdkVersion
1330                         > brOptions.getMaxManifestReceiverApiLevel())) {
1331             skip = true;
1332         }
1333         if (!skip && !mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid,
1334                 component.getPackageName(), info.activityInfo.applicationInfo.uid)) {
1335             Slog.w(TAG, "Association not allowed: broadcasting "
1336                     + r.intent.toString()
1337                     + " from " + r.callerPackage + " (pid=" + r.callingPid
1338                     + ", uid=" + r.callingUid + ") to " + component.flattenToShortString());
1339             skip = true;
1340         }
1341         if (!skip) {
1342             skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
1343                     r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
1344             if (skip) {
1345                 Slog.w(TAG, "Firewall blocked: broadcasting "
1346                         + r.intent.toString()
1347                         + " from " + r.callerPackage + " (pid=" + r.callingPid
1348                         + ", uid=" + r.callingUid + ") to " + component.flattenToShortString());
1349             }
1350         }
1351         int perm = mService.checkComponentPermission(info.activityInfo.permission,
1352                 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
1353                 info.activityInfo.exported);
1354         if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
1355             if (!info.activityInfo.exported) {
1356                 Slog.w(TAG, "Permission Denial: broadcasting "
1357                         + r.intent.toString()
1358                         + " from " + r.callerPackage + " (pid=" + r.callingPid
1359                         + ", uid=" + r.callingUid + ")"
1360                         + " is not exported from uid " + info.activityInfo.applicationInfo.uid
1361                         + " due to receiver " + component.flattenToShortString());
1362             } else {
1363                 Slog.w(TAG, "Permission Denial: broadcasting "
1364                         + r.intent.toString()
1365                         + " from " + r.callerPackage + " (pid=" + r.callingPid
1366                         + ", uid=" + r.callingUid + ")"
1367                         + " requires " + info.activityInfo.permission
1368                         + " due to receiver " + component.flattenToShortString());
1369             }
1370             skip = true;
1371         } else if (!skip && info.activityInfo.permission != null) {
1372             final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
1373             if (opCode != AppOpsManager.OP_NONE
1374                     && mService.getAppOpsManager().noteOpNoThrow(opCode, r.callingUid, r.callerPackage,
1375                     r.callerFeatureId, "") != AppOpsManager.MODE_ALLOWED) {
1376                 Slog.w(TAG, "Appop Denial: broadcasting "
1377                         + r.intent.toString()
1378                         + " from " + r.callerPackage + " (pid="
1379                         + r.callingPid + ", uid=" + r.callingUid + ")"
1380                         + " requires appop " + AppOpsManager.permissionToOp(
1381                                 info.activityInfo.permission)
1382                         + " due to registered receiver "
1383                         + component.flattenToShortString());
1384                 skip = true;
1385             }
1386         }
1387         if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
1388             r.requiredPermissions != null && r.requiredPermissions.length > 0) {
1389             for (int i = 0; i < r.requiredPermissions.length; i++) {
1390                 String requiredPermission = r.requiredPermissions[i];
1391                 try {
1392                     perm = AppGlobals.getPackageManager().
1393                             checkPermission(requiredPermission,
1394                                     info.activityInfo.applicationInfo.packageName,
1395                                     UserHandle
1396                                             .getUserId(info.activityInfo.applicationInfo.uid));
1397                 } catch (RemoteException e) {
1398                     perm = PackageManager.PERMISSION_DENIED;
1399                 }
1400                 if (perm != PackageManager.PERMISSION_GRANTED) {
1401                     Slog.w(TAG, "Permission Denial: receiving "
1402                             + r.intent + " to "
1403                             + component.flattenToShortString()
1404                             + " requires " + requiredPermission
1405                             + " due to sender " + r.callerPackage
1406                             + " (uid " + r.callingUid + ")");
1407                     skip = true;
1408                     break;
1409                 }
1410                 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
1411                 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
1412                         && mService.getAppOpsManager().noteOpNoThrow(appOp,
1413                         info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
1414                         null /* default featureId */, "")
1415                         != AppOpsManager.MODE_ALLOWED) {
1416                     Slog.w(TAG, "Appop Denial: receiving "
1417                             + r.intent + " to "
1418                             + component.flattenToShortString()
1419                             + " requires appop " + AppOpsManager.permissionToOp(
1420                             requiredPermission)
1421                             + " due to sender " + r.callerPackage
1422                             + " (uid " + r.callingUid + ")");
1423                     skip = true;
1424                     break;
1425                 }
1426             }
1427         }
1428         if (!skip && r.appOp != AppOpsManager.OP_NONE
1429                 && mService.getAppOpsManager().noteOpNoThrow(r.appOp,
1430                 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
1431                 null  /* default featureId */, "")
1432                 != AppOpsManager.MODE_ALLOWED) {
1433             Slog.w(TAG, "Appop Denial: receiving "
1434                     + r.intent + " to "
1435                     + component.flattenToShortString()
1436                     + " requires appop " + AppOpsManager.opToName(r.appOp)
1437                     + " due to sender " + r.callerPackage
1438                     + " (uid " + r.callingUid + ")");
1439             skip = true;
1440         }
1441         boolean isSingleton = false;
1442         try {
1443             isSingleton = mService.isSingleton(info.activityInfo.processName,
1444                     info.activityInfo.applicationInfo,
1445                     info.activityInfo.name, info.activityInfo.flags);
1446         } catch (SecurityException e) {
1447             Slog.w(TAG, e.getMessage());
1448             skip = true;
1449         }
1450         if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
1451             if (ActivityManager.checkUidPermission(
1452                     android.Manifest.permission.INTERACT_ACROSS_USERS,
1453                     info.activityInfo.applicationInfo.uid)
1454                             != PackageManager.PERMISSION_GRANTED) {
1455                 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
1456                         + " requests FLAG_SINGLE_USER, but app does not hold "
1457                         + android.Manifest.permission.INTERACT_ACROSS_USERS);
1458                 skip = true;
1459             }
1460         }
1461         if (!skip && info.activityInfo.applicationInfo.isInstantApp()
1462                 && r.callingUid != info.activityInfo.applicationInfo.uid) {
1463             Slog.w(TAG, "Instant App Denial: receiving "
1464                     + r.intent
1465                     + " to " + component.flattenToShortString()
1466                     + " due to sender " + r.callerPackage
1467                     + " (uid " + r.callingUid + ")"
1468                     + " Instant Apps do not support manifest receivers");
1469             skip = true;
1470         }
1471         if (!skip && r.callerInstantApp
1472                 && (info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0
1473                 && r.callingUid != info.activityInfo.applicationInfo.uid) {
1474             Slog.w(TAG, "Instant App Denial: receiving "
1475                     + r.intent
1476                     + " to " + component.flattenToShortString()
1477                     + " requires receiver have visibleToInstantApps set"
1478                     + " due to sender " + r.callerPackage
1479                     + " (uid " + r.callingUid + ")");
1480             skip = true;
1481         }
1482         if (r.curApp != null && r.curApp.isCrashing()) {
1483             // If the target process is crashing, just skip it.
1484             Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1485                     + " to " + r.curApp + ": process crashing");
1486             skip = true;
1487         }
1488         if (!skip) {
1489             boolean isAvailable = false;
1490             try {
1491                 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1492                         info.activityInfo.packageName,
1493                         UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1494             } catch (Exception e) {
1495                 // all such failures mean we skip this receiver
1496                 Slog.w(TAG, "Exception getting recipient info for "
1497                         + info.activityInfo.packageName, e);
1498             }
1499             if (!isAvailable) {
1500                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1501                         "Skipping delivery to " + info.activityInfo.packageName + " / "
1502                         + info.activityInfo.applicationInfo.uid
1503                         + " : package no longer available");
1504                 skip = true;
1505             }
1506         }
1507 
1508         // If permissions need a review before any of the app components can run, we drop
1509         // the broadcast and if the calling app is in the foreground and the broadcast is
1510         // explicit we launch the review UI passing it a pending intent to send the skipped
1511         // broadcast.
1512         if (!skip) {
1513             if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1514                     info.activityInfo.packageName, UserHandle.getUserId(
1515                             info.activityInfo.applicationInfo.uid))) {
1516                 skip = true;
1517             }
1518         }
1519 
1520         // This is safe to do even if we are skipping the broadcast, and we need
1521         // this information now to evaluate whether it is going to be allowed to run.
1522         final int receiverUid = info.activityInfo.applicationInfo.uid;
1523         // If it's a singleton, it needs to be the same app or a special app
1524         if (r.callingUid != Process.SYSTEM_UID && isSingleton
1525                 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1526             info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1527         }
1528         String targetProcess = info.activityInfo.processName;
1529         ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1530                 info.activityInfo.applicationInfo.uid, false);
1531 
1532         if (!skip) {
1533             final int allowed = mService.getAppStartModeLocked(
1534                     info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
1535                     info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false, false);
1536             if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1537                 // We won't allow this receiver to be launched if the app has been
1538                 // completely disabled from launches, or it was not explicitly sent
1539                 // to it and the app is in a state that should not receive it
1540                 // (depending on how getAppStartModeLocked has determined that).
1541                 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
1542                     Slog.w(TAG, "Background execution disabled: receiving "
1543                             + r.intent + " to "
1544                             + component.flattenToShortString());
1545                     skip = true;
1546                 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
1547                         || (r.intent.getComponent() == null
1548                             && r.intent.getPackage() == null
1549                             && ((r.intent.getFlags()
1550                                     & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0)
1551                             && !isSignaturePerm(r.requiredPermissions))) {
1552                     mService.addBackgroundCheckViolationLocked(r.intent.getAction(),
1553                             component.getPackageName());
1554                     Slog.w(TAG, "Background execution not allowed: receiving "
1555                             + r.intent + " to "
1556                             + component.flattenToShortString());
1557                     skip = true;
1558                 }
1559             }
1560         }
1561 
1562         if (!skip && !Intent.ACTION_SHUTDOWN.equals(r.intent.getAction())
1563                 && !mService.mUserController
1564                 .isUserRunning(UserHandle.getUserId(info.activityInfo.applicationInfo.uid),
1565                         0 /* flags */)) {
1566             skip = true;
1567             Slog.w(TAG,
1568                     "Skipping delivery to " + info.activityInfo.packageName + " / "
1569                             + info.activityInfo.applicationInfo.uid + " : user is not running");
1570         }
1571 
1572         if (skip) {
1573             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1574                     "Skipping delivery of ordered [" + mQueueName + "] "
1575                     + r + " for reason described above");
1576             r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
1577             r.receiver = null;
1578             r.curFilter = null;
1579             r.state = BroadcastRecord.IDLE;
1580             r.manifestSkipCount++;
1581             scheduleBroadcastsLocked();
1582             return;
1583         }
1584         r.manifestCount++;
1585 
1586         r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
1587         r.state = BroadcastRecord.APP_RECEIVE;
1588         r.curComponent = component;
1589         r.curReceiver = info.activityInfo;
1590         if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
1591             Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1592                     + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1593                     + receiverUid);
1594         }
1595 
1596         final boolean isActivityCapable =
1597                 (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0);
1598         if (isActivityCapable) {
1599             scheduleTempWhitelistLocked(receiverUid,
1600                     brOptions.getTemporaryAppWhitelistDuration(), r);
1601         }
1602 
1603         // Broadcast is being executed, its package can't be stopped.
1604         try {
1605             AppGlobals.getPackageManager().setPackageStoppedState(
1606                     r.curComponent.getPackageName(), false, r.userId);
1607         } catch (RemoteException e) {
1608         } catch (IllegalArgumentException e) {
1609             Slog.w(TAG, "Failed trying to unstop package "
1610                     + r.curComponent.getPackageName() + ": " + e);
1611         }
1612 
1613         // Is this receiver's application already running?
1614         if (app != null && app.thread != null && !app.killed) {
1615             try {
1616                 app.addPackage(info.activityInfo.packageName,
1617                         info.activityInfo.applicationInfo.longVersionCode, mService.mProcessStats);
1618                 maybeAddAllowBackgroundActivityStartsToken(app, r);
1619                 processCurBroadcastLocked(r, app, skipOomAdj);
1620                 return;
1621             } catch (RemoteException e) {
1622                 Slog.w(TAG, "Exception when sending broadcast to "
1623                       + r.curComponent, e);
1624             } catch (RuntimeException e) {
1625                 Slog.wtf(TAG, "Failed sending broadcast to "
1626                         + r.curComponent + " with " + r.intent, e);
1627                 // If some unexpected exception happened, just skip
1628                 // this broadcast.  At this point we are not in the call
1629                 // from a client, so throwing an exception out from here
1630                 // will crash the entire system instead of just whoever
1631                 // sent the broadcast.
1632                 logBroadcastReceiverDiscardLocked(r);
1633                 finishReceiverLocked(r, r.resultCode, r.resultData,
1634                         r.resultExtras, r.resultAbort, false);
1635                 scheduleBroadcastsLocked();
1636                 // We need to reset the state if we failed to start the receiver.
1637                 r.state = BroadcastRecord.IDLE;
1638                 return;
1639             }
1640 
1641             // If a dead object exception was thrown -- fall through to
1642             // restart the application.
1643         }
1644 
1645         // Not running -- get it started, to be executed when the app comes up.
1646         if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1647                 "Need to start app ["
1648                 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1649         if ((r.curApp=mService.startProcessLocked(targetProcess,
1650                 info.activityInfo.applicationInfo, true,
1651                 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1652                 new HostingRecord("broadcast", r.curComponent),
1653                 isActivityCapable ? ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE : ZYGOTE_POLICY_FLAG_EMPTY,
1654                 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
1655                         == null) {
1656             // Ah, this recipient is unavailable.  Finish it if necessary,
1657             // and mark the broadcast record as ready for the next.
1658             Slog.w(TAG, "Unable to launch app "
1659                     + info.activityInfo.applicationInfo.packageName + "/"
1660                     + receiverUid + " for broadcast "
1661                     + r.intent + ": process is bad");
1662             logBroadcastReceiverDiscardLocked(r);
1663             finishReceiverLocked(r, r.resultCode, r.resultData,
1664                     r.resultExtras, r.resultAbort, false);
1665             scheduleBroadcastsLocked();
1666             r.state = BroadcastRecord.IDLE;
1667             return;
1668         }
1669 
1670         maybeAddAllowBackgroundActivityStartsToken(r.curApp, r);
1671         mPendingBroadcast = r;
1672         mPendingBroadcastRecvIndex = recIdx;
1673     }
1674 
maybeAddAllowBackgroundActivityStartsToken(ProcessRecord proc, BroadcastRecord r)1675     private void maybeAddAllowBackgroundActivityStartsToken(ProcessRecord proc, BroadcastRecord r) {
1676         if (r == null || proc == null || !r.allowBackgroundActivityStarts) {
1677             return;
1678         }
1679         String msgToken = (proc.toShortString() + r.toString()).intern();
1680         // first, if there exists a past scheduled request to remove this token, drop
1681         // that request - we don't want the token to be swept from under our feet...
1682         mHandler.removeCallbacksAndMessages(msgToken);
1683         // ...then add the token
1684         proc.addAllowBackgroundActivityStartsToken(r);
1685     }
1686 
setBroadcastTimeoutLocked(long timeoutTime)1687     final void setBroadcastTimeoutLocked(long timeoutTime) {
1688         if (! mPendingBroadcastTimeoutMessage) {
1689             Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1690             mHandler.sendMessageAtTime(msg, timeoutTime);
1691             mPendingBroadcastTimeoutMessage = true;
1692         }
1693     }
1694 
cancelBroadcastTimeoutLocked()1695     final void cancelBroadcastTimeoutLocked() {
1696         if (mPendingBroadcastTimeoutMessage) {
1697             mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1698             mPendingBroadcastTimeoutMessage = false;
1699         }
1700     }
1701 
broadcastTimeoutLocked(boolean fromMsg)1702     final void broadcastTimeoutLocked(boolean fromMsg) {
1703         if (fromMsg) {
1704             mPendingBroadcastTimeoutMessage = false;
1705         }
1706 
1707         if (mDispatcher.isEmpty() || mDispatcher.getActiveBroadcastLocked() == null) {
1708             return;
1709         }
1710 
1711         long now = SystemClock.uptimeMillis();
1712         BroadcastRecord r = mDispatcher.getActiveBroadcastLocked();
1713         if (fromMsg) {
1714             if (!mService.mProcessesReady) {
1715                 // Only process broadcast timeouts if the system is ready; some early
1716                 // broadcasts do heavy work setting up system facilities
1717                 return;
1718             }
1719 
1720             // If the broadcast is generally exempt from timeout tracking, we're done
1721             if (r.timeoutExempt) {
1722                 if (DEBUG_BROADCAST) {
1723                     Slog.i(TAG_BROADCAST, "Broadcast timeout but it's exempt: "
1724                             + r.intent.getAction());
1725                 }
1726                 return;
1727             }
1728 
1729             long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
1730             if (timeoutTime > now) {
1731                 // We can observe premature timeouts because we do not cancel and reset the
1732                 // broadcast timeout message after each receiver finishes.  Instead, we set up
1733                 // an initial timeout then kick it down the road a little further as needed
1734                 // when it expires.
1735                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1736                         "Premature timeout ["
1737                         + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1738                         + timeoutTime);
1739                 setBroadcastTimeoutLocked(timeoutTime);
1740                 return;
1741             }
1742         }
1743 
1744         if (r.state == BroadcastRecord.WAITING_SERVICES) {
1745             // In this case the broadcast had already finished, but we had decided to wait
1746             // for started services to finish as well before going on.  So if we have actually
1747             // waited long enough time timeout the broadcast, let's give up on the whole thing
1748             // and just move on to the next.
1749             Slog.i(TAG, "Waited long enough for: " + (r.curComponent != null
1750                     ? r.curComponent.flattenToShortString() : "(null)"));
1751             r.curComponent = null;
1752             r.state = BroadcastRecord.IDLE;
1753             processNextBroadcast(false);
1754             return;
1755         }
1756 
1757         // If the receiver app is being debugged we quietly ignore unresponsiveness, just
1758         // tidying up and moving on to the next broadcast without crashing or ANRing this
1759         // app just because it's stopped at a breakpoint.
1760         final boolean debugging = (r.curApp != null && r.curApp.isDebugging());
1761 
1762         Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
1763                 + ", started " + (now - r.receiverTime) + "ms ago");
1764         r.receiverTime = now;
1765         if (!debugging) {
1766             r.anrCount++;
1767         }
1768 
1769         ProcessRecord app = null;
1770         String anrMessage = null;
1771 
1772         Object curReceiver;
1773         if (r.nextReceiver > 0) {
1774             curReceiver = r.receivers.get(r.nextReceiver-1);
1775             r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
1776         } else {
1777             curReceiver = r.curReceiver;
1778         }
1779         Slog.w(TAG, "Receiver during timeout of " + r + " : " + curReceiver);
1780         logBroadcastReceiverDiscardLocked(r);
1781         if (curReceiver != null && curReceiver instanceof BroadcastFilter) {
1782             BroadcastFilter bf = (BroadcastFilter)curReceiver;
1783             if (bf.receiverList.pid != 0
1784                     && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1785                 synchronized (mService.mPidsSelfLocked) {
1786                     app = mService.mPidsSelfLocked.get(
1787                             bf.receiverList.pid);
1788                 }
1789             }
1790         } else {
1791             app = r.curApp;
1792         }
1793 
1794         if (app != null) {
1795             anrMessage = "Broadcast of " + r.intent.toString();
1796         }
1797 
1798         if (mPendingBroadcast == r) {
1799             mPendingBroadcast = null;
1800         }
1801 
1802         // Move on to the next receiver.
1803         finishReceiverLocked(r, r.resultCode, r.resultData,
1804                 r.resultExtras, r.resultAbort, false);
1805         scheduleBroadcastsLocked();
1806 
1807         if (!debugging && anrMessage != null) {
1808             mService.mAnrHelper.appNotResponding(app, anrMessage);
1809         }
1810     }
1811 
ringAdvance(int x, final int increment, final int ringSize)1812     private final int ringAdvance(int x, final int increment, final int ringSize) {
1813         x += increment;
1814         if (x < 0) return (ringSize - 1);
1815         else if (x >= ringSize) return 0;
1816         else return x;
1817     }
1818 
addBroadcastToHistoryLocked(BroadcastRecord original)1819     private final void addBroadcastToHistoryLocked(BroadcastRecord original) {
1820         if (original.callingUid < 0) {
1821             // This was from a registerReceiver() call; ignore it.
1822             return;
1823         }
1824         original.finishTime = SystemClock.uptimeMillis();
1825 
1826         if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1827             Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1828                 createBroadcastTraceTitle(original, BroadcastRecord.DELIVERY_DELIVERED),
1829                 System.identityHashCode(original));
1830         }
1831 
1832         // Note sometimes (only for sticky broadcasts?) we reuse BroadcastRecords,
1833         // So don't change the incoming record directly.
1834         final BroadcastRecord historyRecord = original.maybeStripForHistory();
1835 
1836         mBroadcastHistory[mHistoryNext] = historyRecord;
1837         mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1838 
1839         mBroadcastSummaryHistory[mSummaryHistoryNext] = historyRecord.intent;
1840         mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = historyRecord.enqueueClockTime;
1841         mSummaryHistoryDispatchTime[mSummaryHistoryNext] = historyRecord.dispatchClockTime;
1842         mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1843         mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
1844     }
1845 
cleanupDisabledPackageReceiversLocked( String packageName, Set<String> filterByClasses, int userId, boolean doit)1846     boolean cleanupDisabledPackageReceiversLocked(
1847             String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1848         boolean didSomething = false;
1849         for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1850             didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1851                     packageName, filterByClasses, userId, doit);
1852             if (!doit && didSomething) {
1853                 return true;
1854             }
1855         }
1856 
1857         didSomething |= mDispatcher.cleanupDisabledPackageReceiversLocked(packageName,
1858                 filterByClasses, userId, doit);
1859 
1860         return didSomething;
1861     }
1862 
logBroadcastReceiverDiscardLocked(BroadcastRecord r)1863     final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
1864         final int logIndex = r.nextReceiver - 1;
1865         if (logIndex >= 0 && logIndex < r.receivers.size()) {
1866             Object curReceiver = r.receivers.get(logIndex);
1867             if (curReceiver instanceof BroadcastFilter) {
1868                 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1869                 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
1870                         bf.owningUserId, System.identityHashCode(r),
1871                         r.intent.getAction(), logIndex, System.identityHashCode(bf));
1872             } else {
1873                 ResolveInfo ri = (ResolveInfo) curReceiver;
1874                 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1875                         UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
1876                         System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
1877             }
1878         } else {
1879             if (logIndex < 0) Slog.w(TAG,
1880                     "Discarding broadcast before first receiver is invoked: " + r);
1881             EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1882                     -1, System.identityHashCode(r),
1883                     r.intent.getAction(),
1884                     r.nextReceiver,
1885                     "NONE");
1886         }
1887     }
1888 
createBroadcastTraceTitle(BroadcastRecord record, int state)1889     private String createBroadcastTraceTitle(BroadcastRecord record, int state) {
1890         return String.format("Broadcast %s from %s (%s) %s",
1891                 state == BroadcastRecord.DELIVERY_PENDING ? "in queue" : "dispatched",
1892                 record.callerPackage == null ? "" : record.callerPackage,
1893                 record.callerApp == null ? "process unknown" : record.callerApp.toShortString(),
1894                 record.intent == null ? "" : record.intent.getAction());
1895     }
1896 
isIdle()1897     boolean isIdle() {
1898         return mParallelBroadcasts.isEmpty() && mDispatcher.isEmpty()
1899                 && (mPendingBroadcast == null);
1900     }
1901 
1902     // Used by wait-for-broadcast-idle : fast-forward all current deferrals to
1903     // be immediately deliverable.
cancelDeferrals()1904     void cancelDeferrals() {
1905         synchronized (mService) {
1906             mDispatcher.cancelDeferralsLocked();
1907             scheduleBroadcastsLocked();
1908         }
1909     }
1910 
describeState()1911     String describeState() {
1912         synchronized (mService) {
1913             return mParallelBroadcasts.size() + " parallel; "
1914                     + mDispatcher.describeStateLocked();
1915         }
1916     }
1917 
dumpDebug(ProtoOutputStream proto, long fieldId)1918     void dumpDebug(ProtoOutputStream proto, long fieldId) {
1919         long token = proto.start(fieldId);
1920         proto.write(BroadcastQueueProto.QUEUE_NAME, mQueueName);
1921         int N;
1922         N = mParallelBroadcasts.size();
1923         for (int i = N - 1; i >= 0; i--) {
1924             mParallelBroadcasts.get(i).dumpDebug(proto, BroadcastQueueProto.PARALLEL_BROADCASTS);
1925         }
1926         mDispatcher.dumpDebug(proto, BroadcastQueueProto.ORDERED_BROADCASTS);
1927         if (mPendingBroadcast != null) {
1928             mPendingBroadcast.dumpDebug(proto, BroadcastQueueProto.PENDING_BROADCAST);
1929         }
1930 
1931         int lastIndex = mHistoryNext;
1932         int ringIndex = lastIndex;
1933         do {
1934             // increasing index = more recent entry, and we want to print the most
1935             // recent first and work backwards, so we roll through the ring backwards.
1936             ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1937             BroadcastRecord r = mBroadcastHistory[ringIndex];
1938             if (r != null) {
1939                 r.dumpDebug(proto, BroadcastQueueProto.HISTORICAL_BROADCASTS);
1940             }
1941         } while (ringIndex != lastIndex);
1942 
1943         lastIndex = ringIndex = mSummaryHistoryNext;
1944         do {
1945             ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1946             Intent intent = mBroadcastSummaryHistory[ringIndex];
1947             if (intent == null) {
1948                 continue;
1949             }
1950             long summaryToken = proto.start(BroadcastQueueProto.HISTORICAL_BROADCASTS_SUMMARY);
1951             intent.dumpDebug(proto, BroadcastQueueProto.BroadcastSummary.INTENT,
1952                     false, true, true, false);
1953             proto.write(BroadcastQueueProto.BroadcastSummary.ENQUEUE_CLOCK_TIME_MS,
1954                     mSummaryHistoryEnqueueTime[ringIndex]);
1955             proto.write(BroadcastQueueProto.BroadcastSummary.DISPATCH_CLOCK_TIME_MS,
1956                     mSummaryHistoryDispatchTime[ringIndex]);
1957             proto.write(BroadcastQueueProto.BroadcastSummary.FINISH_CLOCK_TIME_MS,
1958                     mSummaryHistoryFinishTime[ringIndex]);
1959             proto.end(summaryToken);
1960         } while (ringIndex != lastIndex);
1961         proto.end(token);
1962     }
1963 
dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, boolean needSep)1964     final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1965             int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
1966         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
1967         if (!mParallelBroadcasts.isEmpty() || !mDispatcher.isEmpty()
1968                 || mPendingBroadcast != null) {
1969             boolean printed = false;
1970             for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1971                 BroadcastRecord br = mParallelBroadcasts.get(i);
1972                 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1973                     continue;
1974                 }
1975                 if (!printed) {
1976                     if (needSep) {
1977                         pw.println();
1978                     }
1979                     needSep = true;
1980                     printed = true;
1981                     pw.println("  Active broadcasts [" + mQueueName + "]:");
1982                 }
1983                 pw.println("  Active Broadcast " + mQueueName + " #" + i + ":");
1984                 br.dump(pw, "    ", sdf);
1985             }
1986 
1987             mDispatcher.dumpLocked(pw, dumpPackage, mQueueName, sdf);
1988 
1989             if (dumpPackage == null || (mPendingBroadcast != null
1990                     && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1991                 pw.println();
1992                 pw.println("  Pending broadcast [" + mQueueName + "]:");
1993                 if (mPendingBroadcast != null) {
1994                     mPendingBroadcast.dump(pw, "    ", sdf);
1995                 } else {
1996                     pw.println("    (null)");
1997                 }
1998                 needSep = true;
1999             }
2000         }
2001 
2002         mConstants.dump(pw);
2003 
2004         int i;
2005         boolean printed = false;
2006 
2007         i = -1;
2008         int lastIndex = mHistoryNext;
2009         int ringIndex = lastIndex;
2010         do {
2011             // increasing index = more recent entry, and we want to print the most
2012             // recent first and work backwards, so we roll through the ring backwards.
2013             ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
2014             BroadcastRecord r = mBroadcastHistory[ringIndex];
2015             if (r == null) {
2016                 continue;
2017             }
2018 
2019             i++; // genuine record of some sort even if we're filtering it out
2020             if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
2021                 continue;
2022             }
2023             if (!printed) {
2024                 if (needSep) {
2025                     pw.println();
2026                 }
2027                 needSep = true;
2028                 pw.println("  Historical broadcasts [" + mQueueName + "]:");
2029                 printed = true;
2030             }
2031             if (dumpAll) {
2032                 pw.print("  Historical Broadcast " + mQueueName + " #");
2033                         pw.print(i); pw.println(":");
2034                 r.dump(pw, "    ", sdf);
2035             } else {
2036                 pw.print("  #"); pw.print(i); pw.print(": "); pw.println(r);
2037                 pw.print("    ");
2038                 pw.println(r.intent.toShortString(false, true, true, false));
2039                 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
2040                     pw.print("    targetComp: "); pw.println(r.targetComp.toShortString());
2041                 }
2042                 Bundle bundle = r.intent.getExtras();
2043                 if (bundle != null) {
2044                     pw.print("    extras: "); pw.println(bundle.toString());
2045                 }
2046             }
2047         } while (ringIndex != lastIndex);
2048 
2049         if (dumpPackage == null) {
2050             lastIndex = ringIndex = mSummaryHistoryNext;
2051             if (dumpAll) {
2052                 printed = false;
2053                 i = -1;
2054             } else {
2055                 // roll over the 'i' full dumps that have already been issued
2056                 for (int j = i;
2057                         j > 0 && ringIndex != lastIndex;) {
2058                     ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
2059                     BroadcastRecord r = mBroadcastHistory[ringIndex];
2060                     if (r == null) {
2061                         continue;
2062                     }
2063                     j--;
2064                 }
2065             }
2066             // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
2067             // the overall broadcast history.
2068             do {
2069                 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
2070                 Intent intent = mBroadcastSummaryHistory[ringIndex];
2071                 if (intent == null) {
2072                     continue;
2073                 }
2074                 if (!printed) {
2075                     if (needSep) {
2076                         pw.println();
2077                     }
2078                     needSep = true;
2079                     pw.println("  Historical broadcasts summary [" + mQueueName + "]:");
2080                     printed = true;
2081                 }
2082                 if (!dumpAll && i >= 50) {
2083                     pw.println("  ...");
2084                     break;
2085                 }
2086                 i++;
2087                 pw.print("  #"); pw.print(i); pw.print(": ");
2088                 pw.println(intent.toShortString(false, true, true, false));
2089                 pw.print("    ");
2090                 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
2091                         - mSummaryHistoryEnqueueTime[ringIndex], pw);
2092                 pw.print(" dispatch ");
2093                 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
2094                         - mSummaryHistoryDispatchTime[ringIndex], pw);
2095                 pw.println(" finish");
2096                 pw.print("    enq=");
2097                 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
2098                 pw.print(" disp=");
2099                 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
2100                 pw.print(" fin=");
2101                 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
2102                 Bundle bundle = intent.getExtras();
2103                 if (bundle != null) {
2104                     pw.print("    extras: "); pw.println(bundle.toString());
2105                 }
2106             } while (ringIndex != lastIndex);
2107         }
2108 
2109         return needSep;
2110     }
2111 }
2112