Prepare app data only when storage is available.

Before this change, scanning a package aggressively tried checking
to ensure that private app data was prepared.  However, in an FBE
world we may not have access to that data at scan time.  So this
change shifts the preparing of private app data until later: it
prepares DE storage when a user is started, and CE storage when a
user is unlocked.  Wire ourselves into the user lifecycle so we can
prepare storage at both user start and unlock.

When DE/CE storage becomes available, this change reconciles any
found packages against known installed apps, and deletes any orphaned
data directories.

We now need to store the last-restorecon hash in an xattr on a
per-user directory basis, since we can't restorecon CE storage until
it's unlocked, or adopted storage until it's mounted.  Remove a
bunch of used logic for loading dynamic SELinux policy at runtime;
our policy always comes from the system image.

Bug: 26466827, 26544104
Change-Id: I8d0a4ef862c35f4e4ef5c7f20d3bb8f12ba3fd4b
diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java
index ce6b369..5100faf 100644
--- a/services/core/java/com/android/server/pm/UserManagerService.java
+++ b/services/core/java/com/android/server/pm/UserManagerService.java
@@ -75,6 +75,7 @@
 import com.android.internal.util.XmlUtils;
 import com.android.internal.widget.LockPatternUtils;
 import com.android.server.LocalServices;
+import com.android.server.pm.Installer.StorageFlags;
 
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
@@ -2394,15 +2395,28 @@
     }
 
     /**
-     * Called right before a user starts.  This will not be called for the system user.
+     * Called right before a user is started. This gives us a chance to prepare
+     * app storage and apply any user restrictions.
      */
     public void onBeforeStartUser(int userId) {
-        synchronized (mRestrictionsLock) {
-            applyUserRestrictionsLR(userId);
+        mPm.reconcileAppsData(userId, Installer.FLAG_DE_STORAGE);
+
+        if (userId != UserHandle.USER_SYSTEM) {
+            synchronized (mRestrictionsLock) {
+                applyUserRestrictionsLR(userId);
+            }
         }
     }
 
     /**
+     * Called right before a user is unlocked. This gives us a chance to prepare
+     * app storage.
+     */
+    public void onBeforeUnlockUser(int userId) {
+        mPm.reconcileAppsData(userId, Installer.FLAG_CE_STORAGE);
+    }
+
+    /**
      * Make a note of the last started time of a user and do some cleanup.
      * @param userId the user that was just foregrounded
      */