Android 11.0源码系列之PMSinstalld
Posted bubbleben
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 11.0源码系列之PMSinstalld相关的知识,希望对你有一定的参考价值。
本篇涉及到的主要代码:
frameworks\\base\\services\\core\\java\\com\\android\\server\\SystemServer.java
frameworks\\base\\services\\core\\java\\com\\android\\server\\SystemServiceManager.java
frameworks\\base\\services\\core\\java\\com\\android\\server\\pm\\Installer.java
frameworks\\base\\services\\core\\java\\com\\android\\server\\pm\\PackageManagerService.java
frameworks\\native\\cmds\\installd\\
众所周知Android系统框架提供了众多的系统服务,比如管理四大组件的AMS(ActivityManagerService),管理窗口的WMS(WindowManagerService),管理应用安装, 卸载和更新的PMS(PackageManagerService),管理输入事件和输入设备的IMS(InputManagerService)等等,本系列将基于Android 11.0.0_r1代码,从上到下(java->jni->native)对这几大服务进行逐一解读,旨在加深对Android体系结构的理解,了解框架层各组件的运行原理,为以后深入性能分析/系统优化/架构设计等打下坚实的基础。
上一系列我们介绍了InputManagerService
,这一系列我们将开启对PackageManagerService
的解读。
1.1 PackageManagerService的创建
同其他系统服务一样,PackageManagerService
也是在开机时由SystemServer
创建并以"package"为名添加到ServiceManager
中
[-> SystemServer.java]
private PackageManagerService mPackageManagerService;
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
// 创建并初始化Installer[见1.2小节]
Installer installer = mSystemServiceManager.startService(Installer.class);
try {
// 创建PackageManagerService[见1.7小节]
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
} finally {
Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
}
}
private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
if (!mOnlyCore) {
try {
Watchdog.getInstance().pauseWatchingCurrentThread("dexopt");
// 第一次启动时不会执行,我们暂时不用关注
mPackageManagerService.updatePackagesIfNeeded();
} catch (Throwable e) {
reportWtf("update packages", e);
} finally {
Watchdog.getInstance().resumeWatchingCurrentThread("dexopt");
}
}
try {
// 每3天执行一次fstrim
mPackageManagerService.performFstrimIfNeeded();
} catch (Throwable e) {
reportWtf("performing fstrim", e);
}
// PackageManagerService已准备就绪
mPackageManagerService.systemReady();
}
PackageManagerService
需要用到Installer
,所以要先通过SystemServiceManager.startService
来创建和初始化Installer
;
1.2 Installer的初始化
[-> SystemServiceManager.java]
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final T service;
try {
// 通过反射实例化Installer对象[见1.2.1小节]
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
}
// Installer继承于SystemService
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
public void startService(@NonNull final SystemService service) {
// Register it.
// 保存系统所有的SystemService
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
// 执行Installer.onStart方法[见1.2.2小节]
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
}
Installer
继承于抽象类SystemService
,但它并不是一个真正的Service
,主要用来响应system_server
中的各个生命周期事件,所有的SystemService
都会保存到SystemServiceManager
中,system_server
在运行过程中会通过它来切换各个SystemService
的生命周期;
1.2.1 Installer的构造函数
[-> Installer.java]
public Installer(Context context) {
this(context, false);
}
/**
* @param isolated indicates if this object should <em>not</em> connect to
* the real {@code installd}. All remote calls will be ignored
* unless you extend this class and intercept them.
*/
public Installer(Context context, boolean isolated) {
super(context);
// isolate:是否不应该与installd进程连接,默认为false表示需要与installd进行连接
mIsolated = isolated;
}
1.2.2 Installer.onStart
[-> Installer.java]
public void onStart() {
if (mIsolated) {
mInstalld = null;
} else {
// mIsolated为false,所以调用connect进行连接[见1.2.3小节]
connect();
}
}
1.2.3 Installer.connect
[-> Installer.java]
private void connect() {
// 获取installd的binder接口
IBinder binder = ServiceManager.getService("installd");
if (binder != null) {
try {
// 注册binder的死亡回调
binder.linkToDeath(new DeathRecipient() {
@Override
public void binderDied() {
Slog.w(TAG, "installd died; reconnecting");
// 重新与installd进行连接
connect();
}
}, 0);
} catch (RemoteException e) {
binder = null;
}
}
if (binder != null) {
// 获取installd的binder对象
mInstalld = IInstalld.Stub.asInterface(binder);
try {
invalidateMounts();
} catch (InstallerException ignored) {
}
} else {
// 如果installd还没有ready,则不停的等待1s直到binder不为空
BackgroundThread.getHandler().postDelayed(() -> {
connect();
}, DateUtils.SECOND_IN_MILLIS);
}
}
public void invalidateMounts() throws InstallerException {
try {
// 跨进程调用installd的invalidateMounts:主要是通过installd读取/proc/mounts节点内容
mInstalld.invalidateMounts();
} catch (Exception e) {
throw InstallerException.from(e);
}
}
Installer
初始化主要完成了系统服务installd
的获取,以及对installd
的invalidateMounts
方法调用,从Installer
的代码中我们可以看出,它仅仅是完成了对installd
的封装,其实所有的功能最终都是通过installd
实现的,那这里的installd
是指谁呢,为什么它可以像其他系统服务一样通过AIDL的Stub.asInterface获取呢?
1.3 installd
[-> installd.rc]
// installd的定义[见1.3.1小节]
service installd /system/bin/installd
class main
on early-boot
mkdir /config/sdcardfs/extensions/1055
mkdir /config/sdcardfs/extensions/1056
mkdir /config/sdcardfs/extensions/1057
mkdir /config/sdcardfs/extensions/1056/3gpp
mkdir /config/sdcardfs/extensions/1056/3gp
mkdir /config/sdcardfs/extensions/1056/3gpp2
mkdir /config/sdcardfs/extensions/1056/3g2
......
我们知道Android中第一个被启动的进程是init
,它通过解析init.rc
脚本来构建出系统的初始运行形态,其他Android系统服务大多是在rc脚本中描述并被相继启动的:installd
也不例外,它会被init.rc
解析并创建一个名为installd
的可执行文件,其存储路径位于/system/bin/installd
,它的class名为main,同一个class的所有service必须同时启动或者停止,除了installd
以外,/system/bin/inputflinger
和/system/bin/mediaserver
等其他服务的class名都是main;随后会在early-boot阶段创建若干个目录;
1.3.1 installd
[-> Android.bp]
//
// Executable
//
cc_binary {
name: "installd",
defaults: ["installd_defaults"],
// 源文件入口为installd.cpp[见1.3.2小节]
srcs: ["installd.cpp"],
static_libs: ["libdiskusage"],
// rc脚本
init_rc: ["installd.rc"],
}
installd
的入口函数在installd.cpp
;
1.3.2 installd.cpp
[-> installd.cpp]
// 函数入口
int main(const int argc, char *argv[]) {
return android::installd::installd_main(argc, argv);
}
static int installd_main(const int argc ATTRIBUTE_UNUSED, char *argv[]) {
int ret;
// 判断selinux是否使能
int selinux_enabled = (is_selinux_enabled() > 0);
union selinux_callback cb;
cb.func_log = log_callback;
// 设置selinux的日志回调
selinux_set_callback(SELINUX_CB_LOG, cb);
// 初始化全局变量[见1.4小节]
if (!initialize_globals()) {
SLOGE("Could not initialize globals; exiting.\\n");
exit(1);
}
// 初始化所有目录[见1.5小节]
if (initialize_directories() < 0) {
SLOGE("Could not create directories; exiting.\\n");
exit(1);
}
// 如果selinux已使能,则打开selinux的状态
if (selinux_enabled && selinux_status_open(true) < 0) {
SLOGE("Could not open selinux status; exiting.\\n");
exit(1);
}
// 启动服务InstalldNativeService[见1.6小节]
if ((ret = InstalldNativeService::start()) != android::OK) {
SLOGE("Unable to start InstalldNativeService: %d", ret);
exit(1);
}
// 将installd自身加入线程池
IPCThreadState::self()->joinThreadPool();
LOG(INFO) << "installd shutting down";
return 0;
}
installd
的入口函数指向了installd_main
,它主要完成一些初始化工作,最终要的是启动了一个服务InstalldNativeService
,这看起来与我们在1.2.3的疑问开始关联起来,我们接着往下看;
1.4 initialize_globals
[-> installd.cpp]
static bool initialize_globals() {
return init_globals_from_data_and_root();
}
[-> global.cpp]
bool init_globals_from_data_and_root() {
// 获取"ANDROID_DATA"的环境变量,data目录默认为/data
const char* data_path = getenv("ANDROID_DATA");
if (data_path == nullptr) {
LOG(ERROR) << "Could not find ANDROID_DATA";
return false;
}
// 获取"ANDROID_ROOT"的环境变量,根目录默认为/system
const char* root_path = getenv("ANDROID_ROOT");
if (root_path == nullptr) {
LOG(ERROR) << "Could not find ANDROID_ROOT";
return false;
}
return init_globals_from_data_and_root(data_path, root_path);
}
// 如果字符串path最后以'/'为结尾,则直接返回path,否则在字符串末尾添加'/'
static std::string ensure_trailing_slash(const std::string& path) {
if (path.rfind('/') != path.size() - 1) {
return path + '/';
} else {
return path;
}
}
bool init_globals_from_data_and_root(const char* data, const char* root) {
// Get the android data directory.
// 确保path最后以'/'结尾
android_data_dir = ensure_trailing_slash(data);
// Get the android root directory.
// 确保path最后以'/'结尾
android_root_dir = ensure_trailing_slash(root);
// Get the android app directory.
// android_app_dir:/data/app/
android_app_dir = android_data_dir + APP_SUBDIR;
// Get the android protected app directory.
// android_app_private_dir:/data/app-private/
android_app_private_dir = android_data_dir + PRIVATE_APP_SUBDIR;
// Get the android ephemeral app directory.
// android_app_ephemeral_dir:/data/app-ephemeral/
android_app_ephemeral_dir = android_data_dir + EPHEMERAL_APP_SUBDIR;
// Get the android app native library directory.
// android_app_lib_dir:/data/app-lib/
android_app_lib_dir = android_data_dir + APP_LIB_SUBDIR;
// Get the sd-card ASEC mount point.
android_asec_dir = ensure_trailing_slash(getenv(ASEC_MOUNTPOINT_ENV_NAME));
// Get the android media directory.
// android_media_dir:/data/media/
android_media_dir = android_data_dir + MEDIA_SUBDIR;
// Get the android external app directory.
android_mnt_expand_dir = "/mnt/expand/";
// Get the android profiles directory.
// android_profiles_dir:/data/misc/profiles/
android_profiles_dir = android_data_dir + PROFILES_SUBDIR;
// Get the android session staging directory.
// android_staging_dir:/data/app-staging/
android_staging_dir = android_data_dir + STAGING_SUBDIR;
// Take note of the system and vendor directories.
// 清空系统目录
android_system_dirs.clear();
// 添加/system/app
android_system_dirs.push_back(android_root_dir + APP_SUBDIR);
// 添加/system/priv-app
android_system_dirs.push_back(android_root_dir + PRIV_APP_SUBDIR);
// 添加/system/vendor/app
android_system_dirs.push_back("/vendor/app/");
// 添加/system/oem/app
android_system_dirs.push_back("/oem/app/");
return true;
}
这里主要初始化并保存了data和system分区的一些目录,它们分别存放不同的内容,比如存放用户安装应用的/data/app/
,存放系统应用的/system/app/
,存放系统特权应用的/system/priv-app
,存放第三方厂商预置应用的/system/vendor/app
或者/system/oem/app
,存放多媒体数据的/data/media/
等;
1.5 initialize_directories
[-> installd.cpp]
static int initialize_directories() {
int res = -1;
// Read current filesystem layout version to handle upgrade paths
char version_path[PATH_MAX];
// 读取记录文件系统版本号的路径:/data/misc/installd/layout_version
snprintf(version_path, PATH_MAX, "%smisc/installd/layout_version", android_data_dir.c_str());
int oldVersion;
// 读取历史版本号
if (fs_read_atomic_int(version_path, &oldVersion) == -1) {
oldVersion = 0;
}
int version = oldVersion;
if (version < 2) {
SLOGD("Assuming that device has multi-user storage layout; upgrade no longer supported");
version = 2;
}
// 配置主用户路径[见1.5.1]
if (ensure_config_user_dirs(0) == -1) {
SLOGE("Failed to setup misc for user 0");
goto fail;
}
if (version == 2) {
SLOGD("Upgrading to /data/misc/user directories");
char misc_dir[PATH_MAX];
// misc_dir:/data/misc/
snprintf(misc_dir, PATH_MAX, "%smisc", android_data_dir.c_str());
DIR *dir;
struct dirent *dirent;
// 打开/data/user目录
dir = opendir("/data/user");
if (dir != nullptr) {
// 如果/data/user/目录不为空,则循环读取其下的每一个文件夹
while ((dirent = readdir(dir))) {
const char *name = dirent->d_name;
// skip "." and ".."
// 过滤非法目录名
if (name[0] == '.') {
if (name[1] == 0) continue;
if ((name[1] == '.') && (name[2] == 0)) continue;
}
// 将char转换为int
uint32_t user_id = std::stoi(name);
// /data/misc/user/<user_id>
// 同1.5.1小节:创建user_id对应的目录/data/misc/user/user_id
if (ensure_config_user_dirs(user_id) == -1) {
goto fail;
}
}
closedir(dir);
}
version = 3;
}
// Persist layout version if changed
if (version != oldVersion) {
// 更新版本号
if (fs_write_atomic_int(version_path, version) == -1) {
SLOGE("Failed to save version to %s: %s", version_path, strerror(errno));
goto fail;
}
}
// Success!
res = 0;
fail:
return res;
}
1.5.1 ensure_config_user_dirs
[-> utils.cpp]
int ensure_config_user_dirs(userid_t userid) {
// writable by system, readable by any app within the same user
// 获取主用户的uid和gid
const int uid = multiuser_get_uid(userid, AID_SYSTEM);
const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
// Ensure /data/misc/user/<userid> exists
// 创建用户id对应的目录:/data/misc/user/0[见1.5.2小节]
auto path = create_data_misc_legacy_path(userid);
return fs_prepare_dir(path.c_str(), 0750, uid, gid);
}
1.5.2 create_data_misc_legacy_path
[-> utils.cpp]
std::string create_data_misc_legacy_path(userid_t userid) {
// 打印通过create_data_path创建的目录:/data/misc/user/0
return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
}
std::string create_data_path(const char* volume_uuid) {
// 传入的volume_uuid为空,所以直接返回/data
if (volume_uuid == nullptr) {
return "/data";
} else if (!strcmp(volume_uuid, "TEST")) {
CHECK(property_get_bool("ro.debuggable", false));
return "/data/local/tmp";
} else {
CHECK(is_valid_filename(volume_uuid));
return StringPrintf("/mnt/expand/%s", volume_uuid);
}
}
initialize_directories
首先会创建系统主用户/data/misc/user/0/
文件夹,除主用户外(/data/user/0/
)其他每个用户都会在/data/user/目录下面创建一个属于自己的文件夹(比如第一个子用户/data/user/10/
,以此类推)来存放当前用户的用户数据,这里会据此来创建其他用户的/data/misc/user/user_id
目录;
1.6 InstalldNativeService
[-> InstalldNativeService.h]
// InstalldNativeService继承于BinderService和BnInstalld(binder服务端)
class InstalldNativeService : public BinderService<InstalldNativeService>, public os::BnInstalld {
public:
static status_t start();
// InstalldNativeService服务名为installd
static char const* getServiceName() { return "installd"; }
}
[-> InstalldNativeService.cpp]
status_t InstalldNativeService::start() {
IPCThreadState::self()->disableBackgroundScheduling(true);
// InstalldNativeService继承于BinderService,所以会直接调用BinderService的publish方法[见1.6.1小节]
status_t ret = BinderService<InstalldNativeService>::publish();
if (ret != android::OK) {
return ret;
}
// 获取installd进程
sp<ProcessState> ps(ProcessState::self());
// 启动installd的线程池
ps->startThreadPool();
ps->giveThreadPoolName();
sAppDataIsolationEnabled = android::base::GetBoolProperty(
kAppDataIsolationEnabledProperty, true);
return android::OK;
}
1.6.1 BinderService.publish
[-> BinderService.h]
static status_t publish(bool allowIsolated = false,
int dumpFlags = IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT) {
// 获取binder大管家service_manager
sp<IServiceManager> sm(defaultServiceManager());
// InstalldNativeService作为binder服务端被service_manager以"installd"为名添加到系统
return sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated,
dumpFlags);
}
到这里1.2.3的疑问就可以解答:installd
会启动InstalldNativeService
作为binder的服务端,其他进程就可以通过ServiceManager
获取到名为installd
的服务,以此来实现跨进程调用;
1.7 PackageManagerService.main
[-> PackageManagerService.java]
public static PackageManagerService main(Context context, Installer installer,
boolean factoryTest, boolean onlyCore) {
// Self-check for initial settings.
// 创建对象锁lock
final Object lock = new Object();
// 创建对象锁installLock
final Object installLock = new Object();
// 创建Injector并将其作为参数传递给PackageManagerService的构造函数[见1.7.1小节]
Injector injector = new Injector(
context, lock, installer, installLock, new PackageAbiHelperImpl(),
(i, pm) ->
new ComponentResolver(i.getUserManagerService(), pm.mPmInternal, lock),
(i, pm) ->
PermissionManagerService.create(context, lock),
(i, pm) ->
new UserManagerService(context, pm,
new UserDataPreparer(installer, installLock, context, onlyCore),
lock),
(i, pm) ->
new Settings(Environment.getDataDirectory(),
i.getPermissionManagerServiceInternal().getPermissionSettings(),
lock),
new Injector.LocalServicesProducer<>(ActivityTaskManagerInternal.class),
new Injector.LocalServicesProducer<>(ActivityManagerInternal.class),
new Injector.LocalServicesProducer<>(DeviceIdleInternal.class),
new Injector.LocalServicesProducer<>(StorageManagerInternal.class),
new Injector.LocalServicesProducer<>(NetworkPolicyManagerInternal.class),
new Injector.LocalServicesProducer<>(PermissionPolicyInternal.class),
new Injector.LocalServicesProducer<>(DeviceStorageMonitorInternal.class),
new Injector.SystemServiceProducer<>(DisplayManager.class),
new Injector.SystemServiceProducer<>(StorageManager.class),
new Injector.SystemServiceProducer<>(AppOpsManager.class),
(i, pm) -> AppsFilter.create(pm.mPmInternal, i),
(i, pm) -> (PlatformCompat) ServiceManager.getService("platform_compat"));
// 创建PackageManagerService
PackageManagerService m = new PackageManagerService(injector, onlyCore, factoryTest);
// 安装白名单系统应用
m.installWhitelistedSystemPackages();
// 将PackageManagerService添加到ServiceManager
ServiceManager.addService("package", m);
final PackageManagerNative pmn = m.new PackageManagerNative();
ServiceManager.addService("package_native", pmn);
return m;
}
1.7.1 Injector
[-> Injector.java]
public static class Injector {
// Producer主要通过produce方法用来生成对应模板的实例
interface Producer<T> {
/** Produce an instance of type {@link T} */
T produce(Injector injector, PackageManagerService packageManager);
}
// 通过LocalServices获取要produce的各系统服务的LocalService
// 比如ActivityTaskManagerServie对应的ActivityTaskManagerServie.LocalService
static class LocalServicesProducer<T> implements Producer<T> {
private final Class<T> mProducingClass;
LocalServicesProducer(Class<T> clazz) {
this.mProducingClass = clazz;
}
public T produce(Injector injector, PackageManagerService packageManager) {
return LocalServices.getService(mProducingClass);
}
}
// 创建单例对象:只有要实例化的对象不存在时才会执行其Producer的produce方法
static class Singleton<T> {
private final Producer<T> mProducer;
private volatile T mInstance = null;
Singleton(Producer<T> producer) {
this.mProducer = producer;
}
T get(Injector injector, PackageManagerService packageManagerService) {
if (mInstance == null) {
mInstance = mProducer.produce(injector, packageManagerService);
}
return mInstance;
}
}
// Injector作为PackageManagerService的内部类,主要通过Producer来初始化各种单例对象
// 具体作用我们会在后面的业务逻辑中进行分析
Injector(Context context, Object lock, Installer installer,
Object installLock, PackageAbiHelper abiHelper,
Producer<ComponentResolver> componentResolverProducer,
Producer<PermissionManagerServiceInternal> permissionManagerProducer,
Producer<UserManagerService> userManagerProducer,
Producer<Settings> settingsProducer,
Producer<ActivityTaskManagerInternal> activityTaskManagerProducer,
Producer<ActivityManagerInternal> activityManagerInternalProducer,
Producer<DeviceIdleInternal> deviceIdleControllerProducer,
Producer<StorageManagerInternal> storageManagerInternalProducer,
Producer<NetworkPolicyManagerInternal> networkPolicyManagerProducer,
Producer<PermissionPolicyInternal> permissionPolicyProvider,
Producer<DeviceStorageMonitorInternal> deviceStorageMonitorProducer,
Producer<DisplayManager> displayManagerProducer,
Producer<StorageManager> storageManagerProducer,
Producer<AppOpsManager> appOpsManagerProducer,
Producer<AppsFilter> appsFilterProducer,
Producer<PlatformCompat> platformCompatProducer) {
mContext = context;
mLock = lock;
mInstaller = installer;
mAbiHelper = abiHelper;
mInstallLock = installLock;
// 单例-start
mComponentResolverProducer = new Singleton<>(componentResolverProducer);
mPermissionManagerProducer = new Singleton<>(permissionManagerProducer);
mUserManagerProducer = new Singleton<>(userManagerProducer);
mSettingsProducer = new Singleton<>(settingsProducer);
mActivityTaskManagerProducer = new Singleton<>(activityTaskManagerProducer);
mActivityManagerInternalProducer = new Singleton<>(activityManagerInternalProducer);
mLocalDeviceIdleController = new Singleton<>(deviceIdleControllerProducer);
mStorageManagerInternalProducer = new Singleton<>(storageManagerInternalProducer);
mNetworkPolicyManagerProducer = new Singleton<>(networkPolicyManagerProducer);
mPermissionPolicyProducer = new Singleton<>(permissionPolicyProvider);
mDeviceStorageMonitorProducer = new Singleton<>(deviceStorageMonitorProducer);
mDisplayManagerProducer = new Singleton<>(displayManagerProducer);
mStorageManagerProducer = new Singleton<>(storageManagerProducer);
mAppOpsManagerProducer = new Singleton<>(appOpsManagerProducer);
mAppsFilterProducer = new Singleton<>(appsFilterProducer);
mPlatformCompatProducer = new Singleton<>(platformCompatProducer);
// 单例-end
}
}
总结
本篇主要介绍PackageManagerService
创建过程中用到的一些相关类:其中包括Installer
的初始化,installd
进程的创建以及二者之间的交互,最后生成了PackageManagerService
的内部类Injector
,PackageManagerService
的构造以及构造完成(sytemReady
)后的工作内容我们将留在下一篇详细分析。
以上是关于Android 11.0源码系列之PMSinstalld的主要内容,如果未能解决你的问题,请参考以下文章
Android 11.0源码系列之IMSInputManagerService
Android 11.0源码系列之IMSInputManager
Android 11.0源码系列之IMSInputDispatcher