/**
 * Copyright (c) 2014, The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.server.notification;

import static android.app.Flags.FLAG_LIFETIME_EXTENSION_REFACTOR;
import static android.content.Context.BIND_ALLOW_WHITELIST_MANAGEMENT;
import static android.content.Context.BIND_AUTO_CREATE;
import static android.content.Context.BIND_FOREGROUND_SERVICE;
import static android.content.Context.DEVICE_POLICY_SERVICE;
import static android.os.UserHandle.USER_ALL;
import static android.os.UserHandle.USER_SYSTEM;
import static android.service.notification.Flags.reportNlsStartAndEnd;
import static android.service.notification.NotificationListenerService.META_DATA_DEFAULT_AUTOBIND;

import static com.android.server.notification.Flags.FLAG_MANAGED_SERVICES_CONCURRENT_MULTIUSER;
import static com.android.server.notification.Flags.managedServicesConcurrentMultiuser;
import static com.android.server.notification.NotificationManagerService.privateSpaceFlagsEnabled;

import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.annotation.UserIdInt;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.IBinderSession;
import android.app.PendingIntent;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Context.BindServiceFlags;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageManager;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.content.pm.UserInfo;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Looper;
import android.os.Process;
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.Settings;
import android.service.notification.ManagedServiceInfoProto;
import android.service.notification.ManagedServicesProto;
import android.service.notification.ManagedServicesProto.ServiceProto;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.IntArray;
import android.util.Log;
import android.util.Pair;
import android.util.Slog;
import android.util.SparseArray;
import android.util.SparseSetArray;
import android.util.proto.ProtoOutputStream;

import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.XmlUtils;
import com.android.internal.util.function.TriPredicate;
import com.android.modules.utils.TypedXmlPullParser;
import com.android.modules.utils.TypedXmlSerializer;
import com.android.server.LocalServices;
import com.android.server.notification.NotificationManagerService.DumpFilter;
import com.android.server.pm.UserManagerInternal;
import com.android.server.utils.TimingsTraceAndSlog;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * Manages the lifecycle of application-provided services bound by system server.
 *
 * Services managed by this helper must have:
 *  - An associated system settings value with a list of enabled component names.
 *  - A well-known action for services to use in their intent-filter.
 *  - A system permission for services to require in order to ensure system has exclusive binding.
 *  - A settings page for user configuration of enabled services, and associated intent action.
 *  - A remote interface definition (aidl) provided by the service used for communication.
 */
abstract public class ManagedServices {
    protected final String TAG = getClass().getSimpleName().replace('$', '.');
    protected final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);

    private static final int ON_BINDING_DIED_REBIND_DELAY_MS = 10000;
    private boolean mRebindAsyncDelay = true;
    protected static final String ENABLED_SERVICES_SEPARATOR = ":";
    private static final String DB_VERSION_1 = "1";
    private static final String DB_VERSION_2 = "2";
    private static final String DB_VERSION_3 = "3";

    /**
     * List of components and apps that can have running {@link ManagedServices}.
     */
    static final String TAG_MANAGED_SERVICES = "service_listing";
    static final String ATT_APPROVED_LIST = "approved";
    static final String ATT_USER_ID = "user";
    static final String ATT_IS_PRIMARY = "primary";
    static final String ATT_VERSION = "version";
    static final String ATT_DEFAULTS = "defaults";
    static final String ATT_USER_SET = "user_set_services";
    static final String ATT_USER_SET_OLD = "user_set";
    static final String ATT_USER_CHANGED = "user_changed";

    static final String DB_VERSION = "4";

    static final int APPROVAL_BY_PACKAGE = 0;
    static final int APPROVAL_BY_COMPONENT = 1;

    /**
     * Maximum number of entries allowed in the lists of packages/components contained in
     * {@link #mApproved} or {@link #mUserSetServices}. For the first, this effectively limits
     * the number of services (e.g. NLSes) that will be bound per user.
     */
    private static final int MAX_SERVICE_ENTRIES = 100;

    protected final Context mContext;
    protected final Object mMutex;
    private final UserProfiles mUserProfiles;
    protected final IPackageManager mPm;
    protected final UserManager mUm;
    protected final UserManagerInternal mUmInternal;
    private final Config mConfig;
    private final Handler mHandler = new Handler(Looper.getMainLooper());

    // contains connections to all connected services, including app services
    // and system services
    @GuardedBy("mMutex")
    private final ArrayList<ManagedServiceInfo> mServices = new ArrayList<>();
    /**
     * The services that have been bound by us. If the service is also connected, it will also
     * be in {@link #mServices}.
     */
    @GuardedBy("mMutex")
    private final ArrayList<Pair<ComponentName, Integer>> mServicesBound = new ArrayList<>();
    @GuardedBy("mMutex")
    private final ArraySet<Pair<ComponentName, Integer>> mServicesRebinding = new ArraySet<>();
    // we need these packages to be protected because classes that inherit from it need to see it
    protected final Object mDefaultsLock = new Object();
    @GuardedBy("mDefaultsLock")
    protected final ArraySet<ComponentName> mDefaultComponents = new ArraySet<>();
    @GuardedBy("mDefaultsLock")
    protected final ArraySet<String> mDefaultPackages = new ArraySet<>();

    // lists the component names of all enabled (and therefore potentially connected)
    // app services for each user. This is intended to support a concurrent multi-user environment.
    // key value is the resolved userId.
    @GuardedBy("mMutex")
    private final SparseArray<ArraySet<ComponentName>> mEnabledServicesByUser =
            new SparseArray<>();
    // Just the packages from mEnabledServicesByUser
    // This is intended to support a concurrent multi-user environment.
    // key value is the resolved userId.
    @GuardedBy("mMutex")
    private final SparseArray<ArraySet<String>> mEnabledServicesPackageNamesByUser =
            new SparseArray<>();
    // Per user id, list of enabled packages that have nevertheless asked not to be run
    @GuardedBy("mSnoozing")
    private final SparseSetArray<ComponentName> mSnoozing = new SparseSetArray<>();

    // List of approved packages or components (by user, then by primary/secondary) that are
    // allowed to be bound as managed services. A package or component appearing in this list does
    // not mean that we are currently bound to said package/component.
    @GuardedBy("mApproved")
    protected final ArrayMap<Integer, ArrayMap<Boolean, ArraySet<String>>> mApproved =
            new ArrayMap<>();

    // List of approved UIDs, by user
    @GuardedBy("mApproved")
    protected final SparseArray<HashSet<Integer>> mApprovedUids = new SparseArray<>();

    // List of packages or components (by user) that are configured to be enabled/disabled
    // explicitly by the user
    @GuardedBy("mApproved")
    protected ArrayMap<Integer, ArraySet<String>> mUserSetServices = new ArrayMap<>();
    @GuardedBy("mApproved")
    protected ArrayMap<Integer, Boolean> mIsUserChanged = new ArrayMap<>();

    // True if approved services are stored in xml, not settings.
    private boolean mUseXml;

    // Whether managed services are approved individually or package wide
    protected int mApprovalLevel;

    public ManagedServices(Context context, Object mutex, UserProfiles userProfiles,
            IPackageManager pm) {
        mContext = context;
        mMutex = mutex;
        mUserProfiles = userProfiles;
        mPm = pm;
        mConfig = getConfig();
        mApprovalLevel = APPROVAL_BY_COMPONENT;
        mUm = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
        mUmInternal = LocalServices.getService(UserManagerInternal.class);
        // Initialize for the current user.
        mEnabledServicesByUser.put(UserHandle.USER_CURRENT, new ArraySet<>());
        mEnabledServicesPackageNamesByUser.put(UserHandle.USER_CURRENT, new ArraySet<>());
    }

    abstract protected Config getConfig();

    private String getCaption() {
        return mConfig.caption;
    }

    abstract protected IInterface asInterface(IBinder binder);

    abstract protected boolean checkType(IInterface service);

    abstract protected void onServiceAdded(ManagedServiceInfo info);

    abstract protected void ensureFilters(ServiceInfo si, int userId);

    protected List<ManagedServiceInfo> getServices() {
        synchronized (mMutex) {
            List<ManagedServiceInfo> services = new ArrayList<>(mServices);
            return services;
        }
    }

    protected void addDefaultComponentOrPackage(String packageOrComponent) {
        if (!TextUtils.isEmpty(packageOrComponent)) {
            synchronized (mDefaultsLock) {
                if (mApprovalLevel == APPROVAL_BY_PACKAGE) {
                    mDefaultPackages.add(packageOrComponent);
                    return;
                }
                ComponentName cn = ComponentName.unflattenFromString(packageOrComponent);
                if (cn != null  && mApprovalLevel == APPROVAL_BY_COMPONENT) {
                    mDefaultPackages.add(cn.getPackageName());
                    mDefaultComponents.add(cn);
                    return;
                }
            }
        }
    }

    protected abstract void loadDefaultsFromConfig();

    boolean isDefaultComponentOrPackage(String packageOrComponent) {
        synchronized (mDefaultsLock) {
            ComponentName cn = ComponentName.unflattenFromString(packageOrComponent);
            if (cn == null) {
                return mDefaultPackages.contains(packageOrComponent);
            } else {
                return mDefaultComponents.contains(cn);
            }
        }
    }

    ArraySet<ComponentName> getDefaultComponents() {
        synchronized (mDefaultsLock) {
            return new ArraySet<>(mDefaultComponents);
        }
    }

    ArraySet<String> getDefaultPackages() {
        synchronized (mDefaultsLock) {
            return new ArraySet<>(mDefaultPackages);
        }
    }

    UserProfiles getUserProfiles() {
        return mUserProfiles;
    }

    /**
     * When resetting a package, we need to enable default components that belong to that packages
     * we also need to disable components that are not default to return the managed service state
     * to when a new android device is first turned on for that package.
     *
     * @param packageName package to reset.
     * @param userId the android user id
     * @return a list of components that were permitted
     */
    @NonNull
    ArrayMap<Boolean, ArrayList<ComponentName>> resetComponents(String packageName, int userId) {
        // components that we want to enable
        ArrayList<ComponentName> componentsToEnable;
        // components that were removed
        ArrayList<ComponentName> disabledComponents;
        // all components that are enabled now
        ArraySet<ComponentName> enabledComponents = new ArraySet<>(getAllowedComponents(userId));

        boolean changed = false;

        synchronized (mDefaultsLock) {
            componentsToEnable = new ArrayList<>(mDefaultComponents.size());
            disabledComponents = new ArrayList<>(mDefaultComponents.size());

            // record all components that are enabled but should not be by default
            for (int i = 0; i < mDefaultComponents.size() && enabledComponents.size() > 0; i++) {
                ComponentName currentDefault = mDefaultComponents.valueAt(i);
                if (packageName.equals(currentDefault.getPackageName())
                        && !enabledComponents.contains(currentDefault)) {
                    componentsToEnable.add(currentDefault);
                }
            }
            synchronized (mApproved) {
                final ArrayMap<Boolean, ArraySet<String>> approvedByType = mApproved.get(
                        userId);
                if (approvedByType != null) {
                    final int M = approvedByType.size();
                    for (int j = 0; j < M; j++) {
                        final ArraySet<String> approved = approvedByType.valueAt(j);
                        for (int i = 0; i < enabledComponents.size(); i++) {
                            ComponentName currentComponent = enabledComponents.valueAt(i);
                            if (packageName.equals(currentComponent.getPackageName())
                                    && !mDefaultComponents.contains(currentComponent)) {
                                if (approved.remove(currentComponent.flattenToString())) {
                                    disabledComponents.add(currentComponent);
                                    clearUserSetFlagLocked(currentComponent, userId);
                                    changed = true;
                                }
                            }
                        }
                        for (int i = 0; i < componentsToEnable.size(); i++) {
                            ComponentName candidate = componentsToEnable.get(i);
                            changed |= approved.add(candidate.flattenToString());
                        }
                    }

                }
            }
        }
        if (changed) rebindServices(false, USER_ALL);

        ArrayMap<Boolean, ArrayList<ComponentName>> changes = new ArrayMap<>();
        changes.put(true, componentsToEnable);
        changes.put(false, disabledComponents);

        return changes;
    }

    @GuardedBy("mApproved")
    private boolean clearUserSetFlagLocked(ComponentName component, int userId) {
        String approvedValue = getApprovedValue(component.flattenToString());
        ArraySet<String> userSet = mUserSetServices.get(userId);
        return userSet != null && userSet.remove(approvedValue);
    }

    protected long getBindFlags() {
        return BIND_AUTO_CREATE | BIND_FOREGROUND_SERVICE | BIND_ALLOW_WHITELIST_MANAGEMENT;
    }

    protected void onServiceRemovedLocked(ManagedServiceInfo removed) { }

    public void onBootPhaseAppsCanStart() {}

    public void dump(PrintWriter pw, DumpFilter filter) {
        pw.println("    Allowed " + getCaption() + "s:");
        synchronized (mApproved) {
            final int N = mApproved.size();
            for (int i = 0; i < N; i++) {
                final int userId = mApproved.keyAt(i);
                final ArrayMap<Boolean, ArraySet<String>> approvedByType = mApproved.valueAt(i);
                final Boolean userChanged = mIsUserChanged.get(userId);
                if (approvedByType != null) {
                    final int M = approvedByType.size();
                    for (int j = 0; j < M; j++) {
                        final boolean isPrimary = approvedByType.keyAt(j);
                        final ArraySet<String> approved = approvedByType.valueAt(j);
                        if (approvedByType != null && approvedByType.size() > 0) {
                            pw.println("      " + String.join(ENABLED_SERVICES_SEPARATOR, approved)
                                    + " (user: " + userId + " isPrimary: " + isPrimary
                                    + (userChanged == null ? "" : " isUserChanged: "
                                    + userChanged) + ")");
                        }
                    }
                }
                final HashSet<Integer> uids = mApprovedUids.get(userId);
                pw.println("    Approved uids for user " + userId + ": "
                        + (uids != null ? uids.toString() : "none"));
            }
            pw.println("    Has user set:");
            Set<Integer> userIds = mUserSetServices.keySet();
            for (int userId : userIds) {
                if (mIsUserChanged.get(userId) == null) {
                    pw.println("      userId=" + userId + " value="
                            + (mUserSetServices.get(userId)));
                }
            }
        }

        synchronized (mMutex) {
            if (managedServicesConcurrentMultiuser()) {
                for (int i = 0; i < mEnabledServicesByUser.size(); i++) {
                    final int userId = mEnabledServicesByUser.keyAt(i);
                    final ArraySet<ComponentName> componentNames =
                            mEnabledServicesByUser.get(userId);
                    String userString = userId == UserHandle.USER_CURRENT
                            ? "current profiles" : "user " + Integer.toString(userId);
                    pw.println("    All " + getCaption() + "s (" + componentNames.size()
                            + ") enabled for " +  userString + ":");
                    for (ComponentName cmpt : componentNames) {
                        if (filter != null && !filter.matches(cmpt)) continue;
                        pw.println("      " + cmpt);
                    }
                }
            } else {
                final ArraySet<ComponentName> enabledServicesForCurrentProfiles =
                        mEnabledServicesByUser.get(UserHandle.USER_CURRENT);
                pw.println("    All " + getCaption() + "s ("
                        + enabledServicesForCurrentProfiles.size()
                        + ") enabled for current profiles:");
                for (ComponentName cmpt : enabledServicesForCurrentProfiles) {
                    if (filter != null && !filter.matches(cmpt)) continue;
                    pw.println("      " + cmpt);
                }
            }

            pw.println("    Live " + getCaption() + "s (" + mServices.size() + "):");
            for (ManagedServiceInfo info : mServices) {
                if (filter != null && !filter.matches(info.component)) continue;
                pw.println("      " + info.component
                        + " (user " + info.userid + "): " + info.service
                        + (info.isSystem ? " SYSTEM" : "")
                        + (info.isGuest(this) ? " GUEST" : ""));
            }
        }

        final SparseSetArray<ComponentName> snoozingComponents;
        synchronized (mSnoozing) {
            snoozingComponents = new SparseSetArray<>(mSnoozing);
        }
        pw.println("    Snoozed " + getCaption() + "s ("
                + snoozingComponents.size() + "):");
        for (int i = 0; i < snoozingComponents.size(); i++) {
            pw.println("      User: " + snoozingComponents.keyAt(i));
            for (ComponentName name : snoozingComponents.valuesAt(i)) {
                final ServiceInfo info = getServiceInfo(name, snoozingComponents.keyAt(i));
                pw.println("        " + name.flattenToShortString() + (isAutobindAllowed(info) ? ""
                        : " (META_DATA_DEFAULT_AUTOBIND=false)"));
            }
        }
    }

    public void dump(ProtoOutputStream proto, DumpFilter filter) {
        proto.write(ManagedServicesProto.CAPTION, getCaption());
        synchronized (mApproved) {
            final int N = mApproved.size();
            for (int i = 0; i < N; i++) {
                final int userId = mApproved.keyAt(i);
                final ArrayMap<Boolean, ArraySet<String>> approvedByType = mApproved.valueAt(i);
                if (approvedByType != null) {
                    final int M = approvedByType.size();
                    for (int j = 0; j < M; j++) {
                        final boolean isPrimary = approvedByType.keyAt(j);
                        final ArraySet<String> approved = approvedByType.valueAt(j);
                        if (approvedByType != null && approvedByType.size() > 0) {
                            final long sToken = proto.start(ManagedServicesProto.APPROVED);
                            for (String s : approved) {
                                proto.write(ServiceProto.NAME, s);
                            }
                            proto.write(ServiceProto.USER_ID, userId);
                            proto.write(ServiceProto.IS_PRIMARY, isPrimary);
                            proto.end(sToken);
                        }
                    }
                }
            }
        }

        synchronized (mMutex) {
            if (managedServicesConcurrentMultiuser()) {
                for (int i = 0; i < mEnabledServicesByUser.size(); i++) {
                    final int userId = mEnabledServicesByUser.keyAt(i);
                    final ArraySet<ComponentName> componentNames =
                            mEnabledServicesByUser.get(userId);
                    for (ComponentName cmpt : componentNames) {
                        if (filter != null && !filter.matches(cmpt)) continue;
                        cmpt.dumpDebug(proto, ManagedServicesProto.ENABLED);
                    }
                }
            } else {
                final ArraySet<ComponentName> enabledServicesForCurrentProfiles =
                        mEnabledServicesByUser.get(UserHandle.USER_CURRENT);
                for (ComponentName cmpt : enabledServicesForCurrentProfiles) {
                    if (filter != null && !filter.matches(cmpt)) continue;
                    cmpt.dumpDebug(proto, ManagedServicesProto.ENABLED);
                }
            }
            for (ManagedServiceInfo info : mServices) {
                if (filter != null && !filter.matches(info.component)) continue;
                info.dumpDebug(proto, ManagedServicesProto.LIVE_SERVICES, this);
            }
        }

        synchronized (mSnoozing) {
            for (int i = 0; i < mSnoozing.size(); i++) {
                long token = proto.start(ManagedServicesProto.SNOOZED);
                proto.write(ManagedServicesProto.SnoozedServices.USER_ID,
                        mSnoozing.keyAt(i));
                for (ComponentName name : mSnoozing.valuesAt(i)) {
                    name.dumpDebug(proto, ManagedServicesProto.SnoozedServices.SNOOZED);
                }
                proto.end(token);
            }
        }
    }

    protected void onSettingRestored(String element, String value, int backupSdkInt, int userId) {
        if (!mUseXml) {
            Slog.d(TAG, "Restored managed service setting: " + element);
            if (mConfig.secureSettingName.equals(element) ||
                    (mConfig.secondarySettingName != null
                            && mConfig.secondarySettingName.equals(element))) {
                if (backupSdkInt < Build.VERSION_CODES.O) {
                    // automatic system grants were added in O, so append the approved apps
                    // rather than wiping out the setting
                    String currentSetting =
                            getApproved(userId, mConfig.secureSettingName.equals(element));
                    if (!TextUtils.isEmpty(currentSetting)) {
                        if (!TextUtils.isEmpty(value)) {
                            value = value + ENABLED_SERVICES_SEPARATOR + currentSetting;
                        } else {
                            value = currentSetting;
                        }
                    }
                }
                if (shouldReflectToSettings()) {
                    Settings.Secure.putStringForUser(
                            mContext.getContentResolver(), element, value, userId);
                }

                for (UserInfo user : mUm.getUsers()) {
                    addApprovedList(value, user.id, mConfig.secureSettingName.equals(element));
                }
                Slog.d(TAG, "Done loading approved values from settings");
                rebindServices(false, userId);
            }
        }
    }

    void writeDefaults(TypedXmlSerializer out) throws IOException {
        synchronized (mDefaultsLock) {
            List<String> componentStrings = new ArrayList<>(mDefaultComponents.size());
            for (int i = 0; i < mDefaultComponents.size(); i++) {
                componentStrings.add(mDefaultComponents.valueAt(i).flattenToString());
            }
            String defaults = String.join(ENABLED_SERVICES_SEPARATOR, componentStrings);
            out.attribute(null, ATT_DEFAULTS, defaults);
        }
    }

    public void writeXml(TypedXmlSerializer out, boolean forBackup, int userId) throws IOException {
        out.startTag(null, getConfig().xmlTag);

        out.attributeInt(null, ATT_VERSION, Integer.parseInt(DB_VERSION));

        writeDefaults(out);

        if (forBackup) {
            trimApprovedListsAccordingToInstalledServices(userId);
        }

        synchronized (mApproved) {
            final int N = mApproved.size();
            for (int i = 0; i < N; i++) {
                final int approvedUserId = mApproved.keyAt(i);
                if (forBackup && approvedUserId != userId) {
                    continue;
                }
                final ArrayMap<Boolean, ArraySet<String>> approvedByType = mApproved.valueAt(i);
                final Boolean isUserChanged = mIsUserChanged.get(approvedUserId);
                if (approvedByType != null) {
                    final int M = approvedByType.size();
                    for (int j = 0; j < M; j++) {
                        final boolean isPrimary = approvedByType.keyAt(j);
                        final Set<String> approved = approvedByType.valueAt(j);
                        final Set<String> userSet = mUserSetServices.get(approvedUserId);
                        if (approved != null || userSet != null || isUserChanged != null) {
                            String allowedItems = approved == null
                                    ? ""
                                    : String.join(ENABLED_SERVICES_SEPARATOR, approved);
                            out.startTag(null, TAG_MANAGED_SERVICES);
                            out.attribute(null, ATT_APPROVED_LIST, allowedItems);
                            out.attributeInt(null, ATT_USER_ID, approvedUserId);
                            out.attributeBoolean(null, ATT_IS_PRIMARY, isPrimary);
                            if (isUserChanged != null) {
                                out.attributeBoolean(null, ATT_USER_CHANGED, isUserChanged);
                            } else if (userSet != null) {
                                String userSetItems =
                                        String.join(ENABLED_SERVICES_SEPARATOR, userSet);
                                out.attribute(null, ATT_USER_SET, userSetItems);
                            }
                            writeExtraAttributes(out, approvedUserId);
                            out.endTag(null, TAG_MANAGED_SERVICES);

                            if (!forBackup && isPrimary) {
                                if (shouldReflectToSettings()) {
                                    // Also write values to settings, for observers who haven't
                                    // migrated yet
                                    Settings.Secure.putStringForUser(mContext.getContentResolver(),
                                            getConfig().secureSettingName, allowedItems,
                                            approvedUserId);
                                }
                            }

                        }
                    }
                }
            }
        }

        writeExtraXmlTags(out);

        out.endTag(null, getConfig().xmlTag);
    }

    /**
     * Returns whether the approved list of services should also be written to the Settings db
     */
    protected boolean shouldReflectToSettings() {
        return false;
    }

    /**
     * Writes extra xml attributes to {@link #TAG_MANAGED_SERVICES} tag.
     */
    protected void writeExtraAttributes(TypedXmlSerializer out, int userId) throws IOException {}

    /**
     * Writes extra xml tags within the parent tag specified in {@link Config#xmlTag}.
     */
    protected void writeExtraXmlTags(TypedXmlSerializer out) throws IOException {}

    /**
     * This is called to process tags other than {@link #TAG_MANAGED_SERVICES}.
     */
    protected void readExtraTag(String tag, TypedXmlPullParser parser)
            throws IOException, XmlPullParserException {}

    protected final void migrateToXml() {
        for (UserInfo user : mUm.getUsers()) {
            final ContentResolver cr = mContext.getContentResolver();
            if (!TextUtils.isEmpty(getConfig().secureSettingName)) {
                addApprovedList(Settings.Secure.getStringForUser(
                        cr,
                        getConfig().secureSettingName,
                        user.id), user.id, true);
            }
            if (!TextUtils.isEmpty(getConfig().secondarySettingName)) {
                addApprovedList(Settings.Secure.getStringForUser(
                        cr,
                        getConfig().secondarySettingName,
                        user.id), user.id, false);
            }
        }
    }

    void readDefaults(TypedXmlPullParser parser) {
        String defaultComponents = XmlUtils.readStringAttribute(parser, ATT_DEFAULTS);

        if (!TextUtils.isEmpty(defaultComponents)) {
            String[] components = defaultComponents.split(ENABLED_SERVICES_SEPARATOR);
            synchronized (mDefaultsLock) {
                for (int i = 0; i < components.length; i++) {
                    if (!TextUtils.isEmpty(components[i])) {
                        ComponentName cn = ComponentName.unflattenFromString(components[i]);
                        if (cn != null) {
                            mDefaultPackages.add(cn.getPackageName());
                            mDefaultComponents.add(cn);
                        } else {
                            mDefaultPackages.add(components[i]);
                        }
                    }
                }
            }
        }
    }

    public void readXml(
            TypedXmlPullParser parser,
            TriPredicate<String, Integer, String> allowedManagedServicePackages,
            boolean forRestore,
            int userId)
            throws XmlPullParserException, IOException {
        // read grants
        int type;
        String version = XmlUtils.readStringAttribute(parser, ATT_VERSION);
        boolean needUpgradeUserset = false;
        readDefaults(parser);
        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
            String tag = parser.getName();
            if (type == XmlPullParser.END_TAG
                    && getConfig().xmlTag.equals(tag)) {
                break;
            }
            if (type == XmlPullParser.START_TAG) {
                if (TAG_MANAGED_SERVICES.equals(tag)) {
                    Slog.i(TAG, "Read " + mConfig.caption + " permissions from xml");

                    final String approved = XmlUtils.readStringAttribute(parser, ATT_APPROVED_LIST);
                    // Ignore parser's user id for restore.
                    final int resolvedUserId = forRestore
                            ? userId : parser.getAttributeInt(null, ATT_USER_ID, 0);
                    final boolean isPrimary =
                            parser.getAttributeBoolean(null, ATT_IS_PRIMARY, true);

                    // Load three different userSet attributes from xml
                    // user_changed, not null if version == 4 and is NAS setting
                    final String isUserChanged = XmlUtils.readStringAttribute(parser,
                            ATT_USER_CHANGED);
                    // user_set, not null if version <= 3
                    final String isUserChanged_Old = XmlUtils.readStringAttribute(parser,
                            ATT_USER_SET_OLD);
                    // user_set_services, not null if version >= 3 and is non-NAS setting
                    String userSetComponent = XmlUtils.readStringAttribute(parser, ATT_USER_SET);

                    // since the same xml version may have different userSet attributes,
                    // we need to check both xml version and userSet values to know how to set
                    // the userSetComponent/mIsUserChanged to the correct value
                    if (DB_VERSION.equals(version)) {
                        // version 4, NAS contains user_changed and
                        // NLS/others contain user_set_services
                        if (isUserChanged == null) { //NLS
                            userSetComponent = TextUtils.emptyIfNull(userSetComponent);
                        } else { //NAS
                            synchronized (mApproved) {
                                mIsUserChanged.put(resolvedUserId, Boolean.valueOf(isUserChanged));
                            }
                            userSetComponent = Boolean.valueOf(isUserChanged) ? approved : "";
                        }
                    } else {
                        // version 3 may contain user_set (R) or user_set_services (S)
                        // version 2 or older contain user_set or nothing
                        needUpgradeUserset = true;
                        if (userSetComponent == null) { //contains user_set
                            if (isUserChanged_Old != null && Boolean.valueOf(isUserChanged_Old)) {
                                //user_set = true
                                userSetComponent = approved;
                                synchronized (mApproved) {
                                    mIsUserChanged.put(resolvedUserId, true);
                                }
                                needUpgradeUserset = false;
                            } else {
                                userSetComponent = "";
                            }
                        }
                    }
                    readExtraAttributes(tag, parser, resolvedUserId);
                    if (isUserChanged != null && approved.isEmpty()) {
                        // NAS
                        denyPregrantedAppUserSet(resolvedUserId, isPrimary);
                        mUseXml = true;
                    } else {
                        if (allowedManagedServicePackages == null
                                || allowedManagedServicePackages.test(
                                getPackageName(approved), resolvedUserId, getRequiredPermission())
                                || approved.isEmpty()) {
                            if (mUm.getUserInfo(resolvedUserId) != null) {
                                addApprovedList(approved, resolvedUserId, isPrimary,
                                        userSetComponent);
                            }
                            mUseXml = true;
                        }
                    }
                } else {
                    readExtraTag(tag, parser);
                }
            }
        }
        boolean isOldVersion = TextUtils.isEmpty(version)
                || DB_VERSION_1.equals(version)
                || DB_VERSION_2.equals(version)
                || DB_VERSION_3.equals(version);
        if (isOldVersion) {
            upgradeDefaultsXmlVersion();
        }
        if (needUpgradeUserset) {
            upgradeUserSet();
        }

        rebindServices(false, USER_ALL);
    }

    void upgradeDefaultsXmlVersion() {
        int defaultsSize;
        synchronized (mDefaultsLock) {
            // check if any defaults are loaded
            defaultsSize = mDefaultComponents.size() + mDefaultPackages.size();
        }
        if (defaultsSize == 0) {
            // load defaults from current allowed
            if (this.mApprovalLevel == APPROVAL_BY_COMPONENT) {
                List<ComponentName> approvedComponents = getAllowedComponents(USER_SYSTEM);
                for (int i = 0; i < approvedComponents.size(); i++) {
                    addDefaultComponentOrPackage(approvedComponents.get(i).flattenToString());
                }
            }
            if (this.mApprovalLevel == APPROVAL_BY_PACKAGE) {
                List<String> approvedPkgs = getAllowedPackages(USER_SYSTEM);
                for (int i = 0; i < approvedPkgs.size(); i++) {
                    addDefaultComponentOrPackage(approvedPkgs.get(i));
                }
            }
        }
        synchronized (mDefaultsLock) {
            defaultsSize = mDefaultComponents.size() + mDefaultPackages.size();
        }
        // if no defaults are loaded, then load from config
        if (defaultsSize == 0) {
            loadDefaultsFromConfig();
        }
    }

    protected void upgradeUserSet() {};

    /**
     * Read extra attributes in the {@link #TAG_MANAGED_SERVICES} tag.
     */
    protected void readExtraAttributes(String tag, TypedXmlPullParser parser, int userId)
            throws IOException {}

    protected abstract String getRequiredPermission();

    protected void addApprovedList(String approved, int userId, boolean isPrimary) {
        addApprovedList(approved, userId, isPrimary, approved);
    }

    protected void addApprovedList(String approved, int userId, boolean isPrimary, String userSet) {
        if (TextUtils.isEmpty(approved)) {
            approved = "";
        }
        if (userSet == null) {
            userSet = approved;
        }
        synchronized (mApproved) {
            ArrayMap<Boolean, ArraySet<String>> approvedByType = mApproved.get(userId);
            if (approvedByType == null) {
                approvedByType = new ArrayMap<>();
                mApproved.put(userId, approvedByType);
            }
            ArraySet<String> approvedList = approvedByType.get(isPrimary);
            if (approvedList == null) {
                approvedList = new ArraySet<>();
                approvedByType.put(isPrimary, approvedList);
            }

            HashSet<Integer> approvedUids = mApprovedUids.get(userId);
            if (approvedUids == null) {
                approvedUids = new HashSet<>();
                mApprovedUids.put(userId, approvedUids);
            }

            String[] approvedArray = approved.split(ENABLED_SERVICES_SEPARATOR);
            for (String pkgOrComponent : approvedArray) {
                String approvedItem = getApprovedValue(pkgOrComponent);
                if (approvedItem != null) {
                    approvedList.add(approvedItem);
                }
                int uid = getUidForPackageOrComponent(pkgOrComponent, userId);
                if (uid != Process.INVALID_UID) {
                    approvedUids.add(uid);
                }
            }

            ArraySet<String> userSetList = mUserSetServices.get(userId);
            if (userSetList == null) {
                userSetList = new ArraySet<>();
                mUserSetServices.put(userId, userSetList);
            }
            String[] userSetArray = userSet.split(ENABLED_SERVICES_SEPARATOR);
            for (String pkgOrComponent : userSetArray) {
                String approvedItem = getApprovedValue(pkgOrComponent);
                if (approvedItem != null) {
                    userSetList.add(approvedItem);
                }
            }
        }
    }

    protected void denyPregrantedAppUserSet(int userId, boolean isPrimary) {
        synchronized (mApproved) {
            ArrayMap<Boolean, ArraySet<String>> approvedByType = mApproved.get(userId);
            if (approvedByType == null) {
                approvedByType = new ArrayMap<>();
                mApproved.put(userId, approvedByType);
            }
            approvedByType.put(isPrimary, new ArraySet<>());
        }
    }

    /** convenience method for looking in mEnabledServicesPackageNamesByUser
     * for UserHandle.USER_CURRENT.
     * This is a legacy API. When FLAG_MANAGED_SERVICES_CONCURRENT_MULTIUSER becomes
     * trunk stable,  this API should be deprecated.  Additionally, when this method
     * is deprecated, the unit tests written using this method should also be revised.
     *
     * @param pkg target package name
     * @return boolean value that indicates whether it is enabled for the current profiles
     */
    protected boolean isComponentEnabledForPackage(String pkg) {
        return isComponentEnabledForPackage(pkg, UserHandle.USER_CURRENT);
    }

    /** convenience method for looking in mEnabledServicesPackageNamesByUser
     *
     * @param pkg target package name
     * @param userId the id of the target user
     * @return boolean value that indicates whether it is enabled for the target user
     */
    @FlaggedApi(FLAG_MANAGED_SERVICES_CONCURRENT_MULTIUSER)
    protected boolean isComponentEnabledForPackage(String pkg, int userId) {
        synchronized (mMutex) {
            ArraySet<String> enabledServicesPackageNames =
                    mEnabledServicesPackageNamesByUser.get(resolveUserId(userId));
            return enabledServicesPackageNames != null && enabledServicesPackageNames.contains(pkg);
        }
    }

    protected boolean setPackageOrComponentEnabled(String pkgOrComponent, int userId,
            boolean isPrimary, boolean enabled) {
        return setPackageOrComponentEnabled(pkgOrComponent, userId, isPrimary, enabled, true);
    }

    /**
     * Changes the enabled state of a managed service.
     *
     * @return true if the change (enabling or disabling) was applied; false otherwise
     */
    protected boolean setPackageOrComponentEnabled(String pkgOrComponent, int userId,
            boolean isPrimary, boolean enabled, boolean userSet) {
        Slog.i(TAG,
                (enabled ? " Allowing " : "Disallowing ") + mConfig.caption + " "
                        + pkgOrComponent + " (userSet: " + userSet + ")");
        boolean changed = false;
        synchronized (mApproved) {
            ArrayMap<Boolean, ArraySet<String>> allowedByType = mApproved.get(userId);
            if (allowedByType == null) {
                allowedByType = new ArrayMap<>();
                mApproved.put(userId, allowedByType);
            }
            HashSet<Integer> approvedUids = mApprovedUids.get(userId);
            if (approvedUids == null) {
                approvedUids = new HashSet<>();
                mApprovedUids.put(userId, approvedUids);
            }
            ArraySet<String> approved = allowedByType.get(isPrimary);
            if (approved == null) {
                approved = new ArraySet<>();
                allowedByType.put(isPrimary, approved);
            }
            String approvedItem = getApprovedValue(pkgOrComponent);

            if (approvedItem != null) {
                int uid = getUidForPackageOrComponent(pkgOrComponent, userId);
                if (enabled) {
                    if (!Flags.limitManagedServicesCount()
                            || approved.size() < MAX_SERVICE_ENTRIES) {
                        approved.add(approvedItem);
                        if (uid != Process.INVALID_UID) {
                            approvedUids.add(uid);
                        }
                        changed = true;
                    } else {
                        Slog.w(TAG, TextUtils.formatSimple(
                                "Failed to allow %s %s because there are too many already",
                                mConfig.caption, pkgOrComponent));
                    }
                } else {
                    approved.remove(approvedItem);
                    if (uid != Process.INVALID_UID) {
                        approvedUids.remove(uid);
                    }
                    changed = true;
                }
            }

            if (changed) {
                ArraySet<String> userSetServices = mUserSetServices.get(userId);
                if (userSetServices == null) {
                    userSetServices = new ArraySet<>();
                    mUserSetServices.put(userId, userSetServices);
                }
                if (userSet) {
                    if (!Flags.limitManagedServicesCount()
                            || userSetServices.size() < MAX_SERVICE_ENTRIES) {
                        userSetServices.add(pkgOrComponent);
                    }
                } else {
                    userSetServices.remove(pkgOrComponent);
                }
            }
        }

        if (!Flags.limitManagedServicesCount() || changed) {
            rebindServices(false, userId);
        }

        return changed;
    }

    private int getUidForPackageOrComponent(String pkgOrComponent, int userId) {
        String packageName = getPackageName(pkgOrComponent);

        try {
            return mContext.getPackageManager().getPackageUidAsUser(packageName, userId);
        } catch (NameNotFoundException e) {
            return Process.INVALID_UID;
        }
    }

    private String getApprovedValue(String pkgOrComponent) {
        if (mApprovalLevel == APPROVAL_BY_COMPONENT) {
            if(ComponentName.unflattenFromString(pkgOrComponent) != null) {
                return pkgOrComponent;
            }
            return null;
        } else {
            return getPackageName(pkgOrComponent);
        }
    }

    protected String getApproved(int userId, boolean primary) {
        synchronized (mApproved) {
            final ArrayMap<Boolean, ArraySet<String>> allowedByType =
                    mApproved.getOrDefault(userId, new ArrayMap<>());
            ArraySet<String> approved = allowedByType.getOrDefault(primary, new ArraySet<>());
            return String.join(ENABLED_SERVICES_SEPARATOR, approved);
        }
    }

    protected List<ComponentName> getAllowedComponents(int userId) {
        final List<ComponentName> allowedComponents = new ArrayList<>();
        synchronized (mApproved) {
            final ArrayMap<Boolean, ArraySet<String>> allowedByType =
                    mApproved.getOrDefault(userId, new ArrayMap<>());
            for (int i = 0; i < allowedByType.size(); i++) {
                final ArraySet<String> allowed = allowedByType.valueAt(i);
                for (int j = 0; j < allowed.size(); j++) {
                    ComponentName cn = ComponentName.unflattenFromString(allowed.valueAt(j));
                    if (cn != null) {
                        allowedComponents.add(cn);
                    }
                }
            }
        }
        return allowedComponents;
    }

    @NonNull
    protected List<String> getAllowedPackages(int userId) {
        final List<String> allowedPackages = new ArrayList<>();
        synchronized (mApproved) {
            final ArrayMap<Boolean, ArraySet<String>> allowedByType =
                    mApproved.getOrDefault(userId, new ArrayMap<>());
            for (int i = 0; i < allowedByType.size(); i++) {
                final ArraySet<String> allowed = allowedByType.valueAt(i);
                for (int j = 0; j < allowed.size(); j++) {
                    String pkgName = getPackageName(allowed.valueAt(j));
                    if (!TextUtils.isEmpty(pkgName)) {
                        allowedPackages.add(pkgName);
                    }
                }
            }
        }
        return allowedPackages;
    }

    protected boolean isUidAllowed(int uid) {
        synchronized (mApproved) {
            HashSet<Integer> allowedUids = mApprovedUids.get(UserHandle.getUserId(uid));
            return allowedUids != null && allowedUids.contains(uid);
        }
    }

    protected boolean isPackageOrComponentAllowed(String pkgOrComponent, int userId) {
        synchronized (mApproved) {
            ArrayMap<Boolean, ArraySet<String>> allowedByType =
                    mApproved.getOrDefault(userId, new ArrayMap<>());
            for (int i = 0; i < allowedByType.size(); i++) {
                ArraySet<String> allowed = allowedByType.valueAt(i);
                if (allowed.contains(pkgOrComponent)) {
                    return true;
                }
            }
        }
        return false;
    }

    protected boolean isPackageOrComponentAllowedWithPermission(ComponentName component,
            int userId) {
        if (!(isPackageOrComponentAllowed(component.flattenToString(), userId)
                || isPackageOrComponentAllowed(component.getPackageName(), userId))) {
            return false;
        }
        return componentHasBindPermission(component, userId);
    }

    private boolean componentHasBindPermission(ComponentName component, int userId) {
        ServiceInfo info = getServiceInfo(component, userId);
        if (info == null) {
            return false;
        }
        return mConfig.bindPermission.equals(info.permission);
    }

    boolean isPackageOrComponentUserSet(String pkgOrComponent, int userId) {
        synchronized (mApproved) {
            ArraySet<String> services = mUserSetServices.get(userId);
            return services != null && services.contains(pkgOrComponent);
        }
    }

    protected boolean isPackageAllowed(String pkg, int userId) {
        if (pkg == null) {
            return false;
        }
        synchronized (mApproved) {
            ArrayMap<Boolean, ArraySet<String>> allowedByType =
                    mApproved.getOrDefault(userId, new ArrayMap<>());
            for (int i = 0; i < allowedByType.size(); i++) {
                ArraySet<String> allowed = allowedByType.valueAt(i);
                for (String allowedEntry : allowed) {
                    ComponentName component = ComponentName.unflattenFromString(allowedEntry);
                    if (component != null) {
                        if (pkg.equals(component.getPackageName())) {
                            return true;
                        }
                    } else {
                        if (pkg.equals(allowedEntry)) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    public void onPackagesChanged(boolean removingPackage, String[] pkgList, int[] uidList) {
        if (DEBUG) {
            synchronized (mMutex) {
                int resolvedUserId = (managedServicesConcurrentMultiuser()
                        && (uidList != null && uidList.length > 0))
                        ? resolveUserId(UserHandle.getUserId(uidList[0]))
                        : UserHandle.USER_CURRENT;
                Slog.d(TAG, "onPackagesChanged removingPackage=" + removingPackage
                        + " pkgList=" + (pkgList == null ? null : Arrays.asList(pkgList))
                        + " mEnabledServicesPackageNames="
                        + mEnabledServicesPackageNamesByUser.get(resolvedUserId));
            }
        }

        if (pkgList != null && (pkgList.length > 0)) {
            boolean anyServicesInvolved = false;
            // Remove notification settings for uninstalled package
            if (removingPackage && uidList != null) {
                int size = Math.min(pkgList.length, uidList.length);
                for (int i = 0; i < size; i++) {
                    final String pkg = pkgList[i];
                    final int userId = UserHandle.getUserId(uidList[i]);
                    anyServicesInvolved = removeUninstalledItemsFromApprovedLists(userId, pkg);
                }
            }
            for (String pkgName : pkgList) {
                if (!managedServicesConcurrentMultiuser()) {
                    if (isComponentEnabledForPackage(pkgName)) {
                        anyServicesInvolved = true;
                    }
                }
                if (uidList != null && uidList.length > 0) {
                    for (int uid : uidList) {
                        if (managedServicesConcurrentMultiuser()) {
                            if (isComponentEnabledForPackage(pkgName, UserHandle.getUserId(uid))) {
                                anyServicesInvolved = true;
                            }
                        }
                        if (isPackageAllowed(pkgName, UserHandle.getUserId(uid))) {
                            anyServicesInvolved = true;
                            trimApprovedListsForInvalidServices(pkgName, UserHandle.getUserId(uid));
                        }
                    }
                }
            }
            if (!Flags.useOnBindingDied()) {
                if (anyServicesInvolved) {
                    // make sure we're still bound to any of our services who may have just upgraded
                    rebindServices(false, USER_ALL);
                }
            }
        }
    }

    public void onUserRemoved(int user) {
        Slog.i(TAG, "Removing approved services for removed user " + user);
        synchronized (mApproved) {
            mApproved.remove(user);
            mApprovedUids.remove(user);
        }
        synchronized (mSnoozing) {
            mSnoozing.remove(user);
        }
        unbindUserServices(user);
    }

    /**
     * Call this method when a user is stopped
     *
     * @param user the id of the stopped user
     */
    public void onUserStopped(int user) {
        if (!managedServicesConcurrentMultiuser()) {
            return;
        }
        boolean hasAny = false;
        synchronized (mMutex) {
            if (mEnabledServicesByUser.contains(user)
                    && mEnabledServicesPackageNamesByUser.contains(user)) {
                // Through the ManagedServices.resolveUserId,
                // we resolve UserHandle.USER_CURRENT as the key for users
                // other than the visible background user.
                // Therefore, the user IDs that exist as keys for each member variable
                // correspond to the visible background user.
                // We need to unbind services of the stopped visible background user.
                mEnabledServicesByUser.remove(user);
                mEnabledServicesPackageNamesByUser.remove(user);
                hasAny = true;
            }
        }
        if (hasAny) {
            Slog.i(TAG, "Removing approved services for stopped user " + user);
            unbindUserServices(user);
        }
    }

    public void onUserSwitched(int user) {
        if (DEBUG) Slog.d(TAG, "onUserSwitched u=" + user);
        unbindOtherUserServices(user);
        rebindServices(true, user);
    }

    public void onUserUnlocked(int user) {
        if (DEBUG) Slog.d(TAG, "onUserUnlocked u=" + user);
        rebindServices(false, user);
    }

    private ManagedServiceInfo getServiceFromTokenLocked(IInterface service) {
        if (service == null) {
            return null;
        }
        final IBinder token = service.asBinder();
        synchronized (mMutex) {
            final int nServices = mServices.size();
            for (int i = 0; i < nServices; i++) {
                final ManagedServiceInfo info = mServices.get(i);
                if (info.service.asBinder() == token) return info;
            }
        }
        return null;
    }

    protected boolean isServiceTokenValidLocked(IInterface service) {
        if (service == null) {
            return false;
        }
        ManagedServiceInfo info = getServiceFromTokenLocked(service);
        if (info != null) {
            return true;
        }
        return false;
    }

    protected ManagedServiceInfo checkServiceTokenLocked(IInterface service) {
        checkNotNull(service);
        ManagedServiceInfo info = getServiceFromTokenLocked(service);
        if (info != null) {
            return info;
        }
        throw new SecurityException("Disallowed call from unknown " + getCaption() + ": "
                + service.asBinder() + " " + service.getClass());
    }

    public boolean isSameUser(IInterface service, int userId) {
        checkNotNull(service);
        synchronized (mMutex) {
            ManagedServiceInfo info = getServiceFromTokenLocked(service);
            if (info != null) {
                return info.isSameUser(userId);
            }
            return false;
        }
    }

    public void unregisterService(IInterface service, int userid) {
        checkNotNull(service);
        // no need to check permissions; if your service binder is in the list,
        // that's proof that you had permission to add it in the first place
        unregisterServiceImpl(service, userid);
    }

    public void registerSystemService(IInterface service, ComponentName component, int userid,
            int uid) {
        checkNotNull(service);
        ManagedServiceInfo info = registerServiceImpl(
                service, component, userid, Build.VERSION_CODES.CUR_DEVELOPMENT, uid);
        if (info != null) {
            onServiceAdded(info);
        }
    }

    /**
     * Add a service to our callbacks. The lifecycle of this service is managed externally,
     * but unlike a system service, it should not be considered privileged.
     * */
    protected void registerGuestService(ManagedServiceInfo guest) {
        checkNotNull(guest.service);
        if (!checkType(guest.service)) {
            throw new IllegalArgumentException();
        }
        if (registerServiceImpl(guest) != null) {
            onServiceAdded(guest);
        }
    }

    protected void setComponentState(ComponentName component, int userId, boolean enabled) {
        synchronized (mSnoozing) {
            boolean previous = !mSnoozing.contains(userId, component);
            if (previous == enabled) {
                return;
            }

            if (enabled) {
                mSnoozing.remove(userId, component);
            } else {
                mSnoozing.add(userId, component);
            }
        }

        // State changed
        Slog.d(TAG, ((enabled) ? "Enabling " : "Disabling ") + "component " +
                component.flattenToShortString());

        synchronized (mMutex) {
            if (enabled) {
                if (isPackageOrComponentAllowedWithPermission(component, userId)) {
                    registerServiceLocked(component, userId);
                } else {
                    Slog.d(TAG, component + " no longer has permission to be bound");
                }
            } else {
                unregisterServiceLocked(component, userId);
            }
        }
    }

    private @NonNull ArraySet<ComponentName> loadComponentNamesFromValues(
            ArraySet<String> approved, int userId) {
        if (approved == null || approved.size() == 0)
            return new ArraySet<>();
        ArraySet<ComponentName> result = new ArraySet<>(approved.size());
        for (int i = 0; i < approved.size(); i++) {
            final String packageOrComponent = approved.valueAt(i);
            if (!TextUtils.isEmpty(packageOrComponent)) {
                ComponentName component = ComponentName.unflattenFromString(packageOrComponent);
                if (component != null) {
                    result.add(component);
                } else {
                    result.addAll(queryPackageForServices(packageOrComponent, userId));
                }
            }
        }
        return result;
    }

    protected Set<ComponentName> queryPackageForServices(String packageName, int userId) {
        return queryPackageForServices(packageName, 0, userId);
    }

    protected ArraySet<ComponentName> queryPackageForServices(String packageName, int extraFlags,
            int userId) {
        ArraySet<ComponentName> installed = new ArraySet<>();
        final PackageManager pm = mContext.getPackageManager();
        Intent queryIntent = new Intent(mConfig.serviceInterface);
        if (!TextUtils.isEmpty(packageName)) {
            queryIntent.setPackage(packageName);
        }
        List<ResolveInfo> installedServices = pm.queryIntentServicesAsUser(
                queryIntent,
                PackageManager.GET_SERVICES | PackageManager.GET_META_DATA | extraFlags,
                userId);
        if (DEBUG)
            Slog.v(TAG, mConfig.serviceInterface + " services: " + installedServices);
        if (installedServices != null) {
            for (int i = 0, count = installedServices.size(); i < count; i++) {
                ResolveInfo resolveInfo = installedServices.get(i);
                ServiceInfo info = resolveInfo.serviceInfo;

                ComponentName component = new ComponentName(info.packageName, info.name);
                if (!mConfig.bindPermission.equals(info.permission)) {
                    Slog.w(TAG, "Skipping " + getCaption() + " service "
                        + info.packageName + "/" + info.name
                        + ": it does not require the permission "
                        + mConfig.bindPermission);
                    continue;
                }
                installed.add(component);
            }
        }
        return installed;
    }

    private void trimApprovedListsAccordingToInstalledServices(int userId) {
        synchronized (mApproved) {
            final ArrayMap<Boolean, ArraySet<String>> approvedByType = mApproved.get(userId);
            if (approvedByType == null) {
                return;
            }
            for (int i = 0; i < approvedByType.size(); i++) {
                final ArraySet<String> approved = approvedByType.valueAt(i);
                for (int j = approved.size() - 1; j >= 0; j--) {
                    final String approvedPackageOrComponent = approved.valueAt(j);
                    if (!isValidEntry(approvedPackageOrComponent, userId)) {
                        approved.removeAt(j);
                        Slog.v(TAG, "Removing " + approvedPackageOrComponent
                                + " from approved list; no matching services found");
                    } else {
                        if (DEBUG) {
                            Slog.v(TAG, "Keeping " + approvedPackageOrComponent
                                    + " on approved list; matching services found");
                        }
                    }
                }
            }
        }
    }

    private boolean removeUninstalledItemsFromApprovedLists(int uninstalledUserId, String pkg) {
        boolean removed = false;
        synchronized (mApproved) {
            final ArrayMap<Boolean, ArraySet<String>> approvedByType = mApproved.get(
                    uninstalledUserId);
            if (approvedByType != null) {
                int M = approvedByType.size();
                for (int j = 0; j < M; j++) {
                    final ArraySet<String> approved = approvedByType.valueAt(j);
                    int O = approved.size();
                    for (int k = O - 1; k >= 0; k--) {
                        final String packageOrComponent = approved.valueAt(k);
                        final String packageName = getPackageName(packageOrComponent);
                        if (TextUtils.equals(pkg, packageName)) {
                            approved.removeAt(k);
                            if (DEBUG) {
                                Slog.v(TAG, "Removing " + packageOrComponent
                                        + " from approved list; uninstalled");
                            }
                        }
                    }
                }
            }
            // Remove uninstalled components from user-set list
            final ArraySet<String> userSet = mUserSetServices.get(uninstalledUserId);
            if (userSet != null) {
                int numServices = userSet.size();
                for (int i = numServices - 1; i >= 0; i--) {
                    String pkgOrComponent = userSet.valueAt(i);
                    if (TextUtils.equals(pkg, getPackageName(pkgOrComponent))) {
                        userSet.removeAt(i);
                        if (DEBUG) {
                            Slog.v(TAG, "Removing " + pkgOrComponent
                                    + " from user-set list; uninstalled");
                        }
                    }
                }
            }
        }
        return removed;
    }

    private void trimApprovedListsForInvalidServices(String packageName, int userId) {
        synchronized (mApproved) {
            final ArrayMap<Boolean, ArraySet<String>> approvedByType = mApproved.get(userId);
            if (approvedByType == null) {
                return;
            }
            for (int i = 0; i < approvedByType.size(); i++) {
                final ArraySet<String> approved = approvedByType.valueAt(i);
                for (int j = approved.size() - 1; j >= 0; j--) {
                    final String approvedPackageOrComponent = approved.valueAt(j);
                    if (TextUtils.equals(getPackageName(approvedPackageOrComponent), packageName)) {
                        final ComponentName component = ComponentName.unflattenFromString(
                                approvedPackageOrComponent);
                        if (component != null && !componentHasBindPermission(component, userId)) {
                            approved.removeAt(j);
                            if (DEBUG) {
                                Slog.v(TAG, "Removing " + approvedPackageOrComponent
                                        + " from approved list; no bind permission found "
                                        + mConfig.bindPermission);
                            }
                        }
                    }
                }
            }
        }
    }

    protected String getPackageName(String packageOrComponent) {
        final ComponentName component = ComponentName.unflattenFromString(packageOrComponent);
        if (component != null) {
            return component.getPackageName();
        } else {
            return packageOrComponent;
        }
    }

    protected boolean isValidEntry(String packageOrComponent, int userId) {
        return hasMatchingServices(packageOrComponent, userId);
    }

    private boolean hasMatchingServices(String packageOrComponent, int userId) {
        if (!TextUtils.isEmpty(packageOrComponent)) {
            final String packageName = getPackageName(packageOrComponent);
            return queryPackageForServices(packageName, userId).size() > 0;
        }
        return false;
    }

    @VisibleForTesting
    protected SparseArray<ArraySet<ComponentName>> getAllowedComponents(IntArray userIds) {
        final int nUserIds = userIds.size();
        final SparseArray<ArraySet<ComponentName>> componentsByUser = new SparseArray<>();

        for (int i = 0; i < nUserIds; ++i) {
            final int userId = userIds.get(i);
            synchronized (mApproved) {
                final ArrayMap<Boolean, ArraySet<String>> approvedLists = mApproved.get(userId);
                if (approvedLists != null) {
                    final int N = approvedLists.size();
                    for (int j = 0; j < N; j++) {
                        ArraySet<ComponentName> approvedByUser = componentsByUser.get(userId);
                        if (approvedByUser == null) {
                            approvedByUser = new ArraySet<>();
                            componentsByUser.put(userId, approvedByUser);
                        }
                        approvedByUser.addAll(
                                loadComponentNamesFromValues(approvedLists.valueAt(j), userId));
                    }
                }
            }
        }
        return componentsByUser;
    }

    @GuardedBy("mMutex")
    protected void populateComponentsToBind(SparseArray<Set<ComponentName>> componentsToBind,
            final IntArray activeUsers,
            SparseArray<ArraySet<ComponentName>> approvedComponentsByUser) {
        final int nUserIds = activeUsers.size();
        if (managedServicesConcurrentMultiuser()) {
            for (int i = 0; i < nUserIds; ++i) {
                final int resolvedUserId = resolveUserId(activeUsers.get(i));
                if (mEnabledServicesByUser.get(resolvedUserId) != null) {
                    mEnabledServicesByUser.get(resolvedUserId).clear();
                }
                if (mEnabledServicesPackageNamesByUser.get(resolvedUserId) != null) {
                    mEnabledServicesPackageNamesByUser.get(resolvedUserId).clear();
                }
            }
        } else {
            mEnabledServicesByUser.get(UserHandle.USER_CURRENT).clear();
            mEnabledServicesPackageNamesByUser.get(UserHandle.USER_CURRENT).clear();
        }
        for (int i = 0; i < nUserIds; ++i) {
            final int userId = activeUsers.get(i);
            // decode the list of components
            final ArraySet<ComponentName> userComponents = approvedComponentsByUser.get(userId);
            if (null == userComponents) {
                componentsToBind.put(userId, new ArraySet<>());
                continue;
            }

            final int resolvedUserId = managedServicesConcurrentMultiuser()
                    ? resolveUserId(userId)
                    : UserHandle.USER_CURRENT;
            ArraySet<ComponentName> enabledServices =
                    mEnabledServicesByUser.contains(resolvedUserId)
                    ? mEnabledServicesByUser.get(resolvedUserId)
                    : new ArraySet<>();
            ArraySet<String> enabledServicesPackageName =
                    mEnabledServicesPackageNamesByUser.contains(resolvedUserId)
                    ? mEnabledServicesPackageNamesByUser.get(resolvedUserId)
                    : new ArraySet<>();

            final Set<ComponentName> add = new HashSet<>(userComponents);
            synchronized (mSnoozing) {
                ArraySet<ComponentName> snoozed = mSnoozing.get(userId);
                if (snoozed != null) {
                    add.removeAll(snoozed);
                }
            }

            componentsToBind.put(userId, add);

            enabledServices.addAll(userComponents);
            for (int j = 0; j < userComponents.size(); j++) {
                enabledServicesPackageName.add(userComponents.valueAt(j).getPackageName());
            }
            mEnabledServicesByUser.put(resolvedUserId, enabledServices);
            mEnabledServicesPackageNamesByUser.put(resolvedUserId, enabledServicesPackageName);
        }
    }

    @GuardedBy("mMutex")
    protected Set<ManagedServiceInfo> getRemovableConnectedServices() {
        final Set<ManagedServiceInfo> removableBoundServices = new ArraySet<>();
        for (ManagedServiceInfo service : mServices) {
            if (!service.isSystem && !service.isGuest(this)) {
                removableBoundServices.add(service);
            }
        }
        return removableBoundServices;
    }

    protected void populateComponentsToUnbind(
            boolean forceRebind,
            Set<ManagedServiceInfo> removableBoundServices,
            SparseArray<Set<ComponentName>> allowedComponentsToBind,
            SparseArray<Set<ComponentName>> componentsToUnbind) {
        for (ManagedServiceInfo info : removableBoundServices) {
            final Set<ComponentName> allowedComponents = allowedComponentsToBind.get(info.userid);
            if (allowedComponents != null) {
                if (forceRebind || !allowedComponents.contains(info.component)) {
                    Set<ComponentName> toUnbind =
                            componentsToUnbind.get(info.userid, new ArraySet<>());
                    toUnbind.add(info.component);
                    componentsToUnbind.put(info.userid, toUnbind);
                }
            }
        }
    }

    /**
     * Called whenever packages change, the user switches, or the secure setting
     * is altered. (For example in response to USER_SWITCHED in our broadcast receiver)
     */
    protected void rebindServices(boolean forceRebind, int userToRebind) {
        if (DEBUG) Slog.d(TAG, "rebindServices " + forceRebind + " " + userToRebind);
        boolean rebindAllCurrentUsers = mUserProfiles.isProfileUser(userToRebind, mContext)
                && allowRebindForParentUser();
        IntArray userIds = getUserIdsForRebindServices(userToRebind, rebindAllCurrentUsers);

        final SparseArray<Set<ComponentName>> componentsToBind = new SparseArray<>();
        final SparseArray<Set<ComponentName>> componentsToUnbind = new SparseArray<>();

        synchronized (mMutex) {
            final SparseArray<ArraySet<ComponentName>> approvedComponentsByUser =
                    getAllowedComponents(userIds);
            final Set<ManagedServiceInfo> removableBoundServices = getRemovableConnectedServices();

            // Filter approvedComponentsByUser to collect all of the components that are allowed
            // for the currently active user(s).
            populateComponentsToBind(componentsToBind, userIds, approvedComponentsByUser);

            // For every current non-system connection, disconnect services that are no longer
            // approved, or ALL services if we are force rebinding
            populateComponentsToUnbind(
                    forceRebind, removableBoundServices, componentsToBind, componentsToUnbind);
        }

        unbindFromServices(componentsToUnbind);
        bindToServices(componentsToBind);
    }

    private IntArray getUserIdsForRebindServices(int userToRebind, boolean rebindAllCurrentUsers) {
        IntArray userIds = mUserProfiles.getCurrentProfileIds();
        if (userToRebind != USER_ALL && !rebindAllCurrentUsers) {
            userIds = new IntArray(1);
            userIds.add(userToRebind);
        } else if (managedServicesConcurrentMultiuser()
                && userToRebind == USER_ALL) {
            for (UserInfo user : mUm.getUsers()) {
                if (mUmInternal.isVisibleBackgroundFullUser(user.id)
                        && !userIds.contains(user.id)) {
                    userIds.add(user.id);
                }
            }
        }
        return userIds;
    }

    /**
     * Called when user switched to unbind all services from other users.
     */
    @VisibleForTesting
    void unbindOtherUserServices(int currentUser) {
        TimingsTraceAndSlog t = new TimingsTraceAndSlog();
        t.traceBegin("ManagedServices.unbindOtherUserServices_current" + currentUser);
        unbindServicesImpl(currentUser, true /* allExceptUser */);
        t.traceEnd();
    }

    void unbindUserServices(int user) {
        TimingsTraceAndSlog t = new TimingsTraceAndSlog();
        t.traceBegin("ManagedServices.unbindUserServices" + user);
        unbindServicesImpl(user, false /* allExceptUser */);
        t.traceEnd();
    }

    void unbindServicesImpl(int user, boolean allExceptUser) {
        final SparseArray<Set<ComponentName>> componentsToUnbind = new SparseArray<>();
        synchronized (mMutex) {
            final Set<ManagedServiceInfo> removableBoundServices = getRemovableConnectedServices();
            for (ManagedServiceInfo info : removableBoundServices) {
                // User switching is the event for the forground user.
                // It should not affect the service of the visible background user.
                if ((allExceptUser && (info.userid != user)
                        && !(managedServicesConcurrentMultiuser()
                            && info.isVisibleBackgroundUserService))
                        || (!allExceptUser && (info.userid == user))) {
                    Set<ComponentName> toUnbind =
                            componentsToUnbind.get(info.userid, new ArraySet<>());
                    toUnbind.add(info.component);
                    componentsToUnbind.put(info.userid, toUnbind);
                }
            }
        }
        unbindFromServices(componentsToUnbind);
    }

    protected void unbindFromServices(SparseArray<Set<ComponentName>> componentsToUnbind) {
        for (int i = 0; i < componentsToUnbind.size(); i++) {
            final int userId = componentsToUnbind.keyAt(i);
            final Set<ComponentName> removableComponents = componentsToUnbind.get(userId);
            for (ComponentName cn : removableComponents) {
                // No longer allowed to be bound, or must rebind.
                Slog.v(TAG, "disabling " + getCaption() + " for user " + userId + ": " + cn);
                unregisterService(cn, userId);
            }
        }
    }

    // Attempt to bind to services, skipping those that cannot be found or lack the permission.
    private void bindToServices(SparseArray<Set<ComponentName>> componentsToBind) {
        for (int i = 0; i < componentsToBind.size(); i++) {
            final int userId = componentsToBind.keyAt(i);
            final Set<ComponentName> add = componentsToBind.get(userId);
            for (ComponentName component : add) {
                ServiceInfo info = getServiceInfo(component, userId);
                if (info == null) {
                    Slog.w(TAG, "Not binding " + getCaption() + " service " + component
                            + ": service not found");
                    continue;
                }
                if (!mConfig.bindPermission.equals(info.permission)) {
                    Slog.w(TAG, "Not binding " + getCaption() + " service " + component
                            + ": it does not require the permission " + mConfig.bindPermission);
                    continue;
                }
                // Do not (auto)bind if service has meta-data to explicitly disallow it
                if (!isAutobindAllowed(info) && !isBoundOrRebinding(component, userId)) {
                    synchronized (mSnoozing) {
                        Slog.d(TAG, "Not binding " + getCaption() + " service " + component
                                + ": has META_DATA_DEFAULT_AUTOBIND = false");
                        mSnoozing.add(userId, component);
                    }
                    continue;
                }

                Slog.v(TAG,
                        "enabling " + getCaption() + " for " + userId + ": " + component);
                registerService(info, userId);
            }
        }
    }

    /**
     * Version of registerService that takes the name of a service component to bind to.
     */
    @VisibleForTesting
    void registerService(final ServiceInfo si, final int userId) {
        ensureFilters(si, userId);
        registerService(si.getComponentName(), userId);
    }

    @VisibleForTesting
    void registerService(final ComponentName cn, final int userId) {
        synchronized (mMutex) {
            registerServiceLocked(cn, userId);
        }
    }

    @VisibleForTesting
    void reregisterService(final ComponentName cn, final int userId) {
        // If rebinding a package that died, ensure it still has permission
        // after the rebind delay
        if (isPackageOrComponentAllowedWithPermission(cn, userId)) {
            registerService(cn, userId);
        } else {
            if (Flags.useOnBindingDied()) {
                // clean up enabled component list
                mEnabledServicesByUser.get(resolveUserId(userId)).remove(cn);
            }
            if (DEBUG) Slog.v(TAG, "skipped reregisterService cn=" + cn + " u=" + userId
                    + " because of isPackageOrComponentAllowedWithPermission check");
        }
    }

    /**
     * Inject a system service into the management list.
     */
    public void registerSystemService(final ComponentName name, final int userid) {
        synchronized (mMutex) {
            registerServiceLocked(name, userid, true /* isSystem */);
        }
    }

    @GuardedBy("mMutex")
    private void disconnectServiceLocked(ServiceConnection sc, IInterface service,
            @UserIdInt int userId, ComponentName cn) {
        if (service != null) {
            Slog.w(TAG, userId + " " + getCaption() + " unregister: " + cn);
            unregisterService(service, userId);
        } else {
            Slog.w(TAG, userId + " " + getCaption() + " unbind: " + cn);
            unbindService(sc, cn, userId);
        }
    }

    @GuardedBy("mMutex")
    private void registerServiceLocked(final ComponentName name, final int userid) {
        registerServiceLocked(name, userid, false /* isSystem */);
    }

    @GuardedBy("mMutex")
    private boolean isServiceAlreadyBoundLocked(ManagedServiceInfo info) {
        for (ManagedServiceInfo info2 : mServices) {
            if (Objects.equals(info.component, info2.component) && info.userid == info2.userid) {
                return true;
            }
        }
        return false;
    }

    @GuardedBy("mMutex")
    private void registerServiceLocked(final ComponentName name, final int userid,
            final boolean isSystem) {
        if (DEBUG) Slog.v(TAG, "registerService: " + name + " u=" + userid);

        final Pair<ComponentName, Integer> servicesBindingTag = Pair.create(name, userid);
        if (mServicesBound.contains(servicesBindingTag)) {
            Slog.v(TAG, "Not registering " + name + " is already binding");
            // stop registering this thing already! we're working on it
            return;
        }
        mServicesBound.add(servicesBindingTag);

        if (!Flags.useOnBindingDied()) {
            final int N = mServices.size();
            for (int i = N - 1; i >= 0; i--) {
                final ManagedServiceInfo info = mServices.get(i);
                if (name.equals(info.component)
                        && info.userid == userid) {
                    // cut old connections
                    Slog.v(TAG, "    disconnecting old " + getCaption() + ": " + info.service);
                    removeServiceLocked(i);
                    if (info.connection != null) {
                        unbindService(info.connection, info.component, info.userid);
                    }
                }
            }
        }

        Intent intent = new Intent(mConfig.serviceInterface);
        intent.setComponent(name);

        intent.putExtra(Intent.EXTRA_CLIENT_LABEL, mConfig.clientLabel);

        final ActivityOptions activityOptions = ActivityOptions.makeBasic();
        activityOptions.setPendingIntentCreatorBackgroundActivityStartMode(
                ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_DENIED);
        final PendingIntent pendingIntent = PendingIntent.getActivity(
                mContext, 0, new Intent(mConfig.settingsAction), PendingIntent.FLAG_IMMUTABLE,
                activityOptions.toBundle());
        intent.putExtra(Intent.EXTRA_CLIENT_INTENT, pendingIntent);

        ApplicationInfo appInfo = null;
        try {
            appInfo = mContext.getPackageManager().getApplicationInfoAsUser(
                name.getPackageName(), 0, userid);
        } catch (NameNotFoundException e) {
            // Ignore if the package doesn't exist we won't be able to bind to the service.
        }
        final int targetSdkVersion =
            appInfo != null ? appInfo.targetSdkVersion : Build.VERSION_CODES.BASE;
        final int uid = appInfo != null ? appInfo.uid : -1;

        try {
            Slog.v(TAG, "binding: " + intent);
            ServiceConnection serviceConnection = new ServiceConnection() {
                IInterface mService;

                @Override
                public void onServiceConnected(ComponentName name, IBinder binder,
                        IBinderSession binderSession) {
                    Slog.v(TAG, userid + " " + getCaption() + " service connected: " + name);
                    boolean added = false;
                    ManagedServiceInfo info = null;
                    synchronized (mMutex) {
                        mServicesRebinding.remove(servicesBindingTag);
                        try {
                            mService = asInterface(binder);
                            if (reportNlsStartAndEnd()) {
                                info = new ManagedServiceInfo(mService, name, userid, isSystem,
                                        this, targetSdkVersion, uid, binderSession);
                            } else {
                                info = new ManagedServiceInfo(mService, name, userid, isSystem,
                                        this, targetSdkVersion, uid);
                            }
                            if (!Flags.useOnBindingDied()) {
                                binder.linkToDeath(info, 0);
                            }
                            if (Flags.useOnBindingDied() && isServiceAlreadyBoundLocked(info)) {
                                Slog.wtfStack(TAG, "Duplicate binding " + info);
                            }
                            added = mServices.add(info);
                        } catch (RemoteException e) {
                            if (Flags.useOnBindingDied()) {
                                // This block is likely unreachable because RemoteException is
                                // typically thrown by binder.linkToDeath, which is skipped
                                // when Flags.useOnBindingDied() is true.
                                mServicesBound.remove(servicesBindingTag);
                            }
                            Slog.e(TAG, "Failed to linkToDeath, already dead", e);
                        }
                    }
                    if (added) {
                        onServiceAdded(info);
                    }
                }

                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    Slog.wtfStack(TAG,
                            "onServiceConnected(ComponentName, IBinder) called even when "
                                    + "onServiceConnected(ComponentName, IBinder, IBinderSession)"
                                    + " was overridden");
                }

                @Override
                public void onServiceDisconnected(ComponentName name) {
                    Slog.v(TAG, userid + " " + getCaption() + " connection lost: " + name);
                }

                @Override
                public void onBindingDied(ComponentName name) {
                    Slog.w(TAG, userid + " " + getCaption() + " binding died: " + name);
                    synchronized (mMutex) {
                        if (Flags.useOnBindingDied()) {
                            disconnectServiceLocked(this, mService, userid, name);
                        } else {
                            unbindService(this, name, userid);
                        }
                        if (!mServicesRebinding.contains(servicesBindingTag)) {
                            mServicesRebinding.add(servicesBindingTag);
                            if (mRebindAsyncDelay) {
                                mHandler.postDelayed(() ->
                                                reregisterService(name, userid),
                                        ON_BINDING_DIED_REBIND_DELAY_MS);
                            } else {
                                reregisterService(name, userid);
                            }
                        } else {
                            Slog.v(TAG, getCaption() + " not rebinding in user " + userid
                                    + " as a previous rebind attempt was made: " + name);
                        }
                    }
                }

                @Override
                public void onNullBinding(ComponentName name) {
                    Slog.v(TAG, "onNullBinding() called with: name = [" + name + "]");
                    if (Flags.useOnBindingDied()) {
                        disconnectServiceLocked(this, mService, userid, name);
                    } else {
                        mContext.unbindService(this);
                    }
                }
            };
            if (!mContext.bindServiceAsUser(intent,
                    serviceConnection,
                    BindServiceFlags.of(getBindFlags()),
                    new UserHandle(userid))) {
                mServicesBound.remove(servicesBindingTag);
                Slog.w(TAG, "Unable to bind " + getCaption() + " service: " + intent
                        + " in user " + userid);
            }
        } catch (SecurityException ex) {
            mServicesBound.remove(servicesBindingTag);
            Slog.e(TAG, "Unable to bind " + getCaption() + " service: " + intent, ex);
        }
    }

    @VisibleForTesting
    boolean isBound(ComponentName cn, int userId) {
        final Pair<ComponentName, Integer> servicesBindingTag = Pair.create(cn, userId);
        synchronized (mMutex) {
            return mServicesBound.contains(servicesBindingTag);
        }
    }

    protected boolean isBoundOrRebinding(final ComponentName cn, final int userId) {
        synchronized (mMutex) {
            return isBound(cn, userId) || mServicesRebinding.contains(Pair.create(cn, userId));
        }
    }

    /**
     * Remove a service for the given user by ComponentName
     */
    private void unregisterService(ComponentName name, int userid) {
        synchronized (mMutex) {
            unregisterServiceLocked(name, userid);
        }
    }

    @GuardedBy("mMutex")
    private void unregisterServiceLocked(ComponentName name, int userid) {
        final int N = mServices.size();
        for (int i = N - 1; i >= 0; i--) {
            final ManagedServiceInfo info = mServices.get(i);
            if (name.equals(info.component) && info.userid == userid) {
                removeServiceLocked(i);
                if (info.connection != null) {
                    unbindService(info.connection, info.component, info.userid);
                }
            }
        }
    }

    /**
     * Removes a service from the list but does not unbind
     *
     * @return the removed service.
     */
    private ManagedServiceInfo removeServiceImpl(IInterface service, final int userid) {
        if (DEBUG) Slog.d(TAG, "removeServiceImpl service=" + service + " u=" + userid);
        ManagedServiceInfo serviceInfo = null;
        synchronized (mMutex) {
            final int N = mServices.size();
            for (int i = N - 1; i >= 0; i--) {
                final ManagedServiceInfo info = mServices.get(i);
                if (info.service.asBinder() == service.asBinder() && info.userid == userid) {
                    Slog.d(TAG, "Removing active service " + info.component);
                    serviceInfo = removeServiceLocked(i);
                }
            }
        }
        return serviceInfo;
    }

    @GuardedBy("mMutex")
    private ManagedServiceInfo removeServiceLocked(int i) {
        final ManagedServiceInfo info = mServices.remove(i);
        onServiceRemovedLocked(info);
        return info;
    }

    private void checkNotNull(IInterface service) {
        if (service == null) {
            throw new IllegalArgumentException(getCaption() + " must not be null");
        }
    }

    private ManagedServiceInfo registerServiceImpl(final IInterface service,
            final ComponentName component, final int userid, int targetSdk, int uid) {
        ManagedServiceInfo info = new ManagedServiceInfo(service, component, userid,
                true /*isSystem*/, null /*connection*/, targetSdk, uid);
        return registerServiceImpl(info);
    }

    private ManagedServiceInfo registerServiceImpl(ManagedServiceInfo info) {
        synchronized (mMutex) {
            try {
                info.service.asBinder().linkToDeath(info, 0);
                mServices.add(info);
                return info;
            } catch (RemoteException e) {
                // already dead
            }
        }
        return null;
    }

    /**
     * Removes a service from the list and unbinds.
     */
    private void unregisterServiceImpl(IInterface service, int userid) {
        ManagedServiceInfo info = removeServiceImpl(service, userid);
        if (info != null && info.connection != null && !info.isGuest(this)) {
            unbindService(info.connection, info.component, info.userid);
        }
    }

    private void unbindService(ServiceConnection connection, ComponentName component, int userId) {
        try {
            mContext.unbindService(connection);
        } catch (IllegalArgumentException e) {
            Slog.e(TAG, getCaption() + " " + component + " could not be unbound", e);
        }
        synchronized (mMutex) {
            mServicesBound.remove(Pair.create(component, userId));
        }
    }

    private ServiceInfo getServiceInfo(ComponentName component, int userId) {
        try {
            return mPm.getServiceInfo(component,
                    PackageManager.GET_META_DATA
                            | PackageManager.MATCH_DIRECT_BOOT_AWARE
                            | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
                    userId);
        } catch (RemoteException e) {
            e.rethrowFromSystemServer();
        }
        return null;
    }

    private boolean isAutobindAllowed(ServiceInfo serviceInfo) {
        if (serviceInfo != null && serviceInfo.metaData != null && serviceInfo.metaData.containsKey(
                META_DATA_DEFAULT_AUTOBIND)) {
            return serviceInfo.metaData.getBoolean(META_DATA_DEFAULT_AUTOBIND, true);
        }
        return true;
    }

    /**
     * This method returns the mapped id for the incoming user id
     * If the incoming id was not the id of the visible background user, it returns USER_CURRENT.
     * In the other cases, it returns the same value as the input.
     *
     * @param userId the id of the user
     * @return the user id if it is a visible background user, otherwise
     * {@link UserHandle#USER_CURRENT}
     */
    @FlaggedApi(FLAG_MANAGED_SERVICES_CONCURRENT_MULTIUSER)
    @VisibleForTesting
    public int resolveUserId(int userId) {
        if (managedServicesConcurrentMultiuser()) {
            if (mUmInternal.isVisibleBackgroundFullUser(userId)) {
                // The dataset of the visible background user should be managed independently.
                return userId;
            }
        }
        // The data of current user and its profile users need to  be managed
        // in a dataset as before.
        return UserHandle.USER_CURRENT;
    }

    /**
     * Returns true if services in the parent user should be rebound
     *  when rebindServices is called with a profile userId.
     * Must be false for NotificationAssistants.
     */
    protected abstract boolean allowRebindForParentUser();

    @VisibleForTesting
    void setRebindAsyncDelay(boolean rebindAsyncDelay) {
        mRebindAsyncDelay = rebindAsyncDelay;
    }

    public class ManagedServiceInfo implements IBinder.DeathRecipient {
        public IInterface service;
        public ComponentName component;
        public int userid;
        public boolean isSystem;
        @FlaggedApi(FLAG_LIFETIME_EXTENSION_REFACTOR)
        public boolean isSystemUi;
        public ServiceConnection connection;
        public int targetSdkVersion;
        public Pair<ComponentName, Integer> mKey;
        public int uid;
        @FlaggedApi(FLAG_MANAGED_SERVICES_CONCURRENT_MULTIUSER)
        public boolean isVisibleBackgroundUserService;
        public final IBinderSession mBinderSession;

        public ManagedServiceInfo(IInterface service, ComponentName component,
                int userid, boolean isSystem, ServiceConnection connection, int targetSdkVersion,
                int uid) {
            this(service, component, userid, isSystem, connection, targetSdkVersion, uid, null);
        }

        public ManagedServiceInfo(IInterface service, ComponentName component,
                int userid, boolean isSystem, ServiceConnection connection, int targetSdkVersion,
                int uid, IBinderSession binderSession) {
            this.service = service;
            this.component = component;
            this.userid = userid;
            this.isSystem = isSystem;
            this.connection = connection;
            this.targetSdkVersion = targetSdkVersion;
            this.uid = uid;
            if (managedServicesConcurrentMultiuser()) {
                this.isVisibleBackgroundUserService = LocalServices
                        .getService(UserManagerInternal.class).isVisibleBackgroundFullUser(userid);
            }
            mKey = Pair.create(component, userid);
            mBinderSession = binderSession;
        }

        public boolean isGuest(ManagedServices host) {
            return ManagedServices.this != host;
        }

        public ManagedServices getOwner() {
            return ManagedServices.this;
        }

        public IInterface getService() {
            return service;
        }

        public boolean isSystem() {
            return isSystem;
        }

        @FlaggedApi(FLAG_LIFETIME_EXTENSION_REFACTOR)
        public boolean isSystemUi() {
            return isSystemUi;
        }

        @Override
        public String toString() {
            return new StringBuilder("ManagedServiceInfo[")
                    .append("component=").append(component)
                    .append(",userid=").append(userid)
                    .append(",isSystem=").append(isSystem)
                    .append(",targetSdkVersion=").append(targetSdkVersion)
                    .append(",connection=").append(connection == null ? null : "<connection>")
                    .append(",service=").append(service)
                    .append(",serviceAsBinder=").append(service != null ? service.asBinder() : null)
                    .append(']').toString();
        }

        public void dumpDebug(ProtoOutputStream proto, long fieldId, ManagedServices host) {
            final long token = proto.start(fieldId);
            component.dumpDebug(proto, ManagedServiceInfoProto.COMPONENT);
            proto.write(ManagedServiceInfoProto.USER_ID, userid);
            proto.write(ManagedServiceInfoProto.SERVICE, service.getClass().getName());
            proto.write(ManagedServiceInfoProto.IS_SYSTEM, isSystem);
            proto.write(ManagedServiceInfoProto.IS_GUEST, isGuest(host));
            proto.end(token);
        }

        public boolean isSameUser(int userId) {
            if (!isEnabledForUser()) {
                return false;
            }
            return userId == USER_ALL || userId == this.userid;
        }

        public boolean enabledAndUserMatches(int nid) {
            if (!isEnabledForUser()) {
                return false;
            }
            if (this.userid == USER_ALL) return true;
            if (this.isSystem) return true;
            if (nid == USER_ALL || nid == this.userid) return true;
            if (managedServicesConcurrentMultiuser()
                    && mUmInternal.getProfileParentId(nid)
                        != mUmInternal.getProfileParentId(this.userid)) {
                // If the profile parent IDs do not match each other,
                // it is determined that the users do not match.
                // This situation may occur when comparing the current user's ID
                // with the visible background user's ID.
                return false;
            }
            return supportsProfiles()
                    && mUserProfiles.isCurrentProfile(nid)
                    && isPermittedForProfile(nid);
        }

        public boolean supportsProfiles() {
            return targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
        }

        @Override
        public void binderDied() {
            if (Flags.useOnBindingDied()) {
                return;
            }
            if (DEBUG) Slog.d(TAG, "binderDied " + this);
            // Remove the service, but don't unbind from the service. The system will bring the
            // service back up, and the onServiceConnected handler will read the service with the
            // new binding. If this isn't a bound service, and is just a registered
            // service, just removing it from the list is all we need to do anyway.
            removeServiceImpl(this.service, this.userid);
        }

        /**
         * convenience method for looking in mEnabledServicesByUser.
         * If FLAG_MANAGED_SERVICES_CONCURRENT_MULTIUSER is disabled, this manages the data using
         * only UserHandle.USER_CURRENT as the key, in order to behave the same as the legacy logic.
        */
        public boolean isEnabledForUser() {
            if (this.isSystem) return true;
            if (this.connection == null) return false;
            synchronized (mMutex) {
                int resolvedUserId = managedServicesConcurrentMultiuser()
                        ? resolveUserId(this.userid)
                        : UserHandle.USER_CURRENT;
                ArraySet<ComponentName> enabledServices =
                        mEnabledServicesByUser.get(resolvedUserId);
                return enabledServices != null && enabledServices.contains(this.component);
            }
        }

        /**
         * Returns true if this service is allowed to receive events for the given userId. A
         * managed profile owner can disallow non-system services running outside of the profile
         * from receiving events from the profile.
         */
        public boolean isPermittedForProfile(int userId) {
            if (!mUserProfiles.isProfileUser(userId, mContext)) {
                return true;
            }
            DevicePolicyManager dpm =
                    (DevicePolicyManager) mContext.getSystemService(DEVICE_POLICY_SERVICE);
            final long identity = Binder.clearCallingIdentity();
            try {
                return dpm.isNotificationListenerServicePermitted(
                        component.getPackageName(), userId);
            } finally {
                Binder.restoreCallingIdentity(identity);
            }
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            ManagedServiceInfo that = (ManagedServiceInfo) o;
            return userid == that.userid
                    && isSystem == that.isSystem
                    && targetSdkVersion == that.targetSdkVersion
                    && Objects.equals(service, that.service)
                    && Objects.equals(component, that.component)
                    && Objects.equals(connection, that.connection);
        }

        @Override
        public int hashCode() {
            return Objects.hash(service, component, userid, isSystem, connection, targetSdkVersion);
        }
    }

    /** convenience method for looking in mEnabledServicesByUser for UserHandle.USER_CURRENT.
     * This is a legacy API. When FLAG_MANAGED_SERVICES_CONCURRENT_MULTIUSER becomes
     * trunk stable,  this API should be deprecated.  Additionally, when this method
     * is deprecated, the unit tests written using this method should also be revised.
     *
     * @param component target component name
     * @return boolean value that indicates whether it is enabled for the current profiles
     */
    public boolean isComponentEnabledForCurrentProfiles(ComponentName component) {
        return isComponentEnabledForUser(component, UserHandle.USER_CURRENT);
    }

    /** convenience method for looking in mEnabledServicesForUser
     *
     * @param component target component name
     * @param userId the id of the target user
     * @return boolean value that indicates whether it is enabled for the target user
    */
    @FlaggedApi(FLAG_MANAGED_SERVICES_CONCURRENT_MULTIUSER)
    public boolean isComponentEnabledForUser(ComponentName component, int userId) {
        synchronized (mMutex) {
            ArraySet<ComponentName> enabledServicesForUser =
                    mEnabledServicesByUser.get(resolveUserId(userId));
            return enabledServicesForUser != null && enabledServicesForUser.contains(component);
        }
    }

    public static class UserProfiles {
        // Profiles of the current user.
        private final SparseArray<UserInfo> mCurrentProfiles = new SparseArray<>();

        public void updateCache(@NonNull Context context) {
            UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
            if (userManager != null) {
                int currentUserId = ActivityManager.getCurrentUser();
                List<UserInfo> profiles = userManager.getProfiles(currentUserId);
                synchronized (mCurrentProfiles) {
                    mCurrentProfiles.clear();
                    for (UserInfo user : profiles) {
                        mCurrentProfiles.put(user.id, user);
                    }
                }
            }
        }

        /**
         * Returns the currently active users (generally one user and its work profile).
         */
        public IntArray getCurrentProfileIds() {
            synchronized (mCurrentProfiles) {
                IntArray users = new IntArray(mCurrentProfiles.size());
                final int N = mCurrentProfiles.size();
                for (int i = 0; i < N; ++i) {
                    users.add(mCurrentProfiles.keyAt(i));
                }
                return users;
            }
        }

        public boolean isCurrentProfile(int userId) {
            synchronized (mCurrentProfiles) {
                return mCurrentProfiles.get(userId) != null;
            }
        }

        public boolean isProfileUser(int userId, Context context) {
            synchronized (mCurrentProfiles) {
                UserInfo user = mCurrentProfiles.get(userId);
                if (user == null) {
                    return false;
                }
                if (privateSpaceFlagsEnabled()) {
                    return user.isProfile() && hasParent(user, context);
                }
                return user.isManagedProfile() || user.isCloneProfile();
            }
        }

        boolean isManagedProfileUser(int userId) {
            synchronized (mCurrentProfiles) {
                UserInfo user = mCurrentProfiles.get(userId);
                if (user == null) {
                    return false;
                }
                return user.isManagedProfile();
            }
        }

        int getProfileParentId(int userId, Context context) {
            final long identity = Binder.clearCallingIdentity();
            try {
                UserManager um = context.getSystemService(UserManager.class);
                UserInfo parent = um.getProfileParent(userId);
                if (parent != null) {
                    return parent.id;
                }
                return userId;  // if no parent, return itself
            } finally {
                Binder.restoreCallingIdentity(identity);
            }
        }

        boolean hasParent(UserInfo profile, Context context) {
            final long identity = Binder.clearCallingIdentity();
            try {
                UserManager um = context.getSystemService(UserManager.class);
                return um.getProfileParent(profile.id) != null;
            } finally {
                Binder.restoreCallingIdentity(identity);
            }
        }
    }

    public static class Config {
        public String caption;
        public String serviceInterface;
        public String secureSettingName;
        public String secondarySettingName;
        public String xmlTag;
        public String bindPermission;
        public String settingsAction;
        public int clientLabel;
    }
}
