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.app.ActivityManager.RESTRICTION_LEVEL_RESTRICTED_BUCKET;
20 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_START_RECEIVER;
21 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_APP_FREEZING_DELAYED;
22 import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY;
23 import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE;
24 import static android.text.TextUtils.formatSimple;
25 
26 import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED;
27 import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__BOOT_COMPLETED;
28 import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__LOCKED_BOOT_COMPLETED;
29 import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED;
30 import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD;
31 import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM;
32 import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__MANIFEST;
33 import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME;
34 import static com.android.internal.util.FrameworkStatsLog.SERVICE_REQUEST_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_NORMAL;
35 import static com.android.internal.util.FrameworkStatsLog.SERVICE_REQUEST_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_STOPPED;
36 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST;
37 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_DEFERRAL;
38 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT;
39 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
40 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST;
41 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
42 
43 import android.annotation.NonNull;
44 import android.annotation.Nullable;
45 import android.app.Activity;
46 import android.app.ActivityManager;
47 import android.app.ApplicationExitInfo;
48 import android.app.BroadcastOptions;
49 import android.app.IApplicationThread;
50 import android.app.usage.UsageEvents.Event;
51 import android.content.ComponentName;
52 import android.content.ContentResolver;
53 import android.content.IIntentReceiver;
54 import android.content.Intent;
55 import android.content.pm.ActivityInfo;
56 import android.content.pm.ApplicationInfo;
57 import android.content.pm.PackageManager;
58 import android.content.pm.ResolveInfo;
59 import android.content.pm.UserInfo;
60 import android.os.Bundle;
61 import android.os.Handler;
62 import android.os.Looper;
63 import android.os.Message;
64 import android.os.PowerExemptionManager.ReasonCode;
65 import android.os.PowerExemptionManager.TempAllowListType;
66 import android.os.Process;
67 import android.os.RemoteException;
68 import android.os.SystemClock;
69 import android.os.Trace;
70 import android.os.UserHandle;
71 import android.text.TextUtils;
72 import android.util.EventLog;
73 import android.util.IndentingPrintWriter;
74 import android.util.Slog;
75 import android.util.SparseIntArray;
76 import android.util.proto.ProtoOutputStream;
77 
78 import com.android.internal.os.TimeoutRecord;
79 import com.android.internal.util.FrameworkStatsLog;
80 import com.android.server.LocalServices;
81 import com.android.server.pm.UserJourneyLogger;
82 import com.android.server.pm.UserManagerInternal;
83 
84 import dalvik.annotation.optimization.NeverCompile;
85 
86 import java.io.FileDescriptor;
87 import java.io.PrintWriter;
88 import java.text.SimpleDateFormat;
89 import java.util.ArrayList;
90 import java.util.Set;
91 import java.util.function.BooleanSupplier;
92 
93 /**
94  * BROADCASTS
95  *
96  * We keep three broadcast queues and associated bookkeeping, one for those at
97  * foreground priority, and one for normal (background-priority) broadcasts, and one to
98  * offload special broadcasts that we know take a long time, such as BOOT_COMPLETED.
99  */
100 public class BroadcastQueueImpl extends BroadcastQueue {
101     private static final String TAG_MU = TAG + POSTFIX_MU;
102     private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
103 
104     final BroadcastConstants mConstants;
105 
106     /**
107      * If true, we can delay broadcasts while waiting services to finish in the previous
108      * receiver's process.
109      */
110     final boolean mDelayBehindServices;
111 
112     final int mSchedGroup;
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      * Set when we current have a BROADCAST_INTENT_MSG in flight.
139      */
140     boolean mBroadcastsScheduled = false;
141 
142     /**
143      * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
144      */
145     boolean mPendingBroadcastTimeoutMessage;
146 
147     /**
148      * Intent broadcasts that we have tried to start, but are
149      * waiting for the application's process to be created.  We only
150      * need one per scheduling class (instead of a list) because we always
151      * process broadcasts one at a time, so no others can be started while
152      * waiting for this one.
153      */
154     BroadcastRecord mPendingBroadcast = null;
155 
156     /**
157      * The receiver index that is pending, to restart the broadcast if needed.
158      */
159     int mPendingBroadcastRecvIndex;
160 
161     static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
162     static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
163 
164     // log latency metrics for ordered broadcasts during BOOT_COMPLETED processing
165     boolean mLogLatencyMetrics = true;
166 
167     final BroadcastHandler mHandler;
168 
169     private final class BroadcastHandler extends Handler {
BroadcastHandler(Looper looper)170         public BroadcastHandler(Looper looper) {
171             super(looper, null);
172         }
173 
174         @Override
handleMessage(Message msg)175         public void handleMessage(Message msg) {
176             switch (msg.what) {
177                 case BROADCAST_INTENT_MSG: {
178                     if (DEBUG_BROADCAST) Slog.v(
179                             TAG_BROADCAST, "Received BROADCAST_INTENT_MSG ["
180                             + mQueueName + "]");
181                     processNextBroadcast(true);
182                 } break;
183                 case BROADCAST_TIMEOUT_MSG: {
184                     synchronized (mService) {
185                         broadcastTimeoutLocked(true);
186                     }
187                 } break;
188             }
189         }
190     }
191 
BroadcastQueueImpl(ActivityManagerService service, Handler handler, String name, BroadcastConstants constants, boolean allowDelayBehindServices, int schedGroup)192     BroadcastQueueImpl(ActivityManagerService service, Handler handler,
193             String name, BroadcastConstants constants, boolean allowDelayBehindServices,
194             int schedGroup) {
195         this(service, handler, name, constants, new BroadcastSkipPolicy(service),
196                 new BroadcastHistory(constants), allowDelayBehindServices, schedGroup);
197     }
198 
BroadcastQueueImpl(ActivityManagerService service, Handler handler, String name, BroadcastConstants constants, BroadcastSkipPolicy skipPolicy, BroadcastHistory history, boolean allowDelayBehindServices, int schedGroup)199     BroadcastQueueImpl(ActivityManagerService service, Handler handler,
200             String name, BroadcastConstants constants, BroadcastSkipPolicy skipPolicy,
201             BroadcastHistory history, boolean allowDelayBehindServices, int schedGroup) {
202         super(service, handler, name, skipPolicy, history);
203         mHandler = new BroadcastHandler(handler.getLooper());
204         mConstants = constants;
205         mDelayBehindServices = allowDelayBehindServices;
206         mSchedGroup = schedGroup;
207         mDispatcher = new BroadcastDispatcher(this, mConstants, mHandler, mService);
208     }
209 
start(ContentResolver resolver)210     public void start(ContentResolver resolver) {
211         mDispatcher.start();
212         mConstants.startObserving(mHandler, resolver);
213     }
214 
isDelayBehindServices()215     public boolean isDelayBehindServices() {
216         return mDelayBehindServices;
217     }
218 
getPendingBroadcastLocked()219     public BroadcastRecord getPendingBroadcastLocked() {
220         return mPendingBroadcast;
221     }
222 
getActiveBroadcastLocked()223     public BroadcastRecord getActiveBroadcastLocked() {
224         return mDispatcher.getActiveBroadcastLocked();
225     }
226 
getPreferredSchedulingGroupLocked(ProcessRecord app)227     public int getPreferredSchedulingGroupLocked(ProcessRecord app) {
228         final BroadcastRecord active = getActiveBroadcastLocked();
229         if (active != null && active.curApp == app) {
230             return mSchedGroup;
231         }
232         final BroadcastRecord pending = getPendingBroadcastLocked();
233         if (pending != null && pending.curApp == app) {
234             return mSchedGroup;
235         }
236         return ProcessList.SCHED_GROUP_UNDEFINED;
237     }
238 
enqueueBroadcastLocked(BroadcastRecord r)239     public void enqueueBroadcastLocked(BroadcastRecord r) {
240         r.applySingletonPolicy(mService);
241 
242         final boolean replacePending = (r.intent.getFlags()
243                 & Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
244 
245         // Ordered broadcasts obviously need to be dispatched in serial order,
246         // but this implementation expects all manifest receivers to also be
247         // dispatched in a serial fashion
248         boolean serialDispatch = r.ordered;
249         if (!serialDispatch) {
250             final int N = (r.receivers != null) ? r.receivers.size() : 0;
251             for (int i = 0; i < N; i++) {
252                 if (r.receivers.get(i) instanceof ResolveInfo) {
253                     serialDispatch = true;
254                     break;
255                 }
256             }
257         }
258 
259         if (serialDispatch) {
260             final BroadcastRecord oldRecord =
261                     replacePending ? replaceOrderedBroadcastLocked(r) : null;
262             if (oldRecord != null) {
263                 // Replaced, fire the result-to receiver.
264                 if (oldRecord.resultTo != null) {
265                     try {
266                         oldRecord.mIsReceiverAppRunning = true;
267                         performReceiveLocked(oldRecord, oldRecord.resultToApp, oldRecord.resultTo,
268                                 oldRecord.intent,
269                                 Activity.RESULT_CANCELED, null, null,
270                                 false, false, oldRecord.shareIdentity, oldRecord.userId,
271                                 oldRecord.callingUid, r.callingUid, r.callerPackage,
272                                 SystemClock.uptimeMillis() - oldRecord.enqueueTime, 0, 0,
273                                 oldRecord.resultToApp != null
274                                         ? oldRecord.resultToApp.mState.getCurProcState()
275                                         : ActivityManager.PROCESS_STATE_UNKNOWN);
276                     } catch (RemoteException e) {
277                         Slog.w(TAG, "Failure ["
278                                 + mQueueName + "] sending broadcast result of "
279                                 + oldRecord.intent, e);
280 
281                     }
282                 }
283             } else {
284                 enqueueOrderedBroadcastLocked(r);
285                 scheduleBroadcastsLocked();
286             }
287         } else {
288             final boolean replaced = replacePending
289                     && (replaceParallelBroadcastLocked(r) != null);
290             // Note: We assume resultTo is null for non-ordered broadcasts.
291             if (!replaced) {
292                 enqueueParallelBroadcastLocked(r);
293                 scheduleBroadcastsLocked();
294             }
295         }
296     }
297 
enqueueParallelBroadcastLocked(BroadcastRecord r)298     public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
299         r.enqueueClockTime = System.currentTimeMillis();
300         r.enqueueTime = SystemClock.uptimeMillis();
301         r.enqueueRealTime = SystemClock.elapsedRealtime();
302         mParallelBroadcasts.add(r);
303         enqueueBroadcastHelper(r);
304     }
305 
enqueueOrderedBroadcastLocked(BroadcastRecord r)306     public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
307         r.enqueueClockTime = System.currentTimeMillis();
308         r.enqueueTime = SystemClock.uptimeMillis();
309         r.enqueueRealTime = SystemClock.elapsedRealtime();
310         mDispatcher.enqueueOrderedBroadcastLocked(r);
311         enqueueBroadcastHelper(r);
312     }
313 
314     /**
315      * Don't call this method directly; call enqueueParallelBroadcastLocked or
316      * enqueueOrderedBroadcastLocked.
317      */
enqueueBroadcastHelper(BroadcastRecord r)318     private void enqueueBroadcastHelper(BroadcastRecord r) {
319         if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
320             Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
321                 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
322                 System.identityHashCode(r));
323         }
324     }
325 
326     /**
327      * Find the same intent from queued parallel broadcast, replace with a new one and return
328      * the old one.
329      */
replaceParallelBroadcastLocked(BroadcastRecord r)330     public final BroadcastRecord replaceParallelBroadcastLocked(BroadcastRecord r) {
331         return replaceBroadcastLocked(mParallelBroadcasts, r, "PARALLEL");
332     }
333 
334     /**
335      * Find the same intent from queued ordered broadcast, replace with a new one and return
336      * the old one.
337      */
replaceOrderedBroadcastLocked(BroadcastRecord r)338     public final BroadcastRecord replaceOrderedBroadcastLocked(BroadcastRecord r) {
339         return mDispatcher.replaceBroadcastLocked(r, "ORDERED");
340     }
341 
replaceBroadcastLocked(ArrayList<BroadcastRecord> queue, BroadcastRecord r, String typeForLogging)342     private BroadcastRecord replaceBroadcastLocked(ArrayList<BroadcastRecord> queue,
343             BroadcastRecord r, String typeForLogging) {
344         final Intent intent = r.intent;
345         for (int i = queue.size() - 1; i >= 0; i--) {
346             final BroadcastRecord old = queue.get(i);
347             if (old.userId == r.userId && intent.filterEquals(old.intent)) {
348                 if (DEBUG_BROADCAST) {
349                     Slog.v(TAG_BROADCAST, "***** DROPPING "
350                             + typeForLogging + " [" + mQueueName + "]: " + intent);
351                 }
352                 queue.set(i, r);
353                 return old;
354             }
355         }
356         return null;
357     }
358 
processCurBroadcastLocked(BroadcastRecord r, ProcessRecord app)359     private final void processCurBroadcastLocked(BroadcastRecord r,
360             ProcessRecord app) throws RemoteException {
361         if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
362                 "Process cur broadcast " + r + " for app " + app);
363         final IApplicationThread thread = app.getThread();
364         if (thread == null) {
365             throw new RemoteException();
366         }
367         if (app.isInFullBackup()) {
368             skipReceiverLocked(r);
369             return;
370         }
371 
372         r.curApp = app;
373         r.curAppLastProcessState = app.mState.getCurProcState();
374         final ProcessReceiverRecord prr = app.mReceivers;
375         prr.addCurReceiver(r);
376         app.mState.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
377         // Don't bump its LRU position if it's in the background restricted.
378         if (mService.mInternal.getRestrictionLevel(app.info.packageName, app.userId)
379                 < RESTRICTION_LEVEL_RESTRICTED_BUCKET) {
380             mService.updateLruProcessLocked(app, false, null);
381         }
382         // Make sure the oom adj score is updated before delivering the broadcast.
383         // Force an update, even if there are other pending requests, overall it still saves time,
384         // because time(updateOomAdj(N apps)) <= N * time(updateOomAdj(1 app)).
385         mService.enqueueOomAdjTargetLocked(app);
386         mService.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_START_RECEIVER);
387 
388         // Tell the application to launch this receiver.
389         maybeReportBroadcastDispatchedEventLocked(r, r.curReceiver.applicationInfo.uid);
390         r.intent.setComponent(r.curComponent);
391 
392         // See if we need to delay the freezer based on BroadcastOptions
393         if (r.options != null
394                 && r.options.getTemporaryAppAllowlistDuration() > 0
395                 && r.options.getTemporaryAppAllowlistType()
396                     == TEMPORARY_ALLOW_LIST_TYPE_APP_FREEZING_DELAYED) {
397             mService.mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily(app,
398                     CachedAppOptimizer.UNFREEZE_REASON_START_RECEIVER,
399                     r.options.getTemporaryAppAllowlistDuration());
400         }
401 
402         boolean started = false;
403         try {
404             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
405                     "Delivering to component " + r.curComponent
406                     + ": " + r);
407             mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
408                                       PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER);
409             final boolean assumeDelivered = false;
410             thread.scheduleReceiver(
411                     prepareReceiverIntent(r.intent, r.curFilteredExtras),
412                     r.curReceiver, null /* compatInfo (unused but need to keep method signature) */,
413                     r.resultCode, r.resultData, r.resultExtras, r.ordered, assumeDelivered,
414                     r.userId, r.shareIdentity ? r.callingUid : Process.INVALID_UID,
415                     app.mState.getReportedProcState(),
416                     r.shareIdentity ? r.callerPackage : null);
417             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
418                     "Process cur broadcast " + r + " DELIVERED for app " + app);
419             started = true;
420         } finally {
421             if (!started) {
422                 if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
423                         "Process cur broadcast " + r + ": NOT STARTED!");
424                 r.curApp = null;
425                 r.curAppLastProcessState = ActivityManager.PROCESS_STATE_UNKNOWN;
426                 prr.removeCurReceiver(r);
427             }
428         }
429 
430         // if something bad happens here, launch the app and try again
431         if (app.isKilled()) {
432             throw new RemoteException("app gets killed during broadcasting");
433         }
434     }
435 
436     /**
437      * Called by ActivityManagerService to notify that the uid has process started, if there is any
438      * deferred BOOT_COMPLETED broadcast, the BroadcastDispatcher can dispatch the broadcast now.
439      * @param uid
440      */
updateUidReadyForBootCompletedBroadcastLocked(int uid)441     public void updateUidReadyForBootCompletedBroadcastLocked(int uid) {
442         mDispatcher.updateUidReadyForBootCompletedBroadcastLocked(uid);
443         scheduleBroadcastsLocked();
444     }
445 
onApplicationAttachedLocked(ProcessRecord app)446     public boolean onApplicationAttachedLocked(ProcessRecord app)
447             throws BroadcastDeliveryFailedException {
448         updateUidReadyForBootCompletedBroadcastLocked(app.uid);
449 
450         if (mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
451             return sendPendingBroadcastsLocked(app);
452         } else {
453             return false;
454         }
455     }
456 
onApplicationTimeoutLocked(ProcessRecord app)457     public void onApplicationTimeoutLocked(ProcessRecord app) {
458         skipCurrentOrPendingReceiverLocked(app);
459     }
460 
onApplicationProblemLocked(ProcessRecord app)461     public void onApplicationProblemLocked(ProcessRecord app) {
462         skipCurrentOrPendingReceiverLocked(app);
463     }
464 
onApplicationCleanupLocked(ProcessRecord app)465     public void onApplicationCleanupLocked(ProcessRecord app) {
466         skipCurrentOrPendingReceiverLocked(app);
467     }
468 
onProcessFreezableChangedLocked(ProcessRecord app)469     public void onProcessFreezableChangedLocked(ProcessRecord app) {
470         // Not supported; ignore
471     }
472 
sendPendingBroadcastsLocked(ProcessRecord app)473     public boolean sendPendingBroadcastsLocked(ProcessRecord app)
474             throws BroadcastDeliveryFailedException {
475         boolean didSomething = false;
476         final BroadcastRecord br = mPendingBroadcast;
477         if (br != null && br.curApp.getPid() > 0 && br.curApp.getPid() == app.getPid()) {
478             if (br.curApp != app) {
479                 Slog.e(TAG, "App mismatch when sending pending broadcast to "
480                         + app.processName + ", intended target is " + br.curApp.processName);
481                 return false;
482             }
483             try {
484                 mPendingBroadcast = null;
485                 br.mIsReceiverAppRunning = false;
486                 processCurBroadcastLocked(br, app);
487                 didSomething = true;
488             } catch (Exception e) {
489                 Slog.w(TAG, "Exception in new application when starting receiver "
490                         + br.curComponent.flattenToShortString(), e);
491                 logBroadcastReceiverDiscardLocked(br);
492                 finishReceiverLocked(br, br.resultCode, br.resultData,
493                         br.resultExtras, br.resultAbort, false);
494                 scheduleBroadcastsLocked();
495                 // We need to reset the state if we failed to start the receiver.
496                 br.state = BroadcastRecord.IDLE;
497                 throw new BroadcastDeliveryFailedException(e);
498             }
499         }
500         return didSomething;
501     }
502 
503     // Skip the current receiver, if any, that is in flight to the given process
skipCurrentOrPendingReceiverLocked(ProcessRecord app)504     public boolean skipCurrentOrPendingReceiverLocked(ProcessRecord app) {
505         BroadcastRecord r = null;
506         final BroadcastRecord curActive = mDispatcher.getActiveBroadcastLocked();
507         if (curActive != null && curActive.curApp == app) {
508             // confirmed: the current active broadcast is to the given app
509             r = curActive;
510         }
511 
512         // If the current active broadcast isn't this BUT we're waiting for
513         // mPendingBroadcast to spin up the target app, that's what we use.
514         if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
515             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
516                     "[" + mQueueName + "] skip & discard pending app " + r);
517             r = mPendingBroadcast;
518         }
519 
520         if (r != null) {
521             skipReceiverLocked(r);
522             return true;
523         } else {
524             return false;
525         }
526     }
527 
skipReceiverLocked(BroadcastRecord r)528     private void skipReceiverLocked(BroadcastRecord r) {
529         logBroadcastReceiverDiscardLocked(r);
530         finishReceiverLocked(r, r.resultCode, r.resultData,
531                 r.resultExtras, r.resultAbort, false);
532         scheduleBroadcastsLocked();
533     }
534 
scheduleBroadcastsLocked()535     public void scheduleBroadcastsLocked() {
536         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
537                 + mQueueName + "]: current="
538                 + mBroadcastsScheduled);
539 
540         if (mBroadcastsScheduled) {
541             return;
542         }
543         mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
544         mBroadcastsScheduled = true;
545     }
546 
getMatchingOrderedReceiver(ProcessRecord app)547     public BroadcastRecord getMatchingOrderedReceiver(ProcessRecord app) {
548         BroadcastRecord br = mDispatcher.getActiveBroadcastLocked();
549         if (br == null) {
550             Slog.w(TAG_BROADCAST, "getMatchingOrderedReceiver [" + mQueueName
551                     + "] no active broadcast");
552             return null;
553         }
554         if (br.curApp != app) {
555             Slog.w(TAG_BROADCAST, "getMatchingOrderedReceiver [" + mQueueName
556                     + "] active broadcast " + br.curApp + " doesn't match " + app);
557             return null;
558         }
559         return br;
560     }
561 
562     // > 0 only, no worry about "eventual" recycling
nextSplitTokenLocked()563     private int nextSplitTokenLocked() {
564         int next = mNextToken + 1;
565         if (next <= 0) {
566             next = 1;
567         }
568         mNextToken = next;
569         return next;
570     }
571 
postActivityStartTokenRemoval(ProcessRecord app, BroadcastRecord r)572     private void postActivityStartTokenRemoval(ProcessRecord app, BroadcastRecord r) {
573         // the receiver had run for less than allowed bg activity start timeout,
574         // so allow the process to still start activities from bg for some more time
575         String msgToken = (app.toShortString() + r.toString()).intern();
576         // first, if there exists a past scheduled request to remove this token, drop
577         // that request - we don't want the token to be swept from under our feet...
578         mHandler.removeCallbacksAndMessages(msgToken);
579         // ...then schedule the removal of the token after the extended timeout
580         mHandler.postAtTime(() -> {
581             synchronized (mService) {
582                 app.removeBackgroundStartPrivileges(r);
583             }
584         }, msgToken, (r.receiverTime + mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT));
585     }
586 
finishReceiverLocked(ProcessRecord app, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices)587     public boolean finishReceiverLocked(ProcessRecord app, int resultCode,
588             String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
589         final BroadcastRecord r = getMatchingOrderedReceiver(app);
590         if (r != null) {
591             return finishReceiverLocked(r, resultCode,
592                     resultData, resultExtras, resultAbort, waitForServices);
593         } else {
594             return false;
595         }
596     }
597 
finishReceiverLocked(BroadcastRecord r, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices)598     public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
599             String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
600         final int state = r.state;
601         final ActivityInfo receiver = r.curReceiver;
602         final long finishTime = SystemClock.uptimeMillis();
603         final long elapsed = finishTime - r.receiverTime;
604         r.state = BroadcastRecord.IDLE;
605         final int curIndex = r.nextReceiver - 1;
606 
607         final int packageState = r.mWasReceiverAppStopped
608                 ? SERVICE_REQUEST_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_STOPPED
609                 : SERVICE_REQUEST_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_NORMAL;
610 
611         if (curIndex >= 0 && curIndex < r.receivers.size() && r.curApp != null) {
612             final Object curReceiver = r.receivers.get(curIndex);
613             FrameworkStatsLog.write(BROADCAST_DELIVERY_EVENT_REPORTED, r.curApp.uid,
614                     r.callingUid == -1 ? Process.SYSTEM_UID : r.callingUid,
615                     r.intent.getAction(),
616                     curReceiver instanceof BroadcastFilter
617                     ? BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME
618                     : BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__MANIFEST,
619                     r.mIsReceiverAppRunning
620                     ? BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM
621                     : BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD,
622                     r.dispatchTime - r.enqueueTime,
623                     r.receiverTime - r.dispatchTime,
624                     finishTime - r.receiverTime,
625                     packageState,
626                     r.curApp.info.packageName,
627                     r.callerPackage,
628                     r.calculateTypeForLogging(),
629                     r.getDeliveryGroupPolicy(),
630                     r.intent.getFlags(),
631                     BroadcastRecord.getReceiverPriority(curReceiver),
632                     r.callerProcState,
633                     r.curAppLastProcessState);
634         }
635         if (state == BroadcastRecord.IDLE) {
636             Slog.w(TAG_BROADCAST, "finishReceiver [" + mQueueName + "] called but state is IDLE");
637         }
638         if (r.mBackgroundStartPrivileges.allowsAny() && r.curApp != null) {
639             if (elapsed > mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT) {
640                 // if the receiver has run for more than allowed bg activity start timeout,
641                 // just remove the token for this process now and we're done
642                 r.curApp.removeBackgroundStartPrivileges(r);
643             } else {
644                 // It gets more time; post the removal to happen at the appropriate moment
645                 postActivityStartTokenRemoval(r.curApp, r);
646             }
647         }
648         // If we're abandoning this broadcast before any receivers were actually spun up,
649         // nextReceiver is zero; in which case time-to-process bookkeeping doesn't apply.
650         if (r.nextReceiver > 0) {
651             r.terminalTime[r.nextReceiver - 1] = finishTime;
652         }
653 
654         // if this receiver was slow, impose deferral policy on the app.  This will kick in
655         // when processNextBroadcastLocked() next finds this uid as a receiver identity.
656         if (!r.timeoutExempt) {
657             // r.curApp can be null if finish has raced with process death - benign
658             // edge case, and we just ignore it because we're already cleaning up
659             // as expected.
660             if (r.curApp != null
661                     && mConstants.SLOW_TIME > 0 && elapsed > mConstants.SLOW_TIME) {
662                 // Core system packages are exempt from deferral policy
663                 if (!UserHandle.isCore(r.curApp.uid)) {
664                     if (DEBUG_BROADCAST_DEFERRAL) {
665                         Slog.i(TAG_BROADCAST, "Broadcast receiver " + (r.nextReceiver - 1)
666                                 + " was slow: " + receiver + " br=" + r);
667                     }
668                     mDispatcher.startDeferring(r.curApp.uid);
669                 } else {
670                     if (DEBUG_BROADCAST_DEFERRAL) {
671                         Slog.i(TAG_BROADCAST, "Core uid " + r.curApp.uid
672                                 + " receiver was slow but not deferring: "
673                                 + receiver + " br=" + r);
674                     }
675                 }
676             }
677         } else {
678             if (DEBUG_BROADCAST_DEFERRAL) {
679                 Slog.i(TAG_BROADCAST, "Finished broadcast " + r.intent.getAction()
680                         + " is exempt from deferral policy");
681             }
682         }
683 
684         r.intent.setComponent(null);
685         if (r.curApp != null && r.curApp.mReceivers.hasCurReceiver(r)) {
686             r.curApp.mReceivers.removeCurReceiver(r);
687             mService.enqueueOomAdjTargetLocked(r.curApp);
688         }
689         if (r.curFilter != null) {
690             r.curFilter.receiverList.curBroadcast = null;
691         }
692         r.curFilter = null;
693         r.curReceiver = null;
694         r.curApp = null;
695         r.curAppLastProcessState = ActivityManager.PROCESS_STATE_UNKNOWN;
696         r.curFilteredExtras = null;
697         r.mWasReceiverAppStopped = false;
698         mPendingBroadcast = null;
699 
700         r.resultCode = resultCode;
701         r.resultData = resultData;
702         r.resultExtras = resultExtras;
703         if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
704             r.resultAbort = resultAbort;
705         } else {
706             r.resultAbort = false;
707         }
708 
709         // If we want to wait behind services *AND* we're finishing the head/
710         // active broadcast on its queue
711         if (waitForServices && r.curComponent != null && r.queue.isDelayBehindServices()
712                 && ((BroadcastQueueImpl) r.queue).getActiveBroadcastLocked() == r) {
713             ActivityInfo nextReceiver;
714             if (r.nextReceiver < r.receivers.size()) {
715                 Object obj = r.receivers.get(r.nextReceiver);
716                 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
717             } else {
718                 nextReceiver = null;
719             }
720             // Don't do this if the next receive is in the same process as the current one.
721             if (receiver == null || nextReceiver == null
722                     || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
723                     || !receiver.processName.equals(nextReceiver.processName)) {
724                 // In this case, we are ready to process the next receiver for the current broadcast,
725                 // but are on a queue that would like to wait for services to finish before moving
726                 // on.  If there are background services currently starting, then we will go into a
727                 // special state where we hold off on continuing this broadcast until they are done.
728                 if (mService.mServices.hasBackgroundServicesLocked(r.userId)) {
729                     Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
730                     r.state = BroadcastRecord.WAITING_SERVICES;
731                     return false;
732                 }
733             }
734         }
735 
736         r.curComponent = null;
737 
738         // We will process the next receiver right now if this is finishing
739         // an app receiver (which is always asynchronous) or after we have
740         // come back from calling a receiver.
741         final boolean doNext = (state == BroadcastRecord.APP_RECEIVE)
742                 || (state == BroadcastRecord.CALL_DONE_RECEIVE);
743         if (doNext) {
744             processNextBroadcastLocked(/* fromMsg= */ false, /* skipOomAdj= */ true);
745         }
746         return doNext;
747     }
748 
backgroundServicesFinishedLocked(int userId)749     public void backgroundServicesFinishedLocked(int userId) {
750         BroadcastRecord br = mDispatcher.getActiveBroadcastLocked();
751         if (br != null) {
752             if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
753                 Slog.i(TAG, "Resuming delayed broadcast");
754                 br.curComponent = null;
755                 br.state = BroadcastRecord.IDLE;
756                 processNextBroadcastLocked(false, false);
757             }
758         }
759     }
760 
performReceiveLocked(BroadcastRecord r, ProcessRecord app, IIntentReceiver receiver, Intent intent, int resultCode, String data, Bundle extras, boolean ordered, boolean sticky, boolean shareIdentity, int sendingUser, int receiverUid, int callingUid, String callingPackage, long dispatchDelay, long receiveDelay, int priority, int receiverProcessState)761     public void performReceiveLocked(BroadcastRecord r, ProcessRecord app, IIntentReceiver receiver,
762             Intent intent, int resultCode, String data, Bundle extras,
763             boolean ordered, boolean sticky, boolean shareIdentity, int sendingUser,
764             int receiverUid, int callingUid, String callingPackage,
765             long dispatchDelay, long receiveDelay, int priority,
766             int receiverProcessState) throws RemoteException {
767         // If the broadcaster opted-in to sharing their identity, then expose package visibility for
768         // the receiver.
769         if (shareIdentity) {
770             mService.mPackageManagerInt.grantImplicitAccess(sendingUser, intent,
771                     UserHandle.getAppId(receiverUid), callingUid, true);
772         }
773         // Send the intent to the receiver asynchronously using one-way binder calls.
774         if (app != null) {
775             final IApplicationThread thread = app.getThread();
776             if (thread != null) {
777                 // If we have an app thread, do the call through that so it is
778                 // correctly ordered with other one-way calls.
779                 try {
780                     final boolean assumeDelivered = !ordered;
781                     thread.scheduleRegisteredReceiver(
782                             receiver, intent, resultCode,
783                             data, extras, ordered, sticky, assumeDelivered, sendingUser,
784                             app.mState.getReportedProcState(),
785                             shareIdentity ? callingUid : Process.INVALID_UID,
786                             shareIdentity ? callingPackage : null);
787                 } catch (RemoteException ex) {
788                     // Failed to call into the process. It's either dying or wedged. Kill it gently.
789                     synchronized (mService) {
790                         final String msg = "Failed to schedule " + intent + " to " + receiver
791                                 + " via " + app + ": " + ex;
792                         Slog.w(TAG, msg);
793                         app.killLocked("Can't deliver broadcast", ApplicationExitInfo.REASON_OTHER,
794                                 ApplicationExitInfo.SUBREASON_UNDELIVERED_BROADCAST, true);
795                     }
796                     throw ex;
797                 }
798             } else {
799                 // Application has died. Receiver doesn't exist.
800                 throw new RemoteException("app.thread must not be null");
801             }
802         } else {
803             receiver.performReceive(intent, resultCode, data, extras, ordered,
804                     sticky, sendingUser);
805         }
806         if (!ordered) {
807             FrameworkStatsLog.write(BROADCAST_DELIVERY_EVENT_REPORTED,
808                     receiverUid == -1 ? Process.SYSTEM_UID : receiverUid,
809                     callingUid == -1 ? Process.SYSTEM_UID : callingUid,
810                     intent.getAction(),
811                     BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME,
812                     BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM,
813                     dispatchDelay, receiveDelay, 0 /* finish_delay */,
814                     SERVICE_REQUEST_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_NORMAL,
815                     app != null ? app.info.packageName : null, callingPackage,
816                     r.calculateTypeForLogging(), r.getDeliveryGroupPolicy(), r.intent.getFlags(),
817                     priority, r.callerProcState, receiverProcessState);
818         }
819     }
820 
deliverToRegisteredReceiverLocked(BroadcastRecord r, BroadcastFilter filter, boolean ordered, int index)821     private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
822             BroadcastFilter filter, boolean ordered, int index) {
823         boolean skip = mSkipPolicy.shouldSkip(r, filter);
824 
825         // Filter packages in the intent extras, skipping delivery if none of the packages is
826         // visible to the receiver.
827         Bundle filteredExtras = null;
828         if (!skip && r.filterExtrasForReceiver != null) {
829             final Bundle extras = r.intent.getExtras();
830             if (extras != null) {
831                 filteredExtras = r.filterExtrasForReceiver.apply(filter.receiverList.uid, extras);
832                 if (filteredExtras == null) {
833                     if (DEBUG_BROADCAST) {
834                         Slog.v(TAG, "Skipping delivery to "
835                                 + filter.receiverList.app
836                                 + " : receiver is filtered by the package visibility");
837                     }
838                     skip = true;
839                 }
840             }
841         }
842 
843         if (skip) {
844             r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
845             return;
846         }
847 
848         r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
849 
850         // If this is not being sent as an ordered broadcast, then we
851         // don't want to touch the fields that keep track of the current
852         // state of ordered broadcasts.
853         if (ordered) {
854             r.curFilter = filter;
855             filter.receiverList.curBroadcast = r;
856             r.state = BroadcastRecord.CALL_IN_RECEIVE;
857             if (filter.receiverList.app != null) {
858                 // Bump hosting application to no longer be in background
859                 // scheduling class.  Note that we can't do that if there
860                 // isn't an app...  but we can only be in that case for
861                 // things that directly call the IActivityManager API, which
862                 // are already core system stuff so don't matter for this.
863                 r.curApp = filter.receiverList.app;
864                 r.curAppLastProcessState = r.curApp.mState.getCurProcState();
865                 filter.receiverList.app.mReceivers.addCurReceiver(r);
866                 mService.enqueueOomAdjTargetLocked(r.curApp);
867                 mService.updateOomAdjPendingTargetsLocked(
868                         OOM_ADJ_REASON_START_RECEIVER);
869             }
870         } else if (filter.receiverList.app != null) {
871             mService.mOomAdjuster.unfreezeTemporarily(filter.receiverList.app,
872                     CachedAppOptimizer.UNFREEZE_REASON_START_RECEIVER);
873         }
874 
875         try {
876             if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
877                     "Delivering to " + filter + " : " + r);
878             final boolean isInFullBackup = (filter.receiverList.app != null)
879                     && filter.receiverList.app.isInFullBackup();
880             final boolean isKilled = (filter.receiverList.app != null)
881                     && filter.receiverList.app.isKilled();
882             if (isInFullBackup || isKilled) {
883                 // Skip delivery if full backup in progress
884                 // If it's an ordered broadcast, we need to continue to the next receiver.
885                 if (ordered) {
886                     skipReceiverLocked(r);
887                 }
888             } else {
889                 r.receiverTime = SystemClock.uptimeMillis();
890                 r.scheduledTime[index] = r.receiverTime;
891                 maybeAddBackgroundStartPrivileges(filter.receiverList.app, r);
892                 maybeScheduleTempAllowlistLocked(filter.owningUid, r, r.options);
893                 maybeReportBroadcastDispatchedEventLocked(r, filter.owningUid);
894                 performReceiveLocked(r, filter.receiverList.app, filter.receiverList.receiver,
895                         prepareReceiverIntent(r.intent, filteredExtras), r.resultCode, r.resultData,
896                         r.resultExtras, r.ordered, r.initialSticky, r.shareIdentity, r.userId,
897                         filter.receiverList.uid, r.callingUid, r.callerPackage,
898                         r.dispatchTime - r.enqueueTime,
899                         r.receiverTime - r.dispatchTime, filter.getPriority(),
900                         filter.receiverList.app != null
901                                 ? filter.receiverList.app.mState.getCurProcState()
902                                 : ActivityManager.PROCESS_STATE_UNKNOWN);
903                 // parallel broadcasts are fire-and-forget, not bookended by a call to
904                 // finishReceiverLocked(), so we manage their activity-start token here
905                 if (filter.receiverList.app != null
906                         && r.mBackgroundStartPrivileges.allowsAny()
907                         && !r.ordered) {
908                     postActivityStartTokenRemoval(filter.receiverList.app, r);
909                 }
910             }
911             if (ordered) {
912                 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
913             }
914         } catch (RemoteException e) {
915             Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
916             // Clean up ProcessRecord state related to this broadcast attempt
917             if (filter.receiverList.app != null) {
918                 filter.receiverList.app.removeBackgroundStartPrivileges(r);
919                 if (ordered) {
920                     filter.receiverList.app.mReceivers.removeCurReceiver(r);
921                     // Something wrong, its oom adj could be downgraded, but not in a hurry.
922                     mService.enqueueOomAdjTargetLocked(r.curApp);
923                 }
924             }
925             // And BroadcastRecord state related to ordered delivery, if appropriate
926             if (ordered) {
927                 r.curFilter = null;
928                 filter.receiverList.curBroadcast = null;
929             }
930         }
931     }
932 
maybeScheduleTempAllowlistLocked(int uid, BroadcastRecord r, @Nullable BroadcastOptions brOptions)933     void maybeScheduleTempAllowlistLocked(int uid, BroadcastRecord r,
934             @Nullable BroadcastOptions brOptions) {
935         if (brOptions == null || brOptions.getTemporaryAppAllowlistDuration() <= 0) {
936             return;
937         }
938         long duration = brOptions.getTemporaryAppAllowlistDuration();
939         final @TempAllowListType int type = brOptions.getTemporaryAppAllowlistType();
940         final @ReasonCode int reasonCode = brOptions.getTemporaryAppAllowlistReasonCode();
941         final String reason = brOptions.getTemporaryAppAllowlistReason();
942 
943         if (duration > Integer.MAX_VALUE) {
944             duration = Integer.MAX_VALUE;
945         }
946         // XXX ideally we should pause the broadcast until everything behind this is done,
947         // or else we will likely start dispatching the broadcast before we have opened
948         // access to the app (there is a lot of asynchronicity behind this).  It is probably
949         // not that big a deal, however, because the main purpose here is to allow apps
950         // to hold wake locks, and they will be able to acquire their wake lock immediately
951         // it just won't be enabled until we get through this work.
952         StringBuilder b = new StringBuilder();
953         b.append("broadcast:");
954         UserHandle.formatUid(b, r.callingUid);
955         b.append(":");
956         if (r.intent.getAction() != null) {
957             b.append(r.intent.getAction());
958         } else if (r.intent.getComponent() != null) {
959             r.intent.getComponent().appendShortString(b);
960         } else if (r.intent.getData() != null) {
961             b.append(r.intent.getData());
962         }
963         b.append(",reason:");
964         b.append(reason);
965         if (DEBUG_BROADCAST) {
966             Slog.v(TAG, "Broadcast temp allowlist uid=" + uid + " duration=" + duration
967                     + " type=" + type + " : " + b.toString());
968         }
969 
970         // Only add to temp allowlist if it's not the APP_FREEZING_DELAYED type. That will be
971         // handled when the broadcast is actually being scheduled on the app thread.
972         if (type != TEMPORARY_ALLOW_LIST_TYPE_APP_FREEZING_DELAYED) {
973             mService.tempAllowlistUidLocked(uid, duration, reasonCode, b.toString(), type,
974                     r.callingUid);
975         }
976     }
977 
processNextBroadcast(boolean fromMsg)978     private void processNextBroadcast(boolean fromMsg) {
979         synchronized (mService) {
980             processNextBroadcastLocked(fromMsg, false);
981         }
982     }
983 
prepareReceiverIntent(@onNull Intent originalIntent, @Nullable Bundle filteredExtras)984     private static Intent prepareReceiverIntent(@NonNull Intent originalIntent,
985             @Nullable Bundle filteredExtras) {
986         final Intent intent = new Intent(originalIntent);
987         if (filteredExtras != null) {
988             intent.replaceExtras(filteredExtras);
989         }
990         return intent;
991     }
992 
processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj)993     public void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj) {
994         BroadcastRecord r;
995 
996         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
997                 + mQueueName + "]: "
998                 + mParallelBroadcasts.size() + " parallel broadcasts; "
999                 + mDispatcher.describeStateLocked());
1000 
1001         mService.updateCpuStats();
1002 
1003         if (fromMsg) {
1004             mBroadcastsScheduled = false;
1005         }
1006 
1007         // First, deliver any non-serialized broadcasts right away.
1008         while (mParallelBroadcasts.size() > 0) {
1009             r = mParallelBroadcasts.remove(0);
1010             r.dispatchTime = SystemClock.uptimeMillis();
1011             r.dispatchRealTime = SystemClock.elapsedRealtime();
1012             r.dispatchClockTime = System.currentTimeMillis();
1013             r.mIsReceiverAppRunning = true;
1014 
1015             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1016                 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1017                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
1018                     System.identityHashCode(r));
1019                 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1020                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
1021                     System.identityHashCode(r));
1022             }
1023 
1024             final int N = r.receivers.size();
1025             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
1026                     + mQueueName + "] " + r);
1027             for (int i=0; i<N; i++) {
1028                 Object target = r.receivers.get(i);
1029                 if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1030                         "Delivering non-ordered on [" + mQueueName + "] to registered "
1031                         + target + ": " + r);
1032                 deliverToRegisteredReceiverLocked(r,
1033                         (BroadcastFilter) target, false, i);
1034             }
1035             addBroadcastToHistoryLocked(r);
1036             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
1037                     + mQueueName + "] " + r);
1038         }
1039 
1040         // Now take care of the next serialized one...
1041 
1042         // If we are waiting for a process to come up to handle the next
1043         // broadcast, then do nothing at this point.  Just in case, we
1044         // check that the process we're waiting for still exists.
1045         if (mPendingBroadcast != null) {
1046             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
1047                     "processNextBroadcast [" + mQueueName + "]: waiting for "
1048                     + mPendingBroadcast.curApp);
1049 
1050             boolean isDead;
1051             if (mPendingBroadcast.curApp.getPid() > 0) {
1052                 synchronized (mService.mPidsSelfLocked) {
1053                     ProcessRecord proc = mService.mPidsSelfLocked.get(
1054                             mPendingBroadcast.curApp.getPid());
1055                     isDead = proc == null || proc.mErrorState.isCrashing();
1056                 }
1057             } else {
1058                 final ProcessRecord proc = mService.mProcessList.getProcessNamesLOSP().get(
1059                         mPendingBroadcast.curApp.processName, mPendingBroadcast.curApp.uid);
1060                 isDead = proc == null || !proc.isPendingStart();
1061             }
1062             if (!isDead) {
1063                 // It's still alive, so keep waiting
1064                 return;
1065             } else {
1066                 Slog.w(TAG, "pending app  ["
1067                         + mQueueName + "]" + mPendingBroadcast.curApp
1068                         + " died before responding to broadcast");
1069                 mPendingBroadcast.state = BroadcastRecord.IDLE;
1070                 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
1071                 mPendingBroadcast = null;
1072             }
1073         }
1074 
1075         boolean looped = false;
1076 
1077         do {
1078             final long now = SystemClock.uptimeMillis();
1079             r = mDispatcher.getNextBroadcastLocked(now);
1080 
1081             if (r == null) {
1082                 // No more broadcasts are deliverable right now, so all done!
1083                 mDispatcher.scheduleDeferralCheckLocked(false);
1084                 synchronized (mService.mAppProfiler.mProfilerLock) {
1085                     mService.mAppProfiler.scheduleAppGcsLPf();
1086                 }
1087                 if (looped && !skipOomAdj) {
1088                     // If we had finished the last ordered broadcast, then
1089                     // make sure all processes have correct oom and sched
1090                     // adjustments.
1091                     mService.updateOomAdjPendingTargetsLocked(
1092                             OOM_ADJ_REASON_START_RECEIVER);
1093                 }
1094 
1095                 // when we have no more ordered broadcast on this queue, stop logging
1096                 if (mService.mUserController.mBootCompleted && mLogLatencyMetrics) {
1097                     mLogLatencyMetrics = false;
1098                 }
1099 
1100                 return;
1101             }
1102 
1103             boolean forceReceive = false;
1104 
1105             // Ensure that even if something goes awry with the timeout
1106             // detection, we catch "hung" broadcasts here, discard them,
1107             // and continue to make progress.
1108             //
1109             // This is only done if the system is ready so that early-stage receivers
1110             // don't get executed with timeouts; and of course other timeout-
1111             // exempt broadcasts are ignored.
1112             int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
1113             if (mService.mProcessesReady && !r.timeoutExempt && r.dispatchTime > 0) {
1114                 if ((numReceivers > 0) &&
1115                         (now > r.dispatchTime + (2 * mConstants.TIMEOUT * numReceivers))) {
1116                     Slog.w(TAG, "Hung broadcast ["
1117                             + mQueueName + "] discarded after timeout failure:"
1118                             + " now=" + now
1119                             + " dispatchTime=" + r.dispatchTime
1120                             + " startTime=" + r.receiverTime
1121                             + " intent=" + r.intent
1122                             + " numReceivers=" + numReceivers
1123                             + " nextReceiver=" + r.nextReceiver
1124                             + " state=" + r.state);
1125                     broadcastTimeoutLocked(false); // forcibly finish this broadcast
1126                     forceReceive = true;
1127                     r.state = BroadcastRecord.IDLE;
1128                 }
1129             }
1130 
1131             if (r.state != BroadcastRecord.IDLE) {
1132                 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
1133                         "processNextBroadcast("
1134                         + mQueueName + ") called when not idle (state="
1135                         + r.state + ")");
1136                 return;
1137             }
1138 
1139             // Is the current broadcast is done for any reason?
1140             if (r.receivers == null || r.nextReceiver >= numReceivers
1141                     || r.resultAbort || forceReceive) {
1142                 // Send the final result if requested
1143                 if (r.resultTo != null) {
1144                     boolean sendResult = true;
1145 
1146                     // if this was part of a split/deferral complex, update the refcount and only
1147                     // send the completion when we clear all of them
1148                     if (r.splitToken != 0) {
1149                         int newCount = mSplitRefcounts.get(r.splitToken) - 1;
1150                         if (newCount == 0) {
1151                             // done!  clear out this record's bookkeeping and deliver
1152                             if (DEBUG_BROADCAST_DEFERRAL) {
1153                                 Slog.i(TAG_BROADCAST,
1154                                         "Sending broadcast completion for split token "
1155                                         + r.splitToken + " : " + r.intent.getAction());
1156                             }
1157                             mSplitRefcounts.delete(r.splitToken);
1158                         } else {
1159                             // still have some split broadcast records in flight; update refcount
1160                             // and hold off on the callback
1161                             if (DEBUG_BROADCAST_DEFERRAL) {
1162                                 Slog.i(TAG_BROADCAST,
1163                                         "Result refcount now " + newCount + " for split token "
1164                                         + r.splitToken + " : " + r.intent.getAction()
1165                                         + " - not sending completion yet");
1166                             }
1167                             sendResult = false;
1168                             mSplitRefcounts.put(r.splitToken, newCount);
1169                         }
1170                     }
1171                     if (sendResult) {
1172                         if (r.callerApp != null) {
1173                             mService.mOomAdjuster.unfreezeTemporarily(
1174                                     r.callerApp,
1175                                     CachedAppOptimizer.UNFREEZE_REASON_FINISH_RECEIVER);
1176                         }
1177                         try {
1178                             if (DEBUG_BROADCAST) {
1179                                 Slog.i(TAG_BROADCAST, "Finishing broadcast [" + mQueueName + "] "
1180                                         + r.intent.getAction() + " app=" + r.callerApp);
1181                             }
1182                             if (r.dispatchTime == 0) {
1183                                 // The dispatch time here could be 0, in case it's a parallel
1184                                 // broadcast but it has a result receiver. Set it to now.
1185                                 r.dispatchTime = now;
1186                             }
1187                             r.mIsReceiverAppRunning = true;
1188                             performReceiveLocked(r, r.resultToApp, r.resultTo,
1189                                     new Intent(r.intent), r.resultCode,
1190                                     r.resultData, r.resultExtras, false, false, r.shareIdentity,
1191                                     r.userId, r.callingUid, r.callingUid, r.callerPackage,
1192                                     r.dispatchTime - r.enqueueTime,
1193                                     now - r.dispatchTime, 0,
1194                                     r.resultToApp != null
1195                                             ? r.resultToApp.mState.getCurProcState()
1196                                             : ActivityManager.PROCESS_STATE_UNKNOWN);
1197                             logBootCompletedBroadcastCompletionLatencyIfPossible(r);
1198                             // Set this to null so that the reference
1199                             // (local and remote) isn't kept in the mBroadcastHistory.
1200                             r.resultTo = null;
1201                         } catch (RemoteException e) {
1202                             r.resultTo = null;
1203                             Slog.w(TAG, "Failure ["
1204                                     + mQueueName + "] sending broadcast result of "
1205                                     + r.intent, e);
1206                         }
1207                     }
1208                 }
1209 
1210                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
1211                 cancelBroadcastTimeoutLocked();
1212 
1213                 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
1214                         "Finished with ordered broadcast " + r);
1215 
1216                 // ... and on to the next...
1217                 addBroadcastToHistoryLocked(r);
1218                 if (r.intent.getComponent() == null && r.intent.getPackage() == null
1219                         && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
1220                     // This was an implicit broadcast... let's record it for posterity.
1221                     mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
1222                             r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
1223                 }
1224                 mDispatcher.retireBroadcastLocked(r);
1225                 r = null;
1226                 looped = true;
1227                 continue;
1228             }
1229 
1230             // Check whether the next receiver is under deferral policy, and handle that
1231             // accordingly.  If the current broadcast was already part of deferred-delivery
1232             // tracking, we know that it must now be deliverable as-is without re-deferral.
1233             if (!r.deferred) {
1234                 final int receiverUid = r.getReceiverUid(r.receivers.get(r.nextReceiver));
1235                 if (mDispatcher.isDeferringLocked(receiverUid)) {
1236                     if (DEBUG_BROADCAST_DEFERRAL) {
1237                         Slog.i(TAG_BROADCAST, "Next receiver in " + r + " uid " + receiverUid
1238                                 + " at " + r.nextReceiver + " is under deferral");
1239                     }
1240                     // If this is the only (remaining) receiver in the broadcast, "splitting"
1241                     // doesn't make sense -- just defer it as-is and retire it as the
1242                     // currently active outgoing broadcast.
1243                     BroadcastRecord defer;
1244                     if (r.nextReceiver + 1 == numReceivers) {
1245                         if (DEBUG_BROADCAST_DEFERRAL) {
1246                             Slog.i(TAG_BROADCAST, "Sole receiver of " + r
1247                                     + " is under deferral; setting aside and proceeding");
1248                         }
1249                         defer = r;
1250                         mDispatcher.retireBroadcastLocked(r);
1251                     } else {
1252                         // Nontrivial case; split out 'uid's receivers to a new broadcast record
1253                         // and defer that, then loop and pick up continuing delivery of the current
1254                         // record (now absent those receivers).
1255 
1256                         // The split operation is guaranteed to match at least at 'nextReceiver'
1257                         defer = r.splitRecipientsLocked(receiverUid, r.nextReceiver);
1258                         if (DEBUG_BROADCAST_DEFERRAL) {
1259                             Slog.i(TAG_BROADCAST, "Post split:");
1260                             Slog.i(TAG_BROADCAST, "Original broadcast receivers:");
1261                             for (int i = 0; i < r.receivers.size(); i++) {
1262                                 Slog.i(TAG_BROADCAST, "  " + r.receivers.get(i));
1263                             }
1264                             Slog.i(TAG_BROADCAST, "Split receivers:");
1265                             for (int i = 0; i < defer.receivers.size(); i++) {
1266                                 Slog.i(TAG_BROADCAST, "  " + defer.receivers.get(i));
1267                             }
1268                         }
1269                         // Track completion refcount as well if relevant
1270                         if (r.resultTo != null) {
1271                             int token = r.splitToken;
1272                             if (token == 0) {
1273                                 // first split of this record; refcount for 'r' and 'deferred'
1274                                 r.splitToken = defer.splitToken = nextSplitTokenLocked();
1275                                 mSplitRefcounts.put(r.splitToken, 2);
1276                                 if (DEBUG_BROADCAST_DEFERRAL) {
1277                                     Slog.i(TAG_BROADCAST,
1278                                             "Broadcast needs split refcount; using new token "
1279                                             + r.splitToken);
1280                                 }
1281                             } else {
1282                                 // new split from an already-refcounted situation; increment count
1283                                 final int curCount = mSplitRefcounts.get(token);
1284                                 if (DEBUG_BROADCAST_DEFERRAL) {
1285                                     if (curCount == 0) {
1286                                         Slog.wtf(TAG_BROADCAST,
1287                                                 "Split refcount is zero with token for " + r);
1288                                     }
1289                                 }
1290                                 mSplitRefcounts.put(token, curCount + 1);
1291                                 if (DEBUG_BROADCAST_DEFERRAL) {
1292                                     Slog.i(TAG_BROADCAST, "New split count for token " + token
1293                                             + " is " + (curCount + 1));
1294                                 }
1295                             }
1296                         }
1297                     }
1298                     mDispatcher.addDeferredBroadcast(receiverUid, defer);
1299                     r = null;
1300                     looped = true;
1301                     continue;
1302                 }
1303             }
1304         } while (r == null);
1305 
1306         // Get the next receiver...
1307         int recIdx = r.nextReceiver++;
1308 
1309         // Keep track of when this receiver started, and make sure there
1310         // is a timeout message pending to kill it if need be.
1311         r.receiverTime = SystemClock.uptimeMillis();
1312         r.scheduledTime[recIdx] = r.receiverTime;
1313         if (recIdx == 0) {
1314             r.dispatchTime = r.receiverTime;
1315             r.dispatchRealTime = SystemClock.elapsedRealtime();
1316             r.dispatchClockTime = System.currentTimeMillis();
1317 
1318             if (mLogLatencyMetrics) {
1319                 FrameworkStatsLog.write(
1320                         FrameworkStatsLog.BROADCAST_DISPATCH_LATENCY_REPORTED,
1321                         r.dispatchClockTime - r.enqueueClockTime);
1322             }
1323 
1324             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1325                 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1326                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
1327                     System.identityHashCode(r));
1328                 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1329                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
1330                     System.identityHashCode(r));
1331             }
1332             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
1333                     + mQueueName + "] " + r);
1334         }
1335         if (! mPendingBroadcastTimeoutMessage) {
1336             long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
1337             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1338                     "Submitting BROADCAST_TIMEOUT_MSG ["
1339                     + mQueueName + "] for " + r + " at " + timeoutTime);
1340             setBroadcastTimeoutLocked(timeoutTime);
1341         }
1342 
1343         final BroadcastOptions brOptions = r.options;
1344         final Object nextReceiver = r.receivers.get(recIdx);
1345 
1346         if (nextReceiver instanceof BroadcastFilter) {
1347             // Simple case: this is a registered receiver who gets
1348             // a direct call.
1349             BroadcastFilter filter = (BroadcastFilter)nextReceiver;
1350             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1351                     "Delivering ordered ["
1352                     + mQueueName + "] to registered "
1353                     + filter + ": " + r);
1354             r.mIsReceiverAppRunning = true;
1355             deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
1356             if ((r.curReceiver == null && r.curFilter == null) || !r.ordered) {
1357                 // The receiver has already finished, so schedule to
1358                 // process the next one.
1359                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
1360                         + mQueueName + "]: ordered=" + r.ordered
1361                         + " curFilter=" + r.curFilter
1362                         + " curReceiver=" + r.curReceiver);
1363                 r.state = BroadcastRecord.IDLE;
1364                 scheduleBroadcastsLocked();
1365             } else {
1366                 if (filter.receiverList != null) {
1367                     maybeAddBackgroundStartPrivileges(filter.receiverList.app, r);
1368                     // r is guaranteed ordered at this point, so we know finishReceiverLocked()
1369                     // will get a callback and handle the activity start token lifecycle.
1370                 }
1371             }
1372             return;
1373         }
1374 
1375         // Hard case: need to instantiate the receiver, possibly
1376         // starting its application process to host it.
1377 
1378         final ResolveInfo info =
1379             (ResolveInfo)nextReceiver;
1380         final ComponentName component = new ComponentName(
1381                 info.activityInfo.applicationInfo.packageName,
1382                 info.activityInfo.name);
1383         final int receiverUid = info.activityInfo.applicationInfo.uid;
1384 
1385         final String targetProcess = info.activityInfo.processName;
1386         final ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1387                 info.activityInfo.applicationInfo.uid);
1388 
1389         boolean skip = mSkipPolicy.shouldSkip(r, info);
1390 
1391         // Filter packages in the intent extras, skipping delivery if none of the packages is
1392         // visible to the receiver.
1393         Bundle filteredExtras = null;
1394         if (!skip && r.filterExtrasForReceiver != null) {
1395             final Bundle extras = r.intent.getExtras();
1396             if (extras != null) {
1397                 filteredExtras = r.filterExtrasForReceiver.apply(receiverUid, extras);
1398                 if (filteredExtras == null) {
1399                     if (DEBUG_BROADCAST) {
1400                         Slog.v(TAG, "Skipping delivery to "
1401                                 + info.activityInfo.packageName + " / " + receiverUid
1402                                 + " : receiver is filtered by the package visibility");
1403                     }
1404                     skip = true;
1405                 }
1406             }
1407         }
1408 
1409         if (skip) {
1410             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1411                     "Skipping delivery of ordered [" + mQueueName + "] "
1412                     + r + " for reason described above");
1413             r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
1414             r.curFilter = null;
1415             r.state = BroadcastRecord.IDLE;
1416             r.manifestSkipCount++;
1417             scheduleBroadcastsLocked();
1418             return;
1419         }
1420         r.manifestCount++;
1421 
1422         r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
1423         r.state = BroadcastRecord.APP_RECEIVE;
1424         r.curComponent = component;
1425         r.curReceiver = info.activityInfo;
1426         r.curFilteredExtras = filteredExtras;
1427         if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
1428             Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1429                     + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1430                     + receiverUid);
1431         }
1432         final boolean isActivityCapable =
1433                 (brOptions != null && brOptions.getTemporaryAppAllowlistDuration() > 0);
1434         maybeScheduleTempAllowlistLocked(receiverUid, r, brOptions);
1435 
1436         // Report that a component is used for explicit broadcasts.
1437         if (r.intent.getComponent() != null && r.curComponent != null
1438                 && !TextUtils.equals(r.curComponent.getPackageName(), r.callerPackage)) {
1439             mService.mUsageStatsService.reportEvent(
1440                     r.curComponent.getPackageName(), r.userId, Event.APP_COMPONENT_USED);
1441         }
1442 
1443         // Broadcast is being executed, its package can't be stopped.
1444         try {
1445             mService.mPackageManagerInt.setPackageStoppedState(
1446                     r.curComponent.getPackageName(), false, r.userId);
1447         } catch (IllegalArgumentException e) {
1448             Slog.w(TAG, "Failed trying to unstop package "
1449                     + r.curComponent.getPackageName() + ": " + e);
1450         }
1451 
1452         // Is this receiver's application already running?
1453         if (app != null && app.getThread() != null && !app.isKilled()) {
1454             try {
1455                 app.addPackage(info.activityInfo.packageName,
1456                         info.activityInfo.applicationInfo.longVersionCode, mService.mProcessStats);
1457                 maybeAddBackgroundStartPrivileges(app, r);
1458                 r.mIsReceiverAppRunning = true;
1459                 processCurBroadcastLocked(r, app);
1460                 return;
1461             } catch (RemoteException e) {
1462                 final String msg = "Failed to schedule " + r.intent + " to " + info
1463                         + " via " + app + ": " + e;
1464                 Slog.w(TAG, msg);
1465                 app.killLocked("Can't deliver broadcast", ApplicationExitInfo.REASON_OTHER,
1466                         ApplicationExitInfo.SUBREASON_UNDELIVERED_BROADCAST, true);
1467             } catch (RuntimeException e) {
1468                 Slog.wtf(TAG, "Failed sending broadcast to "
1469                         + r.curComponent + " with " + r.intent, e);
1470                 // If some unexpected exception happened, just skip
1471                 // this broadcast.  At this point we are not in the call
1472                 // from a client, so throwing an exception out from here
1473                 // will crash the entire system instead of just whoever
1474                 // sent the broadcast.
1475                 logBroadcastReceiverDiscardLocked(r);
1476                 finishReceiverLocked(r, r.resultCode, r.resultData,
1477                         r.resultExtras, r.resultAbort, false);
1478                 scheduleBroadcastsLocked();
1479                 // We need to reset the state if we failed to start the receiver.
1480                 r.state = BroadcastRecord.IDLE;
1481                 return;
1482             }
1483 
1484             // If a dead object exception was thrown -- fall through to
1485             // restart the application.
1486         }
1487 
1488         // Registered whether we're bringing this package out of a stopped state
1489         r.mWasReceiverAppStopped =
1490                 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_STOPPED) != 0;
1491         // Not running -- get it started, to be executed when the app comes up.
1492         if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1493                 "Need to start app ["
1494                 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1495         r.curApp = mService.startProcessLocked(targetProcess,
1496                 info.activityInfo.applicationInfo, true,
1497                 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1498                 new HostingRecord(HostingRecord.HOSTING_TYPE_BROADCAST, r.curComponent,
1499                         r.intent.getAction(), r.getHostingRecordTriggerType()),
1500                 isActivityCapable ? ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE : ZYGOTE_POLICY_FLAG_EMPTY,
1501                 (r.intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false);
1502         r.curAppLastProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
1503         if (r.curApp == null) {
1504             // Ah, this recipient is unavailable.  Finish it if necessary,
1505             // and mark the broadcast record as ready for the next.
1506             Slog.w(TAG, "Unable to launch app "
1507                     + info.activityInfo.applicationInfo.packageName + "/"
1508                     + receiverUid + " for broadcast "
1509                     + r.intent + ": process is bad");
1510             logBroadcastReceiverDiscardLocked(r);
1511             finishReceiverLocked(r, r.resultCode, r.resultData,
1512                     r.resultExtras, r.resultAbort, false);
1513             scheduleBroadcastsLocked();
1514             r.state = BroadcastRecord.IDLE;
1515             return;
1516         }
1517 
1518         maybeAddBackgroundStartPrivileges(r.curApp, r);
1519         mPendingBroadcast = r;
1520         mPendingBroadcastRecvIndex = recIdx;
1521     }
1522 
1523     @Nullable
getTargetPackage(BroadcastRecord r)1524     private String getTargetPackage(BroadcastRecord r) {
1525         if (r.intent == null) {
1526             return null;
1527         }
1528         if (r.intent.getPackage() != null) {
1529             return r.intent.getPackage();
1530         } else if (r.intent.getComponent() != null) {
1531             return r.intent.getComponent().getPackageName();
1532         }
1533         return null;
1534     }
1535 
logBootCompletedBroadcastCompletionLatencyIfPossible(BroadcastRecord r)1536     static void logBootCompletedBroadcastCompletionLatencyIfPossible(BroadcastRecord r) {
1537         // Only log after last receiver.
1538         // In case of split BOOT_COMPLETED broadcast, make sure only call this method on the
1539         // last BroadcastRecord of the split broadcast which has non-null resultTo.
1540         final int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
1541         if (r.nextReceiver < numReceivers) {
1542             return;
1543         }
1544         final String action = r.intent.getAction();
1545         int event = 0;
1546         if (Intent.ACTION_LOCKED_BOOT_COMPLETED.equals(action)) {
1547             event = BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__LOCKED_BOOT_COMPLETED;
1548         } else if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
1549             event = BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__BOOT_COMPLETED;
1550         }
1551         if (event != 0) {
1552             final int dispatchLatency = (int)(r.dispatchTime - r.enqueueTime);
1553             final int completeLatency = (int)
1554                     (SystemClock.uptimeMillis() - r.enqueueTime);
1555             final int dispatchRealLatency = (int)(r.dispatchRealTime - r.enqueueRealTime);
1556             final int completeRealLatency = (int)
1557                     (SystemClock.elapsedRealtime() - r.enqueueRealTime);
1558             int userType = FrameworkStatsLog.USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__TYPE_UNKNOWN;
1559             // This method is called very infrequently, no performance issue we call
1560             // LocalServices.getService() here.
1561             final UserManagerInternal umInternal = LocalServices.getService(
1562                     UserManagerInternal.class);
1563             final UserInfo userInfo =
1564                     (umInternal != null) ? umInternal.getUserInfo(r.userId) : null;
1565             if (userInfo != null) {
1566                 userType = UserJourneyLogger.getUserTypeForStatsd(userInfo.userType);
1567             }
1568             Slog.i(TAG_BROADCAST,
1569                     "BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED action:"
1570                             + action
1571                             + " dispatchLatency:" + dispatchLatency
1572                             + " completeLatency:" + completeLatency
1573                             + " dispatchRealLatency:" + dispatchRealLatency
1574                             + " completeRealLatency:" + completeRealLatency
1575                             + " receiversSize:" + numReceivers
1576                             + " userId:" + r.userId
1577                             + " userType:" + (userInfo != null? userInfo.userType : null));
1578             FrameworkStatsLog.write(
1579                     BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED,
1580                     event,
1581                     dispatchLatency,
1582                     completeLatency,
1583                     dispatchRealLatency,
1584                     completeRealLatency,
1585                     r.userId,
1586                     userType);
1587         }
1588     }
1589 
maybeReportBroadcastDispatchedEventLocked(BroadcastRecord r, int targetUid)1590     private void maybeReportBroadcastDispatchedEventLocked(BroadcastRecord r, int targetUid) {
1591         if (r.options == null || r.options.getIdForResponseEvent() <= 0) {
1592             return;
1593         }
1594         final String targetPackage = getTargetPackage(r);
1595         // Ignore non-explicit broadcasts
1596         if (targetPackage == null) {
1597             return;
1598         }
1599         mService.mUsageStatsService.reportBroadcastDispatched(
1600                 r.callingUid, targetPackage, UserHandle.of(r.userId),
1601                 r.options.getIdForResponseEvent(), SystemClock.elapsedRealtime(),
1602                 mService.getUidStateLocked(targetUid));
1603     }
1604 
maybeAddBackgroundStartPrivileges(ProcessRecord proc, BroadcastRecord r)1605     private void maybeAddBackgroundStartPrivileges(ProcessRecord proc, BroadcastRecord r) {
1606         if (r == null || proc == null || !r.mBackgroundStartPrivileges.allowsAny()) {
1607             return;
1608         }
1609         String msgToken = (proc.toShortString() + r.toString()).intern();
1610         // first, if there exists a past scheduled request to remove this token, drop
1611         // that request - we don't want the token to be swept from under our feet...
1612         mHandler.removeCallbacksAndMessages(msgToken);
1613         // ...then add the token
1614         proc.addOrUpdateBackgroundStartPrivileges(r, r.mBackgroundStartPrivileges);
1615     }
1616 
setBroadcastTimeoutLocked(long timeoutTime)1617     final void setBroadcastTimeoutLocked(long timeoutTime) {
1618         if (! mPendingBroadcastTimeoutMessage) {
1619             Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1620             mHandler.sendMessageAtTime(msg, timeoutTime);
1621             mPendingBroadcastTimeoutMessage = true;
1622         }
1623     }
1624 
cancelBroadcastTimeoutLocked()1625     final void cancelBroadcastTimeoutLocked() {
1626         if (mPendingBroadcastTimeoutMessage) {
1627             mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1628             mPendingBroadcastTimeoutMessage = false;
1629         }
1630     }
1631 
broadcastTimeoutLocked(boolean fromMsg)1632     final void broadcastTimeoutLocked(boolean fromMsg) {
1633         if (fromMsg) {
1634             mPendingBroadcastTimeoutMessage = false;
1635         }
1636 
1637         if (mDispatcher.isEmpty() || mDispatcher.getActiveBroadcastLocked() == null) {
1638             return;
1639         }
1640         Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastTimeoutLocked()");
1641         try {
1642             long now = SystemClock.uptimeMillis();
1643             BroadcastRecord r = mDispatcher.getActiveBroadcastLocked();
1644             if (fromMsg) {
1645                 if (!mService.mProcessesReady) {
1646                     // Only process broadcast timeouts if the system is ready; some early
1647                     // broadcasts do heavy work setting up system facilities
1648                     return;
1649                 }
1650 
1651                 // If the broadcast is generally exempt from timeout tracking, we're done
1652                 if (r.timeoutExempt) {
1653                     if (DEBUG_BROADCAST) {
1654                         Slog.i(TAG_BROADCAST, "Broadcast timeout but it's exempt: "
1655                                 + r.intent.getAction());
1656                     }
1657                     return;
1658                 }
1659                 long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
1660                 if (timeoutTime > now) {
1661                     // We can observe premature timeouts because we do not cancel and reset the
1662                     // broadcast timeout message after each receiver finishes.  Instead, we set up
1663                     // an initial timeout then kick it down the road a little further as needed
1664                     // when it expires.
1665                     if (DEBUG_BROADCAST) {
1666                         Slog.v(TAG_BROADCAST,
1667                                 "Premature timeout ["
1668                                 + mQueueName + "] @ " + now
1669                                 + ": resetting BROADCAST_TIMEOUT_MSG for "
1670                                 + timeoutTime);
1671                     }
1672                     setBroadcastTimeoutLocked(timeoutTime);
1673                     return;
1674                 }
1675             }
1676 
1677             if (r.state == BroadcastRecord.WAITING_SERVICES) {
1678                 // In this case the broadcast had already finished, but we had decided to wait
1679                 // for started services to finish as well before going on.  So if we have actually
1680                 // waited long enough time timeout the broadcast, let's give up on the whole thing
1681                 // and just move on to the next.
1682                 Slog.i(TAG, "Waited long enough for: " + (r.curComponent != null
1683                         ? r.curComponent.flattenToShortString() : "(null)"));
1684                 r.curComponent = null;
1685                 r.state = BroadcastRecord.IDLE;
1686                 processNextBroadcastLocked(false, false);
1687                 return;
1688             }
1689 
1690             // If the receiver app is being debugged we quietly ignore unresponsiveness, just
1691             // tidying up and moving on to the next broadcast without crashing or ANRing this
1692             // app just because it's stopped at a breakpoint.
1693             final boolean debugging = (r.curApp != null && r.curApp.isDebugging());
1694 
1695             long timeoutDurationMs = now - r.receiverTime;
1696             Slog.w(TAG, "Timeout of broadcast " + r + " - curFilter=" + r.curFilter
1697                     + " curReceiver=" + r.curReceiver + ", started " + timeoutDurationMs
1698                     + "ms ago");
1699             r.receiverTime = now;
1700             if (!debugging) {
1701                 r.anrCount++;
1702             }
1703 
1704             ProcessRecord app = null;
1705             Object curReceiver;
1706             if (r.nextReceiver > 0) {
1707                 curReceiver = r.receivers.get(r.nextReceiver - 1);
1708                 r.delivery[r.nextReceiver - 1] = BroadcastRecord.DELIVERY_TIMEOUT;
1709             } else {
1710                 curReceiver = r.curReceiver;
1711             }
1712             Slog.w(TAG, "Receiver during timeout of " + r + " : " + curReceiver);
1713             logBroadcastReceiverDiscardLocked(r);
1714             TimeoutRecord timeoutRecord = TimeoutRecord.forBroadcastReceiver(r.intent,
1715                     timeoutDurationMs);
1716             if (curReceiver != null && curReceiver instanceof BroadcastFilter) {
1717                 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1718                 if (bf.receiverList.pid != 0
1719                         && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1720                     timeoutRecord.mLatencyTracker.waitingOnPidLockStarted();
1721                     synchronized (mService.mPidsSelfLocked) {
1722                         timeoutRecord.mLatencyTracker.waitingOnPidLockEnded();
1723                         app = mService.mPidsSelfLocked.get(
1724                                 bf.receiverList.pid);
1725                     }
1726                 }
1727             } else {
1728                 app = r.curApp;
1729             }
1730 
1731             if (mPendingBroadcast == r) {
1732                 mPendingBroadcast = null;
1733             }
1734 
1735             // Move on to the next receiver.
1736             finishReceiverLocked(r, r.resultCode, r.resultData,
1737                     r.resultExtras, r.resultAbort, false);
1738             scheduleBroadcastsLocked();
1739 
1740             // The ANR should only be triggered if we have a process record (app is non-null)
1741             if (!debugging && app != null) {
1742                 mService.appNotResponding(app, timeoutRecord);
1743             }
1744 
1745         } finally {
1746             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1747         }
1748 
1749     }
1750 
addBroadcastToHistoryLocked(BroadcastRecord original)1751     private final void addBroadcastToHistoryLocked(BroadcastRecord original) {
1752         if (original.callingUid < 0) {
1753             // This was from a registerReceiver() call; ignore it.
1754             return;
1755         }
1756         original.finishTime = SystemClock.uptimeMillis();
1757 
1758         if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1759             Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1760                 createBroadcastTraceTitle(original, BroadcastRecord.DELIVERY_DELIVERED),
1761                 System.identityHashCode(original));
1762         }
1763 
1764         mService.notifyBroadcastFinishedLocked(original);
1765         mHistory.addBroadcastToHistoryLocked(original);
1766     }
1767 
cleanupDisabledPackageReceiversLocked( String packageName, Set<String> filterByClasses, int userId)1768     public boolean cleanupDisabledPackageReceiversLocked(
1769             String packageName, Set<String> filterByClasses, int userId) {
1770         boolean didSomething = false;
1771         for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1772             didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1773                     packageName, filterByClasses, userId, true);
1774         }
1775 
1776         didSomething |= mDispatcher.cleanupDisabledPackageReceiversLocked(packageName,
1777                 filterByClasses, userId, true);
1778 
1779         return didSomething;
1780     }
1781 
logBroadcastReceiverDiscardLocked(BroadcastRecord r)1782     final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
1783         final int logIndex = r.nextReceiver - 1;
1784         if (logIndex >= 0 && logIndex < r.receivers.size()) {
1785             Object curReceiver = r.receivers.get(logIndex);
1786             if (curReceiver instanceof BroadcastFilter) {
1787                 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1788                 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
1789                         bf.owningUserId, System.identityHashCode(r),
1790                         r.intent.getAction(), logIndex, System.identityHashCode(bf));
1791             } else {
1792                 ResolveInfo ri = (ResolveInfo) curReceiver;
1793                 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1794                         UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
1795                         System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
1796             }
1797         } else {
1798             if (logIndex < 0) Slog.w(TAG,
1799                     "Discarding broadcast before first receiver is invoked: " + r);
1800             EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1801                     -1, System.identityHashCode(r),
1802                     r.intent.getAction(),
1803                     r.nextReceiver,
1804                     "NONE");
1805         }
1806     }
1807 
createBroadcastTraceTitle(BroadcastRecord record, int state)1808     private String createBroadcastTraceTitle(BroadcastRecord record, int state) {
1809         return formatSimple("Broadcast %s from %s (%s) %s",
1810                 state == BroadcastRecord.DELIVERY_PENDING ? "in queue" : "dispatched",
1811                 record.callerPackage == null ? "" : record.callerPackage,
1812                 record.callerApp == null ? "process unknown" : record.callerApp.toShortString(),
1813                 record.intent == null ? "" : record.intent.getAction());
1814     }
1815 
isIdleLocked()1816     public boolean isIdleLocked() {
1817         return mParallelBroadcasts.isEmpty() && mDispatcher.isIdle()
1818                 && (mPendingBroadcast == null);
1819     }
1820 
isBeyondBarrierLocked(long barrierTime)1821     public boolean isBeyondBarrierLocked(long barrierTime) {
1822         // If nothing active, we're beyond barrier
1823         if (isIdleLocked()) return true;
1824 
1825         // Check if parallel broadcasts are beyond barrier
1826         for (int i = 0; i < mParallelBroadcasts.size(); i++) {
1827             if (mParallelBroadcasts.get(i).enqueueTime <= barrierTime) {
1828                 return false;
1829             }
1830         }
1831 
1832         // Check if pending broadcast is beyond barrier
1833         final BroadcastRecord pending = getPendingBroadcastLocked();
1834         if ((pending != null) && pending.enqueueTime <= barrierTime) {
1835             return false;
1836         }
1837 
1838         return mDispatcher.isBeyondBarrier(barrierTime);
1839     }
1840 
isDispatchedLocked(Intent intent)1841     public boolean isDispatchedLocked(Intent intent) {
1842         if (isIdleLocked()) return true;
1843 
1844         for (int i = 0; i < mParallelBroadcasts.size(); i++) {
1845             if (intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
1846                 return false;
1847             }
1848         }
1849 
1850         final BroadcastRecord pending = getPendingBroadcastLocked();
1851         if ((pending != null) && intent.filterEquals(pending.intent)) {
1852             return false;
1853         }
1854 
1855         return mDispatcher.isDispatched(intent);
1856     }
1857 
waitForIdle(PrintWriter pw)1858     public void waitForIdle(PrintWriter pw) {
1859         waitFor(() -> isIdleLocked(), pw, "idle");
1860     }
1861 
waitForBarrier(PrintWriter pw)1862     public void waitForBarrier(PrintWriter pw) {
1863         final long barrierTime = SystemClock.uptimeMillis();
1864         waitFor(() -> isBeyondBarrierLocked(barrierTime), pw, "barrier");
1865     }
1866 
waitForDispatched(Intent intent, PrintWriter pw)1867     public void waitForDispatched(Intent intent, PrintWriter pw) {
1868         waitFor(() -> isDispatchedLocked(intent), pw, "dispatch");
1869     }
1870 
waitFor(BooleanSupplier condition, PrintWriter pw, String conditionName)1871     private void waitFor(BooleanSupplier condition, PrintWriter pw, String conditionName) {
1872         long lastPrint = 0;
1873         while (true) {
1874             synchronized (mService) {
1875                 if (condition.getAsBoolean()) {
1876                     final String msg = "Queue [" + mQueueName + "] reached " + conditionName
1877                             + " condition";
1878                     Slog.v(TAG, msg);
1879                     if (pw != null) {
1880                         pw.println(msg);
1881                         pw.flush();
1882                     }
1883                     return;
1884                 }
1885             }
1886 
1887             // Print at most every second
1888             final long now = SystemClock.uptimeMillis();
1889             if (now >= lastPrint + 1000) {
1890                 lastPrint = now;
1891                 final String msg = "Queue [" + mQueueName + "] waiting for " + conditionName
1892                         + " condition; state is " + describeStateLocked();
1893                 Slog.v(TAG, msg);
1894                 if (pw != null) {
1895                     pw.println(msg);
1896                     pw.flush();
1897                 }
1898             }
1899 
1900             // Push through any deferrals to try meeting our condition
1901             cancelDeferrals();
1902             SystemClock.sleep(100);
1903         }
1904     }
1905 
1906     // Used by wait-for-broadcast-idle : fast-forward all current deferrals to
1907     // be immediately deliverable.
cancelDeferrals()1908     public void cancelDeferrals() {
1909         synchronized (mService) {
1910             mDispatcher.cancelDeferralsLocked();
1911             scheduleBroadcastsLocked();
1912         }
1913     }
1914 
describeStateLocked()1915     public String describeStateLocked() {
1916         return mParallelBroadcasts.size() + " parallel; "
1917                 + mDispatcher.describeStateLocked();
1918     }
1919 
1920     @NeverCompile
dumpDebug(ProtoOutputStream proto, long fieldId)1921     public void dumpDebug(ProtoOutputStream proto, long fieldId) {
1922         long token = proto.start(fieldId);
1923         proto.write(BroadcastQueueProto.QUEUE_NAME, mQueueName);
1924         int N;
1925         N = mParallelBroadcasts.size();
1926         for (int i = N - 1; i >= 0; i--) {
1927             mParallelBroadcasts.get(i).dumpDebug(proto, BroadcastQueueProto.PARALLEL_BROADCASTS);
1928         }
1929         mDispatcher.dumpDebug(proto, BroadcastQueueProto.ORDERED_BROADCASTS);
1930         if (mPendingBroadcast != null) {
1931             mPendingBroadcast.dumpDebug(proto, BroadcastQueueProto.PENDING_BROADCAST);
1932         }
1933         mHistory.dumpDebug(proto);
1934         proto.end(token);
1935     }
1936 
1937     @NeverCompile
dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpConstants, boolean dumpHistory, boolean dumpAll, String dumpPackage, boolean needSep)1938     public boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1939             int opti, boolean dumpConstants, boolean dumpHistory, boolean dumpAll,
1940             String dumpPackage, boolean needSep) {
1941         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
1942         if (!mParallelBroadcasts.isEmpty() || !mDispatcher.isEmpty()
1943                 || mPendingBroadcast != null) {
1944             boolean printed = false;
1945             for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1946                 BroadcastRecord br = mParallelBroadcasts.get(i);
1947                 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1948                     continue;
1949                 }
1950                 if (!printed) {
1951                     if (needSep) {
1952                         pw.println();
1953                     }
1954                     needSep = true;
1955                     printed = true;
1956                     pw.println("  Active broadcasts [" + mQueueName + "]:");
1957                 }
1958                 pw.println("  Active Broadcast " + mQueueName + " #" + i + ":");
1959                 br.dump(pw, "    ", sdf);
1960             }
1961 
1962             mDispatcher.dumpLocked(pw, dumpPackage, mQueueName, sdf);
1963 
1964             if (dumpPackage == null || (mPendingBroadcast != null
1965                     && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1966                 pw.println();
1967                 pw.println("  Pending broadcast [" + mQueueName + "]:");
1968                 if (mPendingBroadcast != null) {
1969                     mPendingBroadcast.dump(pw, "    ", sdf);
1970                 } else {
1971                     pw.println("    (null)");
1972                 }
1973                 needSep = true;
1974             }
1975         }
1976         if (dumpConstants) {
1977             mConstants.dump(new IndentingPrintWriter(pw));
1978         }
1979         if (dumpHistory) {
1980             needSep = mHistory.dumpLocked(pw, dumpPackage, mQueueName, sdf, dumpAll, needSep);
1981         }
1982         return needSep;
1983     }
1984 }
1985