if (Process.isSdkSandboxUid(callingUid)) { SdkSandboxManagerLocal sdkSandboxManagerLocal = LocalManagerRegistry.getManager( SdkSandboxManagerLocal.class); if (sdkSandboxManagerLocal == null) { thrownew IllegalStateException("SdkSandboxManagerLocal not found when starting" + " an activity from an SDK sandbox uid."); } sdkSandboxManagerLocal.enforceAllowedToStartActivity(intent); }
/** * Start an activity and determine if the activity should be adding to the top of an existing * task or delivered new intent to an existing activity. Also manipulating the activity task * onto requested or valid root-task/display. * * Note: This method should only be called from {@link #startActivityUnchecked}. */ // TODO(b/152429287): Make it easier to exercise code paths through startActivityInner @VisibleForTesting intstartActivityInner(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, ActivityOptions options, Task inTask, TaskFragment inTaskFragment, BalVerdict balVerdict, NeededUriGrants intentGrants, int realCallingUid){ setInitialState(r, options, inTask, inTaskFragment, startFlags, sourceRecord, voiceSession, voiceInteractor, balVerdict, realCallingUid); // ... // Check if starting activity on given task or on a new task is allowed. int startResult = isAllowedToStart(r, newTask, targetTask); if (startResult != START_SUCCESS) { if (r.resultTo != null) { r.resultTo.sendResult(INVALID_UID, r.resultWho, r.requestCode, RESULT_CANCELED, null/* data */, null/* callerToken */, null/* dataGrants */); } return startResult; } // ... }
@VisibleForTesting intisAllowedToStart(ActivityRecord r, boolean newTask, Task targetTask){ // Do not allow background activity start in new task or in a task that uid is not present. // Also do not allow pinned window to start single instance activity in background, // as it will recreate the window and makes it to foreground. boolean blockBalInTask = (newTask || !targetTask.isUidPresent(mCallingUid) || (LAUNCH_SINGLE_INSTANCE == mLaunchMode && targetTask.inPinnedWindowingMode()));
if (mBalVerdict.blocks() && blockBalInTask && handleBackgroundActivityAbort(r)) { Slog.e(TAG, "Abort background activity starts from " + mCallingUid); return START_ABORTED; }
staticclassBalVerdict{ staticfinal BalVerdict BLOCK = new BalVerdict(BAL_BLOCK, "Blocked", true); staticfinal BalVerdict ALLOW_BY_DEFAULT = new BalVerdict(BAL_ALLOW_DEFAULT, "Default", true); // Careful using this - it will bypass all ASM checks. staticfinal BalVerdict ALLOW_PRIVILEGED = new BalVerdict(BAL_ALLOW_ALLOWLISTED_UID, "PRIVILEGED", true); privatefinal@BalCodeint mCode; privatefinal String mMessage; privatefinalboolean mImmutable; private String mProcessInfo; // indicates BAL would be blocked because only creator of the PI has the privilege to allow // BAL, the sender does not have the privilege to allow BAL. privateboolean mOnlyCreatorAllows; /** indicates that this verdict is based on the real calling UID and not the calling UID */ privateboolean mBasedOnRealCaller; privateboolean mAllowlisteUid; privateboolean mInGracePeriod; privateboolean mAllowsNewTask; privateboolean mVisibleOrForeground; private SparseBooleanArray mAdditionalBalCodes; booleanblocks(){ return mCode == BAL_BLOCK; }
if (mAutoOptInCaller) { // grant BAL privileges unless explicitly opted out mBalAllowedByPiCreator = callerBackgroundActivityStartMode == MODE_BACKGROUND_ACTIVITY_START_DENIED ? BackgroundStartPrivileges.NONE : BackgroundStartPrivileges.ALLOW_BAL; } else { // for PendingIntents we restrict BAL based on target_sdk mBalAllowedByPiCreator = getBackgroundStartPrivilegesAllowedByCreator( callingUid, callingPackage, checkedOptions); }
if (mAutoOptInReason != null) { // grant BAL privileges unless explicitly opted out mBalAllowedByPiSender = realCallerBackgroundActivityStartMode == MODE_BACKGROUND_ACTIVITY_START_DENIED ? BackgroundStartPrivileges.NONE : BackgroundStartPrivileges.ALLOW_BAL; } else { // for PendingIntents we restrict BAL based on target_sdk mBalAllowedByPiSender = PendingIntentRecord.getBackgroundStartPrivilegesAllowedByCaller( checkedOptions, realCallingUid, mRealCallingPackage); }
mAppSwitchState = getService().getBalAppSwitchesState(); mCallingUidProcState = getService().mActiveUids.getUidState(callingUid); mIsCallingUidPersistentSystemProcess = mCallingUidProcState <= ActivityManager.PROCESS_STATE_PERSISTENT_UI; mCallingUidHasVisibleActivity = getService().mVisibleActivityProcessTracker.hasVisibleActivity(callingUid); mCallingUidHasVisibleNotPinnedActivity = getService().mVisibleActivityProcessTracker .hasVisibleNotPinnedActivity(callingUid); mCallingUidHasNonAppVisibleWindow = getService().mActiveUids.hasNonAppVisibleWindow( callingUid); if (realCallingUid == NO_PROCESS_UID) { // no process provided mRealCallingUidProcState = PROCESS_STATE_NONEXISTENT; mRealCallingUidHasVisibleActivity = false; mRealCallingUidHasNonAppVisibleWindow = false; mRealCallingUidHasVisibleNotPinnedActivity = false; mRealCallerApp = null; mIsRealCallingUidPersistentSystemProcess = false; } elseif (callingUid == realCallingUid) { mRealCallingUidProcState = mCallingUidProcState; mRealCallingUidHasVisibleActivity = mCallingUidHasVisibleActivity; mRealCallingUidHasVisibleNotPinnedActivity = mCallingUidHasVisibleNotPinnedActivity; mRealCallingUidHasNonAppVisibleWindow = mCallingUidHasNonAppVisibleWindow; // In the PendingIntent case callerApp is not passed in, so resolve it ourselves. mRealCallerApp = callerApp == null ? getService().getProcessController(realCallingPid, realCallingUid) : callerApp; mIsRealCallingUidPersistentSystemProcess = mIsCallingUidPersistentSystemProcess; } /* else 暂时不分析*/ }
/** * Check if a (background) activity start is allowed. * * @param callingUid The UID that wants to start the activity. * @param callingPid The PID that wants to start the activity. * @param callingPackage The package name that wants to start the activity. * @param realCallingUid The UID that actually calls this method (only if this handles a * PendingIntent, otherwise -1) * @param realCallingPid The PID that actually calls this method (only if this handles a * * PendingIntent, otherwise -1) * @param callerApp The process that calls this method (only if not a PendingIntent) * @param originatingPendingIntent PendingIntentRecord that originated this activity start or * null if not originated by PendingIntent * @param allowBalExemptionForSystemProcess If set to true, the * PendingIntent's sender will allow additional exemptions. * This is only possible if the sender of the PendingIntent is a system process. * @param resultRecord If not null, this indicates that the caller expects a result. * @param intent Intent that should be started. * @param checkedOptions ActivityOptions to allow specific opt-ins/opt outs. * * @return A verdict denoting which BAL rule allows an activity to be started, * or if the launch should be blocked. */ BalVerdict checkBackgroundActivityStart( int callingUid, int callingPid, final String callingPackage, int realCallingUid, int realCallingPid, WindowProcessController callerApp, PendingIntentRecord originatingPendingIntent, boolean allowBalExemptionForSystemProcess, ActivityRecord resultRecord, Intent intent, ActivityOptions checkedOptions){
if (checkedOptions == null) { // replace null with a constant to simplify evaluation checkedOptions = ACTIVITY_OPTIONS_SYSTEM_DEFINED; }
BalState state = new BalState(callingUid, callingPid, callingPackage, realCallingUid, realCallingPid, callerApp, originatingPendingIntent, allowBalExemptionForSystemProcess, resultRecord, intent, checkedOptions);
// In the case of an SDK sandbox calling uid, check if the corresponding app uid has a // visible window. if (Process.isSdkSandboxUid(state.mRealCallingUid)) { int realCallingSdkSandboxUidToAppUid = Process.getAppUidForSdkSandboxUid(state.mRealCallingUid); // realCallingSdkSandboxUidToAppUid should probably just be used instead (or in addition // to realCallingUid when calculating resultForRealCaller below. if (getService().hasActiveVisibleNotPinnedWindow(realCallingSdkSandboxUidToAppUid)) { state.setResultForRealCaller(new BalVerdict(BAL_ALLOW_SDK_SANDBOX, "uid in SDK sandbox has visible (non-toast) window").allowNewTask()); return allowBasedOnRealCaller(state); } }
// In the case of a PCC calling uid, check if the corresponding app uid has a // visible window. if (enablePccFrameworkSupport() && Process.isPrivateComputeCoreUid(state.mRealCallingUid)) { int realCallingAppUid = getService().mContext.getPackageManager() .getAppUidForPrivateComputeCoreUid(state.mRealCallingUid);
if (getService().hasActiveVisibleNotPinnedWindow(realCallingAppUid)) { state.setResultForRealCaller(new BalVerdict( BAL_ALLOW_PCC_DEFINING_APP_HAS_VISIBLE_WINDOW, "PCC process's parent app has visible (non-toast) window") .allowNewTask()); return allowBasedOnRealCaller(state); } }
/** * @return A code denoting which BAL rule allows an activity to be started, * or {@link #BAL_BLOCK} if the launch should be blocked */ BalVerdict checkBackgroundActivityStartAllowedByCaller(BalState state){ boolean evaluateVisibleOnly = state.mCheckedOptions.getPendingIntentCreatorBackgroundActivityStartMode() == MODE_BACKGROUND_ACTIVITY_START_ALLOW_IF_VISIBLE; boolean basedOnRealCaller = false; if (evaluateVisibleOnly) { // 不重要 return evaluateChain(state, basedOnRealCaller, mCheckCallerVisible, mCheckCallerNonAppVisible, mCheckCallerProcessAllowsForeground); } if (state.isPendingIntent()) { // 不重要 // PendingIntents should mostly be allowed by the sender (real caller) or a permission // the creator of the PendingIntent has. Visibility should be the exceptional case, so // test it last (this does not change the result, just the bal code). return evaluateChain(state, basedOnRealCaller, mCheckCallerIsAllowlistedUid, mCheckCallerIsAllowlistedComponent, mCheckCallerHasBackgroundPermission, mCheckCallerHasSawPermission, mCheckCallerHasBgStartAppOp, mCheckCallerProcessAllowsBackground, mCheckCallerVisible, mCheckCallerNonAppVisible, mCheckCallerProcessAllowsForeground, mCheckCallerProcessInGracePeriod); } return evaluateChain(state, basedOnRealCaller, mCheckCallerVisible, mCheckCallerNonAppVisible, mCheckCallerNonActivityTop, mCheckCallerProcessAllowsForeground, mCheckCallerIsAllowlistedUid, mCheckCallerIsAllowlistedComponent, mCheckCallerHasBackgroundPermission, mCheckCallerHasSawPermission, mCheckCallerHasBgStartAppOp, mCheckCallerProcessAllowsBackground, mCheckCallerProcessInGracePeriod); }
private BalVerdict evaluateChain(BalState state, boolean basedOnRealCaller, BalExemptionCheck... checks){ BalVerdict result = BalVerdict.BLOCK; for (BalExemptionCheck check : checks) { if (!result.allows()) { result = check.evaluate(state); } else { // we already have a result, but may need to fill in a few missing parts if (check == mCheckCallerProcessInGracePeriod || check == mCheckRealCallerProcessInGracePeriod) { result.setInGracePeriod(check.evaluate(state).allows()); } elseif (check == mCheckCallerIsAllowlistedUid || check == mCheckRealCallerAllowlistedUid) { result.setAllowlisteUid(check.evaluate(state).allows()); } elseif (DEBUG_ACTIVITY_STARTS) { result.addAdditionalVerdict(check.evaluate(state)); } } } if (basedOnRealCaller && !result.isImmutable()) { result.setBasedOnRealCaller(); } return result; }
privatefinal BalExemptionCheck mCheckCallerVisible = state -> { // This is used to block background activity launch even if the app is still // visible to user after user clicking home button.
// Normal apps with visible app window will be allowed to start activity if app switching // is allowed, or apps like live wallpaper with non app visible window will be allowed. // The home app can start apps even if app switches are usually disallowed. finalboolean appSwitchAllowedOrFg = state.mAppSwitchState == APP_SWITCH_ALLOW || state.mAppSwitchState == APP_SWITCH_FG_ONLY || isHomeApp(state.mCallingUid, state.mCallingPackage); if (appSwitchAllowedOrFg && state.mCallingUidHasVisibleNotPinnedActivity) { returnnew BalVerdict(BAL_ALLOW_VISIBLE_WINDOW, "callingUid has visible non-pinned window") .allowNewTask().setVisibleOrForeground(); } return BalVerdict.BLOCK; };
/** * Check if any Activity is visible (or visibility requested) and not pinned. */ booleanhasVisibleNotPinnedActivity(){ if (!hasVisibleActivities()) returnfalse; for (int i = mActivities.size() - 1; i >= 0; --i) { final ActivityRecord activityRecord = mActivities.get(i); if ((activityRecord.isVisible() || activityRecord.isVisibleRequested()) && !activityRecord.inPinnedWindowingMode()) { returntrue; } } returnfalse; }
privatefinal BalExemptionCheck mCheckCallerNonActivityTop = state -> { // Allows if the UID process state is at the top and the app is not yet hosting any // activities. This is possible if the application starts an activity within its // `Application#onCreate` method when the process started, identifying a visible activity // from that app is not possible because the application process has not yet fully attached. if (state.mCallerApp != null && !state.mCallerApp.hasActivities() && state.mCallingUidProcState == PROCESS_STATE_TOP) { returnnew BalVerdict(BAL_ALLOW_FOREGROUND, "callingUid is the current top"); } return BalVerdict.BLOCK; };
放行没有 activity 但是进程状态为 top 的进程,主要是为了在 Application.onCreate() 里启动 activity 的 app。
/** Called when the surface of non-application (exclude toast) window is shown or hidden. */ synchronizedvoidonNonAppSurfaceVisibilityChanged(int uid, int type, boolean visible){ updateCount(uid, visible, mNumNonAppVisibleWindowMap); updateCount(uid, visible, getNumNonAppVisibleWindowMapByType(type)); }
private SparseIntArray getNumNonAppVisibleWindowMapByType(int type){ SparseIntArray result = mNumNonAppVisibleWindowMapByType.get(type); if (result == null) { result = new SparseIntArray(); mNumNonAppVisibleWindowMapByType.append(type, result); } return result; }
/** * Returns {@code true} if the uid has any non-application (exclude toast) window currently * visible to the user. The application window visibility of a uid can be found from * {@link VisibleActivityProcessTracker}. */ synchronizedbooleanhasNonAppVisibleWindow(int uid){ return mNumNonAppVisibleWindowMap.get(uid) > 0; }
if (shown) { initExclusionRestrictions(); } else { logExclusionRestrictions(EXCLUSION_LEFT); logExclusionRestrictions(EXCLUSION_RIGHT); getDisplayContent().removeImeScreenshotByTarget(this); } // Exclude toast because legacy apps may show toast window by themselves, so the misused // apps won't always be considered as foreground state. // Exclude private presentations as they can only be shown on private virtual displays and // shouldn't be the cause of an app be considered foreground. // Exclude presentations on virtual displays as they are not actually visible. if (mAttrs.type >= FIRST_SYSTEM_WINDOW && mAttrs.type != TYPE_TOAST && mAttrs.type != TYPE_PRIVATE_PRESENTATION && !(mAttrs.type == TYPE_PRESENTATION && isOnVirtualDisplay()) ) { mWmService.mAtmService.mActiveUids.onNonAppSurfaceVisibilityChanged(mOwnerUid, mAttrs.type, shown); } }
privatefinal BalExemptionCheck mCheckCallerIsAllowlistedComponent = state -> { // Always allow home application to start activities. if (isHomeApp(state.mCallingUid, state.mCallingPackage)) { returnnew BalVerdict(BAL_ALLOW_ALLOWLISTED_COMPONENT, "Home app").allowNewTask(); }
finalint callingAppId = UserHandle.getAppId(state.mCallingUid); // IME should always be allowed to start activity, like IME settings. final WindowState imeWindow = getService().mRootWindowContainer.getCurrentImeWindow(); if (imeWindow != null && callingAppId == imeWindow.mOwnerUid) { returnnew BalVerdict(BAL_ALLOW_ALLOWLISTED_COMPONENT, "Active ime").allowNewTask(); }
// don't abort if the callingUid is a persistent system process if (state.mIsCallingUidPersistentSystemProcess) { returnnew BalVerdict(BAL_ALLOW_ALLOWLISTED_COMPONENT, "callingUid is persistent system process").allowNewTask(); }
// don't abort if the caller has the same uid as the recents component if (getSupervisor().mRecentTasks.isCallerRecents(state.mCallingUid)) { returnnew BalVerdict(BAL_ALLOW_ALLOWLISTED_COMPONENT, "Recents Component") .allowNewTask(); } // don't abort if the callingUid is the device owner if (getService().isDeviceOwner(state.mCallingUid)) { returnnew BalVerdict(BAL_ALLOW_ALLOWLISTED_COMPONENT, "Device Owner").allowNewTask(); } // don't abort if the callingUid is a affiliated profile owner if (getService().isAffiliatedProfileOwner(state.mCallingUid)) { returnnew BalVerdict(BAL_ALLOW_ALLOWLISTED_COMPONENT, "Affiliated Profile Owner") .allowNewTask(); } // don't abort if the callingUid has companion device finalint callingUserId = UserHandle.getUserId(state.mCallingUid); if (getService().isAssociatedCompanionApp(callingUserId, state.mCallingUid)) { returnnew BalVerdict(BAL_ALLOW_ALLOWLISTED_COMPONENT, "Companion App").allowNewTask(); } return BalVerdict.BLOCK; };
/** * Keeps track of the static recents package/component which is granted additional permissions * to call recents-related APIs. */ privateint mRecentsUid = -1; /** * Loads the static recents component. This is called after the system is ready, but before * any dependent services (like SystemUI) is started. */ voidloadRecentsComponent(Resources res){ final String rawRecentsComponent = res.getString( com.android.internal.R.string.config_recentsComponentName); if (TextUtils.isEmpty(rawRecentsComponent)) { return; }
final ComponentName cn = ComponentName.unflattenFromString(rawRecentsComponent); if (cn != null) { try { final ApplicationInfo appInfo = AppGlobals.getPackageManager().getApplicationInfo( cn.getPackageName(), PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS, mService.mContext.getUserId()); if (appInfo != null) { mRecentsUid = appInfo.uid; mRecentsComponent = cn; } } catch (RemoteException e) { Slog.w(TAG, "Could not load application info for recents component: " + cn); } } } /** * @return whether the current caller has the same uid as the recents component. */ booleanisCallerRecents(int callingUid){ return isSameApp(callingUid, mRecentsUid); }
/** * Update ActivityManager and ActivityTaskManager exemptions */ publicvoidupdateAtm(int userId, List<AssociationInfo> associations){ final Set<Integer> companionAppUids = new ArraySet<>(); for (AssociationInfo association : associations) { int uid = mPackageManager.getPackageUid(association.getPackageName(), 0, userId); if (uid >= 0) { companionAppUids.add(uid); } } if (mAtmInternal != null) { mAtmInternal.setCompanionAppUids(userId, companionAppUids); } if (mAmInternal != null) { // Make a copy of the set and send it to ActivityManager. mAmInternal.setCompanionAppUids(userId, new ArraySet<>(companionAppUids)); } }
// Don't abort if the callerApp or other processes of that uid are considered to be in the // foreground. privatefinal BalExemptionCheck mCheckCallerProcessAllowsForeground = state -> checkProcessAllowsBal(state.mCallerApp, state, BAL_CHECK_FOREGROUND); // Don't abort if the callerApp or other processes of that uid are allowed in any way. privatefinal BalExemptionCheck mCheckCallerProcessAllowsBackground = state -> checkProcessAllowsBal(state.mCallerApp, state, BAL_CHECK_BACKGROUND); privatefinal BalExemptionCheck mCheckCallerProcessInGracePeriod = state -> checkProcessAllowsBal(state.mCallerApp, state, BAL_CHECK_GRACE_PERIOD);
/** * Check if the app allows BAL. * <p> * See {@link BackgroundLaunchProcessController#areBackgroundActivityStartsAllowed(int, int, * String, int, boolean, boolean, boolean, long, long, long)} for details on the * exceptions. */ @VisibleForTestingBalVerdict checkProcessAllowsBal(WindowProcessController app, BalState state, BalCheckConfiguration balCheckConfiguration){ if (app == null) { return BalVerdict.BLOCK; } // first check the original calling process final BalVerdict balAllowedForCaller = app .areBackgroundActivityStartsAllowed(state.mAppSwitchState, balCheckConfiguration); if (balAllowedForCaller.allows()) { return balAllowedForCaller.withProcessInfo("callerApp process", app); } else { // only if that one wasn't allowed, check the other ones final ArraySet<WindowProcessController> uidProcesses = getService().mProcessMap.getProcesses(app.mUid); if (uidProcesses != null) { for (int i = uidProcesses.size() - 1; i >= 0; i--) { final WindowProcessController proc = uidProcesses.valueAt(i); if (proc != app) { BalVerdict balAllowedForUid = proc.areBackgroundActivityStartsAllowed( state.mAppSwitchState, balCheckConfiguration); if (balAllowedForUid.allows()) { return balAllowedForUid.withProcessInfo("process", proc); } } } } } return BalVerdict.BLOCK; }
BalVerdict areBackgroundActivityStartsAllowed( int pid, int uid, String packageName, int appSwitchState, BalCheckConfiguration checkConfiguration, boolean hasActivityInVisibleTask, boolean inPinnedWindow, boolean hasBackgroundActivityStartPrivileges, long lastStopAppSwitchesTime, long lastActivityLaunchTime, long lastActivityFinishTime){ // Allow if the proc is instrumenting with background activity starts privs. if (checkConfiguration.checkOtherExemptions && hasBackgroundActivityStartPrivileges) { returnnew BalVerdict(BAL_ALLOW_PERMISSION, /*background*/ "process instrumenting with background activity starts privileges") .allowNewTask(); } // Allow if the token is explicitly allowed. if (checkConfiguration.checkOtherExemptions) { BalVerdict tokenVerdict = isBackgroundStartAllowedByToken(uid, packageName, checkConfiguration.isCheckingForFgsStart); if (tokenVerdict.allows()) { return tokenVerdict; } } // Allow if the caller is bound by a UID that's currently foreground. // But still respect the appSwitchState. if (checkConfiguration.checkVisibility && appSwitchState != APP_SWITCH_DISALLOW && isBoundByForegroundUid(checkConfiguration.isCheckingForFgsStart ? mUidHasActiveVisibleWindowPredicate : mUidHasActiveVisibleNotPinnedWindowPredicate)) { returnnew BalVerdict(BAL_ALLOW_BOUND_BY_FOREGROUND, "process bound by foreground uid") .allowNewTask().setVisibleOrForeground(); } // Allow if the caller has an activity in any foreground task, unless it's a pinned window // and not a foreground service start. if ((checkConfiguration.isCheckingForFgsStart || !inPinnedWindow) && checkConfiguration.checkOtherExemptions && hasActivityInVisibleTask && appSwitchState != APP_SWITCH_DISALLOW) { returnnew BalVerdict(BAL_ALLOW_FOREGROUND, /*background*/ "process has activity in foreground task").setVisibleOrForeground(); }
// If app switching is not allowed, we ignore all the start activity grace period // exception so apps cannot start itself in onPause() after pressing home button. if (checkConfiguration.gracePeriod > 0 && appSwitchState == APP_SWITCH_ALLOW) { // Allow if any activity in the caller has either started or finished very recently, and // it must be started or finished after last stop app switches time. if (lastActivityLaunchTime > lastStopAppSwitchesTime || lastActivityFinishTime > lastStopAppSwitchesTime) { finallong now = SystemClock.uptimeMillis(); long timeSinceLastStartOrFinish = now - Math.max(lastActivityLaunchTime, lastActivityFinishTime); if (timeSinceLastStartOrFinish < checkConfiguration.gracePeriod) { returnnew BalVerdict(BAL_ALLOW_GRACE_PERIOD, /*background*/ "within " + checkConfiguration.gracePeriod + "ms grace period (" + timeSinceLastStartOrFinish + "ms)"); } } } return BalVerdict.BLOCK; }
/** * A set of tokens that currently contribute to this process being temporarily allowed * to start activities even if it's not in the foreground. The values of this map are optional * (can be null) and are used to trace back the grant to the notification token mechanism. */ @GuardedBy("this") private@Nullable ArrayMap<Binder, BackgroundStartPrivileges> mBackgroundStartPrivileges;
/** * If there are no tokens, we don't allow *by token*. If there are tokens and * isCheckingForFgsStart is false, we ask the callback if the start is allowed for these tokens, * otherwise if there is no callback we allow. */ private BalVerdict isBackgroundStartAllowedByToken(int uid, String packageName, boolean isCheckingForFgsStart){ synchronized (this) { if (mBackgroundStartPrivileges == null || mBackgroundStartPrivileges.isEmpty()) { // no tokens to allow anything return BalVerdict.BLOCK; } List<IBinder> binderTokens = new ArrayList<>(); for (int i = mBackgroundStartPrivileges.size(); i-- > 0; ) { BackgroundStartPrivileges backgroundStartPrivileges = mBackgroundStartPrivileges.valueAt(i); if (isCheckingForFgsStart) { if (!backgroundStartPrivileges.allowsBackgroundFgsStarts()) { continue; } returnnew BalVerdict(BAL_ALLOW_TOKEN, "process allowed by token"); } if (!backgroundStartPrivileges.allowsBackgroundActivityStarts()) { continue; } if (backgroundStartPrivileges.getOriginatingToken() == null) { // internal token - always allow returnnew BalVerdict(BAL_ALLOW_TOKEN, "process allowed by token") .allowNewTask(); } if (mBackgroundActivityStartCallback == null) { // without a callback accept any token returnnew BalVerdict(BAL_ALLOW_TOKEN, "process allowed by token") .allowNewTask(); } if (!(Flags.balIgnoreCallback() && CompatChanges.isChangeEnabled(CALLBACK_IS_NOOP, packageName, UserHandle.getUserHandleForUid(uid)))) { binderTokens.add(backgroundStartPrivileges.getOriginatingToken()); } } if (binderTokens.isEmpty()) { // no tokens to allow anything return BalVerdict.BLOCK; } // The callback will decide if the token is accepted. BackgroundActivityStartCallback.BackgroundActivityStartCallbackResult activityStartAllowed = mBackgroundActivityStartCallback.isActivityStartAllowed( binderTokens, uid, packageName); if (!activityStartAllowed.allowed()) { return BalVerdict.BLOCK; } returnnew BalVerdict(BAL_ALLOW_NOTIFICATION_TOKEN, "process allowed by callback (token: " + activityStartAllowed.token() + ") tokens: " + binderTokens).allowNewTask(); } }
/** * Privileges granted to a Process that allows it to execute starts from the background. * @hide */ publicfinalclassBackgroundStartPrivileges{ /** No privileges. */ publicstaticfinal BackgroundStartPrivileges NONE = new BackgroundStartPrivileges( false, false, null); /** Allow activity starts (and implies allowing foreground service starts). */ publicstaticfinal BackgroundStartPrivileges ALLOW_BAL = new BackgroundStartPrivileges( true, true, null); /** Allow foreground service starts. */ publicstaticfinal BackgroundStartPrivileges ALLOW_FGS = new BackgroundStartPrivileges( false, true, null);
/** * Return a token that allows background activity starts and attributes it to a specific * originatingToken. */ publicstatic BackgroundStartPrivileges allowBackgroundActivityStarts( @Nullable IBinder originatingToken){ if (originatingToken == null) { // try to avoid creating new instances return ALLOW_BAL; } returnnew BackgroundStartPrivileges(true, true, originatingToken); }
至于这个 token 到底是何方神圣,这个很复杂,我打算在下一篇文章里详细介绍。现在你只需要知道这是 system server 创建的一个 binder 对象,可以在进程之间传递就行了。
言归正传,这个判断检查的是 BackgroundLaunchProcessController 里的 mBackgroundStartPrivileges,也就是检查有没有允许 BAL 的 BackgroundStartPrivileges 附着在了当前进程上。什么时候会发生这种情况?最常见的情况就是当前进程里有服务被特权进程使用 BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS 绑定:
/** * Whether the process this service runs in should be temporarily allowed to start * activities from background depends on the current state of both * {@code mIsAllowedBgActivityStartsByStart} and * {@code mIsAllowedBgActivityStartsByBinding}. If either is true, this ServiceRecord * should be contributing as a token in parent ProcessRecord. * * @see com.android.server.am.ProcessRecord#addOrUpdateBackgroundStartPrivileges(Binder, * BackgroundStartPrivileges) * @see com.android.server.am.ProcessRecord#removeBackgroundStartPrivileges(Binder) */ privatevoidupdateParentProcessBgActivityStartsToken(){ if (getHostProcess() == null) { return; } BackgroundStartPrivileges backgroundStartPrivileges = getBackgroundStartPrivilegesWithExclusiveToken(); if (backgroundStartPrivileges.allowsAny()) { // if the token is already there it's safe to "re-add it" - we're dealing with // a set of Binder objects getHostProcess().addOrUpdateBackgroundStartPrivileges(this, backgroundStartPrivileges); } else { getHostProcess().removeBackgroundStartPrivileges(this); } }
/** * Returns {@link BackgroundStartPrivileges} that represents the privileges a specific * originating token or a generic aggregate token. * * If all privileges are associated with the same token (i.e. the service is only allowed due * to starts) the token will be retained, otherwise (e.g. the privileges were granted by * bindings) the originating token will be empty. */ @Nullable private BackgroundStartPrivileges getBackgroundStartPrivilegesWithExclusiveToken(){ if (mIsAllowedBgActivityStartsByBinding) { return BackgroundStartPrivileges.ALLOW_BAL; } if (mBackgroundStartPrivilegesByStart.isEmpty()) { return BackgroundStartPrivileges.NONE; } return mBackgroundStartPrivilegesByStartMerged; }
if (brOptions.allowsBackgroundActivityStarts()) { // See if the caller is allowed to do this. Note we are checking against // the actual real caller (not whoever provided the operation as say a // PendingIntent), because that who is actually supplied the arguments. if (checkComponentPermission( android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND, realCallingPid, realCallingUid, -1, true) != PackageManager.PERMISSION_GRANTED) { String msg = "Permission Denial: " + intent.getAction() + " broadcast from " + callerPackage + " (pid=" + callingPid + ", uid=" + callingUid + ")" + " requires " + android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND; Slog.w(TAG, msg); thrownew SecurityException(msg); } else { // We set the token to null since if it wasn't for it we'd allow anyway here backgroundStartPrivileges = BackgroundStartPrivileges.ALLOW_BAL; } }
privatebooleanisBoundByForegroundUid(IntPredicate uidVisibilityPredicate){ synchronized (this) { if (mBalOptInBoundClientUids != null) { for (int i = mBalOptInBoundClientUids.size() - 1; i >= 0; i--) { if (uidVisibilityPredicate.test(mBalOptInBoundClientUids.get(i))) { returntrue; } } } } returnfalse; }
mBalOptInBoundClientUids 是绑定到当前进程提供的服务并且允许了 activity 启动(指定了 BIND_ALLOW_ACTIVITY_STARTS 或者 targetSdkVersion 小于 android 14)的服务。注意这里是 BIND_ALLOW_ACTIVITY_STARTS 不是 BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS,前者不需要特权,后者需要系统特权。当进程 A 绑定到进程 B 时,如果使用前者,则只有 A 在前台时允许 B 启动 activity;而如果使用的是后者,则进程 B 无论如何都能启动 activity,但是 A 需要有系统特权。
/** If enabled BAL are prevented by default in applications targeting U and later. */ @ChangeId @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE) @Overridable privatestaticfinallong DEFAULT_RESCIND_BAL_FG_PRIVILEGES_BOUND_SERVICE = 261072174;
/** Set of UIDs of clients currently bound to this process and opt in to allow this process to * launch background activity. */ @GuardedBy("this") private@Nullable IntArray mBalOptInBoundClientUids;
voidaddBoundClientUid(int clientUid, String clientPackageName, long bindFlags){ if (!CompatChanges.isChangeEnabled( DEFAULT_RESCIND_BAL_FG_PRIVILEGES_BOUND_SERVICE, clientPackageName, UserHandle.getUserHandleForUid(clientUid)) || (bindFlags & Context.BIND_ALLOW_ACTIVITY_STARTS) != 0) { if (mBalOptInBoundClientUids == null) { mBalOptInBoundClientUids = new IntArray(); } if (mBalOptInBoundClientUids.indexOf(clientUid) == -1) { mBalOptInBoundClientUids.add(clientUid); } } }
// if we have a process attached, add bound client uid of this connection to it if (getHostProcess() != null) { getHostProcess().mServices.addBoundClientUid(c.clientUid, c.clientPackageName, c.getFlags()); getHostProcess().mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_BOUND_SERVICE); } }
/** Similar to {@link #hasActiveVisibleWindow(int)}, but only considers non pinned app * windows */ booleanhasActiveVisibleNotPinnedWindow(int uid){ if (mVisibleActivityProcessTracker.hasVisibleNotPinnedActivity(uid)) { returntrue; } return mActiveUids.hasNonAppVisibleWindow(uid); }
/** * The state for oom-adjustment calculation. The higher 16 bits are the activity states, and the * lower 16 bits are the task layer rank (see {@link Task#mLayerRank}). This field is written by * window manager and read by activity manager. */ privatevolatileint mActivityStateFlags = ACTIVITY_STATE_FLAG_MASK_MIN_TASK_LAYER;
voidcomputeProcessActivityState(){ // Since there could be more than one activities in a process record, we don't need to // compute the OomAdj with each of them, just need to find out the activity with the // "best" state, the order would be visible, pausing, stopping... for (int i = mActivities.size() - 1; i >= 0; i--) { final ActivityRecord r = mActivities.get(i); if (r.isVisible()) { stateFlags |= ACTIVITY_STATE_FLAG_IS_WINDOW_VISIBLE; } final Task task = r.getTask(); if (task == null) { Slog.e(TAG, "Unexpected detached " + r + " in " + this); continue; } if (task.mLayerRank != Task.LAYER_RANK_INVISIBLE) { stateFlags |= ACTIVITY_STATE_FLAG_HAS_ACTIVITY_IN_VISIBLE_TASK; } // ... } }
// The last time an activity was launched in the process privatevolatilelong mLastActivityLaunchTime; // The last time an activity was finished in the process while the process participated // in a visible task privatevolatilelong mLastActivityFinishTime;
voidsetLastActivityLaunchTime(ActivityRecord r){ long launchTime = r.lastLaunchTime; if (launchTime <= mLastActivityLaunchTime) { if (launchTime < mLastActivityLaunchTime) { Slog.w(TAG, "Tried to set launchTime (" + launchTime + ") < mLastActivityLaunchTime (" + mLastActivityLaunchTime + ")"); } return; } updateRapidActivityLaunch(r, launchTime, mLastActivityLaunchTime); mLastActivityLaunchTime = launchTime; }
// How long we permit background activity starts after an activity in the process // started or finished. staticfinallong ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
private IAppTask startDreamActivityLocked( @NonNull Intent intent, int callingUid, int callingPid, @NonNull WindowProcessController process, @NonNull ApplicationInfo appInfo){ finalint res = getActivityStartController() .obtainStarter(intent, "dream") .setCallingUid(callingUid) .setCallingPid(callingPid) .setCallingPackage(intent.getPackage()) .setActivityInfo(a) .setActivityOptions(createSafeActivityOptionsWithBalAllowed(options)) .setOutActivity(outActivity) // To start the dream from background, we need to start it from a persistent // system process. Here we set the real calling uid to the system server // uid. .setRealCallingUid(Binder.getCallingUid()) .setAllowBalExemptionForSystemProcess(true) .execute();
}
/** * Wrap the {@link ActivityOptions} in {@link SafeActivityOptions} and attach caller options * that allow using the callers permissions to start background activities. */ private SafeActivityOptions createSafeActivityOptionsWithBalAllowed( @Nullable ActivityOptions options){ if (options == null) { options = ActivityOptions.makeBasic().setPendingIntentBackgroundActivityStartMode( ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED); } elseif (options.getPendingIntentBackgroundActivityStartMode() == ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED) { options.setPendingIntentBackgroundActivityStartMode( ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED); } returnnew SafeActivityOptions(options, Binder.getCallingPid(), Binder.getCallingUid()); }
其他有这种特殊处理的还有 startActivityAsCaller()、startVoiceActivity()、startAssistantActivity() 等,但是这些 API 基本都需要权限,不在我们讨论范围之内。