PackageManagerService分析(Android 10)->Pms的兩把鎖

/** * Keep track of all those APKs everywhere. * <p> * Internally there are two important locks: * <ul> * <li>{@link #mPackages} is used to guard all in-memory parsed package details * and other related state. It is a fine-grained lock that should only be held * momentarily, as it's one of the most contended locks in the system. * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose * operations typically involve heavy lifting of application data on disk. Since * {@code installd} is single-threaded, and it's operations can often be slow, * this lock should never be acquired while already holding {@link #mPackages}. * Conversely, it's safe to acquire {@link #mPackages} momentarily while already * holding {@link #mInstallLock}. * </ul> * Many internal methods rely on the caller to hold the appropriate locks, and * this contract is expressed through method name suffixes: * <ul> * <li>fooLI(): the caller must hold {@link #mInstallLock} * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package * being modified must be frozen * <li>fooLPr(): the caller must hold {@link #mPackages} for reading * <li>fooLPw(): the caller must hold {@link #mPackages} for writing * </ul> * <p> * Because this class is very central to the platform's security; please run all * CTS and unit tests whenever making modifications: * * <pre> * $ runtest -c android.content.pm.PackageManagerTests frameworks-core * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases * </pre> */

註釋裏面說的比較清楚Pms有兩把鎖,一把叫mPackages,是fine-grained lock(細粒度的鎖)。 另外一把是mInstallLock,它是一把重量級的鎖。 另外還有四個方法實例表示該方法持有什麼樣的鎖,分別是:java

  • fooLI() LI結尾表示調用者必須持有mInstallLock這把鎖
  • fooLIF() LIF結尾調用者必須持有mInstallLock 這把鎖,而且必須凍結(凍結表示禁止啓動)要修改的軟件包。
  • fooLPr() LPr結尾表示必須持有mPackages才能夠調用,而且該方法只讀mPackages鎖保護的數據。
  • fooLPw() LPw結尾表示必須持有mPackages才能夠調用,而且該方法會修改mPackages鎖保護的數據。

另外因爲mPackages爲細粒度的鎖, mInstallLock爲重量級鎖,因此不該該在持有 mPackages鎖的狀況下再去獲取mInstallLock,不然mPackages也會變成重量級。android

上述都不是重點, 重點是Pms到底如何使用這兩把鎖, 如今由我來給你們說明。express

PackageManagerService主要有兩項工做:
1 應用安裝卸載: mInstallLock 主要保證這個流程是串行執行。而這個過程會修改mPackages鎖保護的數據,mPackages保證安裝卸載過程當中查詢數據正確。
2 應用信息查詢:mPackages 也是保證查詢數據正確,這個過程不會修改mPackages保護的數據。

app

相關文章
相關標籤/搜索