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