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