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         }
795         try {
796             if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
797                     "Delivering to " + filter + " : " + r);
798             if (filter.receiverList.app != null && filter.receiverList.app.inFullBackup) {
799                 // Skip delivery if full backup in progress
800                 // If it's an ordered broadcast, we need to continue to the next receiver.
801                 if (ordered) {
802                     skipReceiverLocked(r);
803                 }
804             } else {
805                 r.receiverTime = SystemClock.uptimeMillis();
806                 maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
807                 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
808                         new Intent(r.intent), r.resultCode, r.resultData,
809                         r.resultExtras, r.ordered, r.initialSticky, r.userId);
810                 // parallel broadcasts are fire-and-forget, not bookended by a call to
811                 // finishReceiverLocked(), so we manage their activity-start token here
812                 if (r.allowBackgroundActivityStarts && !r.ordered) {
813                     postActivityStartTokenRemoval(filter.receiverList.app, r);
814                 }
815             }
816             if (ordered) {
817                 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
818             }
819         } catch (RemoteException e) {
820             Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
821             // Clean up ProcessRecord state related to this broadcast attempt
822             if (filter.receiverList.app != null) {
823                 filter.receiverList.app.removeAllowBackgroundActivityStartsToken(r);
824                 if (ordered) {
825                     filter.receiverList.app.curReceivers.remove(r);
826                 }
827             }
828             // And BroadcastRecord state related to ordered delivery, if appropriate
829             if (ordered) {
830                 r.receiver = null;
831                 r.curFilter = null;
832                 filter.receiverList.curBroadcast = null;
833             }
834         }
835     }
836 
requestStartTargetPermissionsReviewIfNeededLocked( BroadcastRecord receiverRecord, String receivingPackageName, final int receivingUserId)837     private boolean requestStartTargetPermissionsReviewIfNeededLocked(
838             BroadcastRecord receiverRecord, String receivingPackageName,
839             final int receivingUserId) {
840         if (!mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
841                 receivingPackageName, receivingUserId)) {
842             return true;
843         }
844 
845         final boolean callerForeground = receiverRecord.callerApp != null
846                 ? receiverRecord.callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND
847                 : true;
848 
849         // Show a permission review UI only for explicit broadcast from a foreground app
850         if (callerForeground && receiverRecord.intent.getComponent() != null) {
851             IIntentSender target = mService.mPendingIntentController.getIntentSender(
852                     ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
853                     receiverRecord.callerFeatureId, receiverRecord.callingUid,
854                     receiverRecord.userId, null, null, 0,
855                     new Intent[]{receiverRecord.intent},
856                     new String[]{receiverRecord.intent.resolveType(mService.mContext
857                             .getContentResolver())},
858                     PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
859                             | PendingIntent.FLAG_IMMUTABLE, null);
860 
861             final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
862             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
863                     | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
864                     | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
865             intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
866             intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
867 
868             if (DEBUG_PERMISSIONS_REVIEW) {
869                 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
870                         + receivingPackageName);
871             }
872 
873             mHandler.post(new Runnable() {
874                 @Override
875                 public void run() {
876                     mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
877                 }
878             });
879         } else {
880             Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
881                     + receivingPackageName + " requires a permissions review");
882         }
883 
884         return false;
885     }
886 
scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r)887     final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
888         if (duration > Integer.MAX_VALUE) {
889             duration = Integer.MAX_VALUE;
890         }
891         // XXX ideally we should pause the broadcast until everything behind this is done,
892         // or else we will likely start dispatching the broadcast before we have opened
893         // access to the app (there is a lot of asynchronicity behind this).  It is probably
894         // not that big a deal, however, because the main purpose here is to allow apps
895         // to hold wake locks, and they will be able to acquire their wake lock immediately
896         // it just won't be enabled until we get through this work.
897         StringBuilder b = new StringBuilder();
898         b.append("broadcast:");
899         UserHandle.formatUid(b, r.callingUid);
900         b.append(":");
901         if (r.intent.getAction() != null) {
902             b.append(r.intent.getAction());
903         } else if (r.intent.getComponent() != null) {
904             r.intent.getComponent().appendShortString(b);
905         } else if (r.intent.getData() != null) {
906             b.append(r.intent.getData());
907         }
908         if (DEBUG_BROADCAST) {
909             Slog.v(TAG, "Broadcast temp whitelist uid=" + uid + " duration=" + duration
910                     + " : " + b.toString());
911         }
912         mService.tempWhitelistUidLocked(uid, duration, b.toString());
913     }
914 
915     /**
916      * Return true if all given permissions are signature-only perms.
917      */
isSignaturePerm(String[] perms)918     final boolean isSignaturePerm(String[] perms) {
919         if (perms == null) {
920             return false;
921         }
922         IPermissionManager pm = AppGlobals.getPermissionManager();
923         for (int i = perms.length-1; i >= 0; i--) {
924             try {
925                 PermissionInfo pi = pm.getPermissionInfo(perms[i], "android", 0);
926                 if (pi == null) {
927                     // a required permission that no package has actually
928                     // defined cannot be signature-required.
929                     return false;
930                 }
931                 if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE
932                         | PermissionInfo.PROTECTION_FLAG_PRIVILEGED))
933                         != PermissionInfo.PROTECTION_SIGNATURE) {
934                     // If this a signature permission and NOT allowed for privileged apps, it
935                     // is okay...  otherwise, nope!
936                     return false;
937                 }
938             } catch (RemoteException e) {
939                 return false;
940             }
941         }
942         return true;
943     }
944 
processNextBroadcast(boolean fromMsg)945     final void processNextBroadcast(boolean fromMsg) {
946         synchronized (mService) {
947             processNextBroadcastLocked(fromMsg, false);
948         }
949     }
950 
processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj)951     final void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj) {
952         BroadcastRecord r;
953 
954         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
955                 + mQueueName + "]: "
956                 + mParallelBroadcasts.size() + " parallel broadcasts; "
957                 + mDispatcher.describeStateLocked());
958 
959         mService.updateCpuStats();
960 
961         if (fromMsg) {
962             mBroadcastsScheduled = false;
963         }
964 
965         // First, deliver any non-serialized broadcasts right away.
966         while (mParallelBroadcasts.size() > 0) {
967             r = mParallelBroadcasts.remove(0);
968             r.dispatchTime = SystemClock.uptimeMillis();
969             r.dispatchClockTime = System.currentTimeMillis();
970 
971             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
972                 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
973                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
974                     System.identityHashCode(r));
975                 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
976                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
977                     System.identityHashCode(r));
978             }
979 
980             final int N = r.receivers.size();
981             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
982                     + mQueueName + "] " + r);
983             for (int i=0; i<N; i++) {
984                 Object target = r.receivers.get(i);
985                 if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
986                         "Delivering non-ordered on [" + mQueueName + "] to registered "
987                         + target + ": " + r);
988                 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
989             }
990             addBroadcastToHistoryLocked(r);
991             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
992                     + mQueueName + "] " + r);
993         }
994 
995         // Now take care of the next serialized one...
996 
997         // If we are waiting for a process to come up to handle the next
998         // broadcast, then do nothing at this point.  Just in case, we
999         // check that the process we're waiting for still exists.
1000         if (mPendingBroadcast != null) {
1001             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
1002                     "processNextBroadcast [" + mQueueName + "]: waiting for "
1003                     + mPendingBroadcast.curApp);
1004 
1005             boolean isDead;
1006             if (mPendingBroadcast.curApp.pid > 0) {
1007                 synchronized (mService.mPidsSelfLocked) {
1008                     ProcessRecord proc = mService.mPidsSelfLocked.get(
1009                             mPendingBroadcast.curApp.pid);
1010                     isDead = proc == null || proc.isCrashing();
1011                 }
1012             } else {
1013                 final ProcessRecord proc = mService.mProcessList.mProcessNames.get(
1014                         mPendingBroadcast.curApp.processName, mPendingBroadcast.curApp.uid);
1015                 isDead = proc == null || !proc.pendingStart;
1016             }
1017             if (!isDead) {
1018                 // It's still alive, so keep waiting
1019                 return;
1020             } else {
1021                 Slog.w(TAG, "pending app  ["
1022                         + mQueueName + "]" + mPendingBroadcast.curApp
1023                         + " died before responding to broadcast");
1024                 mPendingBroadcast.state = BroadcastRecord.IDLE;
1025                 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
1026                 mPendingBroadcast = null;
1027             }
1028         }
1029 
1030         boolean looped = false;
1031 
1032         do {
1033             final long now = SystemClock.uptimeMillis();
1034             r = mDispatcher.getNextBroadcastLocked(now);
1035 
1036             if (r == null) {
1037                 // No more broadcasts are deliverable right now, so all done!
1038                 mDispatcher.scheduleDeferralCheckLocked(false);
1039                 mService.scheduleAppGcsLocked();
1040                 if (looped) {
1041                     // If we had finished the last ordered broadcast, then
1042                     // make sure all processes have correct oom and sched
1043                     // adjustments.
1044                     mService.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_START_RECEIVER);
1045                 }
1046 
1047                 // when we have no more ordered broadcast on this queue, stop logging
1048                 if (mService.mUserController.mBootCompleted && mLogLatencyMetrics) {
1049                     mLogLatencyMetrics = false;
1050                 }
1051 
1052                 return;
1053             }
1054 
1055             boolean forceReceive = false;
1056 
1057             // Ensure that even if something goes awry with the timeout
1058             // detection, we catch "hung" broadcasts here, discard them,
1059             // and continue to make progress.
1060             //
1061             // This is only done if the system is ready so that early-stage receivers
1062             // don't get executed with timeouts; and of course other timeout-
1063             // exempt broadcasts are ignored.
1064             int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
1065             if (mService.mProcessesReady && !r.timeoutExempt && r.dispatchTime > 0) {
1066                 if ((numReceivers > 0) &&
1067                         (now > r.dispatchTime + (2 * mConstants.TIMEOUT * numReceivers))) {
1068                     Slog.w(TAG, "Hung broadcast ["
1069                             + mQueueName + "] discarded after timeout failure:"
1070                             + " now=" + now
1071                             + " dispatchTime=" + r.dispatchTime
1072                             + " startTime=" + r.receiverTime
1073                             + " intent=" + r.intent
1074                             + " numReceivers=" + numReceivers
1075                             + " nextReceiver=" + r.nextReceiver
1076                             + " state=" + r.state);
1077                     broadcastTimeoutLocked(false); // forcibly finish this broadcast
1078                     forceReceive = true;
1079                     r.state = BroadcastRecord.IDLE;
1080                 }
1081             }
1082 
1083             if (r.state != BroadcastRecord.IDLE) {
1084                 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
1085                         "processNextBroadcast("
1086                         + mQueueName + ") called when not idle (state="
1087                         + r.state + ")");
1088                 return;
1089             }
1090 
1091             // Is the current broadcast is done for any reason?
1092             if (r.receivers == null || r.nextReceiver >= numReceivers
1093                     || r.resultAbort || forceReceive) {
1094                 // Send the final result if requested
1095                 if (r.resultTo != null) {
1096                     boolean sendResult = true;
1097 
1098                     // if this was part of a split/deferral complex, update the refcount and only
1099                     // send the completion when we clear all of them
1100                     if (r.splitToken != 0) {
1101                         int newCount = mSplitRefcounts.get(r.splitToken) - 1;
1102                         if (newCount == 0) {
1103                             // done!  clear out this record's bookkeeping and deliver
1104                             if (DEBUG_BROADCAST_DEFERRAL) {
1105                                 Slog.i(TAG_BROADCAST,
1106                                         "Sending broadcast completion for split token "
1107                                         + r.splitToken + " : " + r.intent.getAction());
1108                             }
1109                             mSplitRefcounts.delete(r.splitToken);
1110                         } else {
1111                             // still have some split broadcast records in flight; update refcount
1112                             // and hold off on the callback
1113                             if (DEBUG_BROADCAST_DEFERRAL) {
1114                                 Slog.i(TAG_BROADCAST,
1115                                         "Result refcount now " + newCount + " for split token "
1116                                         + r.splitToken + " : " + r.intent.getAction()
1117                                         + " - not sending completion yet");
1118                             }
1119                             sendResult = false;
1120                             mSplitRefcounts.put(r.splitToken, newCount);
1121                         }
1122                     }
1123                     if (sendResult) {
1124                         try {
1125                             if (DEBUG_BROADCAST) {
1126                                 Slog.i(TAG_BROADCAST, "Finishing broadcast [" + mQueueName + "] "
1127                                         + r.intent.getAction() + " app=" + r.callerApp);
1128                             }
1129                             performReceiveLocked(r.callerApp, r.resultTo,
1130                                     new Intent(r.intent), r.resultCode,
1131                                     r.resultData, r.resultExtras, false, false, r.userId);
1132                             // Set this to null so that the reference
1133                             // (local and remote) isn't kept in the mBroadcastHistory.
1134                             r.resultTo = null;
1135                         } catch (RemoteException e) {
1136                             r.resultTo = null;
1137                             Slog.w(TAG, "Failure ["
1138                                     + mQueueName + "] sending broadcast result of "
1139                                     + r.intent, e);
1140                         }
1141                     }
1142                 }
1143 
1144                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
1145                 cancelBroadcastTimeoutLocked();
1146 
1147                 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
1148                         "Finished with ordered broadcast " + r);
1149 
1150                 // ... and on to the next...
1151                 addBroadcastToHistoryLocked(r);
1152                 if (r.intent.getComponent() == null && r.intent.getPackage() == null
1153                         && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
1154                     // This was an implicit broadcast... let's record it for posterity.
1155                     mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
1156                             r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
1157                 }
1158                 mDispatcher.retireBroadcastLocked(r);
1159                 r = null;
1160                 looped = true;
1161                 continue;
1162             }
1163 
1164             // Check whether the next receiver is under deferral policy, and handle that
1165             // accordingly.  If the current broadcast was already part of deferred-delivery
1166             // tracking, we know that it must now be deliverable as-is without re-deferral.
1167             if (!r.deferred) {
1168                 final int receiverUid = r.getReceiverUid(r.receivers.get(r.nextReceiver));
1169                 if (mDispatcher.isDeferringLocked(receiverUid)) {
1170                     if (DEBUG_BROADCAST_DEFERRAL) {
1171                         Slog.i(TAG_BROADCAST, "Next receiver in " + r + " uid " + receiverUid
1172                                 + " at " + r.nextReceiver + " is under deferral");
1173                     }
1174                     // If this is the only (remaining) receiver in the broadcast, "splitting"
1175                     // doesn't make sense -- just defer it as-is and retire it as the
1176                     // currently active outgoing broadcast.
1177                     BroadcastRecord defer;
1178                     if (r.nextReceiver + 1 == numReceivers) {
1179                         if (DEBUG_BROADCAST_DEFERRAL) {
1180                             Slog.i(TAG_BROADCAST, "Sole receiver of " + r
1181                                     + " is under deferral; setting aside and proceeding");
1182                         }
1183                         defer = r;
1184                         mDispatcher.retireBroadcastLocked(r);
1185                     } else {
1186                         // Nontrivial case; split out 'uid's receivers to a new broadcast record
1187                         // and defer that, then loop and pick up continuing delivery of the current
1188                         // record (now absent those receivers).
1189 
1190                         // The split operation is guaranteed to match at least at 'nextReceiver'
1191                         defer = r.splitRecipientsLocked(receiverUid, r.nextReceiver);
1192                         if (DEBUG_BROADCAST_DEFERRAL) {
1193                             Slog.i(TAG_BROADCAST, "Post split:");
1194                             Slog.i(TAG_BROADCAST, "Original broadcast receivers:");
1195                             for (int i = 0; i < r.receivers.size(); i++) {
1196                                 Slog.i(TAG_BROADCAST, "  " + r.receivers.get(i));
1197                             }
1198                             Slog.i(TAG_BROADCAST, "Split receivers:");
1199                             for (int i = 0; i < defer.receivers.size(); i++) {
1200                                 Slog.i(TAG_BROADCAST, "  " + defer.receivers.get(i));
1201                             }
1202                         }
1203                         // Track completion refcount as well if relevant
1204                         if (r.resultTo != null) {
1205                             int token = r.splitToken;
1206                             if (token == 0) {
1207                                 // first split of this record; refcount for 'r' and 'deferred'
1208                                 r.splitToken = defer.splitToken = nextSplitTokenLocked();
1209                                 mSplitRefcounts.put(r.splitToken, 2);
1210                                 if (DEBUG_BROADCAST_DEFERRAL) {
1211                                     Slog.i(TAG_BROADCAST,
1212                                             "Broadcast needs split refcount; using new token "
1213                                             + r.splitToken);
1214                                 }
1215                             } else {
1216                                 // new split from an already-refcounted situation; increment count
1217                                 final int curCount = mSplitRefcounts.get(token);
1218                                 if (DEBUG_BROADCAST_DEFERRAL) {
1219                                     if (curCount == 0) {
1220                                         Slog.wtf(TAG_BROADCAST,
1221                                                 "Split refcount is zero with token for " + r);
1222                                     }
1223                                 }
1224                                 mSplitRefcounts.put(token, curCount + 1);
1225                                 if (DEBUG_BROADCAST_DEFERRAL) {
1226                                     Slog.i(TAG_BROADCAST, "New split count for token " + token
1227                                             + " is " + (curCount + 1));
1228                                 }
1229                             }
1230                         }
1231                     }
1232                     mDispatcher.addDeferredBroadcast(receiverUid, defer);
1233                     r = null;
1234                     looped = true;
1235                     continue;
1236                 }
1237             }
1238         } while (r == null);
1239 
1240         // Get the next receiver...
1241         int recIdx = r.nextReceiver++;
1242 
1243         // Keep track of when this receiver started, and make sure there
1244         // is a timeout message pending to kill it if need be.
1245         r.receiverTime = SystemClock.uptimeMillis();
1246         if (recIdx == 0) {
1247             r.dispatchTime = r.receiverTime;
1248             r.dispatchClockTime = System.currentTimeMillis();
1249 
1250             if (mLogLatencyMetrics) {
1251                 FrameworkStatsLog.write(
1252                         FrameworkStatsLog.BROADCAST_DISPATCH_LATENCY_REPORTED,
1253                         r.dispatchClockTime - r.enqueueClockTime);
1254             }
1255 
1256             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1257                 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1258                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
1259                     System.identityHashCode(r));
1260                 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1261                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
1262                     System.identityHashCode(r));
1263             }
1264             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
1265                     + mQueueName + "] " + r);
1266         }
1267         if (! mPendingBroadcastTimeoutMessage) {
1268             long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
1269             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1270                     "Submitting BROADCAST_TIMEOUT_MSG ["
1271                     + mQueueName + "] for " + r + " at " + timeoutTime);
1272             setBroadcastTimeoutLocked(timeoutTime);
1273         }
1274 
1275         final BroadcastOptions brOptions = r.options;
1276         final Object nextReceiver = r.receivers.get(recIdx);
1277 
1278         if (nextReceiver instanceof BroadcastFilter) {
1279             // Simple case: this is a registered receiver who gets
1280             // a direct call.
1281             BroadcastFilter filter = (BroadcastFilter)nextReceiver;
1282             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1283                     "Delivering ordered ["
1284                     + mQueueName + "] to registered "
1285                     + filter + ": " + r);
1286             deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
1287             if (r.receiver == null || !r.ordered) {
1288                 // The receiver has already finished, so schedule to
1289                 // process the next one.
1290                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
1291                         + mQueueName + "]: ordered="
1292                         + r.ordered + " receiver=" + r.receiver);
1293                 r.state = BroadcastRecord.IDLE;
1294                 scheduleBroadcastsLocked();
1295             } else {
1296                 if (filter.receiverList != null) {
1297                     maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
1298                     // r is guaranteed ordered at this point, so we know finishReceiverLocked()
1299                     // will get a callback and handle the activity start token lifecycle.
1300                 }
1301                 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1302                     scheduleTempWhitelistLocked(filter.owningUid,
1303                             brOptions.getTemporaryAppWhitelistDuration(), r);
1304                 }
1305             }
1306             return;
1307         }
1308 
1309         // Hard case: need to instantiate the receiver, possibly
1310         // starting its application process to host it.
1311 
1312         ResolveInfo info =
1313             (ResolveInfo)nextReceiver;
1314         ComponentName component = new ComponentName(
1315                 info.activityInfo.applicationInfo.packageName,
1316                 info.activityInfo.name);
1317 
1318         boolean skip = false;
1319         if (brOptions != null &&
1320                 (info.activityInfo.applicationInfo.targetSdkVersion
1321                         < brOptions.getMinManifestReceiverApiLevel() ||
1322                 info.activityInfo.applicationInfo.targetSdkVersion
1323                         > brOptions.getMaxManifestReceiverApiLevel())) {
1324             skip = true;
1325         }
1326         if (!skip && !mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid,
1327                 component.getPackageName(), info.activityInfo.applicationInfo.uid)) {
1328             Slog.w(TAG, "Association not allowed: broadcasting "
1329                     + r.intent.toString()
1330                     + " from " + r.callerPackage + " (pid=" + r.callingPid
1331                     + ", uid=" + r.callingUid + ") to " + component.flattenToShortString());
1332             skip = true;
1333         }
1334         if (!skip) {
1335             skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
1336                     r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
1337             if (skip) {
1338                 Slog.w(TAG, "Firewall blocked: broadcasting "
1339                         + r.intent.toString()
1340                         + " from " + r.callerPackage + " (pid=" + r.callingPid
1341                         + ", uid=" + r.callingUid + ") to " + component.flattenToShortString());
1342             }
1343         }
1344         int perm = mService.checkComponentPermission(info.activityInfo.permission,
1345                 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
1346                 info.activityInfo.exported);
1347         if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
1348             if (!info.activityInfo.exported) {
1349                 Slog.w(TAG, "Permission Denial: broadcasting "
1350                         + r.intent.toString()
1351                         + " from " + r.callerPackage + " (pid=" + r.callingPid
1352                         + ", uid=" + r.callingUid + ")"
1353                         + " is not exported from uid " + info.activityInfo.applicationInfo.uid
1354                         + " due to receiver " + component.flattenToShortString());
1355             } else {
1356                 Slog.w(TAG, "Permission Denial: broadcasting "
1357                         + r.intent.toString()
1358                         + " from " + r.callerPackage + " (pid=" + r.callingPid
1359                         + ", uid=" + r.callingUid + ")"
1360                         + " requires " + info.activityInfo.permission
1361                         + " due to receiver " + component.flattenToShortString());
1362             }
1363             skip = true;
1364         } else if (!skip && info.activityInfo.permission != null) {
1365             final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
1366             if (opCode != AppOpsManager.OP_NONE
1367                     && mService.getAppOpsManager().noteOpNoThrow(opCode, r.callingUid, r.callerPackage,
1368                     r.callerFeatureId, "") != AppOpsManager.MODE_ALLOWED) {
1369                 Slog.w(TAG, "Appop Denial: broadcasting "
1370                         + r.intent.toString()
1371                         + " from " + r.callerPackage + " (pid="
1372                         + r.callingPid + ", uid=" + r.callingUid + ")"
1373                         + " requires appop " + AppOpsManager.permissionToOp(
1374                                 info.activityInfo.permission)
1375                         + " due to registered receiver "
1376                         + component.flattenToShortString());
1377                 skip = true;
1378             }
1379         }
1380         if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
1381             r.requiredPermissions != null && r.requiredPermissions.length > 0) {
1382             for (int i = 0; i < r.requiredPermissions.length; i++) {
1383                 String requiredPermission = r.requiredPermissions[i];
1384                 try {
1385                     perm = AppGlobals.getPackageManager().
1386                             checkPermission(requiredPermission,
1387                                     info.activityInfo.applicationInfo.packageName,
1388                                     UserHandle
1389                                             .getUserId(info.activityInfo.applicationInfo.uid));
1390                 } catch (RemoteException e) {
1391                     perm = PackageManager.PERMISSION_DENIED;
1392                 }
1393                 if (perm != PackageManager.PERMISSION_GRANTED) {
1394                     Slog.w(TAG, "Permission Denial: receiving "
1395                             + r.intent + " to "
1396                             + component.flattenToShortString()
1397                             + " requires " + requiredPermission
1398                             + " due to sender " + r.callerPackage
1399                             + " (uid " + r.callingUid + ")");
1400                     skip = true;
1401                     break;
1402                 }
1403                 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
1404                 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
1405                         && mService.getAppOpsManager().noteOpNoThrow(appOp,
1406                         info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
1407                         null /* default featureId */, "")
1408                         != AppOpsManager.MODE_ALLOWED) {
1409                     Slog.w(TAG, "Appop Denial: receiving "
1410                             + r.intent + " to "
1411                             + component.flattenToShortString()
1412                             + " requires appop " + AppOpsManager.permissionToOp(
1413                             requiredPermission)
1414                             + " due to sender " + r.callerPackage
1415                             + " (uid " + r.callingUid + ")");
1416                     skip = true;
1417                     break;
1418                 }
1419             }
1420         }
1421         if (!skip && r.appOp != AppOpsManager.OP_NONE
1422                 && mService.getAppOpsManager().noteOpNoThrow(r.appOp,
1423                 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
1424                 null  /* default featureId */, "")
1425                 != AppOpsManager.MODE_ALLOWED) {
1426             Slog.w(TAG, "Appop Denial: receiving "
1427                     + r.intent + " to "
1428                     + component.flattenToShortString()
1429                     + " requires appop " + AppOpsManager.opToName(r.appOp)
1430                     + " due to sender " + r.callerPackage
1431                     + " (uid " + r.callingUid + ")");
1432             skip = true;
1433         }
1434         boolean isSingleton = false;
1435         try {
1436             isSingleton = mService.isSingleton(info.activityInfo.processName,
1437                     info.activityInfo.applicationInfo,
1438                     info.activityInfo.name, info.activityInfo.flags);
1439         } catch (SecurityException e) {
1440             Slog.w(TAG, e.getMessage());
1441             skip = true;
1442         }
1443         if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
1444             if (ActivityManager.checkUidPermission(
1445                     android.Manifest.permission.INTERACT_ACROSS_USERS,
1446                     info.activityInfo.applicationInfo.uid)
1447                             != PackageManager.PERMISSION_GRANTED) {
1448                 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
1449                         + " requests FLAG_SINGLE_USER, but app does not hold "
1450                         + android.Manifest.permission.INTERACT_ACROSS_USERS);
1451                 skip = true;
1452             }
1453         }
1454         if (!skip && info.activityInfo.applicationInfo.isInstantApp()
1455                 && r.callingUid != info.activityInfo.applicationInfo.uid) {
1456             Slog.w(TAG, "Instant App Denial: receiving "
1457                     + r.intent
1458                     + " to " + component.flattenToShortString()
1459                     + " due to sender " + r.callerPackage
1460                     + " (uid " + r.callingUid + ")"
1461                     + " Instant Apps do not support manifest receivers");
1462             skip = true;
1463         }
1464         if (!skip && r.callerInstantApp
1465                 && (info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0
1466                 && r.callingUid != info.activityInfo.applicationInfo.uid) {
1467             Slog.w(TAG, "Instant App Denial: receiving "
1468                     + r.intent
1469                     + " to " + component.flattenToShortString()
1470                     + " requires receiver have visibleToInstantApps set"
1471                     + " due to sender " + r.callerPackage
1472                     + " (uid " + r.callingUid + ")");
1473             skip = true;
1474         }
1475         if (r.curApp != null && r.curApp.isCrashing()) {
1476             // If the target process is crashing, just skip it.
1477             Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1478                     + " to " + r.curApp + ": process crashing");
1479             skip = true;
1480         }
1481         if (!skip) {
1482             boolean isAvailable = false;
1483             try {
1484                 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1485                         info.activityInfo.packageName,
1486                         UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1487             } catch (Exception e) {
1488                 // all such failures mean we skip this receiver
1489                 Slog.w(TAG, "Exception getting recipient info for "
1490                         + info.activityInfo.packageName, e);
1491             }
1492             if (!isAvailable) {
1493                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1494                         "Skipping delivery to " + info.activityInfo.packageName + " / "
1495                         + info.activityInfo.applicationInfo.uid
1496                         + " : package no longer available");
1497                 skip = true;
1498             }
1499         }
1500 
1501         // If permissions need a review before any of the app components can run, we drop
1502         // the broadcast and if the calling app is in the foreground and the broadcast is
1503         // explicit we launch the review UI passing it a pending intent to send the skipped
1504         // broadcast.
1505         if (!skip) {
1506             if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1507                     info.activityInfo.packageName, UserHandle.getUserId(
1508                             info.activityInfo.applicationInfo.uid))) {
1509                 skip = true;
1510             }
1511         }
1512 
1513         // This is safe to do even if we are skipping the broadcast, and we need
1514         // this information now to evaluate whether it is going to be allowed to run.
1515         final int receiverUid = info.activityInfo.applicationInfo.uid;
1516         // If it's a singleton, it needs to be the same app or a special app
1517         if (r.callingUid != Process.SYSTEM_UID && isSingleton
1518                 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1519             info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1520         }
1521         String targetProcess = info.activityInfo.processName;
1522         ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1523                 info.activityInfo.applicationInfo.uid, false);
1524 
1525         if (!skip) {
1526             final int allowed = mService.getAppStartModeLocked(
1527                     info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
1528                     info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false, false);
1529             if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1530                 // We won't allow this receiver to be launched if the app has been
1531                 // completely disabled from launches, or it was not explicitly sent
1532                 // to it and the app is in a state that should not receive it
1533                 // (depending on how getAppStartModeLocked has determined that).
1534                 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
1535                     Slog.w(TAG, "Background execution disabled: receiving "
1536                             + r.intent + " to "
1537                             + component.flattenToShortString());
1538                     skip = true;
1539                 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
1540                         || (r.intent.getComponent() == null
1541                             && r.intent.getPackage() == null
1542                             && ((r.intent.getFlags()
1543                                     & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0)
1544                             && !isSignaturePerm(r.requiredPermissions))) {
1545                     mService.addBackgroundCheckViolationLocked(r.intent.getAction(),
1546                             component.getPackageName());
1547                     Slog.w(TAG, "Background execution not allowed: receiving "
1548                             + r.intent + " to "
1549                             + component.flattenToShortString());
1550                     skip = true;
1551                 }
1552             }
1553         }
1554 
1555         if (!skip && !Intent.ACTION_SHUTDOWN.equals(r.intent.getAction())
1556                 && !mService.mUserController
1557                 .isUserRunning(UserHandle.getUserId(info.activityInfo.applicationInfo.uid),
1558                         0 /* flags */)) {
1559             skip = true;
1560             Slog.w(TAG,
1561                     "Skipping delivery to " + info.activityInfo.packageName + " / "
1562                             + info.activityInfo.applicationInfo.uid + " : user is not running");
1563         }
1564 
1565         if (skip) {
1566             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1567                     "Skipping delivery of ordered [" + mQueueName + "] "
1568                     + r + " for reason described above");
1569             r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
1570             r.receiver = null;
1571             r.curFilter = null;
1572             r.state = BroadcastRecord.IDLE;
1573             r.manifestSkipCount++;
1574             scheduleBroadcastsLocked();
1575             return;
1576         }
1577         r.manifestCount++;
1578 
1579         r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
1580         r.state = BroadcastRecord.APP_RECEIVE;
1581         r.curComponent = component;
1582         r.curReceiver = info.activityInfo;
1583         if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
1584             Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1585                     + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1586                     + receiverUid);
1587         }
1588 
1589         final boolean isActivityCapable =
1590                 (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0);
1591         if (isActivityCapable) {
1592             scheduleTempWhitelistLocked(receiverUid,
1593                     brOptions.getTemporaryAppWhitelistDuration(), r);
1594         }
1595 
1596         // Broadcast is being executed, its package can't be stopped.
1597         try {
1598             AppGlobals.getPackageManager().setPackageStoppedState(
1599                     r.curComponent.getPackageName(), false, r.userId);
1600         } catch (RemoteException e) {
1601         } catch (IllegalArgumentException e) {
1602             Slog.w(TAG, "Failed trying to unstop package "
1603                     + r.curComponent.getPackageName() + ": " + e);
1604         }
1605 
1606         // Is this receiver's application already running?
1607         if (app != null && app.thread != null && !app.killed) {
1608             try {
1609                 app.addPackage(info.activityInfo.packageName,
1610                         info.activityInfo.applicationInfo.longVersionCode, mService.mProcessStats);
1611                 maybeAddAllowBackgroundActivityStartsToken(app, r);
1612                 processCurBroadcastLocked(r, app, skipOomAdj);
1613                 return;
1614             } catch (RemoteException e) {
1615                 Slog.w(TAG, "Exception when sending broadcast to "
1616                       + r.curComponent, e);
1617             } catch (RuntimeException e) {
1618                 Slog.wtf(TAG, "Failed sending broadcast to "
1619                         + r.curComponent + " with " + r.intent, e);
1620                 // If some unexpected exception happened, just skip
1621                 // this broadcast.  At this point we are not in the call
1622                 // from a client, so throwing an exception out from here
1623                 // will crash the entire system instead of just whoever
1624                 // sent the broadcast.
1625                 logBroadcastReceiverDiscardLocked(r);
1626                 finishReceiverLocked(r, r.resultCode, r.resultData,
1627                         r.resultExtras, r.resultAbort, false);
1628                 scheduleBroadcastsLocked();
1629                 // We need to reset the state if we failed to start the receiver.
1630                 r.state = BroadcastRecord.IDLE;
1631                 return;
1632             }
1633 
1634             // If a dead object exception was thrown -- fall through to
1635             // restart the application.
1636         }
1637 
1638         // Not running -- get it started, to be executed when the app comes up.
1639         if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1640                 "Need to start app ["
1641                 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1642         if ((r.curApp=mService.startProcessLocked(targetProcess,
1643                 info.activityInfo.applicationInfo, true,
1644                 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1645                 new HostingRecord("broadcast", r.curComponent),
1646                 isActivityCapable ? ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE : ZYGOTE_POLICY_FLAG_EMPTY,
1647                 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
1648                         == null) {
1649             // Ah, this recipient is unavailable.  Finish it if necessary,
1650             // and mark the broadcast record as ready for the next.
1651             Slog.w(TAG, "Unable to launch app "
1652                     + info.activityInfo.applicationInfo.packageName + "/"
1653                     + receiverUid + " for broadcast "
1654                     + r.intent + ": process is bad");
1655             logBroadcastReceiverDiscardLocked(r);
1656             finishReceiverLocked(r, r.resultCode, r.resultData,
1657                     r.resultExtras, r.resultAbort, false);
1658             scheduleBroadcastsLocked();
1659             r.state = BroadcastRecord.IDLE;
1660             return;
1661         }
1662 
1663         maybeAddAllowBackgroundActivityStartsToken(r.curApp, r);
1664         mPendingBroadcast = r;
1665         mPendingBroadcastRecvIndex = recIdx;
1666     }
1667 
maybeAddAllowBackgroundActivityStartsToken(ProcessRecord proc, BroadcastRecord r)1668     private void maybeAddAllowBackgroundActivityStartsToken(ProcessRecord proc, BroadcastRecord r) {
1669         if (r == null || proc == null || !r.allowBackgroundActivityStarts) {
1670             return;
1671         }
1672         String msgToken = (proc.toShortString() + r.toString()).intern();
1673         // first, if there exists a past scheduled request to remove this token, drop
1674         // that request - we don't want the token to be swept from under our feet...
1675         mHandler.removeCallbacksAndMessages(msgToken);
1676         // ...then add the token
1677         proc.addAllowBackgroundActivityStartsToken(r);
1678     }
1679 
setBroadcastTimeoutLocked(long timeoutTime)1680     final void setBroadcastTimeoutLocked(long timeoutTime) {
1681         if (! mPendingBroadcastTimeoutMessage) {
1682             Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1683             mHandler.sendMessageAtTime(msg, timeoutTime);
1684             mPendingBroadcastTimeoutMessage = true;
1685         }
1686     }
1687 
cancelBroadcastTimeoutLocked()1688     final void cancelBroadcastTimeoutLocked() {
1689         if (mPendingBroadcastTimeoutMessage) {
1690             mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1691             mPendingBroadcastTimeoutMessage = false;
1692         }
1693     }
1694 
broadcastTimeoutLocked(boolean fromMsg)1695     final void broadcastTimeoutLocked(boolean fromMsg) {
1696         if (fromMsg) {
1697             mPendingBroadcastTimeoutMessage = false;
1698         }
1699 
1700         if (mDispatcher.isEmpty() || mDispatcher.getActiveBroadcastLocked() == null) {
1701             return;
1702         }
1703 
1704         long now = SystemClock.uptimeMillis();
1705         BroadcastRecord r = mDispatcher.getActiveBroadcastLocked();
1706         if (fromMsg) {
1707             if (!mService.mProcessesReady) {
1708                 // Only process broadcast timeouts if the system is ready; some early
1709                 // broadcasts do heavy work setting up system facilities
1710                 return;
1711             }
1712 
1713             // If the broadcast is generally exempt from timeout tracking, we're done
1714             if (r.timeoutExempt) {
1715                 if (DEBUG_BROADCAST) {
1716                     Slog.i(TAG_BROADCAST, "Broadcast timeout but it's exempt: "
1717                             + r.intent.getAction());
1718                 }
1719                 return;
1720             }
1721 
1722             long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
1723             if (timeoutTime > now) {
1724                 // We can observe premature timeouts because we do not cancel and reset the
1725                 // broadcast timeout message after each receiver finishes.  Instead, we set up
1726                 // an initial timeout then kick it down the road a little further as needed
1727                 // when it expires.
1728                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1729                         "Premature timeout ["
1730                         + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1731                         + timeoutTime);
1732                 setBroadcastTimeoutLocked(timeoutTime);
1733                 return;
1734             }
1735         }
1736 
1737         if (r.state == BroadcastRecord.WAITING_SERVICES) {
1738             // In this case the broadcast had already finished, but we had decided to wait
1739             // for started services to finish as well before going on.  So if we have actually
1740             // waited long enough time timeout the broadcast, let's give up on the whole thing
1741             // and just move on to the next.
1742             Slog.i(TAG, "Waited long enough for: " + (r.curComponent != null
1743                     ? r.curComponent.flattenToShortString() : "(null)"));
1744             r.curComponent = null;
1745             r.state = BroadcastRecord.IDLE;
1746             processNextBroadcast(false);
1747             return;
1748         }
1749 
1750         // If the receiver app is being debugged we quietly ignore unresponsiveness, just
1751         // tidying up and moving on to the next broadcast without crashing or ANRing this
1752         // app just because it's stopped at a breakpoint.
1753         final boolean debugging = (r.curApp != null && r.curApp.isDebugging());
1754 
1755         Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
1756                 + ", started " + (now - r.receiverTime) + "ms ago");
1757         r.receiverTime = now;
1758         if (!debugging) {
1759             r.anrCount++;
1760         }
1761 
1762         ProcessRecord app = null;
1763         String anrMessage = null;
1764 
1765         Object curReceiver;
1766         if (r.nextReceiver > 0) {
1767             curReceiver = r.receivers.get(r.nextReceiver-1);
1768             r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
1769         } else {
1770             curReceiver = r.curReceiver;
1771         }
1772         Slog.w(TAG, "Receiver during timeout of " + r + " : " + curReceiver);
1773         logBroadcastReceiverDiscardLocked(r);
1774         if (curReceiver != null && curReceiver instanceof BroadcastFilter) {
1775             BroadcastFilter bf = (BroadcastFilter)curReceiver;
1776             if (bf.receiverList.pid != 0
1777                     && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1778                 synchronized (mService.mPidsSelfLocked) {
1779                     app = mService.mPidsSelfLocked.get(
1780                             bf.receiverList.pid);
1781                 }
1782             }
1783         } else {
1784             app = r.curApp;
1785         }
1786 
1787         if (app != null) {
1788             anrMessage = "Broadcast of " + r.intent.toString();
1789         }
1790 
1791         if (mPendingBroadcast == r) {
1792             mPendingBroadcast = null;
1793         }
1794 
1795         // Move on to the next receiver.
1796         finishReceiverLocked(r, r.resultCode, r.resultData,
1797                 r.resultExtras, r.resultAbort, false);
1798         scheduleBroadcastsLocked();
1799 
1800         if (!debugging && anrMessage != null) {
1801             mService.mAnrHelper.appNotResponding(app, anrMessage);
1802         }
1803     }
1804 
ringAdvance(int x, final int increment, final int ringSize)1805     private final int ringAdvance(int x, final int increment, final int ringSize) {
1806         x += increment;
1807         if (x < 0) return (ringSize - 1);
1808         else if (x >= ringSize) return 0;
1809         else return x;
1810     }
1811 
addBroadcastToHistoryLocked(BroadcastRecord original)1812     private final void addBroadcastToHistoryLocked(BroadcastRecord original) {
1813         if (original.callingUid < 0) {
1814             // This was from a registerReceiver() call; ignore it.
1815             return;
1816         }
1817         original.finishTime = SystemClock.uptimeMillis();
1818 
1819         if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1820             Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1821                 createBroadcastTraceTitle(original, BroadcastRecord.DELIVERY_DELIVERED),
1822                 System.identityHashCode(original));
1823         }
1824 
1825         // Note sometimes (only for sticky broadcasts?) we reuse BroadcastRecords,
1826         // So don't change the incoming record directly.
1827         final BroadcastRecord historyRecord = original.maybeStripForHistory();
1828 
1829         mBroadcastHistory[mHistoryNext] = historyRecord;
1830         mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1831 
1832         mBroadcastSummaryHistory[mSummaryHistoryNext] = historyRecord.intent;
1833         mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = historyRecord.enqueueClockTime;
1834         mSummaryHistoryDispatchTime[mSummaryHistoryNext] = historyRecord.dispatchClockTime;
1835         mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1836         mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
1837     }
1838 
cleanupDisabledPackageReceiversLocked( String packageName, Set<String> filterByClasses, int userId, boolean doit)1839     boolean cleanupDisabledPackageReceiversLocked(
1840             String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1841         boolean didSomething = false;
1842         for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1843             didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1844                     packageName, filterByClasses, userId, doit);
1845             if (!doit && didSomething) {
1846                 return true;
1847             }
1848         }
1849 
1850         didSomething |= mDispatcher.cleanupDisabledPackageReceiversLocked(packageName,
1851                 filterByClasses, userId, doit);
1852 
1853         return didSomething;
1854     }
1855 
logBroadcastReceiverDiscardLocked(BroadcastRecord r)1856     final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
1857         final int logIndex = r.nextReceiver - 1;
1858         if (logIndex >= 0 && logIndex < r.receivers.size()) {
1859             Object curReceiver = r.receivers.get(logIndex);
1860             if (curReceiver instanceof BroadcastFilter) {
1861                 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1862                 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
1863                         bf.owningUserId, System.identityHashCode(r),
1864                         r.intent.getAction(), logIndex, System.identityHashCode(bf));
1865             } else {
1866                 ResolveInfo ri = (ResolveInfo) curReceiver;
1867                 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1868                         UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
1869                         System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
1870             }
1871         } else {
1872             if (logIndex < 0) Slog.w(TAG,
1873                     "Discarding broadcast before first receiver is invoked: " + r);
1874             EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1875                     -1, System.identityHashCode(r),
1876                     r.intent.getAction(),
1877                     r.nextReceiver,
1878                     "NONE");
1879         }
1880     }
1881 
createBroadcastTraceTitle(BroadcastRecord record, int state)1882     private String createBroadcastTraceTitle(BroadcastRecord record, int state) {
1883         return String.format("Broadcast %s from %s (%s) %s",
1884                 state == BroadcastRecord.DELIVERY_PENDING ? "in queue" : "dispatched",
1885                 record.callerPackage == null ? "" : record.callerPackage,
1886                 record.callerApp == null ? "process unknown" : record.callerApp.toShortString(),
1887                 record.intent == null ? "" : record.intent.getAction());
1888     }
1889 
isIdle()1890     boolean isIdle() {
1891         return mParallelBroadcasts.isEmpty() && mDispatcher.isEmpty()
1892                 && (mPendingBroadcast == null);
1893     }
1894 
1895     // Used by wait-for-broadcast-idle : fast-forward all current deferrals to
1896     // be immediately deliverable.
cancelDeferrals()1897     void cancelDeferrals() {
1898         synchronized (mService) {
1899             mDispatcher.cancelDeferralsLocked();
1900             scheduleBroadcastsLocked();
1901         }
1902     }
1903 
describeState()1904     String describeState() {
1905         synchronized (mService) {
1906             return mParallelBroadcasts.size() + " parallel; "
1907                     + mDispatcher.describeStateLocked();
1908         }
1909     }
1910 
dumpDebug(ProtoOutputStream proto, long fieldId)1911     void dumpDebug(ProtoOutputStream proto, long fieldId) {
1912         long token = proto.start(fieldId);
1913         proto.write(BroadcastQueueProto.QUEUE_NAME, mQueueName);
1914         int N;
1915         N = mParallelBroadcasts.size();
1916         for (int i = N - 1; i >= 0; i--) {
1917             mParallelBroadcasts.get(i).dumpDebug(proto, BroadcastQueueProto.PARALLEL_BROADCASTS);
1918         }
1919         mDispatcher.dumpDebug(proto, BroadcastQueueProto.ORDERED_BROADCASTS);
1920         if (mPendingBroadcast != null) {
1921             mPendingBroadcast.dumpDebug(proto, BroadcastQueueProto.PENDING_BROADCAST);
1922         }
1923 
1924         int lastIndex = mHistoryNext;
1925         int ringIndex = lastIndex;
1926         do {
1927             // increasing index = more recent entry, and we want to print the most
1928             // recent first and work backwards, so we roll through the ring backwards.
1929             ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1930             BroadcastRecord r = mBroadcastHistory[ringIndex];
1931             if (r != null) {
1932                 r.dumpDebug(proto, BroadcastQueueProto.HISTORICAL_BROADCASTS);
1933             }
1934         } while (ringIndex != lastIndex);
1935 
1936         lastIndex = ringIndex = mSummaryHistoryNext;
1937         do {
1938             ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1939             Intent intent = mBroadcastSummaryHistory[ringIndex];
1940             if (intent == null) {
1941                 continue;
1942             }
1943             long summaryToken = proto.start(BroadcastQueueProto.HISTORICAL_BROADCASTS_SUMMARY);
1944             intent.dumpDebug(proto, BroadcastQueueProto.BroadcastSummary.INTENT,
1945                     false, true, true, false);
1946             proto.write(BroadcastQueueProto.BroadcastSummary.ENQUEUE_CLOCK_TIME_MS,
1947                     mSummaryHistoryEnqueueTime[ringIndex]);
1948             proto.write(BroadcastQueueProto.BroadcastSummary.DISPATCH_CLOCK_TIME_MS,
1949                     mSummaryHistoryDispatchTime[ringIndex]);
1950             proto.write(BroadcastQueueProto.BroadcastSummary.FINISH_CLOCK_TIME_MS,
1951                     mSummaryHistoryFinishTime[ringIndex]);
1952             proto.end(summaryToken);
1953         } while (ringIndex != lastIndex);
1954         proto.end(token);
1955     }
1956 
dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, boolean needSep)1957     final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1958             int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
1959         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
1960         if (!mParallelBroadcasts.isEmpty() || !mDispatcher.isEmpty()
1961                 || mPendingBroadcast != null) {
1962             boolean printed = false;
1963             for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1964                 BroadcastRecord br = mParallelBroadcasts.get(i);
1965                 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1966                     continue;
1967                 }
1968                 if (!printed) {
1969                     if (needSep) {
1970                         pw.println();
1971                     }
1972                     needSep = true;
1973                     printed = true;
1974                     pw.println("  Active broadcasts [" + mQueueName + "]:");
1975                 }
1976                 pw.println("  Active Broadcast " + mQueueName + " #" + i + ":");
1977                 br.dump(pw, "    ", sdf);
1978             }
1979 
1980             mDispatcher.dumpLocked(pw, dumpPackage, mQueueName, sdf);
1981 
1982             if (dumpPackage == null || (mPendingBroadcast != null
1983                     && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1984                 pw.println();
1985                 pw.println("  Pending broadcast [" + mQueueName + "]:");
1986                 if (mPendingBroadcast != null) {
1987                     mPendingBroadcast.dump(pw, "    ", sdf);
1988                 } else {
1989                     pw.println("    (null)");
1990                 }
1991                 needSep = true;
1992             }
1993         }
1994 
1995         mConstants.dump(pw);
1996 
1997         int i;
1998         boolean printed = false;
1999 
2000         i = -1;
2001         int lastIndex = mHistoryNext;
2002         int ringIndex = lastIndex;
2003         do {
2004             // increasing index = more recent entry, and we want to print the most
2005             // recent first and work backwards, so we roll through the ring backwards.
2006             ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
2007             BroadcastRecord r = mBroadcastHistory[ringIndex];
2008             if (r == null) {
2009                 continue;
2010             }
2011 
2012             i++; // genuine record of some sort even if we're filtering it out
2013             if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
2014                 continue;
2015             }
2016             if (!printed) {
2017                 if (needSep) {
2018                     pw.println();
2019                 }
2020                 needSep = true;
2021                 pw.println("  Historical broadcasts [" + mQueueName + "]:");
2022                 printed = true;
2023             }
2024             if (dumpAll) {
2025                 pw.print("  Historical Broadcast " + mQueueName + " #");
2026                         pw.print(i); pw.println(":");
2027                 r.dump(pw, "    ", sdf);
2028             } else {
2029                 pw.print("  #"); pw.print(i); pw.print(": "); pw.println(r);
2030                 pw.print("    ");
2031                 pw.println(r.intent.toShortString(false, true, true, false));
2032                 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
2033                     pw.print("    targetComp: "); pw.println(r.targetComp.toShortString());
2034                 }
2035                 Bundle bundle = r.intent.getExtras();
2036                 if (bundle != null) {
2037                     pw.print("    extras: "); pw.println(bundle.toString());
2038                 }
2039             }
2040         } while (ringIndex != lastIndex);
2041 
2042         if (dumpPackage == null) {
2043             lastIndex = ringIndex = mSummaryHistoryNext;
2044             if (dumpAll) {
2045                 printed = false;
2046                 i = -1;
2047             } else {
2048                 // roll over the 'i' full dumps that have already been issued
2049                 for (int j = i;
2050                         j > 0 && ringIndex != lastIndex;) {
2051                     ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
2052                     BroadcastRecord r = mBroadcastHistory[ringIndex];
2053                     if (r == null) {
2054                         continue;
2055                     }
2056                     j--;
2057                 }
2058             }
2059             // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
2060             // the overall broadcast history.
2061             do {
2062                 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
2063                 Intent intent = mBroadcastSummaryHistory[ringIndex];
2064                 if (intent == null) {
2065                     continue;
2066                 }
2067                 if (!printed) {
2068                     if (needSep) {
2069                         pw.println();
2070                     }
2071                     needSep = true;
2072                     pw.println("  Historical broadcasts summary [" + mQueueName + "]:");
2073                     printed = true;
2074                 }
2075                 if (!dumpAll && i >= 50) {
2076                     pw.println("  ...");
2077                     break;
2078                 }
2079                 i++;
2080                 pw.print("  #"); pw.print(i); pw.print(": ");
2081                 pw.println(intent.toShortString(false, true, true, false));
2082                 pw.print("    ");
2083                 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
2084                         - mSummaryHistoryEnqueueTime[ringIndex], pw);
2085                 pw.print(" dispatch ");
2086                 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
2087                         - mSummaryHistoryDispatchTime[ringIndex], pw);
2088                 pw.println(" finish");
2089                 pw.print("    enq=");
2090                 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
2091                 pw.print(" disp=");
2092                 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
2093                 pw.print(" fin=");
2094                 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
2095                 Bundle bundle = intent.getExtras();
2096                 if (bundle != null) {
2097                     pw.print("    extras: "); pw.println(bundle.toString());
2098                 }
2099             } while (ringIndex != lastIndex);
2100         }
2101 
2102         return needSep;
2103     }
2104 }
2105