1 /*
2  * Copyright (C) 2006 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_BACKGROUND_RESTRICTED;
20 import static android.app.AppProtoEnums.BROADCAST_TYPE_ALARM;
21 import static android.app.AppProtoEnums.BROADCAST_TYPE_BACKGROUND;
22 import static android.app.AppProtoEnums.BROADCAST_TYPE_DEFERRABLE_UNTIL_ACTIVE;
23 import static android.app.AppProtoEnums.BROADCAST_TYPE_FOREGROUND;
24 import static android.app.AppProtoEnums.BROADCAST_TYPE_INITIAL_STICKY;
25 import static android.app.AppProtoEnums.BROADCAST_TYPE_INTERACTIVE;
26 import static android.app.AppProtoEnums.BROADCAST_TYPE_NONE;
27 import static android.app.AppProtoEnums.BROADCAST_TYPE_ORDERED;
28 import static android.app.AppProtoEnums.BROADCAST_TYPE_PRIORITIZED;
29 import static android.app.AppProtoEnums.BROADCAST_TYPE_PUSH_MESSAGE;
30 import static android.app.AppProtoEnums.BROADCAST_TYPE_PUSH_MESSAGE_OVER_QUOTA;
31 import static android.app.AppProtoEnums.BROADCAST_TYPE_RESULT_TO;
32 import static android.app.AppProtoEnums.BROADCAST_TYPE_STICKY;
33 
34 import static com.android.server.am.BroadcastConstants.DEFER_BOOT_COMPLETED_BROADCAST_ALL;
35 import static com.android.server.am.BroadcastConstants.DEFER_BOOT_COMPLETED_BROADCAST_BACKGROUND_RESTRICTED_ONLY;
36 import static com.android.server.am.BroadcastConstants.DEFER_BOOT_COMPLETED_BROADCAST_CHANGE_ID;
37 import static com.android.server.am.BroadcastConstants.DEFER_BOOT_COMPLETED_BROADCAST_NONE;
38 import static com.android.server.am.BroadcastConstants.DEFER_BOOT_COMPLETED_BROADCAST_TARGET_T_ONLY;
39 
40 import android.annotation.CheckResult;
41 import android.annotation.CurrentTimeMillisLong;
42 import android.annotation.ElapsedRealtimeLong;
43 import android.annotation.IntDef;
44 import android.annotation.NonNull;
45 import android.annotation.Nullable;
46 import android.annotation.UptimeMillisLong;
47 import android.app.ActivityManager.ProcessState;
48 import android.app.ActivityManagerInternal;
49 import android.app.AppOpsManager;
50 import android.app.BackgroundStartPrivileges;
51 import android.app.BroadcastOptions;
52 import android.app.BroadcastOptions.DeliveryGroupPolicy;
53 import android.app.compat.CompatChanges;
54 import android.content.ComponentName;
55 import android.content.IIntentReceiver;
56 import android.content.Intent;
57 import android.content.IntentFilter;
58 import android.content.pm.ActivityInfo;
59 import android.content.pm.ResolveInfo;
60 import android.os.Binder;
61 import android.os.Bundle;
62 import android.os.SystemClock;
63 import android.os.UserHandle;
64 import android.util.PrintWriterPrinter;
65 import android.util.SparseArray;
66 import android.util.TimeUtils;
67 import android.util.proto.ProtoOutputStream;
68 
69 import com.android.internal.annotations.VisibleForTesting;
70 
71 import dalvik.annotation.optimization.NeverCompile;
72 
73 import java.io.PrintWriter;
74 import java.lang.annotation.Retention;
75 import java.lang.annotation.RetentionPolicy;
76 import java.text.SimpleDateFormat;
77 import java.util.ArrayList;
78 import java.util.Arrays;
79 import java.util.Date;
80 import java.util.List;
81 import java.util.Objects;
82 import java.util.Set;
83 import java.util.concurrent.atomic.AtomicInteger;
84 import java.util.function.BiFunction;
85 
86 /**
87  * An active intent broadcast.
88  */
89 final class BroadcastRecord extends Binder {
90     final @NonNull Intent intent;    // the original intent that generated us
91     final @Nullable ComponentName targetComp; // original component name set on the intent
92     final @Nullable ProcessRecord callerApp; // process that sent this
93     final @Nullable String callerPackage; // who sent this
94     final @Nullable String callerFeatureId; // which feature in the package sent this
95     final int callingPid;   // the pid of who sent this
96     final int callingUid;   // the uid of who sent this
97     final @ProcessState int callerProcState; // Procstate of the caller process at enqueue time.
98 
99     final int originalStickyCallingUid;
100             // if this is a sticky broadcast, the Uid of the original sender
101     final boolean callerInstantApp; // caller is an Instant App?
102     final boolean callerInstrumented; // caller is being instrumented?
103     final boolean ordered;  // serialize the send to receivers?
104     final boolean sticky;   // originated from existing sticky data?
105     final boolean alarm;    // originated from an alarm triggering?
106     final boolean pushMessage; // originated from a push message?
107     final boolean pushMessageOverQuota; // originated from a push message which was over quota?
108     final boolean interactive; // originated from user interaction?
109     final boolean initialSticky; // initial broadcast from register to sticky?
110     final boolean prioritized; // contains more than one priority tranche
111     final boolean deferUntilActive; // infinitely deferrable broadcast
112     final boolean shareIdentity;  // whether the broadcaster's identity should be shared
113     final boolean urgent;    // has been classified as "urgent"
114     final int userId;       // user id this broadcast was for
115     final @Nullable String resolvedType; // the resolved data type
116     final @Nullable String[] requiredPermissions; // permissions the caller has required
117     final @Nullable String[] excludedPermissions; // permissions to exclude
118     final @Nullable String[] excludedPackages; // packages to exclude
119     final int appOp;        // an app op that is associated with this broadcast
120     final @Nullable BroadcastOptions options; // BroadcastOptions supplied by caller
121     final @NonNull List<Object> receivers;   // contains BroadcastFilter and ResolveInfo
122     final @DeliveryState int[] delivery;   // delivery state of each receiver
123     final @NonNull String[] deliveryReasons; // reasons for delivery state of each receiver
124     final int[] blockedUntilBeyondCount; // blocked until count of each receiver
125     @Nullable ProcessRecord resultToApp; // who receives final result if non-null
126     @Nullable IIntentReceiver resultTo; // who receives final result if non-null
127     boolean deferred;
128     int splitCount;         // refcount for result callback, when split
129     int splitToken;         // identifier for cross-BroadcastRecord refcount
130     @UptimeMillisLong       long enqueueTime;        // when broadcast enqueued
131     @ElapsedRealtimeLong    long enqueueRealTime;    // when broadcast enqueued
132     @CurrentTimeMillisLong  long enqueueClockTime;   // when broadcast enqueued
133     // When broadcast is originally enqueued. Only used in case of replacing broadcasts
134     // with FLAG_RECEIVER_REPLACE_PENDING. If it is 0, then 'enqueueClockTime' is the original
135     // enqueue time.
136     @UptimeMillisLong       long originalEnqueueClockTime;
137     @UptimeMillisLong       long dispatchTime;       // when broadcast dispatch started
138     @ElapsedRealtimeLong    long dispatchRealTime;   // when broadcast dispatch started
139     @CurrentTimeMillisLong  long dispatchClockTime;  // when broadcast dispatch started
140     @UptimeMillisLong       long receiverTime;       // when receiver started for timeouts
141     @UptimeMillisLong       long finishTime;         // when broadcast finished
142     final @UptimeMillisLong long[] scheduledTime;    // when each receiver was scheduled
143     final @UptimeMillisLong long[] terminalTime;     // when each receiver was terminal
144     final boolean timeoutExempt;  // true if this broadcast is not subject to receiver timeouts
145     int resultCode;         // current result code value.
146     @Nullable String resultData;      // current result data value.
147     @Nullable Bundle resultExtras;    // current result extra data values.
148     boolean resultAbort;    // current result abortBroadcast value.
149     int nextReceiver;       // next receiver to be executed.
150     int state;
151     int anrCount;           // has this broadcast record hit any ANRs?
152     int manifestCount;      // number of manifest receivers dispatched.
153     int manifestSkipCount;  // number of manifest receivers skipped.
154     int terminalCount;      // number of receivers in terminal state.
155     int deferredCount;      // number of receivers in deferred state.
156     int beyondCount;        // high-water number of receivers we've moved beyond.
157     @Nullable BroadcastQueue queue;   // the outbound queue handling this broadcast
158 
159     // Determines the privileges the app's process has in regard to background starts.
160     final BackgroundStartPrivileges mBackgroundStartPrivileges;
161 
162     // Filter the intent extras by using the rules of the package visibility before broadcasting
163     // the intent to the receiver.
164     @Nullable
165     final BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver;
166 
167     private @Nullable String mCachedToString;
168     private @Nullable String mCachedToShortString;
169 
170     /**
171      * When enabled, assume that {@link UserHandle#isCore(int)} apps should
172      * treat {@link BroadcastOptions#DEFERRAL_POLICY_DEFAULT} as
173      * {@link BroadcastOptions#DEFERRAL_POLICY_UNTIL_ACTIVE}.
174      */
175     static boolean CORE_DEFER_UNTIL_ACTIVE = false;
176 
177     /** Empty immutable list of receivers */
178     static final List<Object> EMPTY_RECEIVERS = List.of();
179 
180     static final int IDLE = 0;
181     static final int APP_RECEIVE = 1;
182     static final int CALL_IN_RECEIVE = 2;
183     static final int CALL_DONE_RECEIVE = 3;
184     static final int WAITING_SERVICES = 4;
185 
186     /** Initial state: waiting to run in future */
187     static final int DELIVERY_PENDING = 0;
188     /** Terminal state: finished successfully */
189     static final int DELIVERY_DELIVERED = 1;
190     /** Terminal state: skipped due to internal policy */
191     static final int DELIVERY_SKIPPED = 2;
192     /** Terminal state: timed out during attempted delivery */
193     static final int DELIVERY_TIMEOUT = 3;
194     /** Intermediate state: currently executing */
195     static final int DELIVERY_SCHEDULED = 4;
196     /** Terminal state: failure to dispatch */
197     static final int DELIVERY_FAILURE = 5;
198     /** Intermediate state: currently deferred while app is cached */
199     static final int DELIVERY_DEFERRED = 6;
200 
201     @IntDef(flag = false, prefix = { "DELIVERY_" }, value = {
202             DELIVERY_PENDING,
203             DELIVERY_DELIVERED,
204             DELIVERY_SKIPPED,
205             DELIVERY_TIMEOUT,
206             DELIVERY_SCHEDULED,
207             DELIVERY_FAILURE,
208             DELIVERY_DEFERRED,
209     })
210     @Retention(RetentionPolicy.SOURCE)
211     public @interface DeliveryState {}
212 
deliveryStateToString(@eliveryState int deliveryState)213     static @NonNull String deliveryStateToString(@DeliveryState int deliveryState) {
214         switch (deliveryState) {
215             case DELIVERY_PENDING: return "PENDING";
216             case DELIVERY_DELIVERED: return "DELIVERED";
217             case DELIVERY_SKIPPED: return "SKIPPED";
218             case DELIVERY_TIMEOUT: return "TIMEOUT";
219             case DELIVERY_SCHEDULED: return "SCHEDULED";
220             case DELIVERY_FAILURE: return "FAILURE";
221             case DELIVERY_DEFERRED: return "DEFERRED";
222             default: return Integer.toString(deliveryState);
223         }
224     }
225 
226     /**
227      * Return if the given delivery state is "terminal", where no additional
228      * delivery state changes will be made.
229      */
isDeliveryStateTerminal(@eliveryState int deliveryState)230     static boolean isDeliveryStateTerminal(@DeliveryState int deliveryState) {
231         switch (deliveryState) {
232             case DELIVERY_DELIVERED:
233             case DELIVERY_SKIPPED:
234             case DELIVERY_TIMEOUT:
235             case DELIVERY_FAILURE:
236                 return true;
237             default:
238                 return false;
239         }
240     }
241 
242     /**
243      * Return if the given delivery state is "beyond", which means that we've
244      * moved beyond this receiver, and future receivers are now unblocked.
245      */
isDeliveryStateBeyond(@eliveryState int deliveryState)246     static boolean isDeliveryStateBeyond(@DeliveryState int deliveryState) {
247         switch (deliveryState) {
248             case DELIVERY_DELIVERED:
249             case DELIVERY_SKIPPED:
250             case DELIVERY_TIMEOUT:
251             case DELIVERY_FAILURE:
252             case DELIVERY_DEFERRED:
253                 return true;
254             default:
255                 return false;
256         }
257     }
258 
259     /**
260      * Return true if this receiver should be assumed to have been delivered.
261      */
isAssumedDelivered(int index)262     boolean isAssumedDelivered(int index) {
263         return (receivers.get(index) instanceof BroadcastFilter) && !ordered
264                 && (resultTo == null);
265     }
266 
267     ProcessRecord curApp;       // hosting application of current receiver.
268     ComponentName curComponent; // the receiver class that is currently running.
269     ActivityInfo curReceiver;   // the manifest receiver that is currently running.
270     BroadcastFilter curFilter;  // the registered receiver currently running.
271     Bundle curFilteredExtras;   // the bundle that has been filtered by the package visibility rules
272 
273     int curAppLastProcessState; // The last process state of the current receiver before receiving
274 
275     boolean mIsReceiverAppRunning; // Was the receiver's app already running.
276 
277     boolean mWasReceiverAppStopped; // Was the receiver app stopped prior to starting
278 
279     // Private refcount-management bookkeeping; start > 0
280     static AtomicInteger sNextToken = new AtomicInteger(1);
281 
282     @NeverCompile
dump(PrintWriter pw, String prefix, SimpleDateFormat sdf)283     void dump(PrintWriter pw, String prefix, SimpleDateFormat sdf) {
284         final long now = SystemClock.uptimeMillis();
285 
286         pw.print(prefix); pw.print(this); pw.print(" to user "); pw.println(userId);
287         pw.print(prefix); pw.println(intent.toInsecureString());
288         if (targetComp != null && targetComp != intent.getComponent()) {
289             pw.print(prefix); pw.print("  targetComp: "); pw.println(targetComp.toShortString());
290         }
291         Bundle bundle = intent.getExtras();
292         if (bundle != null) {
293             pw.print(prefix); pw.print("  extras: "); pw.println(bundle.toString());
294         }
295         pw.print(prefix); pw.print("caller="); pw.print(callerPackage); pw.print(" ");
296                 pw.print(callerApp != null ? callerApp.toShortString() : "null");
297                 pw.print(" pid="); pw.print(callingPid);
298                 pw.print(" uid="); pw.println(callingUid);
299         if ((requiredPermissions != null && requiredPermissions.length > 0)
300                 || appOp != AppOpsManager.OP_NONE) {
301             pw.print(prefix); pw.print("requiredPermissions=");
302             pw.print(Arrays.toString(requiredPermissions));
303             pw.print("  appOp="); pw.println(appOp);
304         }
305         if (excludedPermissions != null && excludedPermissions.length > 0) {
306             pw.print(prefix); pw.print("excludedPermissions=");
307             pw.print(Arrays.toString(excludedPermissions));
308         }
309         if (excludedPackages != null && excludedPackages.length > 0) {
310             pw.print(prefix); pw.print("excludedPackages=");
311             pw.print(Arrays.toString(excludedPackages));
312         }
313         if (options != null) {
314             pw.print(prefix); pw.print("options="); pw.println(options.toBundle());
315         }
316         pw.print(prefix); pw.print("enqueueClockTime=");
317                 pw.print(sdf.format(new Date(enqueueClockTime)));
318                 pw.print(" dispatchClockTime=");
319                 pw.print(sdf.format(new Date(dispatchClockTime)));
320         if (originalEnqueueClockTime > 0) {
321             pw.print(" originalEnqueueClockTime=");
322             pw.print(sdf.format(new Date(originalEnqueueClockTime)));
323         }
324         pw.println();
325         pw.print(prefix); pw.print("dispatchTime=");
326                 TimeUtils.formatDuration(dispatchTime, now, pw);
327                 pw.print(" (");
328                 TimeUtils.formatDuration(dispatchTime - enqueueTime, pw);
329                 pw.print(" since enq)");
330         if (finishTime != 0) {
331             pw.print(" finishTime="); TimeUtils.formatDuration(finishTime, now, pw);
332             pw.print(" (");
333             TimeUtils.formatDuration(finishTime-dispatchTime, pw);
334             pw.print(" since disp)");
335         } else {
336             pw.print(" receiverTime="); TimeUtils.formatDuration(receiverTime, now, pw);
337         }
338         pw.println("");
339         if (anrCount != 0) {
340             pw.print(prefix); pw.print("anrCount="); pw.println(anrCount);
341         }
342         if (resultTo != null || resultCode != -1 || resultData != null) {
343             pw.print(prefix); pw.print("resultTo="); pw.print(resultTo);
344                     pw.print(" resultCode="); pw.print(resultCode);
345                     pw.print(" resultData="); pw.println(resultData);
346         }
347         if (resultExtras != null) {
348             pw.print(prefix); pw.print("resultExtras="); pw.println(resultExtras);
349         }
350         if (resultAbort || ordered || sticky || initialSticky) {
351             pw.print(prefix); pw.print("resultAbort="); pw.print(resultAbort);
352                     pw.print(" ordered="); pw.print(ordered);
353                     pw.print(" sticky="); pw.print(sticky);
354                     pw.print(" initialSticky="); pw.print(initialSticky);
355                     pw.print(" originalStickyCallingUid="); pw.println(originalStickyCallingUid);
356         }
357         if (nextReceiver != 0) {
358             pw.print(prefix); pw.print("nextReceiver="); pw.println(nextReceiver);
359         }
360         if (curFilter != null) {
361             pw.print(prefix); pw.print("curFilter="); pw.println(curFilter);
362         }
363         if (curReceiver != null) {
364             pw.print(prefix); pw.print("curReceiver="); pw.println(curReceiver);
365         }
366         if (curApp != null) {
367             pw.print(prefix); pw.print("curApp="); pw.println(curApp);
368             pw.print(prefix); pw.print("curComponent=");
369                     pw.println((curComponent != null ? curComponent.toShortString() : "--"));
370             if (curReceiver != null && curReceiver.applicationInfo != null) {
371                 pw.print(prefix); pw.print("curSourceDir=");
372                         pw.println(curReceiver.applicationInfo.sourceDir);
373             }
374         }
375         if (curFilteredExtras != null) {
376             pw.print(" filtered extras: "); pw.println(curFilteredExtras);
377         }
378         if (state != IDLE) {
379             String stateStr = " (?)";
380             switch (state) {
381                 case APP_RECEIVE:       stateStr=" (APP_RECEIVE)"; break;
382                 case CALL_IN_RECEIVE:   stateStr=" (CALL_IN_RECEIVE)"; break;
383                 case CALL_DONE_RECEIVE: stateStr=" (CALL_DONE_RECEIVE)"; break;
384                 case WAITING_SERVICES:  stateStr=" (WAITING_SERVICES)"; break;
385             }
386             pw.print(prefix); pw.print("state="); pw.print(state); pw.println(stateStr);
387         }
388         pw.print(prefix); pw.print("terminalCount="); pw.println(terminalCount);
389         final int N = receivers != null ? receivers.size() : 0;
390         String p2 = prefix + "  ";
391         PrintWriterPrinter printer = new PrintWriterPrinter(pw);
392         for (int i = 0; i < N; i++) {
393             Object o = receivers.get(i);
394             pw.print(prefix);
395             pw.print(deliveryStateToString(delivery[i]));
396             pw.print(' ');
397             if (scheduledTime[i] != 0) {
398                 pw.print("scheduled ");
399                 TimeUtils.formatDuration(scheduledTime[i] - enqueueTime, pw);
400                 pw.print(' ');
401             }
402             if (terminalTime[i] != 0) {
403                 pw.print("terminal ");
404                 TimeUtils.formatDuration(terminalTime[i] - scheduledTime[i], pw);
405                 pw.print(' ');
406             }
407             pw.print("("); pw.print(blockedUntilBeyondCount[i]); pw.print(") ");
408             pw.print("#"); pw.print(i); pw.print(": ");
409             if (o instanceof BroadcastFilter) {
410                 pw.println(o);
411                 ((BroadcastFilter) o).dumpBrief(pw, p2);
412             } else if (o instanceof ResolveInfo) {
413                 pw.println("(manifest)");
414                 ((ResolveInfo) o).dump(printer, p2, 0);
415             } else {
416                 pw.println(o);
417             }
418             if (deliveryReasons[i] != null) {
419                 pw.print(p2); pw.print("reason: "); pw.println(deliveryReasons[i]);
420             }
421         }
422     }
423 
BroadcastRecord(BroadcastQueue queue, Intent intent, ProcessRecord callerApp, String callerPackage, @Nullable String callerFeatureId, int callingPid, int callingUid, boolean callerInstantApp, String resolvedType, String[] requiredPermissions, String[] excludedPermissions, String[] excludedPackages, int appOp, BroadcastOptions options, List receivers, ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, boolean serialized, boolean sticky, boolean initialSticky, int userId, @NonNull BackgroundStartPrivileges backgroundStartPrivileges, boolean timeoutExempt, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, int callerAppProcessState)424     BroadcastRecord(BroadcastQueue queue,
425             Intent intent, ProcessRecord callerApp, String callerPackage,
426             @Nullable String callerFeatureId, int callingPid, int callingUid,
427             boolean callerInstantApp, String resolvedType,
428             String[] requiredPermissions, String[] excludedPermissions,
429             String[] excludedPackages, int appOp,
430             BroadcastOptions options, List receivers,
431             ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode,
432             String resultData, Bundle resultExtras, boolean serialized, boolean sticky,
433             boolean initialSticky, int userId,
434             @NonNull BackgroundStartPrivileges backgroundStartPrivileges,
435             boolean timeoutExempt,
436             @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver,
437             int callerAppProcessState) {
438         this(queue, intent, callerApp, callerPackage, callerFeatureId, callingPid,
439                 callingUid, callerInstantApp, resolvedType, requiredPermissions,
440                 excludedPermissions, excludedPackages, appOp, options, receivers, resultToApp,
441                 resultTo, resultCode, resultData, resultExtras, serialized, sticky,
442                 initialSticky, userId, -1, backgroundStartPrivileges, timeoutExempt,
443                 filterExtrasForReceiver, callerAppProcessState);
444     }
445 
BroadcastRecord(BroadcastQueue _queue, Intent _intent, ProcessRecord _callerApp, String _callerPackage, @Nullable String _callerFeatureId, int _callingPid, int _callingUid, boolean _callerInstantApp, String _resolvedType, String[] _requiredPermissions, String[] _excludedPermissions, String[] _excludedPackages, int _appOp, BroadcastOptions _options, List _receivers, ProcessRecord _resultToApp, IIntentReceiver _resultTo, int _resultCode, String _resultData, Bundle _resultExtras, boolean _serialized, boolean _sticky, boolean _initialSticky, int _userId, int originalStickyCallingUid, @NonNull BackgroundStartPrivileges backgroundStartPrivileges, boolean timeoutExempt, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, int callerAppProcessState)446     BroadcastRecord(BroadcastQueue _queue,
447             Intent _intent, ProcessRecord _callerApp, String _callerPackage,
448             @Nullable String _callerFeatureId, int _callingPid, int _callingUid,
449             boolean _callerInstantApp, String _resolvedType,
450             String[] _requiredPermissions, String[] _excludedPermissions,
451             String[] _excludedPackages, int _appOp,
452             BroadcastOptions _options, List _receivers,
453             ProcessRecord _resultToApp, IIntentReceiver _resultTo, int _resultCode,
454             String _resultData, Bundle _resultExtras, boolean _serialized, boolean _sticky,
455             boolean _initialSticky, int _userId, int originalStickyCallingUid,
456             @NonNull BackgroundStartPrivileges backgroundStartPrivileges,
457             boolean timeoutExempt,
458             @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver,
459             int callerAppProcessState) {
460         if (_intent == null) {
461             throw new NullPointerException("Can't construct with a null intent");
462         }
463         queue = _queue;
464         intent = Objects.requireNonNull(_intent);
465         targetComp = _intent.getComponent();
466         callerApp = _callerApp;
467         callerPackage = _callerPackage;
468         callerFeatureId = _callerFeatureId;
469         callingPid = _callingPid;
470         callingUid = _callingUid;
471         callerProcState = callerAppProcessState;
472         callerInstantApp = _callerInstantApp;
473         callerInstrumented = isCallerInstrumented(_callerApp, _callingUid);
474         resolvedType = _resolvedType;
475         requiredPermissions = _requiredPermissions;
476         excludedPermissions = _excludedPermissions;
477         excludedPackages = _excludedPackages;
478         appOp = _appOp;
479         options = _options;
480         receivers = (_receivers != null) ? _receivers : EMPTY_RECEIVERS;
481         delivery = new int[_receivers != null ? _receivers.size() : 0];
482         deliveryReasons = new String[delivery.length];
483         urgent = calculateUrgent(_intent, _options);
484         deferUntilActive = calculateDeferUntilActive(_callingUid,
485                 _options, _resultTo, _serialized, urgent);
486         blockedUntilBeyondCount = calculateBlockedUntilBeyondCount(receivers, _serialized);
487         scheduledTime = new long[delivery.length];
488         terminalTime = new long[delivery.length];
489         resultToApp = _resultToApp;
490         resultTo = _resultTo;
491         resultCode = _resultCode;
492         resultData = _resultData;
493         resultExtras = _resultExtras;
494         ordered = _serialized;
495         sticky = _sticky;
496         initialSticky = _initialSticky;
497         prioritized = isPrioritized(blockedUntilBeyondCount, _serialized);
498         userId = _userId;
499         nextReceiver = 0;
500         state = IDLE;
501         mBackgroundStartPrivileges = backgroundStartPrivileges;
502         this.timeoutExempt = timeoutExempt;
503         alarm = options != null && options.isAlarmBroadcast();
504         pushMessage = options != null && options.isPushMessagingBroadcast();
505         pushMessageOverQuota = options != null && options.isPushMessagingOverQuotaBroadcast();
506         interactive = options != null && options.isInteractive();
507         shareIdentity = options != null && options.isShareIdentityEnabled();
508         this.filterExtrasForReceiver = filterExtrasForReceiver;
509         this.originalStickyCallingUid = originalStickyCallingUid;
510     }
511 
512     /**
513      * Copy constructor which takes a different intent.
514      * Only used by {@link #maybeStripForHistory}.
515      */
BroadcastRecord(BroadcastRecord from, Intent newIntent)516     private BroadcastRecord(BroadcastRecord from, Intent newIntent) {
517         intent = Objects.requireNonNull(newIntent);
518         targetComp = newIntent.getComponent();
519 
520         callerApp = from.callerApp;
521         callerPackage = from.callerPackage;
522         callerFeatureId = from.callerFeatureId;
523         callingPid = from.callingPid;
524         callingUid = from.callingUid;
525         callerProcState = from.callerProcState;
526         callerInstantApp = from.callerInstantApp;
527         callerInstrumented = from.callerInstrumented;
528         ordered = from.ordered;
529         sticky = from.sticky;
530         initialSticky = from.initialSticky;
531         prioritized = from.prioritized;
532         userId = from.userId;
533         resolvedType = from.resolvedType;
534         requiredPermissions = from.requiredPermissions;
535         excludedPermissions = from.excludedPermissions;
536         excludedPackages = from.excludedPackages;
537         appOp = from.appOp;
538         options = from.options;
539         receivers = from.receivers;
540         delivery = from.delivery;
541         deliveryReasons = from.deliveryReasons;
542         deferUntilActive = from.deferUntilActive;
543         blockedUntilBeyondCount = from.blockedUntilBeyondCount;
544         scheduledTime = from.scheduledTime;
545         terminalTime = from.terminalTime;
546         resultToApp = from.resultToApp;
547         resultTo = from.resultTo;
548         enqueueTime = from.enqueueTime;
549         enqueueRealTime = from.enqueueRealTime;
550         enqueueClockTime = from.enqueueClockTime;
551         dispatchTime = from.dispatchTime;
552         dispatchRealTime = from.dispatchRealTime;
553         dispatchClockTime = from.dispatchClockTime;
554         receiverTime = from.receiverTime;
555         finishTime = from.finishTime;
556         resultCode = from.resultCode;
557         resultData = from.resultData;
558         resultExtras = from.resultExtras;
559         resultAbort = from.resultAbort;
560         nextReceiver = from.nextReceiver;
561         state = from.state;
562         anrCount = from.anrCount;
563         manifestCount = from.manifestCount;
564         manifestSkipCount = from.manifestSkipCount;
565         queue = from.queue;
566         mBackgroundStartPrivileges = from.mBackgroundStartPrivileges;
567         timeoutExempt = from.timeoutExempt;
568         alarm = from.alarm;
569         pushMessage = from.pushMessage;
570         pushMessageOverQuota = from.pushMessageOverQuota;
571         interactive = from.interactive;
572         shareIdentity = from.shareIdentity;
573         urgent = from.urgent;
574         filterExtrasForReceiver = from.filterExtrasForReceiver;
575         originalStickyCallingUid = from.originalStickyCallingUid;
576     }
577 
578     /**
579      * Split off a new BroadcastRecord that clones this one, but contains only the
580      * recipient records for the current (just-finished) receiver's app, starting
581      * after the just-finished receiver [i.e. at r.nextReceiver].  Returns null
582      * if there are no matching subsequent receivers in this BroadcastRecord.
583      */
splitRecipientsLocked(int slowAppUid, int startingAt)584     BroadcastRecord splitRecipientsLocked(int slowAppUid, int startingAt) {
585         // Do we actually have any matching receivers down the line...?
586         ArrayList splitReceivers = null;
587         for (int i = startingAt; i < receivers.size(); ) {
588             Object o = receivers.get(i);
589             if (getReceiverUid(o) == slowAppUid) {
590                 if (splitReceivers == null) {
591                     splitReceivers = new ArrayList<>();
592                 }
593                 splitReceivers.add(o);
594                 receivers.remove(i);
595             } else {
596                 i++;
597             }
598         }
599 
600         // No later receivers in the same app, so we have no more to do
601         if (splitReceivers == null) {
602             return null;
603         }
604 
605         // build a new BroadcastRecord around that single-target list
606         BroadcastRecord split = new BroadcastRecord(queue, intent, callerApp, callerPackage,
607                 callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
608                 requiredPermissions, excludedPermissions, excludedPackages, appOp, options,
609                 splitReceivers, resultToApp, resultTo, resultCode, resultData, resultExtras,
610                 ordered, sticky, initialSticky, userId,
611                 mBackgroundStartPrivileges, timeoutExempt, filterExtrasForReceiver,
612                 callerProcState);
613         split.enqueueTime = this.enqueueTime;
614         split.enqueueRealTime = this.enqueueRealTime;
615         split.enqueueClockTime = this.enqueueClockTime;
616         split.splitToken = this.splitToken;
617         return split;
618     }
619 
620     /**
621      * Split a BroadcastRecord to a map of deferred receiver UID to deferred BroadcastRecord.
622      *
623      * The receivers that are deferred are removed from original BroadcastRecord's receivers list.
624      * The receivers that are not deferred are kept in original BroadcastRecord's receivers list.
625      *
626      * Only used to split LOCKED_BOOT_COMPLETED or BOOT_COMPLETED BroadcastRecord.
627      * LOCKED_BOOT_COMPLETED or BOOT_COMPLETED broadcast can be deferred until the first time
628      * the receiver's UID has a process started.
629      *
630      * @param ams The ActivityManagerService object.
631      * @param deferType Defer what UID?
632      * @return the deferred UID to BroadcastRecord map, the BroadcastRecord has the list of
633      *         receivers in that UID.
634      */
splitDeferredBootCompletedBroadcastLocked( ActivityManagerInternal activityManagerInternal, @BroadcastConstants.DeferBootCompletedBroadcastType int deferType)635     @NonNull SparseArray<BroadcastRecord> splitDeferredBootCompletedBroadcastLocked(
636             ActivityManagerInternal activityManagerInternal,
637             @BroadcastConstants.DeferBootCompletedBroadcastType int deferType) {
638         final SparseArray<BroadcastRecord> ret = new SparseArray<>();
639         if (deferType == DEFER_BOOT_COMPLETED_BROADCAST_NONE) {
640             return ret;
641         }
642 
643         if (receivers == null) {
644             return ret;
645         }
646 
647         final String action = intent.getAction();
648         if (!Intent.ACTION_LOCKED_BOOT_COMPLETED.equals(action)
649                 && !Intent.ACTION_BOOT_COMPLETED.equals(action)) {
650             return ret;
651         }
652 
653         final SparseArray<List<Object>> uid2receiverList = new SparseArray<>();
654         for (int i = receivers.size() - 1; i >= 0; i--) {
655             final Object receiver = receivers.get(i);
656             final int uid = getReceiverUid(receiver);
657             if (deferType != DEFER_BOOT_COMPLETED_BROADCAST_ALL) {
658                 if ((deferType & DEFER_BOOT_COMPLETED_BROADCAST_BACKGROUND_RESTRICTED_ONLY) != 0) {
659                     if (activityManagerInternal.getRestrictionLevel(uid)
660                             < RESTRICTION_LEVEL_BACKGROUND_RESTRICTED) {
661                         // skip if the UID is not background restricted.
662                         continue;
663                     }
664                 }
665                 if ((deferType & DEFER_BOOT_COMPLETED_BROADCAST_TARGET_T_ONLY) != 0) {
666                     if (!CompatChanges.isChangeEnabled(DEFER_BOOT_COMPLETED_BROADCAST_CHANGE_ID,
667                             uid)) {
668                         // skip if the UID is not targetSdkVersion T+.
669                         continue;
670                     }
671                 }
672             }
673             // Remove receiver from original BroadcastRecord's receivers list.
674             receivers.remove(i);
675             final List<Object> receiverList = uid2receiverList.get(uid);
676             if (receiverList != null) {
677                 receiverList.add(0, receiver);
678             } else {
679                 ArrayList<Object> splitReceivers = new ArrayList<>();
680                 splitReceivers.add(0, receiver);
681                 uid2receiverList.put(uid, splitReceivers);
682             }
683         }
684         final int uidSize = uid2receiverList.size();
685         for (int i = 0; i < uidSize; i++) {
686             final BroadcastRecord br = new BroadcastRecord(queue, intent, callerApp, callerPackage,
687                     callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
688                     requiredPermissions, excludedPermissions, excludedPackages, appOp, options,
689                     uid2receiverList.valueAt(i), null /* _resultToApp */, null /* _resultTo */,
690                     resultCode, resultData, resultExtras, ordered, sticky, initialSticky, userId,
691                     mBackgroundStartPrivileges, timeoutExempt,
692                     filterExtrasForReceiver, callerProcState);
693             br.enqueueTime = this.enqueueTime;
694             br.enqueueRealTime = this.enqueueRealTime;
695             br.enqueueClockTime = this.enqueueClockTime;
696             ret.put(uid2receiverList.keyAt(i), br);
697         }
698         return ret;
699     }
700 
701     /**
702      * Update the delivery state of the given {@link #receivers} index.
703      * Automatically updates any time measurements related to state changes.
704      *
705      * @return if {@link #beyondCount} changed due to this state transition,
706      *         indicating that other events may be unblocked.
707      */
708     @CheckResult
setDeliveryState(int index, @DeliveryState int newDeliveryState, @NonNull String reason)709     boolean setDeliveryState(int index, @DeliveryState int newDeliveryState,
710             @NonNull String reason) {
711         final int oldDeliveryState = delivery[index];
712         if (isDeliveryStateTerminal(oldDeliveryState)
713                 || newDeliveryState == oldDeliveryState) {
714             // We've already arrived in terminal or requested state, so leave
715             // any statistics and reasons intact from the first transition
716             return false;
717         }
718 
719         switch (oldDeliveryState) {
720             case DELIVERY_DEFERRED:
721                 deferredCount--;
722                 break;
723         }
724         switch (newDeliveryState) {
725             case DELIVERY_PENDING:
726                 scheduledTime[index] = 0;
727                 break;
728             case DELIVERY_SCHEDULED:
729                 scheduledTime[index] = SystemClock.uptimeMillis();
730                 break;
731             case DELIVERY_DEFERRED:
732                 deferredCount++;
733                 break;
734             case DELIVERY_DELIVERED:
735             case DELIVERY_SKIPPED:
736             case DELIVERY_TIMEOUT:
737             case DELIVERY_FAILURE:
738                 terminalTime[index] = SystemClock.uptimeMillis();
739                 terminalCount++;
740                 break;
741         }
742 
743         delivery[index] = newDeliveryState;
744         deliveryReasons[index] = reason;
745 
746         // If this state change might bring us to a new high-water mark, bring
747         // ourselves as high as we possibly can
748         final int oldBeyondCount = beyondCount;
749         if (index >= beyondCount) {
750             for (int i = beyondCount; i < delivery.length; i++) {
751                 if (isDeliveryStateBeyond(getDeliveryState(i))) {
752                     beyondCount = i + 1;
753                 } else {
754                     break;
755                 }
756             }
757         }
758         return (beyondCount != oldBeyondCount);
759     }
760 
getDeliveryState(int index)761     @DeliveryState int getDeliveryState(int index) {
762         return delivery[index];
763     }
764 
765     /**
766      * @return if the given {@link #receivers} index should be considered
767      *         blocked based on the current status of the overall broadcast.
768      */
isBlocked(int index)769     boolean isBlocked(int index) {
770         return (beyondCount < blockedUntilBeyondCount[index]);
771     }
772 
wasDeliveryAttempted(int index)773     boolean wasDeliveryAttempted(int index) {
774         final int deliveryState = getDeliveryState(index);
775         switch (deliveryState) {
776             case DELIVERY_DELIVERED:
777             case DELIVERY_TIMEOUT:
778             case DELIVERY_FAILURE:
779                 return true;
780             default:
781                 return false;
782         }
783     }
784 
copyEnqueueTimeFrom(@onNull BroadcastRecord replacedBroadcast)785     void copyEnqueueTimeFrom(@NonNull BroadcastRecord replacedBroadcast) {
786         originalEnqueueClockTime = enqueueClockTime;
787         enqueueTime = replacedBroadcast.enqueueTime;
788         enqueueRealTime = replacedBroadcast.enqueueRealTime;
789         enqueueClockTime = replacedBroadcast.enqueueClockTime;
790     }
791 
isForeground()792     boolean isForeground() {
793         return (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
794     }
795 
isReplacePending()796     boolean isReplacePending() {
797         return (intent.getFlags() & Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
798     }
799 
isNoAbort()800     boolean isNoAbort() {
801         return (intent.getFlags() & Intent.FLAG_RECEIVER_NO_ABORT) != 0;
802     }
803 
isOffload()804     boolean isOffload() {
805         return (intent.getFlags() & Intent.FLAG_RECEIVER_OFFLOAD) != 0;
806     }
807 
isDeferUntilActive()808     boolean isDeferUntilActive() {
809         return deferUntilActive;
810     }
811 
isUrgent()812     boolean isUrgent() {
813         return urgent;
814     }
815 
getHostingRecordTriggerType()816     @NonNull String getHostingRecordTriggerType() {
817         if (alarm) {
818             return HostingRecord.TRIGGER_TYPE_ALARM;
819         } else if (pushMessage) {
820             return HostingRecord.TRIGGER_TYPE_PUSH_MESSAGE;
821         } else if (pushMessageOverQuota) {
822             return HostingRecord.TRIGGER_TYPE_PUSH_MESSAGE_OVER_QUOTA;
823         }
824         return HostingRecord.TRIGGER_TYPE_UNKNOWN;
825     }
826 
827     /**
828      * Return an instance of {@link #intent} specialized for the given receiver.
829      * For example, this returns a new specialized instance if the extras need
830      * to be filtered, or a {@link ResolveInfo} needs to be configured.
831      *
832      * @return a specialized intent, otherwise {@code null} to indicate that the
833      *         broadcast should not be delivered to this receiver, typically due
834      *         to it being filtered away by {@link #filterExtrasForReceiver}.
835      */
getReceiverIntent(@onNull Object receiver)836     @Nullable Intent getReceiverIntent(@NonNull Object receiver) {
837         Intent newIntent = null;
838         if (filterExtrasForReceiver != null) {
839             final Bundle extras = intent.getExtras();
840             if (extras != null) {
841                 final int receiverUid = getReceiverUid(receiver);
842                 final Bundle filteredExtras = filterExtrasForReceiver.apply(receiverUid, extras);
843                 if (filteredExtras == null) {
844                     // Completely filtered; skip the broadcast!
845                     return null;
846                 } else {
847                     newIntent = new Intent(intent);
848                     newIntent.replaceExtras(filteredExtras);
849                 }
850             }
851         }
852         if (receiver instanceof ResolveInfo) {
853             if (newIntent == null) {
854                 newIntent = new Intent(intent);
855             }
856             newIntent.setComponent(((ResolveInfo) receiver).activityInfo.getComponentName());
857         }
858         return (newIntent != null) ? newIntent : intent;
859     }
860 
isCallerInstrumented(@ullable ProcessRecord callerApp, int callingUid)861     static boolean isCallerInstrumented(@Nullable ProcessRecord callerApp, int callingUid) {
862         switch (UserHandle.getAppId(callingUid)) {
863             case android.os.Process.ROOT_UID:
864             case android.os.Process.SHELL_UID:
865                 // Broadcasts sent via "shell" are typically invoked by test
866                 // suites, so we treat them as if the caller was instrumented
867                 return true;
868         }
869         return (callerApp != null) ? (callerApp.getActiveInstrumentation() != null) : false;
870     }
871 
872     /**
873      * Determine if the result of {@link #calculateBlockedUntilTerminalCount}
874      * has prioritized tranches of receivers.
875      */
876     @VisibleForTesting
isPrioritized(@onNull int[] blockedUntilBeyondCount, boolean ordered)877     static boolean isPrioritized(@NonNull int[] blockedUntilBeyondCount,
878             boolean ordered) {
879         return !ordered && (blockedUntilBeyondCount.length > 0)
880                 && (blockedUntilBeyondCount[0] != -1);
881     }
882 
883     /**
884      * Calculate the {@link #beyondCount} that each receiver should be
885      * considered blocked until.
886      * <p>
887      * For example, in an ordered broadcast, receiver {@code N} is blocked until
888      * receiver {@code N-1} reaches a terminal or deferred state. Similarly, in
889      * a prioritized broadcast, receiver {@code N} is blocked until all
890      * receivers of a higher priority reach a terminal or deferred state.
891      * <p>
892      * When there are no beyond count constraints, the blocked value for each
893      * receiver is {@code -1}.
894      */
895     @VisibleForTesting
calculateBlockedUntilBeyondCount( @onNull List<Object> receivers, boolean ordered)896     static @NonNull int[] calculateBlockedUntilBeyondCount(
897             @NonNull List<Object> receivers, boolean ordered) {
898         final int N = receivers.size();
899         final int[] blockedUntilBeyondCount = new int[N];
900         int lastPriority = 0;
901         int lastPriorityIndex = 0;
902         for (int i = 0; i < N; i++) {
903             if (ordered) {
904                 // When sending an ordered broadcast, we need to block this
905                 // receiver until all previous receivers have terminated
906                 blockedUntilBeyondCount[i] = i;
907             } else {
908                 // When sending a prioritized broadcast, we only need to wait
909                 // for the previous tranche of receivers to be terminated
910                 final int thisPriority = getReceiverPriority(receivers.get(i));
911                 if ((i == 0) || (thisPriority != lastPriority)) {
912                     lastPriority = thisPriority;
913                     lastPriorityIndex = i;
914                     blockedUntilBeyondCount[i] = i;
915                 } else {
916                     blockedUntilBeyondCount[i] = lastPriorityIndex;
917                 }
918             }
919         }
920         // If the entire list is in the same priority tranche, mark as -1 to
921         // indicate that none of them need to wait
922         if (N > 0 && blockedUntilBeyondCount[N - 1] == 0) {
923             Arrays.fill(blockedUntilBeyondCount, -1);
924         }
925         return blockedUntilBeyondCount;
926     }
927 
getReceiverUid(@onNull Object receiver)928     static int getReceiverUid(@NonNull Object receiver) {
929         if (receiver instanceof BroadcastFilter) {
930             return ((BroadcastFilter) receiver).owningUid;
931         } else /* if (receiver instanceof ResolveInfo) */ {
932             return ((ResolveInfo) receiver).activityInfo.applicationInfo.uid;
933         }
934     }
935 
getReceiverProcessName(@onNull Object receiver)936     static @NonNull String getReceiverProcessName(@NonNull Object receiver) {
937         if (receiver instanceof BroadcastFilter) {
938             return ((BroadcastFilter) receiver).receiverList.app.processName;
939         } else /* if (receiver instanceof ResolveInfo) */ {
940             return ((ResolveInfo) receiver).activityInfo.processName;
941         }
942     }
943 
getReceiverPackageName(@onNull Object receiver)944     static @NonNull String getReceiverPackageName(@NonNull Object receiver) {
945         if (receiver instanceof BroadcastFilter) {
946             return ((BroadcastFilter) receiver).receiverList.app.info.packageName;
947         } else /* if (receiver instanceof ResolveInfo) */ {
948             return ((ResolveInfo) receiver).activityInfo.packageName;
949         }
950     }
951 
getReceiverClassName(@onNull Object receiver)952     static @Nullable String getReceiverClassName(@NonNull Object receiver) {
953         if (receiver instanceof BroadcastFilter) {
954             return ((BroadcastFilter) receiver).getReceiverClassName();
955         } else /* if (receiver instanceof ResolveInfo) */ {
956             return ((ResolveInfo) receiver).activityInfo.name;
957         }
958     }
959 
getReceiverPriority(@onNull Object receiver)960     static int getReceiverPriority(@NonNull Object receiver) {
961         if (receiver instanceof BroadcastFilter) {
962             return ((BroadcastFilter) receiver).getPriority();
963         } else /* if (receiver instanceof ResolveInfo) */ {
964             return ((ResolveInfo) receiver).priority;
965         }
966     }
967 
isReceiverEquals(@onNull Object a, @NonNull Object b)968     static boolean isReceiverEquals(@NonNull Object a, @NonNull Object b) {
969         if (a == b) {
970             return true;
971         } else if (a instanceof ResolveInfo && b instanceof ResolveInfo) {
972             final ResolveInfo infoA = (ResolveInfo) a;
973             final ResolveInfo infoB = (ResolveInfo) b;
974             return Objects.equals(infoA.activityInfo.packageName, infoB.activityInfo.packageName)
975                     && Objects.equals(infoA.activityInfo.name, infoB.activityInfo.name);
976         } else {
977             return false;
978         }
979     }
980 
981     /**
982      * Core policy determination about this broadcast's delivery prioritization
983      */
984     @VisibleForTesting
calculateUrgent(@onNull Intent intent, @Nullable BroadcastOptions options)985     static boolean calculateUrgent(@NonNull Intent intent, @Nullable BroadcastOptions options) {
986         // TODO: flags for controlling policy
987         // TODO: migrate alarm-prioritization flag to BroadcastConstants
988         if ((intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0) {
989             return true;
990         }
991         if (options != null) {
992             if (options.isInteractive()) {
993                 return true;
994             }
995             if (options.isAlarmBroadcast()) {
996                 return true;
997             }
998         }
999         return false;
1000     }
1001 
1002     /**
1003      * Resolve the requested {@link BroadcastOptions#setDeferralPolicy(int)}
1004      * against this broadcast state to determine if it should be marked as
1005      * "defer until active".
1006      */
1007     @VisibleForTesting
calculateDeferUntilActive(int callingUid, @Nullable BroadcastOptions options, @Nullable IIntentReceiver resultTo, boolean ordered, boolean urgent)1008     static boolean calculateDeferUntilActive(int callingUid, @Nullable BroadcastOptions options,
1009             @Nullable IIntentReceiver resultTo, boolean ordered, boolean urgent) {
1010         // Ordered broadcasts can never be deferred until active
1011         if (ordered) {
1012             return false;
1013         }
1014 
1015         // Unordered resultTo broadcasts are always deferred until active
1016         if (!ordered && resultTo != null) {
1017             return true;
1018         }
1019 
1020         // Determine if a strong preference in either direction was expressed;
1021         // a preference here overrides all remaining policies
1022         if (options != null) {
1023             switch (options.getDeferralPolicy()) {
1024                 case BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE:
1025                     return true;
1026                 case BroadcastOptions.DEFERRAL_POLICY_NONE:
1027                     return false;
1028             }
1029         }
1030 
1031         // Urgent broadcasts aren't deferred until active
1032         if (urgent) {
1033             return false;
1034         }
1035 
1036         // Otherwise, choose a reasonable default
1037         if (CORE_DEFER_UNTIL_ACTIVE && UserHandle.isCore(callingUid)) {
1038             return true;
1039         } else {
1040             return false;
1041         }
1042     }
1043 
calculateTypeForLogging()1044     int calculateTypeForLogging() {
1045         int type = BROADCAST_TYPE_NONE;
1046         if (isForeground()) {
1047             type |= BROADCAST_TYPE_FOREGROUND;
1048         } else {
1049             type |= BROADCAST_TYPE_BACKGROUND;
1050         }
1051         if (alarm) {
1052             type |= BROADCAST_TYPE_ALARM;
1053         }
1054         if (interactive) {
1055             type |= BROADCAST_TYPE_INTERACTIVE;
1056         }
1057         if (ordered) {
1058             type |= BROADCAST_TYPE_ORDERED;
1059         }
1060         if (prioritized) {
1061             type |= BROADCAST_TYPE_PRIORITIZED;
1062         }
1063         if (resultTo != null) {
1064             type |= BROADCAST_TYPE_RESULT_TO;
1065         }
1066         if (deferUntilActive) {
1067             type |= BROADCAST_TYPE_DEFERRABLE_UNTIL_ACTIVE;
1068         }
1069         if (pushMessage) {
1070             type |= BROADCAST_TYPE_PUSH_MESSAGE;
1071         }
1072         if (pushMessageOverQuota) {
1073             type |= BROADCAST_TYPE_PUSH_MESSAGE_OVER_QUOTA;
1074         }
1075         if (sticky) {
1076             type |= BROADCAST_TYPE_STICKY;
1077         }
1078         if (initialSticky) {
1079             type |= BROADCAST_TYPE_INITIAL_STICKY;
1080         }
1081         return type;
1082     }
1083 
maybeStripForHistory()1084     public BroadcastRecord maybeStripForHistory() {
1085         if (!intent.canStripForHistory()) {
1086             return this;
1087         }
1088         return new BroadcastRecord(this, intent.maybeStripForHistory());
1089     }
1090 
1091     @VisibleForTesting
cleanupDisabledPackageReceiversLocked( String packageName, Set<String> filterByClasses, int userId, boolean doit)1092     boolean cleanupDisabledPackageReceiversLocked(
1093             String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1094         if (receivers == null) {
1095             return false;
1096         }
1097 
1098         final boolean cleanupAllUsers = userId == UserHandle.USER_ALL;
1099         final boolean sendToAllUsers = this.userId == UserHandle.USER_ALL;
1100         if (this.userId != userId && !cleanupAllUsers && !sendToAllUsers) {
1101             return false;
1102         }
1103 
1104         boolean didSomething = false;
1105         Object o;
1106         for (int i = receivers.size() - 1; i >= 0; i--) {
1107             o = receivers.get(i);
1108             if (!(o instanceof ResolveInfo)) {
1109                 continue;
1110             }
1111             ActivityInfo info = ((ResolveInfo)o).activityInfo;
1112 
1113             final boolean sameComponent = packageName == null
1114                     || (info.applicationInfo.packageName.equals(packageName)
1115                     && (filterByClasses == null || filterByClasses.contains(info.name)));
1116             if (sameComponent && (cleanupAllUsers
1117                     || UserHandle.getUserId(info.applicationInfo.uid) == userId)) {
1118                 if (!doit) {
1119                     return true;
1120                 }
1121                 didSomething = true;
1122                 receivers.remove(i);
1123                 if (i < nextReceiver) {
1124                     nextReceiver--;
1125                 }
1126             }
1127         }
1128         nextReceiver = Math.min(nextReceiver, receivers.size());
1129 
1130         return didSomething;
1131     }
1132 
1133     /**
1134      * Apply special treatment to manifest receivers hosted by a singleton
1135      * process, by re-targeting them at {@link UserHandle#USER_SYSTEM}.
1136      */
applySingletonPolicy(@onNull ActivityManagerService service)1137     void applySingletonPolicy(@NonNull ActivityManagerService service) {
1138         if (receivers == null) return;
1139         for (int i = 0; i < receivers.size(); i++) {
1140             final Object receiver = receivers.get(i);
1141             if (receiver instanceof ResolveInfo) {
1142                 final ResolveInfo info = (ResolveInfo) receiver;
1143                 boolean isSingleton = false;
1144                 try {
1145                     isSingleton = service.isSingleton(info.activityInfo.processName,
1146                             info.activityInfo.applicationInfo,
1147                             info.activityInfo.name, info.activityInfo.flags);
1148                 } catch (SecurityException e) {
1149                     BroadcastQueue.logw(e.getMessage());
1150                 }
1151                 final int receiverUid = info.activityInfo.applicationInfo.uid;
1152                 if (callingUid != android.os.Process.SYSTEM_UID && isSingleton
1153                         && service.isValidSingletonCall(callingUid, receiverUid)) {
1154                     info.activityInfo = service.getActivityInfoForUser(info.activityInfo,
1155                             UserHandle.USER_SYSTEM);
1156                 }
1157             }
1158         }
1159     }
1160 
containsReceiver(@onNull Object receiver)1161     boolean containsReceiver(@NonNull Object receiver) {
1162         for (int i = receivers.size() - 1; i >= 0; --i) {
1163             if (isReceiverEquals(receiver, receivers.get(i))) {
1164                 return true;
1165             }
1166         }
1167         return false;
1168     }
1169 
containsAllReceivers(@onNull List<Object> otherReceivers)1170     boolean containsAllReceivers(@NonNull List<Object> otherReceivers) {
1171         for (int i = otherReceivers.size() - 1; i >= 0; --i) {
1172             if (!containsReceiver(otherReceivers.get(i))) {
1173                 return false;
1174             }
1175         }
1176         return true;
1177     }
1178 
1179     @DeliveryGroupPolicy
getDeliveryGroupPolicy()1180     int getDeliveryGroupPolicy() {
1181         return (options != null) ? options.getDeliveryGroupPolicy()
1182                 : BroadcastOptions.DELIVERY_GROUP_POLICY_ALL;
1183     }
1184 
matchesDeliveryGroup(@onNull BroadcastRecord other)1185     boolean matchesDeliveryGroup(@NonNull BroadcastRecord other) {
1186         return matchesDeliveryGroup(this, other);
1187     }
1188 
matchesDeliveryGroup(@onNull BroadcastRecord newRecord, @NonNull BroadcastRecord oldRecord)1189     private static boolean matchesDeliveryGroup(@NonNull BroadcastRecord newRecord,
1190             @NonNull BroadcastRecord oldRecord) {
1191         final IntentFilter newMatchingFilter = getDeliveryGroupMatchingFilter(newRecord);
1192         // If neither delivery group key nor matching filter is specified, then use
1193         // Intent.filterEquals() to identify the delivery group.
1194         if (isMatchingKeyNull(newRecord) && isMatchingKeyNull(oldRecord)
1195                 && newMatchingFilter == null) {
1196             return newRecord.intent.filterEquals(oldRecord.intent);
1197         }
1198         if (newMatchingFilter != null && !newMatchingFilter.asPredicate().test(oldRecord.intent)) {
1199             return false;
1200         }
1201         return areMatchingKeysEqual(newRecord, oldRecord);
1202     }
1203 
isMatchingKeyNull(@onNull BroadcastRecord record)1204     private static boolean isMatchingKeyNull(@NonNull BroadcastRecord record) {
1205         final String namespace = getDeliveryGroupMatchingNamespaceFragment(record);
1206         final String key = getDeliveryGroupMatchingKeyFragment(record);
1207         // If either namespace or key part is null, then treat the entire matching key as null.
1208         return namespace == null || key == null;
1209     }
1210 
areMatchingKeysEqual(@onNull BroadcastRecord newRecord, @NonNull BroadcastRecord oldRecord)1211     private static boolean areMatchingKeysEqual(@NonNull BroadcastRecord newRecord,
1212             @NonNull BroadcastRecord oldRecord) {
1213         final String newNamespaceFragment = getDeliveryGroupMatchingNamespaceFragment(newRecord);
1214         final String oldNamespaceFragment = getDeliveryGroupMatchingNamespaceFragment(oldRecord);
1215         if (!Objects.equals(newNamespaceFragment, oldNamespaceFragment)) {
1216             return false;
1217         }
1218 
1219         final String newKeyFragment = getDeliveryGroupMatchingKeyFragment(newRecord);
1220         final String oldKeyFragment = getDeliveryGroupMatchingKeyFragment(oldRecord);
1221         return Objects.equals(newKeyFragment, oldKeyFragment);
1222     }
1223 
1224     @Nullable
getDeliveryGroupMatchingNamespaceFragment( @onNull BroadcastRecord record)1225     private static String getDeliveryGroupMatchingNamespaceFragment(
1226             @NonNull BroadcastRecord record) {
1227         return record.options == null
1228                 ? null : record.options.getDeliveryGroupMatchingNamespaceFragment();
1229     }
1230 
1231     @Nullable
getDeliveryGroupMatchingKeyFragment(@onNull BroadcastRecord record)1232     private static String getDeliveryGroupMatchingKeyFragment(@NonNull BroadcastRecord record) {
1233         return record.options == null
1234                 ? null : record.options.getDeliveryGroupMatchingKeyFragment();
1235     }
1236 
1237     @Nullable
getDeliveryGroupMatchingFilter(@onNull BroadcastRecord record)1238     private static IntentFilter getDeliveryGroupMatchingFilter(@NonNull BroadcastRecord record) {
1239         return record.options == null ? null : record.options.getDeliveryGroupMatchingFilter();
1240     }
1241 
1242     /**
1243      * Returns {@code true} if all the receivers are still waiting to receive the broadcast.
1244      * Otherwise {@code false}.
1245      */
allReceiversPending()1246     boolean allReceiversPending() {
1247         // We could also count the number of receivers with deliver state DELIVERY_PENDING, but
1248         // checking how many receivers have finished (either skipped or cancelled) and whether or
1249         // not the dispatch has been started should be sufficient.
1250         return (terminalCount == 0 && dispatchTime <= 0);
1251     }
1252 
1253     @Override
toString()1254     public String toString() {
1255         if (mCachedToString == null) {
1256             String label = intent.getAction();
1257             if (label == null) {
1258                 label = intent.toString();
1259             }
1260             mCachedToString = "BroadcastRecord{" + toShortString() + "}";
1261         }
1262         return mCachedToString;
1263     }
1264 
toShortString()1265     public String toShortString() {
1266         if (mCachedToShortString == null) {
1267             String label = intent.getAction();
1268             if (label == null) {
1269                 label = intent.toString();
1270             }
1271             mCachedToShortString = Integer.toHexString(System.identityHashCode(this))
1272                     + " " + label + "/u" + userId;
1273         }
1274         return mCachedToShortString;
1275     }
1276 
1277     @NeverCompile
dumpDebug(ProtoOutputStream proto, long fieldId)1278     public void dumpDebug(ProtoOutputStream proto, long fieldId) {
1279         long token = proto.start(fieldId);
1280         proto.write(BroadcastRecordProto.USER_ID, userId);
1281         proto.write(BroadcastRecordProto.INTENT_ACTION, intent.getAction());
1282         proto.end(token);
1283     }
1284 }
1285