searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

UserManagerService服务启动分析

2023-10-27 07:01:49
91
0
  • 注:本文所分析的代码基于 AOSP android-12.0.0_r3

Android UserManagerService是Android系统中的一个系统服务,负责管理用户信息和用户操作。它是在Android 4.2版本中引入的,用于支持多用户功能。

UserManagerService主要有以下几个功能:

  1. 用户管理:UserManagerService负责创建、删除和切换用户。每个用户都有自己的应用、数据和设置,可以独立地登录和使用设备。通过UserManagerService,可以管理多个用户的账户信息、权限和配置。

  2. 用户身份验证:UserManagerService提供了一套API来验证用户身份。它可以验证用户的密码、PIN码或图案锁,并提供了相应的接口来处理身份验证失败的情况。

  3. 用户权限管理:UserManagerService控制着每个用户对系统资源和应用程序的访问权限。它维护了一个权限列表,记录了每个应用程序在每个用户下所拥有的权限,并根据需要进行授权或撤销授权。

  4. 用户配置管理:UserManagerService负责保存和恢复每个用户的配置信息。这些配置包括语言设置、屏幕亮度、音量等。当切换到不同的用户时,系统会自动加载该用户的配置信息。

  5. 多用户数据隔离:UserManagerService确保不同用户之间的数据是隔离的,一个用户无法访问另一个用户的数据。这样可以保护每个用户的隐私和安全。

总之,Android UserManagerService是一个重要的系统服务,它为Android系统提供了多用户功能,并负责管理用户信息、权限和配置。它在多用户设备上提供了更好的用户体验和数据隔离。

1. UserManagerService启动流程

frameworks/base/services/java/com/android/server/SystemServer.java

 
    /**
     * Starts the small tangle of critical services that are needed to get the system off the
     * ground.  These services have complex mutual dependencies which is why we initialize them all
     * in one place here.  Unless your service is also entwined in these dependencies, it should be
     * initialized in one of the other functions.
     */
    private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
        t.traceBegin("startBootstrapServices");
        ...
        t.traceBegin("StartUserManagerService");
        mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
        t.traceEnd();
        .. 
 

UserManagerService在较早的Bootstrap阶段启动。

2. 多用户机制数据结构

  • UserController 在ActivityManagerService启动的时候实例化,并创建主用户的UserState,添加到UserStarted列表中,在finishingBoot阶段切换状态到RUNNING_UNLOCK;
  • UserInfo 代表一个用户实例;
  • UserData 服务内部使用的UserInfo,非序列化结构;
  • UserState 代表一个用户的状态,分别有BOOTING,RUNNING_LOCK,RUNNING_UNLOCKING,RUNNING_UNLOCKED,STOPPING,SHUTDOWN;
  • ProgressReporter 存放注册的UserProgressListener监听器,注册者可以实时知道用户的运行状态;

3. 创建用户数据目录

3.1 包管理服务createNewUser方法,传入应用黑名单。

frameworks/base/services/core/java/com/android/server/pm/PackageManagerService.java

 
    void createNewUser(int userId, @Nullable Set<String> userTypeInstallablePackages,
            String[] disallowedPackages) {
        synchronized (mInstallLock) {
            mSettings.createNewUserLI(this, mInstaller, userId,
                    userTypeInstallablePackages, disallowedPackages);
        }
        synchronized (mLock) {
            scheduleWritePackageRestrictionsLocked(userId);
            scheduleWritePackageListLocked(userId);
            mAppsFilter.onUsersChanged();
        }
    } 
 

3.2 创建应用数据目录

frameworks/base/services/core/java/com/android/server/pm/Settings.java

    void createNewUserLI(@NonNull PackageManagerService service, @NonNull Installer installer,
            @UserIdInt int userHandle, @Nullable Set<String> userTypeInstallablePackages,
            String[] disallowedPackages) {
        final TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing",
                Trace.TRACE_TAG_PACKAGE_MANAGER);
        t.traceBegin("createNewUser-" + userHandle);
        ..
        t.traceBegin("createAppData");
        try {
            batch.execute(installer);
        } catch (InstallerException e) {
            Slog.w(TAG, "Failed to prepare app data", e);
        }
        t.traceEnd(); // createAppData
        synchronized (mLock) {
            applyDefaultPreferredAppsLPw(userHandle);
        }
        t.traceEnd(); // createNewUser
    }

4. 主用户开机启动流程

ActivityManagerServie实例化UserController时,创建主用户并添加到mStartedUsers中。

frameworks/base/services/core/java/com/android/server/am/UserController.java

    UserController(Injector injector) {
        mInjector = injector;
        mHandler = mInjector.getHandler(this);
        mUiHandler = mInjector.getUiHandler(this);
        // User 0 is the first and only user that runs at boot.
        final UserState uss = new UserState(UserHandle.SYSTEM);
        uss.mUnlockProgress.addListener(new UserProgressListener());
        mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
        mUserLru.add(UserHandle.USER_SYSTEM);
        mLockPatternUtils = mInjector.getLockPatternUtils();
        updateStartedUserArrayLU();
    }

在开机完成后执行ActivityManagerService.finishBooting方法

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

 
final void finishBooting() {
        synchronized (this) {
            if (!mBootAnimationComplete) {
                mCallFinishBooting = true;
                return;
            }
            mCallFinishBooting = false;
        }
        ... 
        // Let system services know.
        mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED);
        ..
                    mUserController.sendBootCompleted(
                    new IIntentReceiver.Stub() {
                        @Override
                        public void performReceive(Intent intent, int resultCode,
                                String data, Bundle extras, boolean ordered,
                                boolean sticky, int sendingUser) {
                            synchronized (ActivityManagerService.this) {
                                requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
                            }
                        }
                    });
            mUserController.scheduleStartProfiles();
 

执行UserController.sendBootCompleted方法,将所有mStartedUsers中登记的User完成状态变更。

frameworks/base/services/core/java/com/android/server/am/UserController.java

 
    void sendBootCompleted(IIntentReceiver resultTo) {
        // Get a copy of mStartedUsers to use outside of lock
        SparseArray<UserState> startedUsers;
        synchronized (mLock) {
            startedUsers = mStartedUsers.clone();
        }
        for (int i = 0; i < startedUsers.size(); i++) {
            UserState uss = startedUsers.valueAt(i);
            if (!UserManager.isHeadlessSystemUserMode()) {
                finishUserBoot(uss, resultTo);
            } else if (uss.mHandle.isSystem()) {
                // In case of headless system user mode, send only locked boot complete broadcast
                // for system user since finishUserBoot call will be made using other code path;
                // for non-system user, do nothing since finishUserBoot will be called elsewhere.
                sendLockedBootCompletedBroadcast(resultTo, uss.mHandle.getIdentifier());
                return;
            }
        }
    } 
 

调用栈log如下:

5. ManagerProfile类型的用户开机自启流程

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

            mUserController.sendBootCompleted(
                    new IIntentReceiver.Stub() {
                        @Override
                        public void performReceive(Intent intent, int resultCode,
                                String data, Bundle extras, boolean ordered,
                                boolean sticky, int sendingUser) {
                            synchronized (mProcLock) {
                                mAppProfiler.requestPssAllProcsLPr(
                                        SystemClock.uptimeMillis(), true, false);
                            }
                        }
                    });
            maybeLogUserspaceRebootEvent();
            mUserController.scheduleStartProfiles();

在ActivityManagerService完成启动方法中启动主用户的ManagerProfile类型子用户,调用链如下:
ActivityManagerService.finishingbooting -> UserController.scheduleStartProfiles -> UserController.startprofiles获取主用户下所有profile -> UserController.startUser(forceground=false)

0条评论
0 / 1000
hi_long
15文章数
0粉丝数
hi_long
15 文章 | 0 粉丝
hi_long
15文章数
0粉丝数
hi_long
15 文章 | 0 粉丝
原创

UserManagerService服务启动分析

2023-10-27 07:01:49
91
0
  • 注:本文所分析的代码基于 AOSP android-12.0.0_r3

Android UserManagerService是Android系统中的一个系统服务,负责管理用户信息和用户操作。它是在Android 4.2版本中引入的,用于支持多用户功能。

UserManagerService主要有以下几个功能:

  1. 用户管理:UserManagerService负责创建、删除和切换用户。每个用户都有自己的应用、数据和设置,可以独立地登录和使用设备。通过UserManagerService,可以管理多个用户的账户信息、权限和配置。

  2. 用户身份验证:UserManagerService提供了一套API来验证用户身份。它可以验证用户的密码、PIN码或图案锁,并提供了相应的接口来处理身份验证失败的情况。

  3. 用户权限管理:UserManagerService控制着每个用户对系统资源和应用程序的访问权限。它维护了一个权限列表,记录了每个应用程序在每个用户下所拥有的权限,并根据需要进行授权或撤销授权。

  4. 用户配置管理:UserManagerService负责保存和恢复每个用户的配置信息。这些配置包括语言设置、屏幕亮度、音量等。当切换到不同的用户时,系统会自动加载该用户的配置信息。

  5. 多用户数据隔离:UserManagerService确保不同用户之间的数据是隔离的,一个用户无法访问另一个用户的数据。这样可以保护每个用户的隐私和安全。

总之,Android UserManagerService是一个重要的系统服务,它为Android系统提供了多用户功能,并负责管理用户信息、权限和配置。它在多用户设备上提供了更好的用户体验和数据隔离。

1. UserManagerService启动流程

frameworks/base/services/java/com/android/server/SystemServer.java

 
    /**
     * Starts the small tangle of critical services that are needed to get the system off the
     * ground.  These services have complex mutual dependencies which is why we initialize them all
     * in one place here.  Unless your service is also entwined in these dependencies, it should be
     * initialized in one of the other functions.
     */
    private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
        t.traceBegin("startBootstrapServices");
        ...
        t.traceBegin("StartUserManagerService");
        mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
        t.traceEnd();
        .. 
 

UserManagerService在较早的Bootstrap阶段启动。

2. 多用户机制数据结构

  • UserController 在ActivityManagerService启动的时候实例化,并创建主用户的UserState,添加到UserStarted列表中,在finishingBoot阶段切换状态到RUNNING_UNLOCK;
  • UserInfo 代表一个用户实例;
  • UserData 服务内部使用的UserInfo,非序列化结构;
  • UserState 代表一个用户的状态,分别有BOOTING,RUNNING_LOCK,RUNNING_UNLOCKING,RUNNING_UNLOCKED,STOPPING,SHUTDOWN;
  • ProgressReporter 存放注册的UserProgressListener监听器,注册者可以实时知道用户的运行状态;

3. 创建用户数据目录

3.1 包管理服务createNewUser方法,传入应用黑名单。

frameworks/base/services/core/java/com/android/server/pm/PackageManagerService.java

 
    void createNewUser(int userId, @Nullable Set<String> userTypeInstallablePackages,
            String[] disallowedPackages) {
        synchronized (mInstallLock) {
            mSettings.createNewUserLI(this, mInstaller, userId,
                    userTypeInstallablePackages, disallowedPackages);
        }
        synchronized (mLock) {
            scheduleWritePackageRestrictionsLocked(userId);
            scheduleWritePackageListLocked(userId);
            mAppsFilter.onUsersChanged();
        }
    } 
 

3.2 创建应用数据目录

frameworks/base/services/core/java/com/android/server/pm/Settings.java

    void createNewUserLI(@NonNull PackageManagerService service, @NonNull Installer installer,
            @UserIdInt int userHandle, @Nullable Set<String> userTypeInstallablePackages,
            String[] disallowedPackages) {
        final TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing",
                Trace.TRACE_TAG_PACKAGE_MANAGER);
        t.traceBegin("createNewUser-" + userHandle);
        ..
        t.traceBegin("createAppData");
        try {
            batch.execute(installer);
        } catch (InstallerException e) {
            Slog.w(TAG, "Failed to prepare app data", e);
        }
        t.traceEnd(); // createAppData
        synchronized (mLock) {
            applyDefaultPreferredAppsLPw(userHandle);
        }
        t.traceEnd(); // createNewUser
    }

4. 主用户开机启动流程

ActivityManagerServie实例化UserController时,创建主用户并添加到mStartedUsers中。

frameworks/base/services/core/java/com/android/server/am/UserController.java

    UserController(Injector injector) {
        mInjector = injector;
        mHandler = mInjector.getHandler(this);
        mUiHandler = mInjector.getUiHandler(this);
        // User 0 is the first and only user that runs at boot.
        final UserState uss = new UserState(UserHandle.SYSTEM);
        uss.mUnlockProgress.addListener(new UserProgressListener());
        mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
        mUserLru.add(UserHandle.USER_SYSTEM);
        mLockPatternUtils = mInjector.getLockPatternUtils();
        updateStartedUserArrayLU();
    }

在开机完成后执行ActivityManagerService.finishBooting方法

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

 
final void finishBooting() {
        synchronized (this) {
            if (!mBootAnimationComplete) {
                mCallFinishBooting = true;
                return;
            }
            mCallFinishBooting = false;
        }
        ... 
        // Let system services know.
        mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED);
        ..
                    mUserController.sendBootCompleted(
                    new IIntentReceiver.Stub() {
                        @Override
                        public void performReceive(Intent intent, int resultCode,
                                String data, Bundle extras, boolean ordered,
                                boolean sticky, int sendingUser) {
                            synchronized (ActivityManagerService.this) {
                                requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
                            }
                        }
                    });
            mUserController.scheduleStartProfiles();
 

执行UserController.sendBootCompleted方法,将所有mStartedUsers中登记的User完成状态变更。

frameworks/base/services/core/java/com/android/server/am/UserController.java

 
    void sendBootCompleted(IIntentReceiver resultTo) {
        // Get a copy of mStartedUsers to use outside of lock
        SparseArray<UserState> startedUsers;
        synchronized (mLock) {
            startedUsers = mStartedUsers.clone();
        }
        for (int i = 0; i < startedUsers.size(); i++) {
            UserState uss = startedUsers.valueAt(i);
            if (!UserManager.isHeadlessSystemUserMode()) {
                finishUserBoot(uss, resultTo);
            } else if (uss.mHandle.isSystem()) {
                // In case of headless system user mode, send only locked boot complete broadcast
                // for system user since finishUserBoot call will be made using other code path;
                // for non-system user, do nothing since finishUserBoot will be called elsewhere.
                sendLockedBootCompletedBroadcast(resultTo, uss.mHandle.getIdentifier());
                return;
            }
        }
    } 
 

调用栈log如下:

5. ManagerProfile类型的用户开机自启流程

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

            mUserController.sendBootCompleted(
                    new IIntentReceiver.Stub() {
                        @Override
                        public void performReceive(Intent intent, int resultCode,
                                String data, Bundle extras, boolean ordered,
                                boolean sticky, int sendingUser) {
                            synchronized (mProcLock) {
                                mAppProfiler.requestPssAllProcsLPr(
                                        SystemClock.uptimeMillis(), true, false);
                            }
                        }
                    });
            maybeLogUserspaceRebootEvent();
            mUserController.scheduleStartProfiles();

在ActivityManagerService完成启动方法中启动主用户的ManagerProfile类型子用户,调用链如下:
ActivityManagerService.finishingbooting -> UserController.scheduleStartProfiles -> UserController.startprofiles获取主用户下所有profile -> UserController.startUser(forceground=false)

文章来自个人专栏
Android
15 文章 | 1 订阅
0条评论
0 / 1000
请输入你的评论
0
0