1 /* 2 * Copyright (C) 2024 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.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST; 20 import static android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND; 21 import static android.Manifest.permission.START_FOREGROUND_SERVICES_FROM_BACKGROUND; 22 import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT; 23 import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY; 24 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL; 25 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_FINISH_RECEIVER; 26 import static android.app.AppOpsManager.OP_NONE; 27 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 28 import static android.os.Process.BLUETOOTH_UID; 29 import static android.os.Process.FIRST_APPLICATION_UID; 30 import static android.os.Process.NETWORK_STACK_UID; 31 import static android.os.Process.NFC_UID; 32 import static android.os.Process.PHONE_UID; 33 import static android.os.Process.ROOT_UID; 34 import static android.os.Process.SE_UID; 35 import static android.os.Process.SHELL_UID; 36 import static android.os.Process.SYSTEM_UID; 37 38 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK; 39 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST; 40 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT; 41 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST; 42 import static com.android.server.am.ActivityManagerService.CLEAR_DNS_CACHE_MSG; 43 import static com.android.server.am.ActivityManagerService.HANDLE_TRUST_STORAGE_UPDATE_MSG; 44 import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS; 45 import static com.android.server.am.ActivityManagerService.TAG; 46 import static com.android.server.am.ActivityManagerService.UPDATE_HTTP_PROXY_MSG; 47 import static com.android.server.am.ActivityManagerService.UPDATE_TIME_PREFERENCE_MSG; 48 import static com.android.server.am.ActivityManagerService.UPDATE_TIME_ZONE; 49 import static com.android.server.am.ActivityManagerService.checkComponentPermission; 50 import static com.android.server.am.BroadcastRecord.debugLog; 51 import static com.android.server.am.BroadcastRecord.intentToString; 52 53 import android.annotation.NonNull; 54 import android.annotation.Nullable; 55 import android.app.Activity; 56 import android.app.ActivityManager; 57 import android.app.AppGlobals; 58 import android.app.ApplicationExitInfo; 59 import android.app.ApplicationThreadConstants; 60 import android.app.BackgroundStartPrivileges; 61 import android.app.BroadcastOptions; 62 import android.app.BroadcastStickyCache; 63 import android.app.IApplicationThread; 64 import android.app.compat.CompatChanges; 65 import android.appwidget.AppWidgetManager; 66 import android.compat.annotation.ChangeId; 67 import android.compat.annotation.EnabledSince; 68 import android.content.ComponentName; 69 import android.content.ContentResolver; 70 import android.content.Context; 71 import android.content.IIntentReceiver; 72 import android.content.Intent; 73 import android.content.IntentFilter; 74 import android.content.pm.ActivityInfo; 75 import android.content.pm.ApplicationInfo; 76 import android.content.pm.IPackageManager; 77 import android.content.pm.PackageManager; 78 import android.content.pm.ResolveInfo; 79 import android.content.pm.UserInfo; 80 import android.media.audiofx.AudioEffect; 81 import android.net.ConnectivityManager; 82 import android.net.Proxy; 83 import android.net.Uri; 84 import android.os.Binder; 85 import android.os.BinderProxy; 86 import android.os.Build; 87 import android.os.Bundle; 88 import android.os.IBinder; 89 import android.os.Message; 90 import android.os.Process; 91 import android.os.RemoteException; 92 import android.os.SystemClock; 93 import android.os.Trace; 94 import android.os.UserHandle; 95 import android.os.UserManager; 96 import android.telephony.TelephonyManager; 97 import android.text.TextUtils; 98 import android.text.style.SuggestionSpan; 99 import android.util.ArrayMap; 100 import android.util.ArraySet; 101 import android.util.EventLog; 102 import android.util.Log; 103 import android.util.PrintWriterPrinter; 104 import android.util.Slog; 105 import android.util.SparseArray; 106 import android.util.TimeUtils; 107 import android.util.proto.ProtoOutputStream; 108 109 import com.android.internal.annotations.GuardedBy; 110 import com.android.internal.annotations.VisibleForTesting; 111 import com.android.server.IntentResolver; 112 import com.android.server.LocalManagerRegistry; 113 import com.android.server.LocalServices; 114 import com.android.server.SystemConfig; 115 import com.android.server.pm.Computer; 116 import com.android.server.pm.SaferIntentUtils; 117 import com.android.server.pm.UserManagerInternal; 118 import com.android.server.pm.snapshot.PackageDataSnapshot; 119 import com.android.server.sdksandbox.SdkSandboxManagerLocal; 120 import com.android.server.utils.Slogf; 121 122 import dalvik.annotation.optimization.NeverCompile; 123 124 import java.io.FileDescriptor; 125 import java.io.PrintWriter; 126 import java.util.ArrayList; 127 import java.util.Arrays; 128 import java.util.HashMap; 129 import java.util.HashSet; 130 import java.util.Iterator; 131 import java.util.List; 132 import java.util.Map; 133 import java.util.function.BiFunction; 134 135 class BroadcastController { 136 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST; 137 138 /** 139 * It is now required for apps to explicitly set either 140 * {@link android.content.Context#RECEIVER_EXPORTED} or 141 * {@link android.content.Context#RECEIVER_NOT_EXPORTED} when registering a receiver for an 142 * unprotected broadcast in code. 143 */ 144 @ChangeId 145 @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE) 146 private static final long DYNAMIC_RECEIVER_EXPLICIT_EXPORT_REQUIRED = 161145287L; 147 148 // Maximum number of receivers an app can register. 149 private static final int MAX_RECEIVERS_ALLOWED_PER_APP = 1000; 150 151 @NonNull 152 private final Context mContext; 153 @NonNull 154 private final ActivityManagerService mService; 155 @NonNull 156 private BroadcastQueue mBroadcastQueue; 157 158 @GuardedBy("mService") 159 BroadcastStats mLastBroadcastStats; 160 161 @GuardedBy("mService") 162 BroadcastStats mCurBroadcastStats; 163 164 /** 165 * Broadcast actions that will always be deliverable to unlaunched/background apps 166 */ 167 @GuardedBy("mService") 168 private ArraySet<String> mBackgroundLaunchBroadcasts; 169 170 /** 171 * State of all active sticky broadcasts per user. Keys are the action of the 172 * sticky Intent, values are an ArrayList of all broadcasted intents with 173 * that action (which should usually be one). The SparseArray is keyed 174 * by the user ID the sticky is for, and can include UserHandle.USER_ALL 175 * for stickies that are sent to all users. 176 */ 177 @GuardedBy("mStickyBroadcasts") 178 final SparseArray<ArrayMap<String, ArrayList<StickyBroadcast>>> mStickyBroadcasts = 179 new SparseArray<>(); 180 181 /** 182 * Keeps track of all IIntentReceivers that have been registered for broadcasts. 183 * Hash keys are the receiver IBinder, hash value is a ReceiverList. 184 */ 185 @GuardedBy("mService") 186 final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>(); 187 188 /** 189 * If {@code false} invalidate the list of {@link android.os.IpcDataCache} present inside the 190 * {@link BroadcastStickyCache} class. 191 * The invalidation is required to start caching of the sticky broadcast in the client side. 192 */ 193 private volatile boolean mAreStickyCachesInvalidated = false; 194 195 /** 196 * Resolver for broadcast intents to registered receivers. 197 * Holds BroadcastFilter (subclass of IntentFilter). 198 */ 199 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver = 200 new IntentResolver<>() { 201 @Override 202 protected boolean allowFilterResult( 203 BroadcastFilter filter, List<BroadcastFilter> dest) { 204 IBinder target = filter.receiverList.receiver.asBinder(); 205 for (int i = dest.size() - 1; i >= 0; i--) { 206 if (dest.get(i).receiverList.receiver.asBinder() == target) { 207 return false; 208 } 209 } 210 return true; 211 } 212 213 @Override 214 protected BroadcastFilter newResult(@NonNull Computer computer, BroadcastFilter filter, 215 int match, int userId, long customFlags) { 216 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL 217 || userId == filter.owningUserId) { 218 return super.newResult(computer, filter, match, userId, customFlags); 219 } 220 return null; 221 } 222 223 @Override 224 protected IntentFilter getIntentFilter(@NonNull BroadcastFilter input) { 225 return input; 226 } 227 228 @Override 229 protected BroadcastFilter[] newArray(int size) { 230 return new BroadcastFilter[size]; 231 } 232 233 @Override 234 protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) { 235 return packageName.equals(filter.packageName); 236 } 237 }; 238 BroadcastController(Context context, ActivityManagerService service, BroadcastQueue queue)239 BroadcastController(Context context, ActivityManagerService service, BroadcastQueue queue) { 240 mContext = context; 241 mService = service; 242 mBroadcastQueue = queue; 243 } 244 setBroadcastQueueForTest(BroadcastQueue broadcastQueue)245 void setBroadcastQueueForTest(BroadcastQueue broadcastQueue) { 246 mBroadcastQueue = broadcastQueue; 247 } 248 registerReceiverWithFeature(IApplicationThread caller, String callerPackage, String callerFeatureId, String receiverId, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)249 Intent registerReceiverWithFeature(IApplicationThread caller, String callerPackage, 250 String callerFeatureId, String receiverId, IIntentReceiver receiver, 251 IntentFilter filter, String permission, int userId, int flags) { 252 traceRegistrationBegin(receiverId, receiver, filter, userId); 253 try { 254 return registerReceiverWithFeatureTraced(caller, callerPackage, callerFeatureId, 255 receiverId, receiver, filter, permission, userId, flags); 256 } finally { 257 traceRegistrationEnd(); 258 } 259 } 260 traceRegistrationBegin(String receiverId, IIntentReceiver receiver, IntentFilter filter, int userId)261 private static void traceRegistrationBegin(String receiverId, IIntentReceiver receiver, 262 IntentFilter filter, int userId) { 263 if (!Flags.traceReceiverRegistration()) { 264 return; 265 } 266 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 267 final StringBuilder sb = new StringBuilder("registerReceiver: "); 268 sb.append(Binder.getCallingUid()); sb.append('/'); 269 sb.append(receiverId == null ? "null" : receiverId); sb.append('/'); 270 sb.append("p:"); sb.append(filter.getPriority()); sb.append('/'); 271 final int actionsCount = filter.safeCountActions(); 272 if (actionsCount > 0) { 273 for (int i = 0; i < actionsCount; ++i) { 274 sb.append(filter.getAction(i)); 275 if (i != actionsCount - 1) sb.append(','); 276 } 277 } else { 278 sb.append("null"); 279 } 280 sb.append('/'); 281 sb.append('u'); sb.append(userId); sb.append('/'); 282 sb.append(receiver == null ? "null" : receiver.asBinder()); 283 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, sb.toString()); 284 } 285 } 286 traceRegistrationEnd()287 private static void traceRegistrationEnd() { 288 if (!Flags.traceReceiverRegistration()) { 289 return; 290 } 291 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 292 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 293 } 294 } 295 registerReceiverWithFeatureTraced(IApplicationThread caller, String callerPackage, String callerFeatureId, String receiverId, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)296 private Intent registerReceiverWithFeatureTraced(IApplicationThread caller, 297 String callerPackage, String callerFeatureId, String receiverId, 298 IIntentReceiver receiver, IntentFilter filter, String permission, 299 int userId, int flags) { 300 mService.enforceNotIsolatedCaller("registerReceiver"); 301 302 if (!mAreStickyCachesInvalidated) { 303 BroadcastStickyCache.invalidateAllCaches(); 304 mAreStickyCachesInvalidated = true; 305 } 306 ArrayList<StickyBroadcast> stickyBroadcasts = null; 307 ProcessRecord callerApp = null; 308 final boolean visibleToInstantApps = 309 (flags & Context.RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0; 310 311 int callingUid; 312 int callingPid; 313 boolean instantApp; 314 synchronized (mService.mProcLock) { 315 callerApp = mService.getRecordForAppLOSP(caller); 316 if (callerApp == null) { 317 Slog.w(TAG, "registerReceiverWithFeature: no app for " + caller); 318 return null; 319 } 320 if (!UserHandle.isCore(callerApp.info.uid) 321 && !callerApp.getPkgList().containsKey(callerPackage)) { 322 throw new SecurityException("Given caller package " + callerPackage 323 + " is not running in process " + callerApp); 324 } 325 callingUid = callerApp.info.uid; 326 callingPid = callerApp.getPid(); 327 328 instantApp = isInstantApp(callerApp, callerPackage, callingUid); 329 } 330 userId = mService.mUserController.handleIncomingUser(callingPid, callingUid, userId, true, 331 ALLOW_FULL_ONLY, "registerReceiver", callerPackage); 332 333 // Warn if system internals are registering for important broadcasts 334 // without also using a priority to ensure they process the event 335 // before normal apps hear about it 336 if (UserHandle.isCore(callingUid)) { 337 final int priority = filter.getPriority(); 338 final boolean systemPriority = (priority >= IntentFilter.SYSTEM_HIGH_PRIORITY) 339 || (priority <= IntentFilter.SYSTEM_LOW_PRIORITY); 340 if (!systemPriority) { 341 final int N = filter.countActions(); 342 for (int i = 0; i < N; i++) { 343 // TODO: expand to additional important broadcasts over time 344 final String action = filter.getAction(i); 345 if (action.startsWith("android.intent.action.USER_") 346 || action.startsWith("android.intent.action.PACKAGE_") 347 || action.startsWith("android.intent.action.UID_") 348 || action.startsWith("android.intent.action.EXTERNAL_") 349 || action.startsWith("android.bluetooth.") 350 || action.equals(Intent.ACTION_SHUTDOWN)) { 351 if (DEBUG_BROADCAST) { 352 Slog.wtf(TAG, 353 "System internals registering for " + filter.toLongString() 354 + " with app priority; this will race with apps!", 355 new Throwable()); 356 } 357 358 // When undefined, assume that system internals need 359 // to hear about the event first; they can use 360 // SYSTEM_LOW_PRIORITY if they need to hear last 361 if (priority == 0) { 362 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 363 } 364 break; 365 } 366 } 367 } 368 } 369 370 Iterator<String> actions = filter.actionsIterator(); 371 if (actions == null) { 372 ArrayList<String> noAction = new ArrayList<String>(1); 373 noAction.add(null); 374 actions = noAction.iterator(); 375 } 376 boolean onlyProtectedBroadcasts = true; 377 378 // Collect stickies of users and check if broadcast is only registered for protected 379 // broadcasts 380 int[] userIds = { UserHandle.USER_ALL, UserHandle.getUserId(callingUid) }; 381 synchronized (mStickyBroadcasts) { 382 while (actions.hasNext()) { 383 String action = actions.next(); 384 for (int id : userIds) { 385 ArrayMap<String, ArrayList<StickyBroadcast>> stickies = 386 mStickyBroadcasts.get(id); 387 if (stickies != null) { 388 ArrayList<StickyBroadcast> broadcasts = stickies.get(action); 389 if (broadcasts != null) { 390 if (stickyBroadcasts == null) { 391 stickyBroadcasts = new ArrayList<>(); 392 } 393 stickyBroadcasts.addAll(broadcasts); 394 } 395 } 396 } 397 if (onlyProtectedBroadcasts) { 398 try { 399 onlyProtectedBroadcasts &= 400 AppGlobals.getPackageManager().isProtectedBroadcast(action); 401 } catch (RemoteException e) { 402 onlyProtectedBroadcasts = false; 403 Slog.w(TAG, "Remote exception", e); 404 } 405 } 406 } 407 } 408 409 if (Process.isSdkSandboxUid(Binder.getCallingUid())) { 410 SdkSandboxManagerLocal sdkSandboxManagerLocal = 411 LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class); 412 if (sdkSandboxManagerLocal == null) { 413 throw new IllegalStateException("SdkSandboxManagerLocal not found when checking" 414 + " whether SDK sandbox uid can register to broadcast receivers."); 415 } 416 if (!sdkSandboxManagerLocal.canRegisterBroadcastReceiver( 417 /*IntentFilter=*/ filter, flags, onlyProtectedBroadcasts)) { 418 throw new SecurityException("SDK sandbox not allowed to register receiver" 419 + " with the given IntentFilter: " + filter.toLongString()); 420 } 421 } 422 423 // If the change is enabled, but neither exported or not exported is set, we need to log 424 // an error so the consumer can know to explicitly set the value for their flag. 425 // If the caller is registering for a sticky broadcast with a null receiver, we won't 426 // require a flag 427 final boolean explicitExportStateDefined = 428 (flags & (Context.RECEIVER_EXPORTED | Context.RECEIVER_NOT_EXPORTED)) != 0; 429 if (((flags & Context.RECEIVER_EXPORTED) != 0) && ( 430 (flags & Context.RECEIVER_NOT_EXPORTED) != 0)) { 431 throw new IllegalArgumentException( 432 "Receiver can't specify both RECEIVER_EXPORTED and RECEIVER_NOT_EXPORTED" 433 + "flag"); 434 } 435 436 // Don't enforce the flag check if we're EITHER registering for only protected 437 // broadcasts, or the receiver is null (a sticky broadcast). Sticky broadcasts should 438 // not be used generally, so we will be marking them as exported by default 439 boolean requireExplicitFlagForDynamicReceivers = CompatChanges.isChangeEnabled( 440 DYNAMIC_RECEIVER_EXPLICIT_EXPORT_REQUIRED, callingUid); 441 442 // A receiver that is visible to instant apps must also be exported. 443 final boolean unexportedReceiverVisibleToInstantApps = 444 ((flags & Context.RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0) && ( 445 (flags & Context.RECEIVER_NOT_EXPORTED) != 0); 446 if (unexportedReceiverVisibleToInstantApps && requireExplicitFlagForDynamicReceivers) { 447 throw new IllegalArgumentException( 448 "Receiver can't specify both RECEIVER_VISIBLE_TO_INSTANT_APPS and " 449 + "RECEIVER_NOT_EXPORTED flag"); 450 } 451 452 if (!onlyProtectedBroadcasts) { 453 if (receiver == null && !explicitExportStateDefined) { 454 // sticky broadcast, no flag specified (flag isn't required) 455 flags |= Context.RECEIVER_EXPORTED; 456 } else if (requireExplicitFlagForDynamicReceivers && !explicitExportStateDefined) { 457 throw new SecurityException( 458 callerPackage + ": One of RECEIVER_EXPORTED or " 459 + "RECEIVER_NOT_EXPORTED should be specified when a receiver " 460 + "isn't being registered exclusively for system broadcasts"); 461 // Assume default behavior-- flag check is not enforced 462 } else if (!requireExplicitFlagForDynamicReceivers && ( 463 (flags & Context.RECEIVER_NOT_EXPORTED) == 0)) { 464 // Change is not enabled, assume exported unless otherwise specified. 465 flags |= Context.RECEIVER_EXPORTED; 466 } 467 } else if ((flags & Context.RECEIVER_NOT_EXPORTED) == 0) { 468 flags |= Context.RECEIVER_EXPORTED; 469 } 470 471 // Dynamic receivers are exported by default for versions prior to T 472 final boolean exported = (flags & Context.RECEIVER_EXPORTED) != 0; 473 474 ArrayList<StickyBroadcast> allSticky = null; 475 if (stickyBroadcasts != null) { 476 final ContentResolver resolver = mContext.getContentResolver(); 477 // Look for any matching sticky broadcasts... 478 for (int i = 0, N = stickyBroadcasts.size(); i < N; i++) { 479 final StickyBroadcast broadcast = stickyBroadcasts.get(i); 480 Intent intent = broadcast.intent; 481 // Don't provided intents that aren't available to instant apps. 482 if (instantApp && (intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) 483 == 0) { 484 continue; 485 } 486 // If intent has scheme "content", it will need to access 487 // provider that needs to lock mProviderMap in ActivityThread 488 // and also it may need to wait application response, so we 489 // cannot lock ActivityManagerService here. 490 final int match; 491 if (Flags.avoidResolvingType()) { 492 match = filter.match(intent.getAction(), broadcast.resolvedDataType, 493 intent.getScheme(), intent.getData(), intent.getCategories(), 494 TAG, false /* supportsWildcards */, null /* ignoreActions */, 495 intent.getExtras()); 496 } else { 497 match = filter.match(resolver, intent, true, TAG); 498 } 499 if (match >= 0) { 500 if (allSticky == null) { 501 allSticky = new ArrayList<>(); 502 } 503 allSticky.add(broadcast); 504 } 505 } 506 } 507 508 // The first sticky in the list is returned directly back to the client. 509 Intent sticky = allSticky != null ? allSticky.get(0).intent : null; 510 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Register receiver " + filter + ": " + sticky); 511 if (receiver == null) { 512 return sticky; 513 } 514 515 // SafetyNet logging for b/177931370. If any process other than system_server tries to 516 // listen to this broadcast action, then log it. 517 if (callingPid != Process.myPid()) { 518 if (filter.hasAction("com.android.server.net.action.SNOOZE_WARNING") 519 || filter.hasAction("com.android.server.net.action.SNOOZE_RAPID")) { 520 EventLog.writeEvent(0x534e4554, "177931370", callingUid, ""); 521 } 522 } 523 524 synchronized (mService) { 525 IApplicationThread thread; 526 if (callerApp != null && ((thread = callerApp.getThread()) == null 527 || thread.asBinder() != caller.asBinder())) { 528 // Original caller already died 529 return null; 530 } 531 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 532 if (rl == null) { 533 rl = new ReceiverList(mService, callerApp, callingPid, callingUid, 534 userId, receiver); 535 if (rl.app != null) { 536 final int totalReceiversForApp = rl.app.mReceivers.numberOfReceivers(); 537 if (totalReceiversForApp >= MAX_RECEIVERS_ALLOWED_PER_APP) { 538 throw new IllegalStateException("Too many receivers, total of " 539 + totalReceiversForApp + ", registered for pid: " 540 + rl.pid + ", callerPackage: " + callerPackage); 541 } 542 rl.app.mReceivers.addReceiver(rl); 543 } else { 544 try { 545 receiver.asBinder().linkToDeath(rl, 0); 546 } catch (RemoteException e) { 547 return sticky; 548 } 549 rl.linkedToDeath = true; 550 } 551 mRegisteredReceivers.put(receiver.asBinder(), rl); 552 } else if (rl.uid != callingUid) { 553 throw new IllegalArgumentException( 554 "Receiver requested to register for uid " + callingUid 555 + " was previously registered for uid " + rl.uid 556 + " callerPackage is " + callerPackage); 557 } else if (rl.pid != callingPid) { 558 throw new IllegalArgumentException( 559 "Receiver requested to register for pid " + callingPid 560 + " was previously registered for pid " + rl.pid 561 + " callerPackage is " + callerPackage); 562 } else if (rl.userId != userId) { 563 throw new IllegalArgumentException( 564 "Receiver requested to register for user " + userId 565 + " was previously registered for user " + rl.userId 566 + " callerPackage is " + callerPackage); 567 } 568 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, callerFeatureId, 569 receiverId, permission, callingUid, userId, instantApp, visibleToInstantApps, 570 exported, callerApp.info, mService.mPlatformCompat); 571 if (rl.containsFilter(filter)) { 572 Slog.w(TAG, "Receiver with filter " + filter 573 + " already registered for pid " + rl.pid 574 + ", callerPackage is " + callerPackage); 575 } else { 576 rl.add(bf); 577 if (!bf.debugCheck()) { 578 Slog.w(TAG, "==> For Dynamic broadcast"); 579 } 580 mReceiverResolver.addFilter(mService.getPackageManagerInternal().snapshot(), bf); 581 } 582 583 // Enqueue broadcasts for all existing stickies that match 584 // this filter. 585 if (allSticky != null) { 586 ArrayList receivers = new ArrayList(); 587 receivers.add(bf); 588 sticky = null; 589 590 final int stickyCount = allSticky.size(); 591 for (int i = 0; i < stickyCount; i++) { 592 final StickyBroadcast broadcast = allSticky.get(i); 593 final int originalStickyCallingUid = allSticky.get(i).originalCallingUid; 594 // TODO(b/281889567): consider using checkComponentPermission instead of 595 // canAccessUnexportedComponents 596 if (sticky == null && (exported || originalStickyCallingUid == callingUid 597 || ActivityManager.canAccessUnexportedComponents( 598 originalStickyCallingUid))) { 599 sticky = broadcast.intent; 600 } 601 BroadcastQueue queue = mBroadcastQueue; 602 BroadcastRecord r = new BroadcastRecord(queue, broadcast.intent, null, 603 null, null, -1, -1, false, null, null, null, null, OP_NONE, 604 BroadcastOptions.makeWithDeferUntilActive(broadcast.deferUntilActive), 605 receivers, null, null, 0, null, null, false, true, true, -1, 606 originalStickyCallingUid, BackgroundStartPrivileges.NONE, 607 false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */, 608 null /* filterExtrasForReceiver */, 609 broadcast.originalCallingAppProcessState, mService.mPlatformCompat); 610 queue.enqueueBroadcastLocked(r); 611 } 612 } 613 614 return sticky; 615 } 616 } 617 unregisterReceiver(IIntentReceiver receiver)618 void unregisterReceiver(IIntentReceiver receiver) { 619 traceUnregistrationBegin(receiver); 620 try { 621 unregisterReceiverTraced(receiver); 622 } finally { 623 traceUnregistrationEnd(); 624 } 625 } 626 traceUnregistrationBegin(IIntentReceiver receiver)627 private static void traceUnregistrationBegin(IIntentReceiver receiver) { 628 if (!Flags.traceReceiverRegistration()) { 629 return; 630 } 631 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 632 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, 633 TextUtils.formatSimple("unregisterReceiver: %d/%s", Binder.getCallingUid(), 634 receiver == null ? "null" : receiver.asBinder())); 635 } 636 } 637 traceUnregistrationEnd()638 private static void traceUnregistrationEnd() { 639 if (!Flags.traceReceiverRegistration()) { 640 return; 641 } 642 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 643 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 644 } 645 } 646 unregisterReceiverTraced(IIntentReceiver receiver)647 private void unregisterReceiverTraced(IIntentReceiver receiver) { 648 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Unregister receiver: " + receiver); 649 650 final long origId = Binder.clearCallingIdentity(); 651 try { 652 boolean doTrim = false; 653 synchronized (mService) { 654 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 655 if (rl != null) { 656 final BroadcastRecord r = rl.curBroadcast; 657 if (r != null) { 658 final boolean doNext = r.queue.finishReceiverLocked( 659 rl.app, r.resultCode, r.resultData, r.resultExtras, 660 r.resultAbort, false); 661 if (doNext) { 662 doTrim = true; 663 } 664 } 665 if (rl.app != null) { 666 rl.app.mReceivers.removeReceiver(rl); 667 } 668 removeReceiverLocked(rl); 669 if (rl.linkedToDeath) { 670 rl.linkedToDeath = false; 671 rl.receiver.asBinder().unlinkToDeath(rl, 0); 672 } 673 } 674 675 // If we actually concluded any broadcasts, we might now be able 676 // to trim the recipients' apps from our working set 677 if (doTrim) { 678 mService.trimApplicationsLocked(false, OOM_ADJ_REASON_FINISH_RECEIVER); 679 return; 680 } 681 } 682 683 } finally { 684 Binder.restoreCallingIdentity(origId); 685 } 686 } 687 removeReceiverLocked(ReceiverList rl)688 void removeReceiverLocked(ReceiverList rl) { 689 mRegisteredReceivers.remove(rl.receiver.asBinder()); 690 for (int i = rl.size() - 1; i >= 0; i--) { 691 mReceiverResolver.removeFilter(rl.get(i)); 692 } 693 } 694 getRegisteredIntentFilters(IIntentReceiver receiver)695 List<IntentFilter> getRegisteredIntentFilters(IIntentReceiver receiver) { 696 synchronized (mService) { 697 final ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 698 if (rl == null) { 699 return null; 700 } 701 final ArrayList<IntentFilter> filters = new ArrayList<>(); 702 final int count = rl.size(); 703 for (int i = 0; i < count; ++i) { 704 filters.add(rl.get(i)); 705 } 706 return filters; 707 } 708 } 709 broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, String[] excludedPackages, int appOp, Bundle bOptions, boolean serialized, boolean sticky, int userId)710 int broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId, 711 Intent intent, String resolvedType, IIntentReceiver resultTo, 712 int resultCode, String resultData, Bundle resultExtras, 713 String[] requiredPermissions, String[] excludedPermissions, 714 String[] excludedPackages, int appOp, Bundle bOptions, 715 boolean serialized, boolean sticky, int userId) { 716 mService.enforceNotIsolatedCaller("broadcastIntent"); 717 final int result; 718 719 synchronized (mService) { 720 intent = verifyBroadcastLocked(intent); 721 722 final ProcessRecord callerApp = mService.getRecordForAppLOSP(caller); 723 final int callingPid = Binder.getCallingPid(); 724 final int callingUid = Binder.getCallingUid(); 725 726 // We're delivering the result to the caller 727 final ProcessRecord resultToApp = callerApp; 728 729 // Permission regimes around sender-supplied broadcast options. 730 enforceBroadcastOptionPermissionsInternal(bOptions, callingUid); 731 732 final ComponentName cn = intent.getComponent(); 733 734 Trace.traceBegin( 735 Trace.TRACE_TAG_ACTIVITY_MANAGER, 736 "broadcastIntent:" + (cn != null ? cn.toString() : intent.getAction())); 737 738 final long origId = Binder.clearCallingIdentity(); 739 try { 740 result = broadcastIntentLocked(callerApp, 741 callerApp != null ? callerApp.info.packageName : null, callingFeatureId, 742 intent, resolvedType, resultToApp, resultTo, resultCode, resultData, 743 resultExtras, requiredPermissions, excludedPermissions, excludedPackages, 744 appOp, bOptions, serialized, sticky, callingPid, callingUid, callingUid, 745 callingPid, userId, BackgroundStartPrivileges.NONE, null, null); 746 } finally { 747 Binder.restoreCallingIdentity(origId); 748 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 749 } 750 } 751 752 if (sticky && result == ActivityManager.BROADCAST_SUCCESS) { 753 BroadcastStickyCache.invalidateCache(intent.getAction()); 754 } 755 return result; 756 } 757 758 // Not the binder call surface broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, int realCallingUid, int realCallingPid, Intent intent, String resolvedType, ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, int userId, BackgroundStartPrivileges backgroundStartPrivileges, @Nullable int[] broadcastAllowList)759 int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, 760 int realCallingUid, int realCallingPid, Intent intent, String resolvedType, 761 ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, 762 String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, 763 boolean serialized, boolean sticky, int userId, 764 BackgroundStartPrivileges backgroundStartPrivileges, 765 @Nullable int[] broadcastAllowList) { 766 final int result; 767 synchronized (mService) { 768 intent = verifyBroadcastLocked(intent); 769 770 final long origId = Binder.clearCallingIdentity(); 771 String[] requiredPermissions = requiredPermission == null ? null 772 : new String[] {requiredPermission}; 773 try { 774 result = broadcastIntentLocked(null, packageName, featureId, intent, resolvedType, 775 resultToApp, resultTo, resultCode, resultData, resultExtras, 776 requiredPermissions, null, null, OP_NONE, bOptions, serialized, sticky, -1, 777 uid, realCallingUid, realCallingPid, userId, 778 backgroundStartPrivileges, broadcastAllowList, 779 null /* filterExtrasForReceiver */); 780 } finally { 781 Binder.restoreCallingIdentity(origId); 782 } 783 } 784 785 if (sticky && result == ActivityManager.BROADCAST_SUCCESS) { 786 BroadcastStickyCache.invalidateCache(intent.getAction()); 787 } 788 return result; 789 } 790 791 @GuardedBy("mService") broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, @Nullable String callerFeatureId, Intent intent, String resolvedType, ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, String[] excludedPackages, int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId, BackgroundStartPrivileges backgroundStartPrivileges, @Nullable int[] broadcastAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver)792 final int broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, 793 @Nullable String callerFeatureId, Intent intent, String resolvedType, 794 ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData, 795 Bundle resultExtras, String[] requiredPermissions, 796 String[] excludedPermissions, String[] excludedPackages, int appOp, Bundle bOptions, 797 boolean ordered, boolean sticky, int callingPid, int callingUid, 798 int realCallingUid, int realCallingPid, int userId, 799 BackgroundStartPrivileges backgroundStartPrivileges, 800 @Nullable int[] broadcastAllowList, 801 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver) { 802 final int cookie = traceBroadcastIntentBegin(intent, resultTo, ordered, sticky, 803 callingUid, realCallingUid, userId); 804 try { 805 final BroadcastSentEventRecord broadcastSentEventRecord = 806 new BroadcastSentEventRecord(); 807 final int res = broadcastIntentLockedTraced(callerApp, callerPackage, callerFeatureId, 808 intent, resolvedType, resultToApp, resultTo, resultCode, resultData, 809 resultExtras, requiredPermissions, excludedPermissions, excludedPackages, 810 appOp, BroadcastOptions.fromBundleNullable(bOptions), ordered, sticky, 811 callingPid, callingUid, realCallingUid, realCallingPid, userId, 812 backgroundStartPrivileges, broadcastAllowList, filterExtrasForReceiver, 813 broadcastSentEventRecord); 814 broadcastSentEventRecord.setResult(res); 815 broadcastSentEventRecord.logToStatsd(); 816 return res; 817 } finally { 818 traceBroadcastIntentEnd(cookie); 819 } 820 } 821 traceBroadcastIntentBegin(Intent intent, IIntentReceiver resultTo, boolean ordered, boolean sticky, int callingUid, int realCallingUid, int userId)822 private static int traceBroadcastIntentBegin(Intent intent, IIntentReceiver resultTo, 823 boolean ordered, boolean sticky, int callingUid, int realCallingUid, int userId) { 824 if (!Flags.traceReceiverRegistration()) { 825 return BroadcastQueue.traceBegin("broadcastIntentLockedTraced"); 826 } 827 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 828 final StringBuilder sb = new StringBuilder("broadcastIntent: "); 829 sb.append(callingUid); sb.append('/'); 830 final String action = intent.getAction(); 831 sb.append(action == null ? null : action); sb.append('/'); 832 sb.append("0x"); sb.append(Integer.toHexString(intent.getFlags())); sb.append('/'); 833 sb.append(ordered ? "O" : "_"); 834 sb.append(sticky ? "S" : "_"); 835 sb.append(resultTo != null ? "C" : "_"); 836 sb.append('/'); 837 sb.append('u'); sb.append(userId); 838 if (callingUid != realCallingUid) { 839 sb.append('/'); 840 sb.append("sender="); sb.append(realCallingUid); 841 } 842 return BroadcastQueue.traceBegin(sb.toString()); 843 } 844 return 0; 845 } 846 traceBroadcastIntentEnd(int cookie)847 private static void traceBroadcastIntentEnd(int cookie) { 848 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { 849 BroadcastQueue.traceEnd(cookie); 850 } 851 } 852 853 @GuardedBy("mService") broadcastIntentLockedTraced(ProcessRecord callerApp, String callerPackage, @Nullable String callerFeatureId, Intent intent, String resolvedType, ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, String[] excludedPackages, int appOp, BroadcastOptions brOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId, BackgroundStartPrivileges backgroundStartPrivileges, @Nullable int[] broadcastAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, @NonNull BroadcastSentEventRecord broadcastSentEventRecord)854 final int broadcastIntentLockedTraced(ProcessRecord callerApp, String callerPackage, 855 @Nullable String callerFeatureId, Intent intent, String resolvedType, 856 ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData, 857 Bundle resultExtras, String[] requiredPermissions, 858 String[] excludedPermissions, String[] excludedPackages, int appOp, 859 BroadcastOptions brOptions, boolean ordered, boolean sticky, int callingPid, 860 int callingUid, int realCallingUid, int realCallingPid, int userId, 861 BackgroundStartPrivileges backgroundStartPrivileges, 862 @Nullable int[] broadcastAllowList, 863 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, 864 @NonNull BroadcastSentEventRecord broadcastSentEventRecord) { 865 // Ensure all internal loopers are registered for idle checks 866 BroadcastLoopers.addMyLooper(); 867 868 if (Process.isSdkSandboxUid(realCallingUid)) { 869 final SdkSandboxManagerLocal sdkSandboxManagerLocal = LocalManagerRegistry.getManager( 870 SdkSandboxManagerLocal.class); 871 if (sdkSandboxManagerLocal == null) { 872 throw new IllegalStateException("SdkSandboxManagerLocal not found when sending" 873 + " a broadcast from an SDK sandbox uid."); 874 } 875 if (!sdkSandboxManagerLocal.canSendBroadcast(intent)) { 876 throw new SecurityException( 877 "Intent " + intent.getAction() + " may not be broadcast from an SDK sandbox" 878 + " uid. Given caller package " + callerPackage 879 + " (pid=" + callingPid + ", realCallingUid=" + realCallingUid 880 + ", callingUid= " + callingUid + ")"); 881 } 882 } 883 884 if ((resultTo != null) && (resultToApp == null)) { 885 if (resultTo.asBinder() instanceof BinderProxy) { 886 // Warn when requesting results without a way to deliver them 887 Slog.wtf(TAG, "Sending broadcast " + intent.getAction() 888 + " with resultTo requires resultToApp", new Throwable()); 889 } else { 890 // If not a BinderProxy above, then resultTo is an in-process 891 // receiver, so splice in system_server process 892 resultToApp = mService.getProcessRecordLocked("system", SYSTEM_UID); 893 } 894 } 895 896 intent = new Intent(intent); 897 broadcastSentEventRecord.setIntent(intent); 898 broadcastSentEventRecord.setOriginalIntentFlags(intent.getFlags()); 899 broadcastSentEventRecord.setSenderUid(callingUid); 900 broadcastSentEventRecord.setRealSenderUid(realCallingUid); 901 broadcastSentEventRecord.setSticky(sticky); 902 broadcastSentEventRecord.setOrdered(ordered); 903 broadcastSentEventRecord.setResultRequested(resultTo != null); 904 final int callerAppProcessState = getRealProcessStateLocked(callerApp, realCallingPid); 905 broadcastSentEventRecord.setSenderProcState(callerAppProcessState); 906 broadcastSentEventRecord.setSenderUidState(getRealUidStateLocked(callerApp, 907 realCallingPid)); 908 909 final boolean callerInstantApp = isInstantApp(callerApp, callerPackage, callingUid); 910 // Instant Apps cannot use FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS 911 if (callerInstantApp) { 912 intent.setFlags(intent.getFlags() & ~Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 913 } 914 915 if (userId == UserHandle.USER_ALL && broadcastAllowList != null) { 916 Slog.e(TAG, "broadcastAllowList only applies when sending to individual users. " 917 + "Assuming restrictive whitelist."); 918 broadcastAllowList = new int[]{}; 919 } 920 921 // By default broadcasts do not go to stopped apps. 922 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES); 923 924 // If we have not finished booting, don't allow this to launch new processes. 925 if (!mService.mProcessesReady 926 && (intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) { 927 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 928 } 929 930 if (DEBUG_BROADCAST_LIGHT) { 931 Slog.v(TAG_BROADCAST, 932 (sticky ? "Broadcast sticky: " : "Broadcast: ") + intent 933 + " ordered=" + ordered + " userid=" + userId 934 + " options=" + (brOptions == null ? "null" : brOptions.toBundle())); 935 } 936 if ((resultTo != null) && !ordered) { 937 if (!UserHandle.isCore(callingUid)) { 938 String msg = "Unauthorized unordered resultTo broadcast " 939 + intent + " sent from uid " + callingUid; 940 Slog.w(TAG, msg); 941 throw new SecurityException(msg); 942 } 943 } 944 945 userId = mService.mUserController.handleIncomingUser(callingPid, callingUid, userId, true, 946 ALLOW_NON_FULL, "broadcast", callerPackage); 947 948 // Make sure that the user who is receiving this broadcast or its parent is running. 949 // If not, we will just skip it. Make an exception for shutdown broadcasts, upgrade steps. 950 if (userId != UserHandle.USER_ALL && !mService.mUserController.isUserOrItsParentRunning( 951 userId)) { 952 if ((callingUid != SYSTEM_UID 953 || (intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) 954 && !Intent.ACTION_SHUTDOWN.equals(intent.getAction())) { 955 Slog.w(TAG, "Skipping broadcast of " + intent 956 + ": user " + userId + " and its parent (if any) are stopped"); 957 scheduleCanceledResultTo(resultToApp, resultTo, intent, userId, 958 brOptions, callingUid, callerPackage); 959 return ActivityManager.BROADCAST_FAILED_USER_STOPPED; 960 } 961 } 962 963 final String action = intent.getAction(); 964 if (brOptions != null) { 965 if (brOptions.getTemporaryAppAllowlistDuration() > 0) { 966 // See if the caller is allowed to do this. Note we are checking against 967 // the actual real caller (not whoever provided the operation as say a 968 // PendingIntent), because that who is actually supplied the arguments. 969 if (checkComponentPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST, 970 realCallingPid, realCallingUid, -1, true) 971 != PackageManager.PERMISSION_GRANTED 972 && checkComponentPermission(START_ACTIVITIES_FROM_BACKGROUND, 973 realCallingPid, realCallingUid, -1, true) 974 != PackageManager.PERMISSION_GRANTED 975 && checkComponentPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND, 976 realCallingPid, realCallingUid, -1, true) 977 != PackageManager.PERMISSION_GRANTED) { 978 String msg = "Permission Denial: " + intent.getAction() 979 + " broadcast from " + callerPackage + " (pid=" + callingPid 980 + ", uid=" + callingUid + ")" 981 + " requires " 982 + CHANGE_DEVICE_IDLE_TEMP_WHITELIST + " or " 983 + START_ACTIVITIES_FROM_BACKGROUND + " or " 984 + START_FOREGROUND_SERVICES_FROM_BACKGROUND; 985 Slog.w(TAG, msg); 986 throw new SecurityException(msg); 987 } 988 } 989 if (brOptions.isDontSendToRestrictedApps() 990 && !mService.isUidActiveLOSP(callingUid) 991 && mService.isBackgroundRestrictedNoCheck(callingUid, callerPackage)) { 992 Slog.i(TAG, "Not sending broadcast " + action + " - app " + callerPackage 993 + " has background restrictions"); 994 return ActivityManager.START_CANCELED; 995 } 996 if (brOptions.allowsBackgroundActivityStarts()) { 997 // See if the caller is allowed to do this. Note we are checking against 998 // the actual real caller (not whoever provided the operation as say a 999 // PendingIntent), because that who is actually supplied the arguments. 1000 if (checkComponentPermission( 1001 android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND, 1002 realCallingPid, realCallingUid, -1, true) 1003 != PackageManager.PERMISSION_GRANTED) { 1004 String msg = "Permission Denial: " + intent.getAction() 1005 + " broadcast from " + callerPackage + " (pid=" + callingPid 1006 + ", uid=" + callingUid + ")" 1007 + " requires " 1008 + android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND; 1009 Slog.w(TAG, msg); 1010 throw new SecurityException(msg); 1011 } else { 1012 // We set the token to null since if it wasn't for it we'd allow anyway here 1013 backgroundStartPrivileges = BackgroundStartPrivileges.ALLOW_BAL; 1014 } 1015 } 1016 1017 if (brOptions.getIdForResponseEvent() > 0) { 1018 mService.enforcePermission( 1019 android.Manifest.permission.ACCESS_BROADCAST_RESPONSE_STATS, 1020 callingPid, callingUid, "recordResponseEventWhileInBackground"); 1021 } 1022 1023 if (brOptions.isDebugLogEnabled()) { 1024 if (!isShellOrRoot(callingUid) 1025 && (callerApp == null || !callerApp.hasActiveInstrumentation())) { 1026 brOptions.setDebugLogEnabled(false); 1027 } 1028 } 1029 } 1030 1031 // Verify that protected broadcasts are only being sent by system code, 1032 // and that system code is only sending protected broadcasts. 1033 final boolean isProtectedBroadcast; 1034 try { 1035 isProtectedBroadcast = AppGlobals.getPackageManager().isProtectedBroadcast(action); 1036 } catch (RemoteException e) { 1037 Slog.w(TAG, "Remote exception", e); 1038 scheduleCanceledResultTo(resultToApp, resultTo, intent, 1039 userId, brOptions, callingUid, callerPackage); 1040 return ActivityManager.BROADCAST_SUCCESS; 1041 } 1042 1043 final boolean isCallerSystem; 1044 switch (UserHandle.getAppId(callingUid)) { 1045 case ROOT_UID: 1046 case SYSTEM_UID: 1047 case PHONE_UID: 1048 case BLUETOOTH_UID: 1049 case NFC_UID: 1050 case SE_UID: 1051 case NETWORK_STACK_UID: 1052 isCallerSystem = true; 1053 break; 1054 default: 1055 isCallerSystem = (callerApp != null) && callerApp.isPersistent(); 1056 break; 1057 } 1058 1059 // First line security check before anything else: stop non-system apps from 1060 // sending protected broadcasts. 1061 if (!isCallerSystem) { 1062 if (isProtectedBroadcast) { 1063 String msg = "Permission Denial: not allowed to send broadcast " 1064 + action + " from pid=" 1065 + callingPid + ", uid=" + callingUid; 1066 Slog.w(TAG, msg); 1067 throw new SecurityException(msg); 1068 1069 } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action) 1070 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { 1071 // Special case for compatibility: we don't want apps to send this, 1072 // but historically it has not been protected and apps may be using it 1073 // to poke their own app widget. So, instead of making it protected, 1074 // just limit it to the caller. 1075 if (callerPackage == null) { 1076 String msg = "Permission Denial: not allowed to send broadcast " 1077 + action + " from unknown caller."; 1078 Slog.w(TAG, msg); 1079 throw new SecurityException(msg); 1080 } else if (intent.getComponent() != null) { 1081 // They are good enough to send to an explicit component... verify 1082 // it is being sent to the calling app. 1083 if (!intent.getComponent().getPackageName().equals( 1084 callerPackage)) { 1085 String msg = "Permission Denial: not allowed to send broadcast " 1086 + action + " to " 1087 + intent.getComponent().getPackageName() + " from " 1088 + callerPackage; 1089 Slog.w(TAG, msg); 1090 throw new SecurityException(msg); 1091 } 1092 } else { 1093 // Limit broadcast to their own package. 1094 intent.setPackage(callerPackage); 1095 } 1096 } 1097 } 1098 1099 boolean timeoutExempt = false; 1100 1101 if (action != null) { 1102 if (getBackgroundLaunchBroadcasts().contains(action)) { 1103 if (DEBUG_BACKGROUND_CHECK) { 1104 Slog.i(TAG, "Broadcast action " + action + " forcing include-background"); 1105 } 1106 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 1107 } 1108 1109 // TODO: b/329211459 - Remove this after background remote intent is fixed. 1110 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH) 1111 && getWearRemoteIntentAction().equals(action)) { 1112 final int callerProcState = callerApp != null 1113 ? callerApp.getCurProcState() 1114 : ActivityManager.PROCESS_STATE_NONEXISTENT; 1115 if (ActivityManager.RunningAppProcessInfo.procStateToImportance(callerProcState) 1116 > ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { 1117 return ActivityManager.START_CANCELED; 1118 } 1119 } 1120 1121 switch (action) { 1122 case Intent.ACTION_MEDIA_SCANNER_SCAN_FILE: 1123 UserManagerInternal umInternal = LocalServices.getService( 1124 UserManagerInternal.class); 1125 UserInfo userInfo = umInternal.getUserInfo(userId); 1126 if (userInfo != null && userInfo.isCloneProfile()) { 1127 userId = umInternal.getProfileParentId(userId); 1128 } 1129 break; 1130 case Intent.ACTION_UID_REMOVED: 1131 case Intent.ACTION_PACKAGE_REMOVED: 1132 case Intent.ACTION_PACKAGE_CHANGED: 1133 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE: 1134 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE: 1135 case Intent.ACTION_PACKAGES_SUSPENDED: 1136 case Intent.ACTION_PACKAGES_UNSUSPENDED: 1137 // Handle special intents: if this broadcast is from the package 1138 // manager about a package being removed, we need to remove all of 1139 // its activities from the history stack. 1140 if (checkComponentPermission( 1141 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED, 1142 callingPid, callingUid, -1, true) 1143 != PackageManager.PERMISSION_GRANTED) { 1144 String msg = "Permission Denial: " + intent.getAction() 1145 + " broadcast from " + callerPackage + " (pid=" + callingPid 1146 + ", uid=" + callingUid + ")" 1147 + " requires " 1148 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED; 1149 Slog.w(TAG, msg); 1150 throw new SecurityException(msg); 1151 } 1152 switch (action) { 1153 case Intent.ACTION_UID_REMOVED: 1154 final int uid = getUidFromIntent(intent); 1155 if (uid >= 0) { 1156 mService.mBatteryStatsService.removeUid(uid); 1157 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 1158 mService.mAppOpsService.resetAllModes(UserHandle.getUserId(uid), 1159 intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME)); 1160 } else { 1161 mService.mAppOpsService.uidRemoved(uid); 1162 mService.mServices.onUidRemovedLocked(uid); 1163 } 1164 } 1165 break; 1166 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE: 1167 // If resources are unavailable just force stop all those packages 1168 // and flush the attribute cache as well. 1169 String[] list = intent.getStringArrayExtra( 1170 Intent.EXTRA_CHANGED_PACKAGE_LIST); 1171 if (list != null && list.length > 0) { 1172 for (int i = 0; i < list.length; i++) { 1173 mService.forceStopPackageLocked(list[i], -1, false, true, true, 1174 false, false, false, userId, "storage unmount"); 1175 } 1176 mService.mAtmInternal.cleanupRecentTasksForUser( 1177 UserHandle.USER_ALL); 1178 sendPackageBroadcastLocked( 1179 ApplicationThreadConstants.EXTERNAL_STORAGE_UNAVAILABLE, 1180 list, userId); 1181 } 1182 break; 1183 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE: 1184 mService.mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL); 1185 break; 1186 case Intent.ACTION_PACKAGE_REMOVED: 1187 case Intent.ACTION_PACKAGE_CHANGED: 1188 Uri data = intent.getData(); 1189 String ssp; 1190 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 1191 boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(action); 1192 final boolean replacing = 1193 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 1194 final boolean killProcess = 1195 !intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false); 1196 final boolean fullUninstall = removed && !replacing; 1197 1198 if (removed) { 1199 if (killProcess) { 1200 mService.forceStopPackageLocked(ssp, UserHandle.getAppId( 1201 intent.getIntExtra(Intent.EXTRA_UID, -1)), 1202 false, true, true, false, fullUninstall, false, 1203 userId, "pkg removed"); 1204 mService.getPackageManagerInternal() 1205 .onPackageProcessKilledForUninstall(ssp); 1206 } else { 1207 // Kill any app zygotes always, since they can't fork new 1208 // processes with references to the old code 1209 mService.forceStopAppZygoteLocked(ssp, UserHandle.getAppId( 1210 intent.getIntExtra(Intent.EXTRA_UID, -1)), 1211 userId); 1212 } 1213 final int cmd = killProcess 1214 ? ApplicationThreadConstants.PACKAGE_REMOVED 1215 : ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL; 1216 sendPackageBroadcastLocked(cmd, 1217 new String[] {ssp}, userId); 1218 if (fullUninstall) { 1219 // Remove all permissions granted from/to this package 1220 mService.mUgmInternal.removeUriPermissionsForPackage(ssp, 1221 userId, true, false); 1222 1223 mService.mAtmInternal.removeRecentTasksByPackageName(ssp, 1224 userId); 1225 1226 mService.mServices.forceStopPackageLocked(ssp, userId); 1227 mService.mAtmInternal.onPackageUninstalled(ssp, userId); 1228 mService.mBatteryStatsService.notePackageUninstalled(ssp); 1229 } 1230 } else { 1231 if (killProcess) { 1232 int reason; 1233 int subReason; 1234 if (replacing) { 1235 reason = ApplicationExitInfo.REASON_PACKAGE_UPDATED; 1236 subReason = ApplicationExitInfo.SUBREASON_UNKNOWN; 1237 } else { 1238 reason = 1239 ApplicationExitInfo.REASON_PACKAGE_STATE_CHANGE; 1240 subReason = ApplicationExitInfo.SUBREASON_UNKNOWN; 1241 } 1242 1243 final int extraUid = intent.getIntExtra(Intent.EXTRA_UID, 1244 -1); 1245 synchronized (mService.mProcLock) { 1246 mService.mProcessList.killPackageProcessesLSP(ssp, 1247 UserHandle.getAppId(extraUid), 1248 userId, ProcessList.INVALID_ADJ, 1249 reason, 1250 subReason, 1251 "change " + ssp); 1252 } 1253 } 1254 mService.cleanupDisabledPackageComponentsLocked(ssp, userId, 1255 intent.getStringArrayExtra( 1256 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST)); 1257 mService.mServices.schedulePendingServiceStartLocked( 1258 ssp, userId); 1259 } 1260 } 1261 break; 1262 case Intent.ACTION_PACKAGES_SUSPENDED: 1263 case Intent.ACTION_PACKAGES_UNSUSPENDED: 1264 final boolean suspended = Intent.ACTION_PACKAGES_SUSPENDED.equals( 1265 intent.getAction()); 1266 final String[] packageNames = intent.getStringArrayExtra( 1267 Intent.EXTRA_CHANGED_PACKAGE_LIST); 1268 final int userIdExtra = intent.getIntExtra( 1269 Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 1270 1271 mService.mAtmInternal.onPackagesSuspendedChanged(packageNames, 1272 suspended, userIdExtra); 1273 1274 final boolean quarantined = intent.getBooleanExtra( 1275 Intent.EXTRA_QUARANTINED, false); 1276 if (suspended && quarantined && packageNames != null) { 1277 for (int i = 0; i < packageNames.length; i++) { 1278 mService.forceStopPackage(packageNames[i], userId, 1279 ActivityManager.FLAG_OR_STOPPED, "quarantined"); 1280 } 1281 } 1282 1283 break; 1284 } 1285 break; 1286 case Intent.ACTION_PACKAGE_REPLACED: { 1287 final Uri data = intent.getData(); 1288 final String ssp; 1289 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 1290 ApplicationInfo aInfo = null; 1291 try { 1292 aInfo = AppGlobals.getPackageManager() 1293 .getApplicationInfo(ssp, STOCK_PM_FLAGS, userId); 1294 } catch (RemoteException ignore) { 1295 } 1296 if (aInfo == null) { 1297 Slog.w(TAG, "Dropping ACTION_PACKAGE_REPLACED for non-existent pkg:" 1298 + " ssp=" + ssp + " data=" + data); 1299 scheduleCanceledResultTo(resultToApp, resultTo, intent, 1300 userId, brOptions, callingUid, callerPackage); 1301 return ActivityManager.BROADCAST_SUCCESS; 1302 } 1303 mService.updateAssociationForApp(aInfo); 1304 mService.mAtmInternal.onPackageReplaced(aInfo); 1305 mService.mServices.updateServiceApplicationInfoLocked(aInfo); 1306 sendPackageBroadcastLocked(ApplicationThreadConstants.PACKAGE_REPLACED, 1307 new String[] {ssp}, userId); 1308 } 1309 break; 1310 } 1311 case Intent.ACTION_PACKAGE_ADDED: { 1312 // Special case for adding a package: by default turn on compatibility mode. 1313 Uri data = intent.getData(); 1314 String ssp; 1315 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 1316 final boolean replacing = 1317 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 1318 mService.mAtmInternal.onPackageAdded(ssp, replacing); 1319 1320 try { 1321 ApplicationInfo ai = AppGlobals.getPackageManager() 1322 .getApplicationInfo(ssp, STOCK_PM_FLAGS, 0); 1323 mService.mBatteryStatsService.notePackageInstalled(ssp, 1324 ai != null ? ai.longVersionCode : 0); 1325 } catch (RemoteException e) { 1326 } 1327 } 1328 break; 1329 } 1330 case Intent.ACTION_PACKAGE_DATA_CLEARED: { 1331 Uri data = intent.getData(); 1332 String ssp; 1333 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 1334 mService.mAtmInternal.onPackageDataCleared(ssp, userId); 1335 } 1336 break; 1337 } 1338 case Intent.ACTION_TIMEZONE_CHANGED: 1339 // If this is the time zone changed action, queue up a message that will reset 1340 // the timezone of all currently running processes. This message will get 1341 // queued up before the broadcast happens. 1342 mService.mHandler.sendEmptyMessage(UPDATE_TIME_ZONE); 1343 break; 1344 case Intent.ACTION_TIME_CHANGED: 1345 // EXTRA_TIME_PREF_24_HOUR_FORMAT is optional so we must distinguish between 1346 // the tri-state value it may contain and "unknown". 1347 // For convenience we re-use the Intent extra values. 1348 final int NO_EXTRA_VALUE_FOUND = -1; 1349 final int timeFormatPreferenceMsgValue = intent.getIntExtra( 1350 Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT, 1351 NO_EXTRA_VALUE_FOUND /* defaultValue */); 1352 // Only send a message if the time preference is available. 1353 if (timeFormatPreferenceMsgValue != NO_EXTRA_VALUE_FOUND) { 1354 Message updateTimePreferenceMsg = 1355 mService.mHandler.obtainMessage(UPDATE_TIME_PREFERENCE_MSG, 1356 timeFormatPreferenceMsgValue, 0); 1357 mService.mHandler.sendMessage(updateTimePreferenceMsg); 1358 } 1359 mService.mBatteryStatsService.noteCurrentTimeChanged(); 1360 break; 1361 case ConnectivityManager.ACTION_CLEAR_DNS_CACHE: 1362 mService.mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG); 1363 break; 1364 case Proxy.PROXY_CHANGE_ACTION: 1365 mService.mHandler.sendMessage(mService.mHandler.obtainMessage( 1366 UPDATE_HTTP_PROXY_MSG)); 1367 break; 1368 case android.hardware.Camera.ACTION_NEW_PICTURE: 1369 case android.hardware.Camera.ACTION_NEW_VIDEO: 1370 // In N we just turned these off; in O we are turing them back on partly, 1371 // only for registered receivers. This will still address the main problem 1372 // (a spam of apps waking up when a picture is taken putting significant 1373 // memory pressure on the system at a bad point), while still allowing apps 1374 // that are already actively running to know about this happening. 1375 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 1376 break; 1377 case android.security.KeyChain.ACTION_TRUST_STORE_CHANGED: 1378 mService.mHandler.sendEmptyMessage(HANDLE_TRUST_STORAGE_UPDATE_MSG); 1379 break; 1380 case "com.android.launcher.action.INSTALL_SHORTCUT": 1381 // As of O, we no longer support this broadcasts, even for pre-O apps. 1382 // Apps should now be using ShortcutManager.pinRequestShortcut(). 1383 Log.w(TAG, "Broadcast " + action 1384 + " no longer supported. It will not be delivered."); 1385 scheduleCanceledResultTo(resultToApp, resultTo, intent, 1386 userId, brOptions, callingUid, callerPackage); 1387 return ActivityManager.BROADCAST_SUCCESS; 1388 case Intent.ACTION_PRE_BOOT_COMPLETED: 1389 timeoutExempt = true; 1390 break; 1391 case Intent.ACTION_CLOSE_SYSTEM_DIALOGS: 1392 if (!mService.mAtmInternal.checkCanCloseSystemDialogs(callingPid, callingUid, 1393 callerPackage)) { 1394 scheduleCanceledResultTo(resultToApp, resultTo, intent, 1395 userId, brOptions, callingUid, callerPackage); 1396 // Returning success seems to be the pattern here 1397 return ActivityManager.BROADCAST_SUCCESS; 1398 } 1399 break; 1400 } 1401 1402 if (Intent.ACTION_PACKAGE_ADDED.equals(action) 1403 || Intent.ACTION_PACKAGE_REMOVED.equals(action) 1404 || Intent.ACTION_PACKAGE_REPLACED.equals(action)) { 1405 final int uid = getUidFromIntent(intent); 1406 if (uid != -1) { 1407 final UidRecord uidRec = mService.mProcessList.getUidRecordLOSP(uid); 1408 if (uidRec != null) { 1409 uidRec.updateHasInternetPermission(); 1410 } 1411 } 1412 } 1413 } 1414 1415 // Add to the sticky list if requested. 1416 if (sticky) { 1417 if (mService.checkPermission(android.Manifest.permission.BROADCAST_STICKY, 1418 callingPid, callingUid) 1419 != PackageManager.PERMISSION_GRANTED) { 1420 String msg = 1421 "Permission Denial: broadcastIntent() requesting a sticky broadcast from" 1422 + " pid=" 1423 + callingPid 1424 + ", uid=" 1425 + callingUid 1426 + " requires " 1427 + android.Manifest.permission.BROADCAST_STICKY; 1428 Slog.w(TAG, msg); 1429 throw new SecurityException(msg); 1430 } 1431 if (requiredPermissions != null && requiredPermissions.length > 0) { 1432 Slog.w(TAG, "Can't broadcast sticky intent " + intent 1433 + " and enforce permissions " + Arrays.toString(requiredPermissions)); 1434 scheduleCanceledResultTo(resultToApp, resultTo, intent, 1435 userId, brOptions, callingUid, callerPackage); 1436 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION; 1437 } 1438 if (intent.getComponent() != null) { 1439 throw new SecurityException( 1440 "Sticky broadcasts can't target a specific component"); 1441 } 1442 synchronized (mStickyBroadcasts) { 1443 // We use userId directly here, since the "all" target is maintained 1444 // as a separate set of sticky broadcasts. 1445 if (userId != UserHandle.USER_ALL) { 1446 // But first, if this is not a broadcast to all users, then 1447 // make sure it doesn't conflict with an existing broadcast to 1448 // all users. 1449 ArrayMap<String, ArrayList<StickyBroadcast>> stickies = mStickyBroadcasts.get( 1450 UserHandle.USER_ALL); 1451 if (stickies != null) { 1452 ArrayList<StickyBroadcast> list = stickies.get(intent.getAction()); 1453 if (list != null) { 1454 int N = list.size(); 1455 int i; 1456 for (i = 0; i < N; i++) { 1457 if (intent.filterEquals(list.get(i).intent)) { 1458 throw new IllegalArgumentException("Sticky broadcast " + intent 1459 + " for user " + userId 1460 + " conflicts with existing global broadcast"); 1461 } 1462 } 1463 } 1464 } 1465 } 1466 ArrayMap<String, ArrayList<StickyBroadcast>> stickies = 1467 mStickyBroadcasts.get(userId); 1468 if (stickies == null) { 1469 stickies = new ArrayMap<>(); 1470 mStickyBroadcasts.put(userId, stickies); 1471 } 1472 ArrayList<StickyBroadcast> list = stickies.get(intent.getAction()); 1473 if (list == null) { 1474 list = new ArrayList<>(); 1475 stickies.put(intent.getAction(), list); 1476 } 1477 final boolean deferUntilActive = BroadcastRecord.calculateDeferUntilActive( 1478 callingUid, brOptions, resultTo, ordered, 1479 BroadcastRecord.calculateUrgent(intent, brOptions)); 1480 final int stickiesCount = list.size(); 1481 int i; 1482 for (i = 0; i < stickiesCount; i++) { 1483 if (intent.filterEquals(list.get(i).intent)) { 1484 // This sticky already exists, replace it. 1485 list.set(i, StickyBroadcast.create(new Intent(intent), deferUntilActive, 1486 callingUid, callerAppProcessState, resolvedType)); 1487 break; 1488 } 1489 } 1490 if (i >= stickiesCount) { 1491 list.add(StickyBroadcast.create(new Intent(intent), deferUntilActive, 1492 callingUid, callerAppProcessState, resolvedType)); 1493 } 1494 BroadcastStickyCache.invalidateCache(intent.getAction()); 1495 } 1496 } 1497 1498 int[] users; 1499 if (userId == UserHandle.USER_ALL) { 1500 // Caller wants broadcast to go to all started users. 1501 users = mService.mUserController.getStartedUserArray(); 1502 } else { 1503 // Caller wants broadcast to go to one specific user. 1504 users = new int[] {userId}; 1505 } 1506 1507 var args = new SaferIntentUtils.IntentArgs(intent, resolvedType, 1508 true /* isReceiver */, true /* resolveForStart */, callingUid, callingPid); 1509 args.platformCompat = mService.mPlatformCompat; 1510 1511 // Figure out who all will receive this broadcast. 1512 final int cookie = BroadcastQueue.traceBegin("queryReceivers"); 1513 List receivers = null; 1514 List<BroadcastFilter> registeredReceivers = null; 1515 // Need to resolve the intent to interested receivers... 1516 if ((intent.getFlags() & Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 1517 receivers = collectReceiverComponents( 1518 intent, resolvedType, callingUid, callingPid, users, broadcastAllowList); 1519 } 1520 if (intent.getComponent() == null) { 1521 final PackageDataSnapshot snapshot = mService.getPackageManagerInternal().snapshot(); 1522 if (userId == UserHandle.USER_ALL && callingUid == SHELL_UID) { 1523 // Query one target user at a time, excluding shell-restricted users 1524 for (int i = 0; i < users.length; i++) { 1525 if (mService.mUserController.hasUserRestriction( 1526 UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) { 1527 continue; 1528 } 1529 List<BroadcastFilter> registeredReceiversForUser = 1530 mReceiverResolver.queryIntent(snapshot, intent, 1531 resolvedType, false /*defaultOnly*/, users[i]); 1532 if (registeredReceivers == null) { 1533 registeredReceivers = registeredReceiversForUser; 1534 } else if (registeredReceiversForUser != null) { 1535 registeredReceivers.addAll(registeredReceiversForUser); 1536 } 1537 } 1538 } else { 1539 registeredReceivers = mReceiverResolver.queryIntent(snapshot, intent, 1540 resolvedType, false /*defaultOnly*/, userId); 1541 } 1542 if (registeredReceivers != null) { 1543 SaferIntentUtils.blockNullAction(args, registeredReceivers); 1544 } 1545 } 1546 BroadcastQueue.traceEnd(cookie); 1547 1548 final boolean replacePending = 1549 (intent.getFlags() & Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0; 1550 1551 if (DEBUG_BROADCAST) { 1552 Slog.v(TAG_BROADCAST, "Enqueueing broadcast: " + intent.getAction() 1553 + " replacePending=" + replacePending); 1554 } 1555 if (registeredReceivers != null && broadcastAllowList != null) { 1556 // if a uid whitelist was provided, remove anything in the application space that wasn't 1557 // in it. 1558 for (int i = registeredReceivers.size() - 1; i >= 0; i--) { 1559 final int owningAppId = UserHandle.getAppId(registeredReceivers.get(i).owningUid); 1560 if (owningAppId >= Process.FIRST_APPLICATION_UID 1561 && Arrays.binarySearch(broadcastAllowList, owningAppId) < 0) { 1562 registeredReceivers.remove(i); 1563 } 1564 } 1565 } 1566 1567 int NR = registeredReceivers != null ? registeredReceivers.size() : 0; 1568 1569 // Merge into one list. 1570 int ir = 0; 1571 if (receivers != null) { 1572 // A special case for PACKAGE_ADDED: do not allow the package 1573 // being added to see this broadcast. This prevents them from 1574 // using this as a back door to get run as soon as they are 1575 // installed. Maybe in the future we want to have a special install 1576 // broadcast or such for apps, but we'd like to deliberately make 1577 // this decision. 1578 String[] skipPackages = null; 1579 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction()) 1580 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction()) 1581 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) { 1582 Uri data = intent.getData(); 1583 if (data != null) { 1584 String pkgName = data.getSchemeSpecificPart(); 1585 if (pkgName != null) { 1586 skipPackages = new String[] { pkgName }; 1587 } 1588 } 1589 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) { 1590 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 1591 } 1592 if (skipPackages != null && (skipPackages.length > 0)) { 1593 for (String skipPackage : skipPackages) { 1594 if (skipPackage != null) { 1595 int NT = receivers.size(); 1596 for (int it = 0; it < NT; it++) { 1597 ResolveInfo curt = (ResolveInfo) receivers.get(it); 1598 if (curt.activityInfo.packageName.equals(skipPackage)) { 1599 receivers.remove(it); 1600 it--; 1601 NT--; 1602 } 1603 } 1604 } 1605 } 1606 } 1607 1608 int NT = receivers != null ? receivers.size() : 0; 1609 int it = 0; 1610 ResolveInfo curt = null; 1611 BroadcastFilter curr = null; 1612 while (it < NT && ir < NR) { 1613 if (curt == null) { 1614 curt = (ResolveInfo) receivers.get(it); 1615 } 1616 if (curr == null) { 1617 curr = registeredReceivers.get(ir); 1618 } 1619 if (curr.getPriority() >= curt.priority) { 1620 // Insert this broadcast record into the final list. 1621 receivers.add(it, curr); 1622 ir++; 1623 curr = null; 1624 it++; 1625 NT++; 1626 } else { 1627 // Skip to the next ResolveInfo in the final list. 1628 it++; 1629 curt = null; 1630 } 1631 } 1632 } 1633 while (ir < NR) { 1634 // Instant Apps cannot use FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS 1635 if (callerInstantApp) { 1636 intent.setFlags(intent.getFlags() & ~Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 1637 } 1638 if (receivers == null) { 1639 receivers = new ArrayList(); 1640 } 1641 receivers.add(registeredReceivers.get(ir)); 1642 ir++; 1643 } 1644 1645 if (isCallerSystem) { 1646 checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid, 1647 isProtectedBroadcast, receivers); 1648 } 1649 1650 if ((receivers != null && receivers.size() > 0) 1651 || resultTo != null) { 1652 BroadcastQueue queue = mBroadcastQueue; 1653 SaferIntentUtils.filterNonExportedComponents(args, receivers); 1654 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage, 1655 callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType, 1656 requiredPermissions, excludedPermissions, excludedPackages, appOp, brOptions, 1657 receivers, resultToApp, resultTo, resultCode, resultData, resultExtras, 1658 ordered, sticky, false, userId, 1659 backgroundStartPrivileges, timeoutExempt, filterExtrasForReceiver, 1660 callerAppProcessState, mService.mPlatformCompat); 1661 broadcastSentEventRecord.setBroadcastRecord(r); 1662 1663 if (DEBUG_BROADCAST || r.debugLog()) { 1664 Slog.v(TAG_BROADCAST, "Enqueueing broadcast " + r); 1665 } 1666 queue.enqueueBroadcastLocked(r); 1667 } else { 1668 // There was nobody interested in the broadcast, but we still want to record 1669 // that it happened. 1670 if (intent.getComponent() == null && intent.getPackage() == null 1671 && (intent.getFlags() & Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 1672 // This was an implicit broadcast... let's record it for posterity. 1673 addBroadcastStatLocked(intent.getAction(), callerPackage, 0, 0, 0); 1674 } 1675 if (DEBUG_BROADCAST || debugLog(brOptions)) { 1676 Slog.v(TAG_BROADCAST, "Skipping broadcast " + intentToString(intent) 1677 + " due to no receivers"); 1678 } 1679 } 1680 1681 return ActivityManager.BROADCAST_SUCCESS; 1682 } 1683 isShellOrRoot(int uid)1684 private boolean isShellOrRoot(int uid) { 1685 return uid == SHELL_UID || uid == ROOT_UID; 1686 } 1687 1688 @GuardedBy("mService") scheduleCanceledResultTo(ProcessRecord resultToApp, IIntentReceiver resultTo, Intent intent, int userId, BroadcastOptions options, int callingUid, String callingPackage)1689 private void scheduleCanceledResultTo(ProcessRecord resultToApp, IIntentReceiver resultTo, 1690 Intent intent, int userId, BroadcastOptions options, int callingUid, 1691 String callingPackage) { 1692 if (resultTo == null) { 1693 return; 1694 } 1695 final ProcessRecord app = resultToApp; 1696 final IApplicationThread thread = (app != null) ? app.getOnewayThread() : null; 1697 if (thread != null) { 1698 try { 1699 final boolean shareIdentity = (options != null && options.isShareIdentityEnabled()); 1700 thread.scheduleRegisteredReceiver( 1701 resultTo, intent, Activity.RESULT_CANCELED, null, null, 1702 false, false, true, userId, app.mState.getReportedProcState(), 1703 shareIdentity ? callingUid : Process.INVALID_UID, 1704 shareIdentity ? callingPackage : null); 1705 } catch (RemoteException e) { 1706 final String msg = "Failed to schedule result of " + intent + " via " 1707 + app + ": " + e; 1708 app.killLocked("Can't schedule resultTo", ApplicationExitInfo.REASON_OTHER, 1709 ApplicationExitInfo.SUBREASON_UNDELIVERED_BROADCAST, true); 1710 Slog.d(TAG, msg); 1711 } 1712 } 1713 } 1714 1715 @GuardedBy("mService") getRealProcessStateLocked(ProcessRecord app, int pid)1716 private int getRealProcessStateLocked(ProcessRecord app, int pid) { 1717 if (app == null) { 1718 synchronized (mService.mPidsSelfLocked) { 1719 app = mService.mPidsSelfLocked.get(pid); 1720 } 1721 } 1722 if (app != null && app.getThread() != null && !app.isKilled()) { 1723 return app.mState.getCurProcState(); 1724 } 1725 return PROCESS_STATE_NONEXISTENT; 1726 } 1727 1728 @GuardedBy("mService") getRealUidStateLocked(ProcessRecord app, int pid)1729 private int getRealUidStateLocked(ProcessRecord app, int pid) { 1730 if (app == null) { 1731 synchronized (mService.mPidsSelfLocked) { 1732 app = mService.mPidsSelfLocked.get(pid); 1733 } 1734 } 1735 if (app != null && app.getThread() != null && !app.isKilled()) { 1736 final UidRecord uidRecord = app.getUidRecord(); 1737 if (uidRecord != null) { 1738 return uidRecord.getCurProcState(); 1739 } 1740 } 1741 return PROCESS_STATE_NONEXISTENT; 1742 } 1743 1744 @VisibleForTesting getStickyBroadcastsForTest(String action, int userId)1745 ArrayList<StickyBroadcast> getStickyBroadcastsForTest(String action, int userId) { 1746 synchronized (mStickyBroadcasts) { 1747 final ArrayMap<String, ArrayList<StickyBroadcast>> stickyBroadcasts = 1748 mStickyBroadcasts.get(userId); 1749 if (stickyBroadcasts == null) { 1750 return null; 1751 } 1752 return stickyBroadcasts.get(action); 1753 } 1754 } 1755 unbroadcastIntent(IApplicationThread caller, Intent intent, int userId)1756 void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) { 1757 // Refuse possible leaked file descriptors 1758 if (intent != null && intent.hasFileDescriptors()) { 1759 throw new IllegalArgumentException("File descriptors passed in Intent"); 1760 } 1761 1762 userId = mService.mUserController.handleIncomingUser(Binder.getCallingPid(), 1763 Binder.getCallingUid(), userId, true, ALLOW_NON_FULL, 1764 "removeStickyBroadcast", null); 1765 1766 if (mService.checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY) 1767 != PackageManager.PERMISSION_GRANTED) { 1768 String msg = "Permission Denial: unbroadcastIntent() from pid=" 1769 + Binder.getCallingPid() 1770 + ", uid=" + Binder.getCallingUid() 1771 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 1772 Slog.w(TAG, msg); 1773 throw new SecurityException(msg); 1774 } 1775 final ArrayList<String> changedStickyBroadcasts = new ArrayList<>(); 1776 synchronized (mStickyBroadcasts) { 1777 ArrayMap<String, ArrayList<StickyBroadcast>> stickies = mStickyBroadcasts.get(userId); 1778 if (stickies != null) { 1779 ArrayList<StickyBroadcast> list = stickies.get(intent.getAction()); 1780 if (list != null) { 1781 int N = list.size(); 1782 int i; 1783 for (i = 0; i < N; i++) { 1784 if (intent.filterEquals(list.get(i).intent)) { 1785 list.remove(i); 1786 break; 1787 } 1788 } 1789 if (list.size() <= 0) { 1790 stickies.remove(intent.getAction()); 1791 } 1792 changedStickyBroadcasts.add(intent.getAction()); 1793 } 1794 if (stickies.size() <= 0) { 1795 mStickyBroadcasts.remove(userId); 1796 } 1797 } 1798 } 1799 for (int i = changedStickyBroadcasts.size() - 1; i >= 0; --i) { 1800 BroadcastStickyCache.invalidateCache(changedStickyBroadcasts.get(i)); 1801 } 1802 } 1803 finishReceiver(IBinder caller, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, int flags)1804 void finishReceiver(IBinder caller, int resultCode, String resultData, 1805 Bundle resultExtras, boolean resultAbort, int flags) { 1806 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Finish receiver: " + caller); 1807 1808 // Refuse possible leaked file descriptors 1809 if (resultExtras != null && resultExtras.hasFileDescriptors()) { 1810 throw new IllegalArgumentException("File descriptors passed in Bundle"); 1811 } 1812 1813 final long origId = Binder.clearCallingIdentity(); 1814 try { 1815 synchronized (mService) { 1816 final ProcessRecord callerApp = mService.getRecordForAppLOSP(caller); 1817 if (callerApp == null) { 1818 Slog.w(TAG, "finishReceiver: no app for " + caller); 1819 return; 1820 } 1821 1822 mBroadcastQueue.finishReceiverLocked(callerApp, resultCode, 1823 resultData, resultExtras, resultAbort, true); 1824 // updateOomAdjLocked() will be done here 1825 mService.trimApplicationsLocked(false, OOM_ADJ_REASON_FINISH_RECEIVER); 1826 } 1827 1828 } finally { 1829 Binder.restoreCallingIdentity(origId); 1830 } 1831 } 1832 1833 /** 1834 * @return uid from the extra field {@link Intent#EXTRA_UID} if present, Otherwise -1 1835 */ getUidFromIntent(Intent intent)1836 private int getUidFromIntent(Intent intent) { 1837 if (intent == null) { 1838 return -1; 1839 } 1840 final Bundle intentExtras = intent.getExtras(); 1841 return intent.hasExtra(Intent.EXTRA_UID) 1842 ? intentExtras.getInt(Intent.EXTRA_UID) : -1; 1843 } 1844 rotateBroadcastStatsIfNeededLocked()1845 final void rotateBroadcastStatsIfNeededLocked() { 1846 final long now = SystemClock.elapsedRealtime(); 1847 if (mCurBroadcastStats == null 1848 || (mCurBroadcastStats.mStartRealtime + (24 * 60 * 60 * 1000) < now)) { 1849 mLastBroadcastStats = mCurBroadcastStats; 1850 if (mLastBroadcastStats != null) { 1851 mLastBroadcastStats.mEndRealtime = SystemClock.elapsedRealtime(); 1852 mLastBroadcastStats.mEndUptime = SystemClock.uptimeMillis(); 1853 } 1854 mCurBroadcastStats = new BroadcastStats(); 1855 } 1856 } 1857 addBroadcastStatLocked(String action, String srcPackage, int receiveCount, int skipCount, long dispatchTime)1858 final void addBroadcastStatLocked(String action, String srcPackage, int receiveCount, 1859 int skipCount, long dispatchTime) { 1860 rotateBroadcastStatsIfNeededLocked(); 1861 mCurBroadcastStats.addBroadcast(action, srcPackage, receiveCount, skipCount, dispatchTime); 1862 } 1863 addBackgroundCheckViolationLocked(String action, String targetPackage)1864 final void addBackgroundCheckViolationLocked(String action, String targetPackage) { 1865 rotateBroadcastStatsIfNeededLocked(); 1866 mCurBroadcastStats.addBackgroundCheckViolation(action, targetPackage); 1867 } 1868 notifyBroadcastFinishedLocked(@onNull BroadcastRecord original)1869 final void notifyBroadcastFinishedLocked(@NonNull BroadcastRecord original) { 1870 final ApplicationInfo info = original.callerApp != null ? original.callerApp.info : null; 1871 final String callerPackage = info != null ? info.packageName : original.callerPackage; 1872 if (callerPackage != null) { 1873 mService.mHandler.obtainMessage(ActivityManagerService.DISPATCH_SENDING_BROADCAST_EVENT, 1874 original.callingUid, 0, callerPackage).sendToTarget(); 1875 } 1876 } 1877 verifyBroadcastLocked(Intent intent)1878 final Intent verifyBroadcastLocked(Intent intent) { 1879 if (intent != null) { 1880 // Refuse possible leaked file descriptors 1881 if (intent.hasFileDescriptors()) { 1882 throw new IllegalArgumentException("File descriptors passed in Intent"); 1883 } 1884 // Remove existing mismatch flag so it can be properly updated later 1885 intent.removeExtendedFlags(Intent.EXTENDED_FLAG_FILTER_MISMATCH); 1886 } 1887 1888 int flags = intent.getFlags(); 1889 1890 if (!mService.mProcessesReady) { 1891 // if the caller really truly claims to know what they're doing, go 1892 // ahead and allow the broadcast without launching any receivers 1893 if ((flags & Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) { 1894 // This will be turned into a FLAG_RECEIVER_REGISTERED_ONLY later on if needed. 1895 } else if ((flags & Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 1896 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent 1897 + " before boot completion"); 1898 throw new IllegalStateException("Cannot broadcast before boot completed"); 1899 } 1900 } 1901 1902 if ((flags & Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 1903 throw new IllegalArgumentException( 1904 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 1905 } 1906 1907 if ((flags & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) { 1908 switch (Binder.getCallingUid()) { 1909 case ROOT_UID: 1910 case SHELL_UID: 1911 break; 1912 default: 1913 Slog.w(TAG, "Removing FLAG_RECEIVER_FROM_SHELL because caller is UID " 1914 + Binder.getCallingUid()); 1915 intent.removeFlags(Intent.FLAG_RECEIVER_FROM_SHELL); 1916 break; 1917 } 1918 } 1919 1920 return intent; 1921 } 1922 getBackgroundLaunchBroadcasts()1923 private ArraySet<String> getBackgroundLaunchBroadcasts() { 1924 if (mBackgroundLaunchBroadcasts == null) { 1925 mBackgroundLaunchBroadcasts = SystemConfig.getInstance().getAllowImplicitBroadcasts(); 1926 } 1927 return mBackgroundLaunchBroadcasts; 1928 } 1929 isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid)1930 private boolean isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid) { 1931 if (UserHandle.getAppId(uid) < FIRST_APPLICATION_UID) { 1932 return false; 1933 } 1934 // Easy case -- we have the app's ProcessRecord. 1935 if (record != null) { 1936 return record.info.isInstantApp(); 1937 } 1938 // Otherwise check with PackageManager. 1939 IPackageManager pm = AppGlobals.getPackageManager(); 1940 try { 1941 if (callerPackage == null) { 1942 final String[] packageNames = pm.getPackagesForUid(uid); 1943 if (packageNames == null || packageNames.length == 0) { 1944 throw new IllegalArgumentException("Unable to determine caller package name"); 1945 } 1946 // Instant Apps can't use shared uids, so its safe to only check the first package. 1947 callerPackage = packageNames[0]; 1948 } 1949 mService.mAppOpsService.checkPackage(uid, callerPackage); 1950 return pm.isInstantApp(callerPackage, UserHandle.getUserId(uid)); 1951 } catch (RemoteException e) { 1952 Slog.e(TAG, "Error looking up if " + callerPackage + " is an instant app.", e); 1953 return true; 1954 } 1955 } 1956 getWearRemoteIntentAction()1957 private String getWearRemoteIntentAction() { 1958 return mContext.getResources().getString( 1959 com.android.internal.R.string.config_wearRemoteIntentAction); 1960 } 1961 sendPackageBroadcastLocked(int cmd, String[] packages, int userId)1962 private void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) { 1963 mService.mProcessList.sendPackageBroadcastLocked(cmd, packages, userId); 1964 } 1965 collectReceiverComponents( Intent intent, String resolvedType, int callingUid, int callingPid, int[] users, int[] broadcastAllowList)1966 private List<ResolveInfo> collectReceiverComponents( 1967 Intent intent, String resolvedType, int callingUid, int callingPid, 1968 int[] users, int[] broadcastAllowList) { 1969 // TODO: come back and remove this assumption to triage all broadcasts 1970 long pmFlags = STOCK_PM_FLAGS | MATCH_DEBUG_TRIAGED_MISSING; 1971 1972 List<ResolveInfo> receivers = null; 1973 HashSet<ComponentName> singleUserReceivers = null; 1974 boolean scannedFirstReceivers = false; 1975 for (int user : users) { 1976 // Skip users that have Shell restrictions 1977 if (callingUid == SHELL_UID 1978 && mService.mUserController.hasUserRestriction( 1979 UserManager.DISALLOW_DEBUGGING_FEATURES, user)) { 1980 continue; 1981 } 1982 List<ResolveInfo> newReceivers = mService.mPackageManagerInt.queryIntentReceivers( 1983 intent, resolvedType, pmFlags, callingUid, callingPid, user, /* forSend */true); 1984 if (user != UserHandle.USER_SYSTEM && newReceivers != null) { 1985 // If this is not the system user, we need to check for 1986 // any receivers that should be filtered out. 1987 for (int i = 0; i < newReceivers.size(); i++) { 1988 ResolveInfo ri = newReceivers.get(i); 1989 if ((ri.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 1990 newReceivers.remove(i); 1991 i--; 1992 } 1993 } 1994 } 1995 // Replace the alias receivers with their targets. 1996 if (newReceivers != null) { 1997 for (int i = newReceivers.size() - 1; i >= 0; i--) { 1998 final ResolveInfo ri = newReceivers.get(i); 1999 final ComponentAliasResolver.Resolution<ResolveInfo> resolution = 2000 mService.mComponentAliasResolver.resolveReceiver(intent, ri, 2001 resolvedType, pmFlags, user, callingUid, callingPid); 2002 if (resolution == null) { 2003 // It was an alias, but the target was not found. 2004 newReceivers.remove(i); 2005 continue; 2006 } 2007 if (resolution.isAlias()) { 2008 newReceivers.set(i, resolution.getTarget()); 2009 } 2010 } 2011 } 2012 if (newReceivers != null && newReceivers.size() == 0) { 2013 newReceivers = null; 2014 } 2015 2016 if (receivers == null) { 2017 receivers = newReceivers; 2018 } else if (newReceivers != null) { 2019 // We need to concatenate the additional receivers 2020 // found with what we have do far. This would be easy, 2021 // but we also need to de-dup any receivers that are 2022 // singleUser. 2023 if (!scannedFirstReceivers) { 2024 // Collect any single user receivers we had already retrieved. 2025 scannedFirstReceivers = true; 2026 for (int i = 0; i < receivers.size(); i++) { 2027 ResolveInfo ri = receivers.get(i); 2028 if ((ri.activityInfo.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 2029 ComponentName cn = new ComponentName( 2030 ri.activityInfo.packageName, ri.activityInfo.name); 2031 if (singleUserReceivers == null) { 2032 singleUserReceivers = new HashSet<ComponentName>(); 2033 } 2034 singleUserReceivers.add(cn); 2035 } 2036 } 2037 } 2038 // Add the new results to the existing results, tracking 2039 // and de-dupping single user receivers. 2040 for (int i = 0; i < newReceivers.size(); i++) { 2041 ResolveInfo ri = newReceivers.get(i); 2042 if ((ri.activityInfo.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 2043 ComponentName cn = new ComponentName( 2044 ri.activityInfo.packageName, ri.activityInfo.name); 2045 if (singleUserReceivers == null) { 2046 singleUserReceivers = new HashSet<ComponentName>(); 2047 } 2048 if (!singleUserReceivers.contains(cn)) { 2049 singleUserReceivers.add(cn); 2050 receivers.add(ri); 2051 } 2052 } else { 2053 receivers.add(ri); 2054 } 2055 } 2056 } 2057 } 2058 if (receivers != null && broadcastAllowList != null) { 2059 for (int i = receivers.size() - 1; i >= 0; i--) { 2060 final int receiverAppId = UserHandle.getAppId( 2061 receivers.get(i).activityInfo.applicationInfo.uid); 2062 if (receiverAppId >= Process.FIRST_APPLICATION_UID 2063 && Arrays.binarySearch(broadcastAllowList, receiverAppId) < 0) { 2064 receivers.remove(i); 2065 } 2066 } 2067 } 2068 return receivers; 2069 } 2070 checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers)2071 private void checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, 2072 String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers) { 2073 if ((intent.getFlags() & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) { 2074 // Don't yell about broadcasts sent via shell 2075 return; 2076 } 2077 2078 final String action = intent.getAction(); 2079 if (isProtectedBroadcast 2080 || Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action) 2081 || Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS.equals(action) 2082 || Intent.ACTION_MEDIA_BUTTON.equals(action) 2083 || Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.equals(action) 2084 || Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS.equals(action) 2085 || Intent.ACTION_MASTER_CLEAR.equals(action) 2086 || Intent.ACTION_FACTORY_RESET.equals(action) 2087 || AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action) 2088 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action) 2089 || TelephonyManager.ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE.equals(action) 2090 || SuggestionSpan.ACTION_SUGGESTION_PICKED.equals(action) 2091 || AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION.equals(action) 2092 || AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION.equals(action)) { 2093 // Broadcast is either protected, or it's a public action that 2094 // we've relaxed, so it's fine for system internals to send. 2095 return; 2096 } 2097 2098 // This broadcast may be a problem... but there are often system components that 2099 // want to send an internal broadcast to themselves, which is annoying to have to 2100 // explicitly list each action as a protected broadcast, so we will check for that 2101 // one safe case and allow it: an explicit broadcast, only being received by something 2102 // that has protected itself. 2103 if (intent.getPackage() != null || intent.getComponent() != null) { 2104 if (receivers == null || receivers.size() == 0) { 2105 // Intent is explicit and there's no receivers. 2106 // This happens, e.g. , when a system component sends a broadcast to 2107 // its own runtime receiver, and there's no manifest receivers for it, 2108 // because this method is called twice for each broadcast, 2109 // for runtime receivers and manifest receivers and the later check would find 2110 // no receivers. 2111 return; 2112 } 2113 boolean allProtected = true; 2114 for (int i = receivers.size() - 1; i >= 0; i--) { 2115 Object target = receivers.get(i); 2116 if (target instanceof ResolveInfo) { 2117 ResolveInfo ri = (ResolveInfo) target; 2118 if (ri.activityInfo.exported && ri.activityInfo.permission == null) { 2119 allProtected = false; 2120 break; 2121 } 2122 } else { 2123 BroadcastFilter bf = (BroadcastFilter) target; 2124 if (bf.exported && bf.requiredPermission == null) { 2125 allProtected = false; 2126 break; 2127 } 2128 } 2129 } 2130 if (allProtected) { 2131 // All safe! 2132 return; 2133 } 2134 } 2135 2136 // The vast majority of broadcasts sent from system internals 2137 // should be protected to avoid security holes, so yell loudly 2138 // to ensure we examine these cases. 2139 if (callerApp != null) { 2140 Log.wtf(TAG, "Sending non-protected broadcast " + action 2141 + " from system " + callerApp.toShortString() + " pkg " + callerPackage, 2142 new Throwable()); 2143 } else { 2144 Log.wtf(TAG, "Sending non-protected broadcast " + action 2145 + " from system uid " + UserHandle.formatUid(callingUid) 2146 + " pkg " + callerPackage, 2147 new Throwable()); 2148 } 2149 } 2150 2151 // Apply permission policy around the use of specific broadcast options enforceBroadcastOptionPermissionsInternal( @ullable Bundle options, int callingUid)2152 void enforceBroadcastOptionPermissionsInternal( 2153 @Nullable Bundle options, int callingUid) { 2154 enforceBroadcastOptionPermissionsInternal(BroadcastOptions.fromBundleNullable(options), 2155 callingUid); 2156 } 2157 enforceBroadcastOptionPermissionsInternal( @ullable BroadcastOptions options, int callingUid)2158 private void enforceBroadcastOptionPermissionsInternal( 2159 @Nullable BroadcastOptions options, int callingUid) { 2160 if (options != null && callingUid != Process.SYSTEM_UID) { 2161 if (options.isAlarmBroadcast()) { 2162 if (DEBUG_BROADCAST_LIGHT) { 2163 Slog.w(TAG, "Non-system caller " + callingUid 2164 + " may not flag broadcast as alarm"); 2165 } 2166 throw new SecurityException( 2167 "Non-system callers may not flag broadcasts as alarm"); 2168 } 2169 if (options.isInteractive()) { 2170 mService.enforceCallingPermission( 2171 android.Manifest.permission.BROADCAST_OPTION_INTERACTIVE, 2172 "setInteractive"); 2173 } 2174 } 2175 } 2176 startBroadcastObservers()2177 void startBroadcastObservers() { 2178 mBroadcastQueue.start(mContext.getContentResolver()); 2179 } 2180 removeStickyBroadcasts(int userId)2181 void removeStickyBroadcasts(int userId) { 2182 final ArrayList<String> changedStickyBroadcasts = new ArrayList<>(); 2183 synchronized (mStickyBroadcasts) { 2184 final ArrayMap<String, ArrayList<StickyBroadcast>> stickies = 2185 mStickyBroadcasts.get(userId); 2186 if (stickies != null) { 2187 changedStickyBroadcasts.addAll(stickies.keySet()); 2188 } 2189 mStickyBroadcasts.remove(userId); 2190 } 2191 for (int i = changedStickyBroadcasts.size() - 1; i >= 0; --i) { 2192 BroadcastStickyCache.invalidateCache(changedStickyBroadcasts.get(i)); 2193 } 2194 } 2195 2196 @NeverCompile dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)2197 void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 2198 int opti, boolean dumpAll, String dumpPackage) { 2199 boolean dumpConstants = true; 2200 boolean dumpHistory = true; 2201 boolean needSep = false; 2202 boolean onlyHistory = false; 2203 boolean printedAnything = false; 2204 boolean onlyReceivers = false; 2205 int filteredUid = Process.INVALID_UID; 2206 boolean onlyFilter = false; 2207 String dumpIntentAction = null; 2208 2209 if ("history".equals(dumpPackage)) { 2210 if (opti < args.length && "-s".equals(args[opti])) { 2211 dumpAll = false; 2212 } 2213 onlyHistory = true; 2214 dumpPackage = null; 2215 } else if ("receivers".equals(dumpPackage)) { 2216 onlyReceivers = true; 2217 dumpPackage = null; 2218 if (opti + 2 <= args.length) { 2219 for (int i = opti; i < args.length; i++) { 2220 String arg = args[i]; 2221 switch (arg) { 2222 case "--uid": 2223 filteredUid = getIntArg(pw, args, ++i, Process.INVALID_UID); 2224 if (filteredUid == Process.INVALID_UID) { 2225 return; 2226 } 2227 break; 2228 default: 2229 pw.printf("Invalid argument at index %d: %s\n", i, arg); 2230 return; 2231 } 2232 } 2233 } 2234 } else if ("filter".equals(dumpPackage)) { 2235 onlyFilter = true; 2236 dumpPackage = null; 2237 if (opti + 2 <= args.length) { 2238 if ("--action".equals(args[opti++])) { 2239 dumpIntentAction = args[opti++]; 2240 if (dumpIntentAction == null) { 2241 pw.printf("Missing argument for --action option\n"); 2242 return; 2243 } 2244 } else { 2245 pw.printf("Unknown argument: %s\n", args[opti]); 2246 return; 2247 } 2248 } 2249 } 2250 2251 if (DEBUG_BROADCAST) { 2252 Slogf.d(TAG_BROADCAST, "dumpBroadcastsLocked(): dumpPackage=%s, onlyHistory=%b, " 2253 + "onlyReceivers=%b, filteredUid=%d", dumpPackage, onlyHistory, 2254 onlyReceivers, filteredUid); 2255 } 2256 2257 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)"); 2258 if (!onlyHistory && !onlyFilter && dumpAll) { 2259 if (mRegisteredReceivers.size() > 0) { 2260 boolean printed = false; 2261 Iterator it = mRegisteredReceivers.values().iterator(); 2262 while (it.hasNext()) { 2263 ReceiverList r = (ReceiverList) it.next(); 2264 if (dumpPackage != null && (r.app == null 2265 || !dumpPackage.equals(r.app.info.packageName))) { 2266 continue; 2267 } 2268 if (filteredUid != Process.INVALID_UID && filteredUid != r.app.uid) { 2269 if (DEBUG_BROADCAST) { 2270 Slogf.v(TAG_BROADCAST, "dumpBroadcastsLocked(): skipping receiver whose" 2271 + " uid (%d) is not %d: %s", r.app.uid, filteredUid, r.app); 2272 } 2273 continue; 2274 } 2275 if (!printed) { 2276 pw.println(" Registered Receivers:"); 2277 needSep = true; 2278 printed = true; 2279 printedAnything = true; 2280 } 2281 pw.print(" * "); pw.println(r); 2282 r.dump(pw, " "); 2283 } 2284 } else { 2285 if (onlyReceivers) { 2286 pw.println(" (no registered receivers)"); 2287 } 2288 } 2289 2290 if (!onlyReceivers) { 2291 if (mReceiverResolver.dump(pw, needSep 2292 ? "\n Receiver Resolver Table:" : " Receiver Resolver Table:", 2293 " ", dumpPackage, false, false)) { 2294 needSep = true; 2295 printedAnything = true; 2296 } 2297 } 2298 } 2299 2300 if (!onlyReceivers) { 2301 needSep = mBroadcastQueue.dumpLocked(fd, pw, args, opti, 2302 dumpConstants, dumpHistory, dumpAll, dumpPackage, dumpIntentAction, needSep); 2303 printedAnything |= needSep; 2304 } 2305 2306 needSep = true; 2307 2308 synchronized (mStickyBroadcasts) { 2309 if (!onlyHistory && !onlyReceivers && !onlyFilter && mStickyBroadcasts != null 2310 && dumpPackage == null) { 2311 for (int user = 0; user < mStickyBroadcasts.size(); user++) { 2312 if (needSep) { 2313 pw.println(); 2314 } 2315 needSep = true; 2316 printedAnything = true; 2317 pw.print(" Sticky broadcasts for user "); 2318 pw.print(mStickyBroadcasts.keyAt(user)); 2319 pw.println(":"); 2320 StringBuilder sb = new StringBuilder(128); 2321 for (Map.Entry<String, ArrayList<StickyBroadcast>> ent 2322 : mStickyBroadcasts.valueAt(user).entrySet()) { 2323 pw.print(" * Sticky action "); 2324 pw.print(ent.getKey()); 2325 if (dumpAll) { 2326 pw.println(":"); 2327 ArrayList<StickyBroadcast> broadcasts = ent.getValue(); 2328 final int N = broadcasts.size(); 2329 for (int i = 0; i < N; i++) { 2330 final Intent intent = broadcasts.get(i).intent; 2331 final boolean deferUntilActive = broadcasts.get(i).deferUntilActive; 2332 sb.setLength(0); 2333 sb.append(" Intent: "); 2334 intent.toShortString(sb, false, true, false, false); 2335 pw.print(sb); 2336 if (deferUntilActive) { 2337 pw.print(" [D]"); 2338 } 2339 pw.println(); 2340 pw.print(" originalCallingUid: "); 2341 pw.println(broadcasts.get(i).originalCallingUid); 2342 pw.println(); 2343 Bundle bundle = intent.getExtras(); 2344 if (bundle != null) { 2345 pw.print(" extras: "); 2346 pw.println(bundle); 2347 } 2348 } 2349 } else { 2350 pw.println(""); 2351 } 2352 } 2353 } 2354 } 2355 } 2356 2357 if (!onlyHistory && !onlyReceivers && !onlyFilter && dumpAll) { 2358 pw.println(); 2359 pw.println(" Queue " + mBroadcastQueue + ": " 2360 + mBroadcastQueue.describeStateLocked()); 2361 pw.println(" mHandler:"); 2362 mService.mHandler.dump(new PrintWriterPrinter(pw), " "); 2363 printedAnything = true; 2364 } 2365 2366 if (!printedAnything) { 2367 pw.println(" (nothing)"); 2368 } 2369 } 2370 2371 /** 2372 * Gets an {@code int} argument from the given {@code index} on {@code args}, logging an error 2373 * message on {@code pw} when it cannot be parsed. 2374 * 2375 * Returns {@code int} argument or {@code invalidValue} if it could not be parsed. 2376 */ getIntArg(PrintWriter pw, String[] args, int index, int invalidValue)2377 private static int getIntArg(PrintWriter pw, String[] args, int index, int invalidValue) { 2378 if (index > args.length) { 2379 pw.println("Missing argument"); 2380 return invalidValue; 2381 } 2382 String arg = args[index]; 2383 try { 2384 return Integer.parseInt(arg); 2385 } catch (Exception e) { 2386 pw.printf("Non-numeric argument at index %d: %s\n", index, arg); 2387 return invalidValue; 2388 } 2389 } 2390 2391 @NeverCompile dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)2392 void dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 2393 int opti, boolean dumpAll, String dumpPackage) { 2394 if (mCurBroadcastStats == null) { 2395 return; 2396 } 2397 2398 pw.println("ACTIVITY MANAGER BROADCAST STATS STATE (dumpsys activity broadcast-stats)"); 2399 final long now = SystemClock.elapsedRealtime(); 2400 if (mLastBroadcastStats != null) { 2401 pw.print(" Last stats (from "); 2402 TimeUtils.formatDuration(mLastBroadcastStats.mStartRealtime, now, pw); 2403 pw.print(" to "); 2404 TimeUtils.formatDuration(mLastBroadcastStats.mEndRealtime, now, pw); 2405 pw.print(", "); 2406 TimeUtils.formatDuration(mLastBroadcastStats.mEndUptime 2407 - mLastBroadcastStats.mStartUptime, pw); 2408 pw.println(" uptime):"); 2409 if (!mLastBroadcastStats.dumpStats(pw, " ", dumpPackage)) { 2410 pw.println(" (nothing)"); 2411 } 2412 pw.println(); 2413 } 2414 pw.print(" Current stats (from "); 2415 TimeUtils.formatDuration(mCurBroadcastStats.mStartRealtime, now, pw); 2416 pw.print(" to now, "); 2417 TimeUtils.formatDuration(SystemClock.uptimeMillis() 2418 - mCurBroadcastStats.mStartUptime, pw); 2419 pw.println(" uptime):"); 2420 if (!mCurBroadcastStats.dumpStats(pw, " ", dumpPackage)) { 2421 pw.println(" (nothing)"); 2422 } 2423 } 2424 2425 @NeverCompile dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean fullCheckin, String dumpPackage)2426 void dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, 2427 int opti, boolean fullCheckin, String dumpPackage) { 2428 if (mCurBroadcastStats == null) { 2429 return; 2430 } 2431 2432 if (mLastBroadcastStats != null) { 2433 mLastBroadcastStats.dumpCheckinStats(pw, dumpPackage); 2434 if (fullCheckin) { 2435 mLastBroadcastStats = null; 2436 return; 2437 } 2438 } 2439 mCurBroadcastStats.dumpCheckinStats(pw, dumpPackage); 2440 if (fullCheckin) { 2441 mCurBroadcastStats = null; 2442 } 2443 } 2444 writeBroadcastsToProtoLocked(ProtoOutputStream proto)2445 void writeBroadcastsToProtoLocked(ProtoOutputStream proto) { 2446 if (mRegisteredReceivers.size() > 0) { 2447 Iterator it = mRegisteredReceivers.values().iterator(); 2448 while (it.hasNext()) { 2449 ReceiverList r = (ReceiverList) it.next(); 2450 r.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_LIST); 2451 } 2452 } 2453 mReceiverResolver.dumpDebug(proto, 2454 ActivityManagerServiceDumpBroadcastsProto.RECEIVER_RESOLVER); 2455 mBroadcastQueue.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.BROADCAST_QUEUE); 2456 synchronized (mStickyBroadcasts) { 2457 for (int user = 0; user < mStickyBroadcasts.size(); user++) { 2458 long token = proto.start( 2459 ActivityManagerServiceDumpBroadcastsProto.STICKY_BROADCASTS); 2460 proto.write(StickyBroadcastProto.USER, mStickyBroadcasts.keyAt(user)); 2461 for (Map.Entry<String, ArrayList<StickyBroadcast>> ent 2462 : mStickyBroadcasts.valueAt(user).entrySet()) { 2463 long actionToken = proto.start(StickyBroadcastProto.ACTIONS); 2464 proto.write(StickyBroadcastProto.StickyAction.NAME, ent.getKey()); 2465 for (StickyBroadcast broadcast : ent.getValue()) { 2466 broadcast.intent.dumpDebug(proto, StickyBroadcastProto.StickyAction.INTENTS, 2467 false, true, true, false); 2468 } 2469 proto.end(actionToken); 2470 } 2471 proto.end(token); 2472 } 2473 } 2474 2475 long handlerToken = proto.start(ActivityManagerServiceDumpBroadcastsProto.HANDLER); 2476 proto.write(ActivityManagerServiceDumpBroadcastsProto.MainHandler.HANDLER, 2477 mService.mHandler.toString()); 2478 mService.mHandler.getLooper().dumpDebug(proto, 2479 ActivityManagerServiceDumpBroadcastsProto.MainHandler.LOOPER); 2480 proto.end(handlerToken); 2481 } 2482 2483 @VisibleForTesting 2484 static final class StickyBroadcast { 2485 public Intent intent; 2486 public boolean deferUntilActive; 2487 public int originalCallingUid; 2488 /** The snapshot process state of the app who sent this broadcast */ 2489 public int originalCallingAppProcessState; 2490 public String resolvedDataType; 2491 create(Intent intent, boolean deferUntilActive, int originalCallingUid, int originalCallingAppProcessState, String resolvedDataType)2492 public static StickyBroadcast create(Intent intent, boolean deferUntilActive, 2493 int originalCallingUid, int originalCallingAppProcessState, 2494 String resolvedDataType) { 2495 final StickyBroadcast b = new StickyBroadcast(); 2496 b.intent = intent; 2497 b.deferUntilActive = deferUntilActive; 2498 b.originalCallingUid = originalCallingUid; 2499 b.originalCallingAppProcessState = originalCallingAppProcessState; 2500 b.resolvedDataType = resolvedDataType; 2501 return b; 2502 } 2503 2504 @Override toString()2505 public String toString() { 2506 return "{intent=" + intent + ", defer=" + deferUntilActive + ", originalCallingUid=" 2507 + originalCallingUid + ", originalCallingAppProcessState=" 2508 + originalCallingAppProcessState + ", type=" + resolvedDataType + "}"; 2509 } 2510 } 2511 } 2512