【Android源码】PackageManagerService 浅析

当系统启动之后,就会注册各种系统服务,如WindowManagerService、ActivityManagerService等,其中就有PackageManagerService。PMS启动之后,就会扫描已安装的apk目录,并解析apk下的androidmanifest.xml文件得到app的信息,而在androidmanifest.xml中又包含了activity、service等组件的注册信息,当PMS解析完成之后,整个app的信息树就被构建出来了。

那么PMS是如何工作的呢,我们来一起分析一下。

PMS的创建

通常情况下,我们可以通过以下方式获取到PackageManager:

PackageManager packageManager = getPackageManager();

点进去可以发现PackageManager也是一个抽象类,而mBase就是Context:

@Override
public PackageManager getPackageManager() {
   return mBase.getPackageManager();
}

所以我们直接看Context的实现类ContextImpl:

@Override
public PackageManager getPackageManager() {
   if (mPackageManager != null) {
       return mPackageManager;
   }

   IPackageManager pm = ActivityThread.getPackageManager();
   if (pm != null) {
       // Doesn't matter if we make more than one instance.
       return (mPackageManager = new ApplicationPackageManager(this, pm));
   }

   return null;
}

跳转到ActivityThread:

public static IPackageManager getPackageManager() {
   if (sPackageManager != null) {
       //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
       return sPackageManager;
   }
   IBinder b = ServiceManager.getService("package");
   //Slog.v("PackageManager", "default service binder = " + b);
   sPackageManager = IPackageManager.Stub.asInterface(b);
   //Slog.v("PackageManager", "default service = " + sPackageManager);
   return sPackageManager;
}

可以发现同样和WMS一样都是通过ServiceManager.getService(“package”)来获得IBinder对象,并最终转化为PackageManager。

那么PMS是如何添加到ServiceManager中的呢?

这个时候我们需要去看SystemServer.java,这个类会创建系统的服务:

private PowerManagerService mPowerManagerService;
private ActivityManagerService mActivityManagerService;
private WebViewUpdateService mWebViewUpdateService;
private DisplayManagerService mDisplayManagerService;
private PackageManagerService mPackageManagerService;

mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
                
// PackageManagerService.java
public static PackageManagerService main(Context context, Installer installer,
       boolean factoryTest, boolean onlyCore) {
   // Self-check for initial settings.
   PackageManagerServiceCompilerMapping.checkProperties();

   PackageManagerService m = new PackageManagerService(context, installer,
           factoryTest, onlyCore);
   m.enableSystemUserPackages();
   // Disable any carrier apps. We do this very early in boot to prevent the apps from being
   // disabled after already being started.
   CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
           UserHandle.USER_SYSTEM);
   ServiceManager.addService("package", m);
   return m;
}

可以发现,在SystemServer中PMS最终通过PackageManagerService.main函数创建出来,并通过ServiceManager.addService(“package”, m)添加到ServiceManager中。

PMS的工作原理

PMS的主要工作就是解析已安装的apk目录,并解析AndroidManifest.xml文件,最终解析出整个apk的信息树。

首先我们先看PMS的构造函数:

public PackageManagerService(Context context, Installer installer,
       boolean factoryTest, boolean onlyCore) {
  // 获取/data目录
    File dataDir = Environment.getDataDirectory();
    // 获取/data/data目录,也就是第三方软件目录
    mAppInstallDir = new File(dataDir, "app");
    // 获取framework资源、系统app资源
    File frameworkDir = new File(Environment.getRootDirectory(), "framework");
    final File systemAppDir = new File(Environment.getRootDirectory(), "app");
    
    // 加载framework资源
    scanDirTracedLI(frameworkDir, mDefParseFlags
                    | PackageParser.PARSE_IS_SYSTEM
                    | PackageParser.PARSE_IS_SYSTEM_DIR
                    | PackageParser.PARSE_IS_PRIVILEGED,
                    scanFlags | SCAN_NO_DEX, 0);
    // 加载系统应用     
    scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
    // 加载第三方应用
    scanDirLI(mEphemeralInstallDir, mDefParseFlags
                        | PackageParser.PARSE_IS_EPHEMERAL,
                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
    
}

从上面的代码可以看到,PMS不仅要加载已经安装好的apk,还需要加载framework的相关西苑,当加载好了之后才开始扫描指定目录下的apk文件并解析。
接下来我们继续看scanDirLI:

private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
   final File[] files = dir.listFiles();
   for (File file : files) {
       final boolean isPackage = (isApkFile(file) || file.isDirectory())
               && !PackageInstallerService.isStageName(file.getName());
       if (!isPackage) {
           // 如果不是package文件,continue
           continue;
       }
       try {
            // 解析apk文件
           scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
                   scanFlags, currentTime, null);
       } catch (PackageManagerException e) {
           Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
       }
   }
}

private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
       int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
   Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
   try {
       return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
   } finally {
       Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   }
}

private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
       long currentTime, UserHandle user) throws PackageManagerException {
   // 创建包解析器
   PackageParser pp = new PackageParser();
   pp.setSeparateProcesses(mSeparateProcesses);
   pp.setOnlyCoreApps(mOnlyCore);
   pp.setDisplayMetrics(mMetrics);

   if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
       parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
   }

   Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
   final PackageParser.Package pkg;
   try {
        // 解析apk
       pkg = pp.parsePackage(scanFile, parseFlags);
   } catch (PackageParserException e) {
       throw PackageManagerException.from(e);
   } finally {
       Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   }

   return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
}

通过一系列的调用最终发现解析apk是通过PackageParser也就是包解析器,对apk文件进行parsePackage方法的解析:

public Package parsePackage(File packageFile, int flags) throws PackageParserException {
   if (packageFile.isDirectory()) {
       return parseClusterPackage(packageFile, flags);
   } else {
        // 解析单个apk
       return parseMonolithicPackage(packageFile, flags);
   }
}

@Deprecated
public Package parseMonolithicPackage(File apkFile, int flags) throws PackageParserException {
   final PackageLite lite = parseMonolithicPackageLite(apkFile, flags);
   if (mOnlyCoreApps) {
       if (!lite.coreApp) {
           throw new PackageParserException(INSTALL_PARSE_FAILED_MANIFEST_MALFORMED,
                   "Not a coreApp: " + apkFile);
       }
   }
    // 构建AssetManager
   final AssetManager assets = new AssetManager();
   try {
       final Package pkg = parseBaseApk(apkFile, assets, flags);
       pkg.setCodePath(apkFile.getAbsolutePath());
       pkg.setUse32bitAbi(lite.use32bitAbi);
       return pkg;
   } finally {
       IoUtils.closeQuietly(assets);
   }
}

private Package parseBaseApk(File apkFile, AssetManager assets, int flags)
       throws PackageParserException {
   final String apkPath = apkFile.getAbsolutePath();
    // 构建资源
   Resources res = null;
   XmlResourceParser parser = null;
   try {
       res = new Resources(assets, mMetrics, null);
       assets.setConfiguration(0, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
               Build.VERSION.RESOURCES_SDK_INT);
       // 获取AndroidManifest.xml解析器
       parser = assets.openXmlResourceParser(cookie, ANDROID_MANIFEST_FILENAME);

       final String[] outError = new String[1];
       // 解析
       final Package pkg = parseBaseApk(res, parser, flags, outError);

       pkg.setVolumeUuid(volumeUuid);
       pkg.setApplicationVolumeUuid(volumeUuid);
       pkg.setBaseCodePath(apkPath);
       pkg.setSignatures(null);

       return pkg;

   } catch (PackageParserException e) {
       throw e;
   } catch (Exception e) {
       throw new PackageParserException(INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION,
               "Failed to read manifest from " + apkPath, e);
   } finally {
       IoUtils.closeQuietly(parser);
   }
}

可以发现调用parser = assets.openXmlResourceParser(cookie, ANDROID_MANIFEST_FILENAME)获取AndroidManifest.xml解析器

private static final String ANDROID_MANIFEST_FILENAME = "AndroidManifest.xml";

从这我们可以得出一个结论如果一个apk包没有AndroidManifest.xml文件,那么我们在打开的时候就会报错,包括lib文件。

我们继续追踪,现在到了parseBaseApk方法:

private Package parseBaseApk(Resources res, XmlResourceParser parser, int flags,
       String[] outError) throws XmlPullParserException, IOException {
   final String splitName;
   final String pkgName;

    // 解析apk的包名
  Pair<String, String> packageSplit = parsePackageSplitNames(parser, parser);
  pkgName = packageSplit.first;
  splitName = packageSplit.second;

    // 构建package对象
   final Package pkg = new Package(pkgName);

   TypedArray sa = res.obtainAttributes(parser,
           com.android.internal.R.styleable.AndroidManifest);
    // 获取apk的versioncode、versionname等信息
   pkg.mVersionCode = pkg.applicationInfo.versionCode = sa.getInteger(
           com.android.internal.R.styleable.AndroidManifest_versionCode, 0);
   pkg.baseRevisionCode = sa.getInteger(
           com.android.internal.R.styleable.AndroidManifest_revisionCode, 0);
   pkg.mVersionName = sa.getNonConfigurationString(
           com.android.internal.R.styleable.AndroidManifest_versionName, 0);
   if (pkg.mVersionName != null) {
       pkg.mVersionName = pkg.mVersionName.intern();
   }
   pkg.coreApp = parser.getAttributeBooleanValue(null, "coreApp", false);
   sa.recycle();

   return parseBaseApkCommon(pkg, null, res, parser, flags, outError);
}

上面这个方法我们通过解析AndroidManifest.xml获取到了apk包的相关信息。
最终return调用的parseBaseApkCommon方法才是解析xml文件的函数。

private Package parseBaseApkCommon(Package pkg, Set<String> acceptedTags, Resources res,
       XmlResourceParser parser, int flags, String[] outError) throws XmlPullParserException,
       IOException {
   mParseInstrumentationArgs = null;
   mParseActivityArgs = null;
   mParseServiceArgs = null;
   mParseProviderArgs = null;
    parseBaseApplication(pkg, res, parser, flags, outError);
}

private boolean parseBaseApplication(Package owner, Resources res,
       XmlResourceParser parser, int flags, String[] outError)
   throws XmlPullParserException, IOException {
    if (tagName.equals("activity")) {
      Activity a = parseActivity(owner, res, parser, flags, outError, false,
              owner.baseHardwareAccelerated);
      if (a == null) {
          mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
          return false;
      }

      owner.activities.add(a);

  } else if (tagName.equals("receiver")) {
      Activity a = parseActivity(owner, res, parser, flags, outError, true, false);
      if (a == null) {
          mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
          return false;
      }

      owner.receivers.add(a);

  }    
}

由于代码太长,只截取了一点典型代码,通过上面我们终于发现了activity、receiver等标签,可以发现就是普通的xml解析,解析出来之后并返回一个Activity的实例,在加入到activities列表中。

public final ArrayList<Activity> activities = new ArrayList<Activity>(0);
public final ArrayList<Activity> receivers = new ArrayList<Activity>(0);
public final ArrayList<Provider> providers = new ArrayList<Provider>(0);
public final ArrayList<Service> services = new ArrayList<Service>(0);

最终通过解析所有的标签,把所有的节点信息都保存到对应的list中。
到这一步的时候,整个apk的信息树就已经被建立好了,整个apk的应用名、包名、图标、activity、service等信息都存储到了系统中。

    原文作者:指间沙似流年
    原文地址: https://www.jianshu.com/p/26e57aaa4cfb
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞