Merge "Don't ensure config for activity that is about to be invisible" into oc-dev
diff --git a/Android.mk b/Android.mk
index 915f103..b8b85ba 100644
--- a/Android.mk
+++ b/Android.mk
@@ -273,7 +273,6 @@
 	core/java/android/security/IKeystoreService.aidl \
 	core/java/android/security/keymaster/IKeyAttestationApplicationIdProvider.aidl \
 	core/java/android/service/autofill/IAutoFillService.aidl \
-	core/java/android/service/autofill/IAutoFillServiceConnection.aidl \
 	core/java/android/service/autofill/IFillCallback.aidl \
 	core/java/android/service/autofill/ISaveCallback.aidl \
 	core/java/android/service/carrier/ICarrierService.aidl \
diff --git a/api/current.txt b/api/current.txt
index cbe4195..cfcdb7d 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -36986,7 +36986,6 @@
 
   public abstract class AutofillService extends android.app.Service {
     ctor public AutofillService();
-    method public final void disableSelf();
     method public final android.os.IBinder onBind(android.content.Intent);
     method public void onConnected();
     method public void onDisconnected();
@@ -47732,6 +47731,7 @@
   public final class AutofillManager {
     method public void cancel();
     method public void commit();
+    method public void disableOwnedAutofillServices();
     method public boolean isEnabled();
     method public void notifyValueChanged(android.view.View);
     method public void notifyValueChanged(android.view.View, int, android.view.autofill.AutofillValue);
@@ -48707,6 +48707,7 @@
     method public abstract int getMixedContentMode();
     method public abstract boolean getOffscreenPreRaster();
     method public abstract deprecated android.webkit.WebSettings.PluginState getPluginState();
+    method public abstract boolean getSafeBrowsingEnabled();
     method public abstract java.lang.String getSansSerifFontFamily();
     method public abstract deprecated boolean getSaveFormData();
     method public abstract deprecated boolean getSavePassword();
@@ -48756,6 +48757,7 @@
     method public abstract void setOffscreenPreRaster(boolean);
     method public abstract deprecated void setPluginState(android.webkit.WebSettings.PluginState);
     method public abstract deprecated void setRenderPriority(android.webkit.WebSettings.RenderPriority);
+    method public abstract void setSafeBrowsingEnabled(boolean);
     method public abstract void setSansSerifFontFamily(java.lang.String);
     method public abstract deprecated void setSaveFormData(boolean);
     method public abstract deprecated void setSavePassword(boolean);
diff --git a/api/system-current.txt b/api/system-current.txt
index 34f05da..df8d49a 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -40082,7 +40082,6 @@
 
   public abstract class AutofillService extends android.app.Service {
     ctor public AutofillService();
-    method public final void disableSelf();
     method public final android.os.IBinder onBind(android.content.Intent);
     method public void onConnected();
     method public void onDisconnected();
@@ -51284,6 +51283,7 @@
   public final class AutofillManager {
     method public void cancel();
     method public void commit();
+    method public void disableOwnedAutofillServices();
     method public boolean isEnabled();
     method public void notifyValueChanged(android.view.View);
     method public void notifyValueChanged(android.view.View, int, android.view.autofill.AutofillValue);
@@ -52341,6 +52341,7 @@
     method public abstract boolean getOffscreenPreRaster();
     method public abstract deprecated android.webkit.WebSettings.PluginState getPluginState();
     method public abstract deprecated boolean getPluginsEnabled();
+    method public abstract boolean getSafeBrowsingEnabled();
     method public abstract java.lang.String getSansSerifFontFamily();
     method public abstract deprecated boolean getSaveFormData();
     method public abstract deprecated boolean getSavePassword();
@@ -52396,6 +52397,7 @@
     method public abstract deprecated void setPluginState(android.webkit.WebSettings.PluginState);
     method public abstract deprecated void setPluginsEnabled(boolean);
     method public abstract deprecated void setRenderPriority(android.webkit.WebSettings.RenderPriority);
+    method public abstract void setSafeBrowsingEnabled(boolean);
     method public abstract void setSansSerifFontFamily(java.lang.String);
     method public abstract deprecated void setSaveFormData(boolean);
     method public abstract deprecated void setSavePassword(boolean);
diff --git a/api/test-current.txt b/api/test-current.txt
index ac49a9b..a8060d8 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -37144,7 +37144,6 @@
 
   public abstract class AutofillService extends android.app.Service {
     ctor public AutofillService();
-    method public final void disableSelf();
     method public final android.os.IBinder onBind(android.content.Intent);
     method public void onConnected();
     method public void onDisconnected();
@@ -48114,6 +48113,7 @@
   public final class AutofillManager {
     method public void cancel();
     method public void commit();
+    method public void disableOwnedAutofillServices();
     method public boolean isEnabled();
     method public void notifyValueChanged(android.view.View);
     method public void notifyValueChanged(android.view.View, int, android.view.autofill.AutofillValue);
@@ -49089,6 +49089,7 @@
     method public abstract int getMixedContentMode();
     method public abstract boolean getOffscreenPreRaster();
     method public abstract deprecated android.webkit.WebSettings.PluginState getPluginState();
+    method public abstract boolean getSafeBrowsingEnabled();
     method public abstract java.lang.String getSansSerifFontFamily();
     method public abstract deprecated boolean getSaveFormData();
     method public abstract deprecated boolean getSavePassword();
@@ -49138,6 +49139,7 @@
     method public abstract void setOffscreenPreRaster(boolean);
     method public abstract deprecated void setPluginState(android.webkit.WebSettings.PluginState);
     method public abstract deprecated void setRenderPriority(android.webkit.WebSettings.RenderPriority);
+    method public abstract void setSafeBrowsingEnabled(boolean);
     method public abstract void setSansSerifFontFamily(java.lang.String);
     method public abstract deprecated void setSaveFormData(boolean);
     method public abstract deprecated void setSavePassword(boolean);
diff --git a/cmds/svc/src/com/android/commands/svc/PowerCommand.java b/cmds/svc/src/com/android/commands/svc/PowerCommand.java
index 6ce29cb..920a52d 100644
--- a/cmds/svc/src/com/android/commands/svc/PowerCommand.java
+++ b/cmds/svc/src/com/android/commands/svc/PowerCommand.java
@@ -22,6 +22,7 @@
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.SystemClock;
+import android.os.SystemProperties;
 
 public class PowerCommand extends Svc.Command {
     public PowerCommand() {
@@ -87,7 +88,7 @@
                         // no confirm, wait till device is rebooted
                         pm.reboot(false, mode, true);
                     } catch (RemoteException e) {
-                        System.err.println("Failed to reboot.");
+                        maybeLogRemoteException("Failed to reboot.");
                     }
                     return;
                 } else if ("shutdown".equals(args[1])) {
@@ -95,7 +96,7 @@
                         // no confirm, wait till device is off
                         pm.shutdown(false, null, true);
                     } catch (RemoteException e) {
-                        System.err.println("Failed to shutdown.");
+                        maybeLogRemoteException("Failed to shutdown.");
                     }
                     return;
                 }
@@ -103,4 +104,14 @@
         }
         System.err.println(longHelp());
     }
+
+    // Check if remote exception is benign during shutdown. Pm can be killed
+    // before system server during shutdown, so remote exception can be ignored
+    // if it is already in shutdown flow.
+    private void maybeLogRemoteException(String msg) {
+        String powerProp = SystemProperties.get("sys.powerctl");
+        if (powerProp.isEmpty()) {
+            System.err.println(msg);
+        }
+    }
 }
diff --git a/core/java/android/accounts/AccountManager.java b/core/java/android/accounts/AccountManager.java
index 2a2fdbd..8052288 100644
--- a/core/java/android/accounts/AccountManager.java
+++ b/core/java/android/accounts/AccountManager.java
@@ -364,11 +364,19 @@
             "android.accounts.key_legacy_visible";
 
     /**
-     * Key to set visibility for applications targeting API level below
-     * {@link android.os.Build.VERSION_CODES#O} with
-     * {@link android.Manifest.permission#GET_ACCOUNTS} permission, or applications with any
-     * targeting API level with the same signature as authenticator. See
-     * {@link #getAccountVisibility}. If the value was not set by authenticator
+     * Key to set visibility for applications which satisfy one of the following conditions:
+     * <ul>
+     * <li>Target API level below {@link android.os.Build.VERSION_CODES#O} and have
+     * deprecated {@link android.Manifest.permission#GET_ACCOUNTS} permission.
+     * </li>
+     * <li> Have {@link android.Manifest.permission#GET_ACCOUNTS_PRIVILEGED} permission. </li>
+     * <li> Have the same signature as authenticator. </li>
+     * <li> Have {@link android.Manifest.permission#READ_CONTACTS} permission and
+     * account type may be associated with contacts data - (verified by
+     * {@link android.Manifest.permission#WRITE_CONTACTS} permission check for the authenticator).
+     * </li>
+     * </ul>
+     * See {@link #getAccountVisibility}. If the value was not set by authenticator
      * {@link #VISIBILITY_USER_MANAGED_VISIBLE} is used.
      */
     public static final String PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE =
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index 4219235..95549d6 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -18,6 +18,7 @@
 
 import android.metrics.LogMaker;
 import android.graphics.Rect;
+import android.view.ViewRootImpl.ActivityConfigCallback;
 import android.view.autofill.AutofillId;
 import android.view.autofill.AutofillManager;
 import android.view.autofill.AutofillPopupWindow;
@@ -6835,12 +6836,12 @@
             CharSequence title, Activity parent, String id,
             NonConfigurationInstances lastNonConfigurationInstances,
             Configuration config, String referrer, IVoiceInteractor voiceInteractor,
-            Window window) {
+            Window window, ActivityConfigCallback activityConfigCallback) {
         attachBaseContext(context);
 
         mFragments.attachHost(null /*parent*/);
 
-        mWindow = new PhoneWindow(this, window);
+        mWindow = new PhoneWindow(this, window, activityConfigCallback);
         mWindow.setWindowControllerCallback(this);
         mWindow.setCallback(this);
         mWindow.setOnWindowDismissedCallback(this);
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index 7299d6b..3167ba7 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -2748,7 +2748,7 @@
                 activity.attach(appContext, this, getInstrumentation(), r.token,
                         r.ident, app, r.intent, r.activityInfo, title, r.parent,
                         r.embeddedID, r.lastNonConfigurationInstances, config,
-                        r.referrer, r.voiceInteractor, window);
+                        r.referrer, r.voiceInteractor, window, r.configCallback);
 
                 if (customIntent != null) {
                     activity.mIntent = customIntent;
@@ -3727,9 +3727,17 @@
                         impl.notifyChildRebuilt();
                     }
                 }
-                if (a.mVisibleFromClient && !a.mWindowAdded) {
-                    a.mWindowAdded = true;
-                    wm.addView(decor, l);
+                if (a.mVisibleFromClient) {
+                    if (!a.mWindowAdded) {
+                        a.mWindowAdded = true;
+                        wm.addView(decor, l);
+                    } else {
+                        // The activity will get a callback for this {@link LayoutParams} change
+                        // earlier. However, at that time the decor will not be set (this is set
+                        // in this method), so no action will be taken. This call ensures the
+                        // callback occurs with the decor set.
+                        a.onWindowAttributesChanged(l);
+                    }
                 }
 
             // If the window has already been added, but during resume
@@ -3769,17 +3777,12 @@
                         wm.updateViewLayout(decor, l);
                     }
                 }
+
                 r.activity.mVisibleFromServer = true;
                 mNumVisibleActivities++;
                 if (r.activity.mVisibleFromClient) {
                     r.activity.makeVisible();
                 }
-                final ViewRootImpl viewRoot = r.activity.mDecor.getViewRootImpl();
-                if (viewRoot != null) {
-                    // TODO: Figure out the best place to set the callback.
-                    // This looks like a place where decor view is already initialized.
-                    viewRoot.setActivityConfigCallback(r.configCallback);
-                }
             }
 
             if (!r.onlyLocalRequest) {
@@ -5147,13 +5150,8 @@
             if (DEBUG_CONFIGURATION) Slog.w(TAG, "Not found target activity to report to: " + r);
             return;
         }
-        final boolean movedToDifferentDisplay = displayId != INVALID_DISPLAY;
-        if (movedToDifferentDisplay) {
-            if (r.activity.getDisplay().getDisplayId() == displayId) {
-                throw new IllegalArgumentException("Activity is already on the target display: "
-                        + displayId);
-            }
-        }
+        final boolean movedToDifferentDisplay = displayId != INVALID_DISPLAY
+                && displayId != r.activity.getDisplay().getDisplayId();
 
         // Perform updates.
         r.overrideConfig = data.overrideConfig;
diff --git a/core/java/android/app/Instrumentation.java b/core/java/android/app/Instrumentation.java
index f9a3ea7..d546f27 100644
--- a/core/java/android/app/Instrumentation.java
+++ b/core/java/android/app/Instrumentation.java
@@ -1146,10 +1146,11 @@
             IllegalAccessException {
         Activity activity = (Activity)clazz.newInstance();
         ActivityThread aThread = null;
-        activity.attach(context, aThread, this, token, 0, application, intent,
+        activity.attach(context, aThread, this, token, 0 /* ident */, application, intent,
                 info, title, parent, id,
                 (Activity.NonConfigurationInstances)lastNonConfigurationInstance,
-                new Configuration(), null, null, null);
+                new Configuration(), null /* referrer */, null /* voiceInteractor */,
+                null /* window */, null /* activityConfigCallback */);
         return activity;
     }
 
diff --git a/core/java/android/companion/CompanionDeviceManager.java b/core/java/android/companion/CompanionDeviceManager.java
index 7b38863..4d788e7 100644
--- a/core/java/android/companion/CompanionDeviceManager.java
+++ b/core/java/android/companion/CompanionDeviceManager.java
@@ -167,7 +167,7 @@
             return Collections.emptyList();
         }
         try {
-            return mService.getAssociations(mContext.getPackageName());
+            return mService.getAssociations(mContext.getPackageName(), mContext.getUserId());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
diff --git a/core/java/android/companion/ICompanionDeviceManager.aidl b/core/java/android/companion/ICompanionDeviceManager.aidl
index 495141d..7798406 100644
--- a/core/java/android/companion/ICompanionDeviceManager.aidl
+++ b/core/java/android/companion/ICompanionDeviceManager.aidl
@@ -29,7 +29,7 @@
         in IFindDeviceCallback callback,
         in String callingPackage);
 
-    List<String> getAssociations(String callingPackage);
+    List<String> getAssociations(String callingPackage, int userId);
     void disassociate(String deviceMacAddress, String callingPackage);
 
     //TODO add these
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index 5415eb5..b382cef 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -3216,13 +3216,6 @@
             "android.intent.action.MEDIA_RESOURCE_GRANTED";
 
     /**
-     * Broadcast Action: An overlay package has been installed. The data
-     * contains the name of the added overlay package.
-     * @hide
-     */
-    public static final String ACTION_OVERLAY_ADDED = "android.intent.action.OVERLAY_ADDED";
-
-    /**
      * Broadcast Action: An overlay package has changed. The data contains the
      * name of the overlay package which has changed. This is broadcast on all
      * changes to the OverlayInfo returned by {@link
@@ -3234,22 +3227,6 @@
     public static final String ACTION_OVERLAY_CHANGED = "android.intent.action.OVERLAY_CHANGED";
 
     /**
-     * Broadcast Action: An overlay package has been removed. The data contains
-     * the name of the overlay package which has been removed.
-     * @hide
-     */
-    public static final String ACTION_OVERLAY_REMOVED = "android.intent.action.OVERLAY_REMOVED";
-
-    /**
-     * Broadcast Action: The order of a package's list of overlay packages has
-     * changed. The data contains the package name of the overlay package that
-     * had its position in the list adjusted.
-     * @hide
-     */
-    public static final String
-            ACTION_OVERLAY_PRIORITY_CHANGED = "android.intent.action.OVERLAY_PRIORITY_CHANGED";
-
-    /**
      * Activity Action: Allow the user to select and return one or more existing
      * documents. When invoked, the system will display the various
      * {@link DocumentsProvider} instances installed on the device, letting the
diff --git a/core/java/android/service/autofill/AutofillService.java b/core/java/android/service/autofill/AutofillService.java
index c82b9eb..d86dd5b 100644
--- a/core/java/android/service/autofill/AutofillService.java
+++ b/core/java/android/service/autofill/AutofillService.java
@@ -94,9 +94,9 @@
 
     private final IAutoFillService mInterface = new IAutoFillService.Stub() {
         @Override
-        public void onInit(IAutoFillServiceConnection connection) {
-            if (connection != null) {
-                mHandlerCaller.obtainMessageO(MSG_CONNECT, connection).sendToTarget();
+        public void onConnectedStateChanged(boolean connected) {
+            if (connected) {
+                mHandlerCaller.obtainMessage(MSG_CONNECT).sendToTarget();
             } else {
                 mHandlerCaller.obtainMessage(MSG_DISCONNECT).sendToTarget();
             }
@@ -127,7 +127,6 @@
     private final HandlerCaller.Callback mHandlerCallback = (msg) -> {
         switch (msg.what) {
             case MSG_CONNECT: {
-                mConnection = (IAutoFillServiceConnection) msg.obj;
                 onConnected();
                 break;
             } case MSG_ON_FILL_REQUEST: {
@@ -152,7 +151,6 @@
                 break;
             } case MSG_DISCONNECT: {
                 onDisconnected();
-                mConnection = null;
                 break;
             } default: {
                 Log.w(TAG, "MyCallbacks received invalid message type: " + msg);
@@ -162,8 +160,6 @@
 
     private HandlerCaller mHandlerCaller;
 
-    private IAutoFillServiceConnection mConnection;
-
     /**
      * {@inheritDoc}
      *
@@ -246,21 +242,9 @@
     public void onDisconnected() {
     }
 
-    /**
-     * Disables the service. After calling this method, the service will
-     * be disabled and settings will show that it is turned off.
-     *
-     * <p>You should call this method only after a call to {@link #onConnected()}
-     * and before the corresponding call to {@link #onDisconnected()}. In other words
-     * you can disable your service only while the system is connected to it.</p>
-     */
+    /** @hide */
     public final void disableSelf() {
-        if (mConnection != null) {
-            try {
-                mConnection.disableSelf();
-            } catch (RemoteException re) {
-                throw re.rethrowFromSystemServer();
-            }
-        }
+        // TODO(b/33197203): Remove when GCore has migrated off this API
+        getSystemService(AutofillManager.class).disableOwnedAutofillServices();
     }
 }
diff --git a/core/java/android/service/autofill/IAutoFillService.aidl b/core/java/android/service/autofill/IAutoFillService.aidl
index 9f296c6..a8d86ca 100644
--- a/core/java/android/service/autofill/IAutoFillService.aidl
+++ b/core/java/android/service/autofill/IAutoFillService.aidl
@@ -18,7 +18,6 @@
 
 import android.app.assist.AssistStructure;
 import android.os.Bundle;
-import android.service.autofill.IAutoFillServiceConnection;
 import android.service.autofill.IFillCallback;
 import android.service.autofill.ISaveCallback;
 import com.android.internal.os.IResultReceiver;
@@ -29,7 +28,7 @@
  * @hide
  */
 oneway interface IAutoFillService {
-    void onInit(in IAutoFillServiceConnection connection);
+    void onConnectedStateChanged(boolean connected);
     void onFillRequest(in AssistStructure structure, in Bundle extras,
             in IFillCallback callback, int flags);
     void onSaveRequest(in AssistStructure structure, in Bundle extras,
diff --git a/core/java/android/service/autofill/IAutoFillServiceConnection.aidl b/core/java/android/service/autofill/IAutoFillServiceConnection.aidl
deleted file mode 100644
index cf73a10..0000000
--- a/core/java/android/service/autofill/IAutoFillServiceConnection.aidl
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.service.autofill;
-
-/**
- * Interface from an auto fill service to the system.
- *
- * @hide
- */
-interface IAutoFillServiceConnection {
-    void disableSelf();
-}
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index 31911cb..076b33c 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -683,8 +683,7 @@
                     mTranslator.translateRectInAppWindowToScreen(mScreenRect);
                 }
 
-                if (mSurfaceControl != null
-                        && (!isHardwareAccelerated() || !mRtHandlingPositionUpdates)) {
+                if (!isHardwareAccelerated() || !mRtHandlingPositionUpdates) {
                     try {
                         if (DEBUG) Log.d(TAG, String.format("%d updateSurfacePosition UI, " +
                                 "postion = [%d, %d, %d, %d]", System.identityHashCode(this),
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 4a7b16e..58ef0af 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -1249,13 +1249,6 @@
         mIsAmbientMode = ambient;
     }
 
-    void setWindowVisibility(int visibility) {
-        if (visibility != mAttachInfo.mWindowVisibility) {
-            mAttachInfo.mWindowVisibility = visibility;
-            mView.dispatchWindowVisibilityChanged(visibility);
-        }
-    }
-
     void setWindowStopped(boolean stopped) {
         if (mStopped != stopped) {
             mStopped = stopped;
@@ -1270,7 +1263,6 @@
                 if (renderer != null) {
                     renderer.destroyHardwareResources(mView);
                 }
-                mView.dispatchWindowVisibilityChanged(View.GONE);
             }
         }
     }
@@ -1305,8 +1297,7 @@
     }
 
     int getHostVisibility() {
-        return (mAppVisible || mForceDecorViewVisibility) && !mStopped
-            ? mView.getVisibility() : View.GONE;
+        return (mAppVisible || mForceDecorViewVisibility) ? mView.getVisibility() : View.GONE;
     }
 
     /**
@@ -1663,8 +1654,8 @@
         }
 
         if (viewVisibilityChanged) {
-            setWindowVisibility(viewVisibility);
-
+            mAttachInfo.mWindowVisibility = viewVisibility;
+            host.dispatchWindowVisibilityChanged(viewVisibility);
             if (viewUserVisibilityChanged) {
                 host.dispatchVisibilityAggregated(viewVisibility == View.VISIBLE);
             }
diff --git a/core/java/android/view/autofill/AutofillManager.java b/core/java/android/view/autofill/AutofillManager.java
index d429d37..ba004b96 100644
--- a/core/java/android/view/autofill/AutofillManager.java
+++ b/core/java/android/view/autofill/AutofillManager.java
@@ -537,6 +537,18 @@
         }
     }
 
+    /**
+     * If the app calling this API has enabled autofill services they
+     * will be disabled.
+     */
+    public void disableOwnedAutofillServices() {
+        try {
+            mService.disableOwnedAutofillServices(mContext.getUserId());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
     private AutofillClient getClientLocked() {
         if (mContext instanceof AutofillClient) {
             return (AutofillClient) mContext;
diff --git a/core/java/android/view/autofill/IAutoFillManager.aidl b/core/java/android/view/autofill/IAutoFillManager.aidl
index 20d09ae..68b3ccabc 100644
--- a/core/java/android/view/autofill/IAutoFillManager.aidl
+++ b/core/java/android/view/autofill/IAutoFillManager.aidl
@@ -35,10 +35,11 @@
             boolean hasCallback, int flags, String packageName);
     boolean restoreSession(int sessionId, in IBinder activityToken, in IBinder appCallback);
     void setWindow(int sessionId, in IBinder windowToken);
-    oneway void updateSession(int sessionId, in AutofillId id, in Rect bounds,
+    void updateSession(int sessionId, in AutofillId id, in Rect bounds,
             in AutofillValue value, int flags, int userId);
     void finishSession(int sessionId, int userId);
     void cancelSession(int sessionId, int userId);
     void setAuthenticationResult(in Bundle data, int sessionId, int userId);
-    oneway void setHasCallback(int sessionId, int userId, boolean hasIt);
+    void setHasCallback(int sessionId, int userId, boolean hasIt);
+    void disableOwnedAutofillServices(int userId);
 }
diff --git a/core/java/android/webkit/WebSettings.java b/core/java/android/webkit/WebSettings.java
index 61920bd..3a6de96 100644
--- a/core/java/android/webkit/WebSettings.java
+++ b/core/java/android/webkit/WebSettings.java
@@ -1385,6 +1385,36 @@
      */
     public abstract boolean getOffscreenPreRaster();
 
+
+    /**
+     * Sets whether Safe Browsing is enabled. Safe browsing allows WebView to
+     * protect against malware and phishing attacks by verifying the links.
+     *
+     * Safe browsing is disabled by default. The recommended way to enable
+     * Safe browsing is using a manifest tag to change the default value to
+     * enabled for all WebViews.
+     * <p>
+     * <pre>
+     * &lt;meta-data android:name="android.webkit.WebView.EnableSafeBrowsing"
+     *            android:value="true" /&gt;
+     * </pre>
+     * </p>
+     *
+     * This API overrides the manifest tag value for this WebView.
+     *
+     * @param enabled Whether Safe browsing is enabled.
+     */
+    public abstract void setSafeBrowsingEnabled(boolean enabled);
+
+    /**
+     * Gets whether Safe browsing is enabled.
+     * See {@link #setSafeBrowsingEnabled}.
+     *
+     * @return true if Safe browsing is enabled and false otherwise.
+     */
+    public abstract boolean getSafeBrowsingEnabled();
+
+
     /**
      * @hide
      */
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 916241c..fe38605 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -2071,15 +2071,16 @@
         @Override
         public boolean reset(boolean detachIfReset) {
             boolean active = false;
+            // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
+            active |= !mSubTimer.reset(false);
             active |= !super.reset(detachIfReset);
-            active |= !mSubTimer.reset(detachIfReset);
             return !active;
         }
 
         @Override
         public void detach() {
-            super.detach();
             mSubTimer.detach();
+            super.detach();
         }
 
         @Override
diff --git a/core/java/com/android/internal/policy/DecorView.java b/core/java/com/android/internal/policy/DecorView.java
index 9760f81..7282492 100644
--- a/core/java/com/android/internal/policy/DecorView.java
+++ b/core/java/com/android/internal/policy/DecorView.java
@@ -1499,6 +1499,7 @@
             // renderer about it.
             mBackdropFrameRenderer.onConfigurationChange();
         }
+        mWindow.onViewRootImplSet(getViewRootImpl());
     }
 
     @Override
diff --git a/core/java/com/android/internal/policy/PhoneWindow.java b/core/java/com/android/internal/policy/PhoneWindow.java
index 6c9280a..7b966de 100644
--- a/core/java/com/android/internal/policy/PhoneWindow.java
+++ b/core/java/com/android/internal/policy/PhoneWindow.java
@@ -47,6 +47,7 @@
 import android.view.ViewManager;
 import android.view.ViewParent;
 import android.view.ViewRootImpl;
+import android.view.ViewRootImpl.ActivityConfigCallback;
 import android.view.Window;
 import android.view.WindowManager;
 import com.android.internal.R;
@@ -287,6 +288,9 @@
 
     private boolean mUseDecorContext = false;
 
+    /** @see ViewRootImpl#mActivityConfigCallback */
+    private ActivityConfigCallback mActivityConfigCallback;
+
     static class WindowManagerHolder {
         static final IWindowManager sWindowManager = IWindowManager.Stub.asInterface(
                 ServiceManager.getService("window"));
@@ -302,7 +306,8 @@
     /**
      * Constructor for main window of an activity.
      */
-    public PhoneWindow(Context context, Window preservedWindow) {
+    public PhoneWindow(Context context, Window preservedWindow,
+            ActivityConfigCallback activityConfigCallback) {
         this(context);
         // Only main activity windows use decor context, all the other windows depend on whatever
         // context that was given to them.
@@ -323,6 +328,7 @@
                 DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
         mSupportsPictureInPicture = forceResizable || context.getPackageManager().hasSystemFeature(
                 PackageManager.FEATURE_PICTURE_IN_PICTURE);
+        mActivityConfigCallback = activityConfigCallback;
     }
 
     @Override
@@ -2060,6 +2066,11 @@
         return mDecor;
     }
 
+    /** Notify when decor view is attached to window and {@link ViewRootImpl} is available. */
+    void onViewRootImplSet(ViewRootImpl viewRoot) {
+        viewRoot.setActivityConfigCallback(mActivityConfigCallback);
+    }
+
     static private final String FOCUSED_ID_TAG = "android:focusedViewId";
     static private final String VIEWS_TAG = "android:views";
     static private final String PANELS_TAG = "android:Panels";
diff --git a/core/java/com/android/internal/util/Preconditions.java b/core/java/com/android/internal/util/Preconditions.java
index 1ead5b3..4e6857a 100644
--- a/core/java/com/android/internal/util/Preconditions.java
+++ b/core/java/com/android/internal/util/Preconditions.java
@@ -114,6 +114,26 @@
     }
 
     /**
+     * Ensures that an object reference passed as a parameter to the calling
+     * method is not null.
+     *
+     * @param reference an object reference
+     * @param messageTemplate a printf-style message template to use if the check fails; will
+     *     be converted to a string using {@link String#format(String, Object...)}
+     * @param messageArgs arguments for {@code messageTemplate}
+     * @return the non-null reference that was validated
+     * @throws NullPointerException if {@code reference} is null
+     */
+    public static @NonNull <T> T checkNotNull(final T reference,
+            final String messageTemplate,
+            final Object... messageArgs) {
+        if (reference == null) {
+            throw new NullPointerException(String.format(messageTemplate, messageArgs));
+        }
+        return reference;
+    }
+
+    /**
      * Ensures the truth of an expression involving the state of the calling
      * instance, but not involving any parameters to the calling method.
      *
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index a27c5ac..bd7f79e 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -804,7 +804,7 @@
          <p>Protection level: dangerous-->
     <permission android:name="android.permission.READ_PHONE_NUMBERS"
         android:permissionGroup="android.permission-group.PHONE"
-        android:label="@string/permlab_readPhoneNumber"
+        android:label="@string/permlab_readPhoneNumbers"
         android:description="@string/permdesc_readPhoneNumbers"
         android:protectionLevel="dangerous|ephemeral" />
 
diff --git a/core/tests/coretests/src/com/android/internal/os/BatteryStatsDualTimerTest.java b/core/tests/coretests/src/com/android/internal/os/BatteryStatsDualTimerTest.java
new file mode 100644
index 0000000..3a5a9f5
--- /dev/null
+++ b/core/tests/coretests/src/com/android/internal/os/BatteryStatsDualTimerTest.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package com.android.internal.os;
+
+import android.os.BatteryStats;
+import android.support.test.filters.SmallTest;
+
+import junit.framework.TestCase;
+
+/**
+ * Test BatteryStatsImpl.DualTimer.
+ */
+public class BatteryStatsDualTimerTest extends TestCase {
+
+    @SmallTest
+    public void testResetDetach() throws Exception {
+        final MockClocks clocks = new MockClocks();
+        clocks.realtime = clocks.uptime = 100;
+
+        final BatteryStatsImpl.TimeBase timeBase = new BatteryStatsImpl.TimeBase();
+        timeBase.init(clocks.uptimeMillis(), clocks.elapsedRealtime());
+        final BatteryStatsImpl.TimeBase subTimeBase = new BatteryStatsImpl.TimeBase();
+        subTimeBase.init(clocks.uptimeMillis(), clocks.elapsedRealtime());
+
+        final BatteryStatsImpl.DualTimer timer = new BatteryStatsImpl.DualTimer(clocks,
+                null, BatteryStats.WAKE_TYPE_PARTIAL, null, timeBase, subTimeBase);
+
+        assertTrue(timeBase.hasObserver(timer));
+        assertFalse(subTimeBase.hasObserver(timer));
+        assertFalse(timeBase.hasObserver(timer.getSubTimer()));
+        assertTrue(subTimeBase.hasObserver(timer.getSubTimer()));
+
+        // Timer is running so resetting it should not remove it from timerbases.
+        clocks.realtime = clocks.uptime = 200;
+        timer.startRunningLocked(clocks.realtime);
+        timer.reset(true);
+        assertTrue(timeBase.hasObserver(timer));
+        assertTrue(subTimeBase.hasObserver(timer.getSubTimer()));
+
+        // Stop timer and ensure that resetting removes it from timebases.
+        clocks.realtime = clocks.uptime = 300;
+        timer.stopRunningLocked(clocks.realtime);
+        timer.reset(true);
+        assertFalse(timeBase.hasObserver(timer));
+        assertFalse(timeBase.hasObserver(timer.getSubTimer()));
+    }
+}
diff --git a/core/tests/coretests/src/com/android/internal/os/BatteryStatsSensorTest.java b/core/tests/coretests/src/com/android/internal/os/BatteryStatsSensorTest.java
index 47bc502..af4a6d9 100644
--- a/core/tests/coretests/src/com/android/internal/os/BatteryStatsSensorTest.java
+++ b/core/tests/coretests/src/com/android/internal/os/BatteryStatsSensorTest.java
@@ -371,4 +371,48 @@
         // Test: UID_2 - background count
         assertEquals(2, bgTimer2.getCountLocked(BatteryStats.STATS_SINCE_CHARGED));
     }
+
+    @SmallTest
+    public void testSensorReset() throws Exception {
+        final MockClocks clocks = new MockClocks();
+        MockBatteryStatsImpl bi = new MockBatteryStatsImpl(clocks);
+        bi.mForceOnBattery = true;
+        clocks.realtime = 100;
+        clocks.uptime = 100;
+        bi.getOnBatteryTimeBase().setRunning(true, 100_000, 100_000);
+        bi.noteUidProcessStateLocked(UID, ActivityManager.PROCESS_STATE_RECEIVER);
+
+        clocks.realtime += 100;
+        clocks.uptime += 100;
+
+        bi.noteStartSensorLocked(UID, SENSOR_ID);
+
+        clocks.realtime += 100;
+        clocks.uptime += 100;
+
+        // The sensor is started and the timer has been created.
+        final BatteryStats.Uid uid = bi.getUidStats().get(UID);
+        assertNotNull(uid);
+
+        BatteryStats.Uid.Sensor sensor = uid.getSensorStats().get(SENSOR_ID);
+        assertNotNull(sensor);
+        assertNotNull(sensor.getSensorTime());
+        assertNotNull(sensor.getSensorBackgroundTime());
+
+        // Reset the stats. Since the sensor is still running, we should still see the timer
+        bi.getUidStatsLocked(UID).reset();
+
+        sensor = uid.getSensorStats().get(SENSOR_ID);
+        assertNotNull(sensor);
+        assertNotNull(sensor.getSensorTime());
+        assertNotNull(sensor.getSensorBackgroundTime());
+
+        bi.noteStopSensorLocked(UID, SENSOR_ID);
+
+        // Now the sensor timer has stopped so this reset should also take out the sensor.
+        bi.getUidStatsLocked(UID).reset();
+
+        sensor = uid.getSensorStats().get(SENSOR_ID);
+        assertNull(sensor);
+    }
 }
diff --git a/core/tests/coretests/src/com/android/internal/os/BatteryStatsTests.java b/core/tests/coretests/src/com/android/internal/os/BatteryStatsTests.java
index 9607a59..57d6934 100644
--- a/core/tests/coretests/src/com/android/internal/os/BatteryStatsTests.java
+++ b/core/tests/coretests/src/com/android/internal/os/BatteryStatsTests.java
@@ -5,6 +5,7 @@
 
 @RunWith(Suite.class)
 @Suite.SuiteClasses({
+        BatteryStatsDualTimerTest.class,
         BatteryStatsDurationTimerTest.class,
         BatteryStatsSamplingTimerTest.class,
         BatteryStatsServTest.class,
diff --git a/native/android/Android.bp b/native/android/Android.bp
index 5843637..eacda93 100644
--- a/native/android/Android.bp
+++ b/native/android/Android.bp
@@ -14,7 +14,7 @@
 
 // The headers module is in frameworks/native/Android.bp.
 ndk_library {
-    name: "libandroid.ndk",
+    name: "libandroid",
     symbol_file: "libandroid.map.txt",
     first_version: "9",
     unversioned_until: "current",
diff --git a/native/graphics/jni/Android.bp b/native/graphics/jni/Android.bp
index 17feb53..d456950 100644
--- a/native/graphics/jni/Android.bp
+++ b/native/graphics/jni/Android.bp
@@ -14,7 +14,7 @@
 
 // The headers module is in frameworks/native/Android.bp.
 ndk_library {
-    name: "libjnigraphics.ndk",
+    name: "libjnigraphics",
     symbol_file: "libjnigraphics.map.txt",
     first_version: "9",
     unversioned_until: "current",
diff --git a/packages/SettingsLib/src/com/android/settingslib/deviceinfo/StorageMeasurement.java b/packages/SettingsLib/src/com/android/settingslib/deviceinfo/StorageMeasurement.java
index 953dda2..60e10a1 100644
--- a/packages/SettingsLib/src/com/android/settingslib/deviceinfo/StorageMeasurement.java
+++ b/packages/SettingsLib/src/com/android/settingslib/deviceinfo/StorageMeasurement.java
@@ -151,8 +151,15 @@
         final MeasurementDetails details = new MeasurementDetails();
         if (mVolume == null) return details;
 
-        details.totalSize = mStats.getTotalBytes(mVolume.fsUuid);
-        details.availSize = mStats.getFreeBytes(mVolume.fsUuid);
+        try {
+            details.totalSize = mStats.getTotalBytes(mVolume.fsUuid);
+            details.availSize = mStats.getFreeBytes(mVolume.fsUuid);
+        } catch (IllegalStateException e) {
+            // The storage volume became null while we were measuring it.
+            Log.w(TAG, e);
+            return details;
+        }
+
 
         final long finishTotal = SystemClock.elapsedRealtime();
         Log.d(TAG, "Measured total storage in " + (finishTotal - start) + "ms");
diff --git a/services/autofill/java/com/android/server/autofill/AutofillManagerService.java b/services/autofill/java/com/android/server/autofill/AutofillManagerService.java
index 89645f4..d6f5256 100644
--- a/services/autofill/java/com/android/server/autofill/AutofillManagerService.java
+++ b/services/autofill/java/com/android/server/autofill/AutofillManagerService.java
@@ -24,6 +24,8 @@
 import static com.android.server.autofill.Helper.bundleToString;
 
 import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.app.ActivityManager;
 import android.app.ActivityManagerInternal;
 import android.content.BroadcastReceiver;
 import android.content.ContentResolver;
@@ -35,6 +37,7 @@
 import android.database.ContentObserver;
 import android.graphics.Rect;
 import android.net.Uri;
+import android.os.Binder;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.IBinder;
@@ -194,15 +197,29 @@
      */
     @NonNull
     AutofillManagerServiceImpl getServiceForUserLocked(int userId) {
-        AutofillManagerServiceImpl service = mServicesCache.get(userId);
+        final int resolvedUserId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
+                Binder.getCallingUid(), userId, false, false, null, null);
+        AutofillManagerServiceImpl service = mServicesCache.get(resolvedUserId);
         if (service == null) {
-            service = new AutofillManagerServiceImpl(mContext, mLock,
-                    mRequestsHistory, userId, mUi, mDisabledUsers.get(userId));
+            service = new AutofillManagerServiceImpl(mContext, mLock, mRequestsHistory,
+                    resolvedUserId, mUi, mDisabledUsers.get(resolvedUserId));
             mServicesCache.put(userId, service);
         }
         return service;
     }
 
+    /**
+     * Peeks the service instance for a user.
+     *
+     * @return service instance or null if not already present
+     */
+    @Nullable
+    AutofillManagerServiceImpl peekServiceForUserLocked(int userId) {
+        final int resolvedUserId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
+                Binder.getCallingUid(), userId, false, false, null, null);
+        return mServicesCache.get(resolvedUserId);
+    }
+
     // Called by Shell command.
     void requestSaveForUser(int userId) {
         Slog.i(TAG, "requestSaveForUser(): " + userId);
@@ -210,7 +227,7 @@
         final IBinder activityToken = getTopActivityForUser();
         if (activityToken != null) {
             synchronized (mLock) {
-                final AutofillManagerServiceImpl service = mServicesCache.get(userId);
+                final AutofillManagerServiceImpl service = peekServiceForUserLocked(userId);
                 if (service == null) {
                     Log.w(TAG, "handleSaveForUser(): no cached service for userId " + userId);
                     return;
@@ -228,7 +245,10 @@
 
         synchronized (mLock) {
             if (userId != UserHandle.USER_ALL) {
-                mServicesCache.get(userId).destroySessionsLocked();
+                AutofillManagerServiceImpl service = peekServiceForUserLocked(userId);
+                if (service != null) {
+                    service.destroySessionsLocked();
+                }
             } else {
                 final int size = mServicesCache.size();
                 for (int i = 0; i < size; i++) {
@@ -253,7 +273,10 @@
 
         synchronized (mLock) {
             if (userId != UserHandle.USER_ALL) {
-                mServicesCache.get(userId).listSessionsLocked(sessions);
+                AutofillManagerServiceImpl service = peekServiceForUserLocked(userId);
+                if (service != null) {
+                    service.listSessionsLocked(sessions);
+                }
             } else {
                 final int size = mServicesCache.size();
                 for (int i = 0; i < size; i++) {
@@ -287,7 +310,7 @@
      * Removes a cached service for a given user.
      */
     private void removeCachedServiceLocked(int userId) {
-        final AutofillManagerServiceImpl service = mServicesCache.get(userId);
+        final AutofillManagerServiceImpl service = peekServiceForUserLocked(userId);
         if (service != null) {
             mServicesCache.delete(userId);
             service.destroyLocked();
@@ -305,7 +328,7 @@
      * Updates a cached service for a given user.
      */
     private void updateCachedServiceLocked(int userId, boolean disabled) {
-        AutofillManagerServiceImpl service = mServicesCache.get(userId);
+        AutofillManagerServiceImpl service = peekServiceForUserLocked(userId);
         if (service != null) {
             service.updateLocked(disabled);
         }
@@ -409,8 +432,7 @@
         public void updateSession(int sessionId, AutofillId id, Rect bounds,
                 AutofillValue value, int flags, int userId) {
             synchronized (mLock) {
-                final AutofillManagerServiceImpl service = mServicesCache.get(
-                        UserHandle.getCallingUserId());
+                final AutofillManagerServiceImpl service = peekServiceForUserLocked(userId);
                 if (service != null) {
                     service.updateSessionLocked(sessionId, getCallingUid(), id, bounds, value,
                             flags);
@@ -421,8 +443,7 @@
         @Override
         public void finishSession(int sessionId, int userId) {
             synchronized (mLock) {
-                final AutofillManagerServiceImpl service = mServicesCache.get(
-                        UserHandle.getCallingUserId());
+                final AutofillManagerServiceImpl service = peekServiceForUserLocked(userId);
                 if (service != null) {
                     service.finishSessionLocked(sessionId, getCallingUid());
                 }
@@ -432,8 +453,7 @@
         @Override
         public void cancelSession(int sessionId, int userId) {
             synchronized (mLock) {
-                final AutofillManagerServiceImpl service = mServicesCache.get(
-                        UserHandle.getCallingUserId());
+                final AutofillManagerServiceImpl service = peekServiceForUserLocked(userId);
                 if (service != null) {
                     service.cancelSessionLocked(sessionId, getCallingUid());
                 }
@@ -441,6 +461,16 @@
         }
 
         @Override
+        public void disableOwnedAutofillServices(int userId) {
+            synchronized (mLock) {
+                final AutofillManagerServiceImpl service = peekServiceForUserLocked(userId);
+                if (service != null) {
+                    service.disableOwnedAutofillServicesLocked(Binder.getCallingUid());
+                }
+            }
+        }
+
+        @Override
         public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
             if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
             synchronized (mLock) {
diff --git a/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java b/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
index 94d534a..63bf373 100644
--- a/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
+++ b/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
@@ -43,6 +43,7 @@
 import android.os.Looper;
 import android.os.RemoteCallbackList;
 import android.os.RemoteException;
+import android.os.UserHandle;
 import android.os.UserManager;
 import android.provider.Settings;
 import android.service.autofill.AutofillService;
@@ -348,6 +349,25 @@
         session.removeSelfLocked();
     }
 
+    void disableOwnedAutofillServicesLocked(int uid) {
+        if (mInfo == null || mInfo.getServiceInfo().applicationInfo.uid
+                != UserHandle.getAppId(uid)) {
+            return;
+        }
+        final long identity = Binder.clearCallingIdentity();
+        try {
+            final String autoFillService = getComponentNameFromSettings();
+            if (mInfo.getServiceInfo().getComponentName().equals(
+                    ComponentName.unflattenFromString(autoFillService))) {
+                Settings.Secure.putStringForUser(mContext.getContentResolver(),
+                        Settings.Secure.AUTOFILL_SERVICE, null, mUserId);
+                destroySessionsLocked();
+            }
+        } finally {
+            Binder.restoreCallingIdentity(identity);
+        }
+    }
+
     private Session createSessionByTokenLocked(@NonNull IBinder activityToken, int uid,
             @Nullable IBinder windowToken, @NonNull IBinder appCallbackToken, boolean hasCallback,
             int flags, @NonNull String packageName) {
@@ -474,20 +494,6 @@
         mSessions.clear();
     }
 
-    void disableSelf() {
-        final long identity = Binder.clearCallingIdentity();
-        try {
-            final String autoFillService = getComponentNameFromSettings();
-            if (mInfo.getServiceInfo().getComponentName().equals(
-                    ComponentName.unflattenFromString(autoFillService))) {
-                Settings.Secure.putStringForUser(mContext.getContentResolver(),
-                        Settings.Secure.AUTOFILL_SERVICE, null, mUserId);
-            }
-        } finally {
-            Binder.restoreCallingIdentity(identity);
-        }
-    }
-
     CharSequence getServiceLabel() {
         return mInfo.getServiceInfo().loadLabel(mContext.getPackageManager());
     }
diff --git a/services/autofill/java/com/android/server/autofill/RemoteFillService.java b/services/autofill/java/com/android/server/autofill/RemoteFillService.java
index 003c8f1..dd520ac 100644
--- a/services/autofill/java/com/android/server/autofill/RemoteFillService.java
+++ b/services/autofill/java/com/android/server/autofill/RemoteFillService.java
@@ -35,7 +35,6 @@
 import android.service.autofill.AutofillService;
 import android.service.autofill.FillResponse;
 import android.service.autofill.IAutoFillService;
-import android.service.autofill.IAutoFillServiceConnection;
 import android.service.autofill.IFillCallback;
 import android.service.autofill.ISaveCallback;
 import android.text.format.DateUtils;
@@ -96,7 +95,6 @@
         void onSaveRequestFailure(@Nullable CharSequence message,
                 @NonNull String servicePackageName);
         void onServiceDied(RemoteFillService service);
-        void onDisableSelf();
     }
 
     public RemoteFillService(Context context, ComponentName componentName,
@@ -203,10 +201,6 @@
         }
     }
 
-    private void handleDisableSelf() {
-        mCallbacks.onDisableSelf();
-    }
-
     private boolean isBound() {
         return mAutoFillService != null;
     }
@@ -246,7 +240,7 @@
         mBinding = false;
         if (isBound()) {
             try {
-                mAutoFillService.onInit(null);
+                mAutoFillService.onConnectedStateChanged(false);
             } catch (Exception e) {
                 Slog.w(LOG_TAG, "Exception calling onDisconnected(): " + e);
             }
@@ -322,12 +316,7 @@
                 return;
             }
             try {
-                mAutoFillService.onInit(new IAutoFillServiceConnection.Stub() {
-                    @Override
-                    public void disableSelf() {
-                        mHandler.obtainMessage(MyHandler.MSG_ON_DISABLE_SELF).sendToTarget();
-                    }
-                });
+                mAutoFillService.onConnectedStateChanged(true);
             } catch (RemoteException e) {
                 Slog.w(LOG_TAG, "Exception calling onConnected(): " + e);
             }
@@ -353,7 +342,6 @@
         public static final int MSG_BINDER_DIED = 2;
         public static final int MSG_UNBIND = 3;
         public static final int MSG_ON_PENDING_REQUEST = 4;
-        public static final int MSG_ON_DISABLE_SELF = 5;
 
         public MyHandler(Context context) {
             // Cannot use lambda - doesn't compile
@@ -381,10 +369,6 @@
                         case MSG_ON_PENDING_REQUEST: {
                             handlePendingRequest((PendingRequest) message.obj);
                         } break;
-
-                        case MSG_ON_DISABLE_SELF: {
-                            handleDisableSelf();
-                        } break;
                     }
                 }
             }, false);
diff --git a/services/autofill/java/com/android/server/autofill/Session.java b/services/autofill/java/com/android/server/autofill/Session.java
index 3ef9cd5..67c2314c 100644
--- a/services/autofill/java/com/android/server/autofill/Session.java
+++ b/services/autofill/java/com/android/server/autofill/Session.java
@@ -311,15 +311,6 @@
 
     // FillServiceCallbacks
     @Override
-    public void onDisableSelf() {
-        mService.disableSelf();
-        synchronized (mLock) {
-            removeSelfLocked();
-        }
-    }
-
-    // FillServiceCallbacks
-    @Override
     public void onServiceDied(RemoteFillService service) {
         // TODO(b/33197203): implement
     }
diff --git a/services/core/java/com/android/server/AlarmManagerService.java b/services/core/java/com/android/server/AlarmManagerService.java
index 8b32c16..21dae4f 100644
--- a/services/core/java/com/android/server/AlarmManagerService.java
+++ b/services/core/java/com/android/server/AlarmManagerService.java
@@ -36,6 +36,7 @@
 import android.net.Uri;
 import android.os.Binder;
 import android.os.Bundle;
+import android.os.Environment;
 import android.os.Handler;
 import android.os.IBinder;
 import android.os.Message;
@@ -949,6 +950,16 @@
         // because kernel doesn't keep this after reboot
         setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
 
+        // Also sure that we're booting with a halfway sensible current time
+        if (mNativeData != 0) {
+            final long systemBuildTime = Environment.getRootDirectory().lastModified();
+            if (System.currentTimeMillis() < systemBuildTime) {
+                Slog.i(TAG, "Current time only " + System.currentTimeMillis()
+                        + ", advancing to build time " + systemBuildTime);
+                setKernelTime(mNativeData, systemBuildTime);
+            }
+        }
+
         PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
         mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
 
diff --git a/services/core/java/com/android/server/accounts/AccountManagerService.java b/services/core/java/com/android/server/accounts/AccountManagerService.java
index 738365d..5f585cc 100644
--- a/services/core/java/com/android/server/accounts/AccountManagerService.java
+++ b/services/core/java/com/android/server/accounts/AccountManagerService.java
@@ -652,20 +652,20 @@
             return visibility;
         }
 
-        boolean isPrivileged = isPermittedForPackage(packageName, accounts.userId,
+        boolean isPrivileged = isPermittedForPackage(packageName, uid, accounts.userId,
                 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
 
         // Device/Profile owner gets visibility by default.
         if (isProfileOwner(uid)) {
             return AccountManager.VISIBILITY_VISIBLE;
         }
-        // Apps with READ_CONTACTS permission get visibility by default even post O.
-        boolean canReadContacts = checkReadContactsPermission(packageName, accounts.userId);
 
         boolean preO = isPreOApplication(packageName);
         if ((signatureCheckResult != SIGNATURE_CHECK_MISMATCH)
-                || (preO && checkGetAccountsPermission(packageName, accounts.userId))
-                || canReadContacts || isPrivileged) {
+                || (preO && checkGetAccountsPermission(packageName, uid, accounts.userId))
+                || (checkReadContactsPermission(packageName, uid, accounts.userId)
+                    && accountTypeManagesContacts(account.type, accounts.userId))
+                || isPrivileged) {
             // Use legacy for preO apps with GET_ACCOUNTS permission or pre/postO with signature
             // match.
             visibility = getAccountVisibilityFromCache(account,
@@ -5022,14 +5022,20 @@
         }
     }
 
-    private boolean isPermittedForPackage(String packageName, int userId, String... permissions) {
+    private boolean isPermittedForPackage(String packageName, int uid, int userId,
+            String... permissions) {
         final long identity = Binder.clearCallingIdentity();
         try {
             IPackageManager pm = ActivityThread.getPackageManager();
             for (String perm : permissions) {
                 if (pm.checkPermission(perm, packageName, userId)
                         == PackageManager.PERMISSION_GRANTED) {
-                    return true;
+                    // Checks runtime permission revocation.
+                    final int opCode = AppOpsManager.permissionToOpCode(perm);
+                    if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
+                            opCode, uid, packageName) == AppOpsManager.MODE_ALLOWED) {
+                        return true;
+                    }
                 }
             }
         } catch (RemoteException e) {
@@ -5145,13 +5151,37 @@
     // Method checks visibility for applications targeing API level below {@link
     // android.os.Build.VERSION_CODES#O},
     // returns true if the the app has GET_ACCOUNTS or GET_ACCOUNTS_PRIVILEGED permission.
-    private boolean checkGetAccountsPermission(String packageName, int userId) {
-        return isPermittedForPackage(packageName, userId, Manifest.permission.GET_ACCOUNTS,
+    private boolean checkGetAccountsPermission(String packageName, int uid, int userId) {
+        return isPermittedForPackage(packageName, uid, userId, Manifest.permission.GET_ACCOUNTS,
                 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
     }
 
-    private boolean checkReadContactsPermission(String packageName, int userId) {
-        return isPermittedForPackage(packageName, userId, Manifest.permission.READ_CONTACTS);
+    private boolean checkReadContactsPermission(String packageName, int uid, int userId) {
+        return isPermittedForPackage(packageName, uid, userId, Manifest.permission.READ_CONTACTS);
+    }
+
+    // Heuristic to check that account type may be associated with some contacts data and
+    // therefore READ_CONTACTS permission grants the access to account by default.
+    private boolean accountTypeManagesContacts(String accountType, int userId) {
+        if (accountType == null) {
+            return false;
+        }
+        long identityToken = Binder.clearCallingIdentity();
+        Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
+        try {
+            serviceInfos = mAuthenticatorCache.getAllServices(userId);
+        } finally {
+            Binder.restoreCallingIdentity(identityToken);
+        }
+        // Check contacts related permissions for authenticator.
+        for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
+                : serviceInfos) {
+            if (accountType.equals(serviceInfo.type.type)) {
+                return isPermittedForPackage(serviceInfo.type.packageName, serviceInfo.uid, userId,
+                    Manifest.permission.WRITE_CONTACTS);
+            }
+        }
+        return false;
     }
 
     /**
diff --git a/services/core/java/com/android/server/am/ActivityStack.java b/services/core/java/com/android/server/am/ActivityStack.java
index 51011b5..78887c6 100644
--- a/services/core/java/com/android/server/am/ActivityStack.java
+++ b/services/core/java/com/android/server/am/ActivityStack.java
@@ -489,10 +489,14 @@
     void reparent(ActivityStackSupervisor.ActivityDisplay activityDisplay, boolean onTop) {
         removeFromDisplay();
         mTmpRect2.setEmpty();
-        mWindowContainerController.reparent(activityDisplay.mDisplayId, mTmpRect2);
         postAddToDisplay(activityDisplay, mTmpRect2.isEmpty() ? null : mTmpRect2, onTop);
         adjustFocusToNextFocusableStackLocked("reparent", true /* allowFocusSelf */);
         mStackSupervisor.resumeFocusedStackTopActivityLocked();
+        // Update visibility of activities before notifying WM. This way it won't try to resize
+        // windows that are no longer visible.
+        mStackSupervisor.ensureActivitiesVisibleLocked(null /* starting */, 0 /* configChanges */,
+                !PRESERVE_WINDOWS);
+        mWindowContainerController.reparent(activityDisplay.mDisplayId, mTmpRect2, onTop);
     }
 
     /**
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
index c9bb9e5..68e25c3 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
@@ -2775,9 +2775,6 @@
             throw new IllegalArgumentException("moveStackToDisplayLocked: Unknown stackId="
                     + stackId);
         }
-
-        ensureActivitiesVisibleLocked(null /* starting */, 0 /* configChanges */,
-                !PRESERVE_WINDOWS);
         // TODO(multi-display): resize stacks properly if moved from split-screen.
     }
 
diff --git a/services/core/java/com/android/server/am/ActivityStarter.java b/services/core/java/com/android/server/am/ActivityStarter.java
index 59f6098..56594d3 100644
--- a/services/core/java/com/android/server/am/ActivityStarter.java
+++ b/services/core/java/com/android/server/am/ActivityStarter.java
@@ -1038,7 +1038,7 @@
             sendPowerHintForLaunchStartIfNeeded(false /* forceSend */);
 
             reusedActivity = setTargetStackAndMoveToFrontIfNeeded(reusedActivity);
-            if (outActivity.length > 0) {
+            if (outActivity != null && outActivity.length > 0) {
                 outActivity[0] = reusedActivity;
             }
 
diff --git a/services/core/java/com/android/server/connectivity/Tethering.java b/services/core/java/com/android/server/connectivity/Tethering.java
index 0e593bd..dad969c 100644
--- a/services/core/java/com/android/server/connectivity/Tethering.java
+++ b/services/core/java/com/android/server/connectivity/Tethering.java
@@ -93,7 +93,9 @@
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
+import java.util.Map;
 import java.util.concurrent.atomic.AtomicInteger;
 
 
@@ -125,12 +127,23 @@
         public final TetherInterfaceStateMachine stateMachine;
         public int lastState;
         public int lastError;
+
         public TetherState(TetherInterfaceStateMachine sm) {
             stateMachine = sm;
             // Assume all state machines start out available and with no errors.
             lastState = IControlsTethering.STATE_AVAILABLE;
             lastError = ConnectivityManager.TETHER_ERROR_NO_ERROR;
         }
+
+        public boolean isCurrentlyServing() {
+            switch (lastState) {
+                case IControlsTethering.STATE_TETHERED:
+                case IControlsTethering.STATE_LOCAL_HOTSPOT:
+                    return true;
+                default:
+                    return false;
+            }
+        }
     }
 
     // used to synchronize public access to members
@@ -146,11 +159,13 @@
     private final StateMachine mTetherMasterSM;
     private final OffloadController mOffloadController;
     private final UpstreamNetworkMonitor mUpstreamNetworkMonitor;
+    private final HashSet<TetherInterfaceStateMachine> mForwardedDownstreams;
 
     private volatile TetheringConfiguration mConfig;
     private String mCurrentUpstreamIface;
     private Notification.Builder mTetheredNotificationBuilder;
     private int mLastNotificationId;
+
     private boolean mRndisEnabled;       // track the RNDIS function enabled state
     private boolean mUsbTetherRequested; // true if USB tethering should be started
                                          // when RNDIS is enabled
@@ -177,6 +192,7 @@
         mOffloadController = new OffloadController(mTetherMasterSM.getHandler());
         mUpstreamNetworkMonitor = new UpstreamNetworkMonitor(
                 mContext, mTetherMasterSM, TetherMasterSM.EVENT_UPSTREAM_CALLBACK);
+        mForwardedDownstreams = new HashSet<>();
 
         mStateReceiver = new StateReceiver();
         IntentFilter filter = new IntentFilter();
@@ -514,6 +530,10 @@
     }
 
     public int tether(String iface) {
+        return tether(iface, IControlsTethering.STATE_TETHERED);
+    }
+
+    private int tether(String iface, int requestedState) {
         if (DBG) Log.d(TAG, "Tethering " + iface);
         synchronized (mPublicSync) {
             TetherState tetherState = mTetherStates.get(iface);
@@ -527,7 +547,13 @@
                 Log.e(TAG, "Tried to Tether an unavailable iface: " + iface + ", ignoring");
                 return ConnectivityManager.TETHER_ERROR_UNAVAIL_IFACE;
             }
-            tetherState.stateMachine.sendMessage(TetherInterfaceStateMachine.CMD_TETHER_REQUESTED);
+            // NOTE: If a CMD_TETHER_REQUESTED message is already in the TISM's
+            // queue but not yet processed, this will be a no-op and it will not
+            // return an error.
+            //
+            // TODO: reexamine the threading and messaging model.
+            tetherState.stateMachine.sendMessage(
+                    TetherInterfaceStateMachine.CMD_TETHER_REQUESTED, requestedState);
             return ConnectivityManager.TETHER_ERROR_NO_ERROR;
         }
     }
@@ -540,8 +566,8 @@
                 Log.e(TAG, "Tried to Untether an unknown iface :" + iface + ", ignoring");
                 return ConnectivityManager.TETHER_ERROR_UNKNOWN_IFACE;
             }
-            if (tetherState.lastState != IControlsTethering.STATE_TETHERED) {
-                Log.e(TAG, "Tried to untether an untethered iface :" + iface + ", ignoring");
+            if (!tetherState.isCurrentlyServing()) {
+                Log.e(TAG, "Tried to untether an inactive iface :" + iface + ", ignoring");
                 return ConnectivityManager.TETHER_ERROR_UNAVAIL_IFACE;
             }
             tetherState.stateMachine.sendMessage(
@@ -568,6 +594,7 @@
         }
     }
 
+    // TODO: Figure out how to update for local hotspot mode interfaces.
     private void sendTetherStateChangedBroadcast() {
         if (!getConnectivityManager().isTetheringSupported()) return;
 
@@ -745,7 +772,9 @@
                 mRndisEnabled = rndisEnabled;
                 // start tethering if we have a request pending
                 if (usbConnected && mRndisEnabled && mUsbTetherRequested) {
-                    tetherMatchingInterfaces(true, ConnectivityManager.TETHERING_USB);
+                    tetherMatchingInterfaces(
+                            IControlsTethering.STATE_TETHERED,
+                            ConnectivityManager.TETHERING_USB);
                 }
                 mUsbTetherRequested = false;
             }
@@ -760,9 +789,11 @@
                         break;
                     case WifiManager.WIFI_AP_STATE_ENABLED:
                         // When the AP comes up and we've been requested to tether it, do so.
-                        if (mWifiTetherRequested) {
-                            tetherMatchingInterfaces(true, ConnectivityManager.TETHERING_WIFI);
-                        }
+                        // Otherwise, assume it's a local-only hotspot request.
+                        final int state = mWifiTetherRequested
+                                ? IControlsTethering.STATE_TETHERED
+                                : IControlsTethering.STATE_LOCAL_HOTSPOT;
+                        tetherMatchingInterfaces(state, ConnectivityManager.TETHERING_WIFI);
                         break;
                     case WifiManager.WIFI_AP_STATE_DISABLED:
                     case WifiManager.WIFI_AP_STATE_DISABLING:
@@ -792,8 +823,16 @@
         }
     }
 
-    private void tetherMatchingInterfaces(boolean enable, int interfaceType) {
-        if (VDBG) Log.d(TAG, "tetherMatchingInterfaces(" + enable + ", " + interfaceType + ")");
+    // TODO: Consider renaming to something more accurate in its description.
+    // This method:
+    //     - allows requesting either tethering or local hotspot serving states
+    //     - handles both enabling and disabling serving states
+    //     - only tethers the first matching interface in listInterfaces()
+    //       order of a given type
+    private void tetherMatchingInterfaces(int requestedState, int interfaceType) {
+        if (VDBG) {
+            Log.d(TAG, "tetherMatchingInterfaces(" + requestedState + ", " + interfaceType + ")");
+        }
 
         String[] ifaces = null;
         try {
@@ -816,7 +855,20 @@
             return;
         }
 
-        int result = (enable ? tether(chosenIface) : untether(chosenIface));
+        final int result;
+        switch (requestedState) {
+            case IControlsTethering.STATE_UNAVAILABLE:
+            case IControlsTethering.STATE_AVAILABLE:
+                result = untether(chosenIface);
+                break;
+            case IControlsTethering.STATE_TETHERED:
+            case IControlsTethering.STATE_LOCAL_HOTSPOT:
+                result = tether(chosenIface, requestedState);
+                break;
+            default:
+                Log.wtf(TAG, "Unknown interface state: " + requestedState);
+                return;
+        }
         if (result != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
             Log.e(TAG, "unable start or stop tethering on iface " + chosenIface);
             return;
@@ -861,7 +913,8 @@
                 if (mRndisEnabled) {
                     final long ident = Binder.clearCallingIdentity();
                     try {
-                        tetherMatchingInterfaces(true, ConnectivityManager.TETHERING_USB);
+                        tetherMatchingInterfaces(IControlsTethering.STATE_TETHERED,
+                                ConnectivityManager.TETHERING_USB);
                     } finally {
                         Binder.restoreCallingIdentity(ident);
                     }
@@ -872,7 +925,8 @@
             } else {
                 final long ident = Binder.clearCallingIdentity();
                 try {
-                    tetherMatchingInterfaces(false, ConnectivityManager.TETHERING_USB);
+                    tetherMatchingInterfaces(IControlsTethering.STATE_AVAILABLE,
+                            ConnectivityManager.TETHERING_USB);
                 } finally {
                     Binder.restoreCallingIdentity(ident);
                 }
@@ -936,6 +990,14 @@
         }
     }
 
+    private boolean upstreamWanted() {
+        if (!mForwardedDownstreams.isEmpty()) return true;
+
+        synchronized (mPublicSync) {
+            return mUsbTetherRequested || mWifiTetherRequested;
+        }
+    }
+
     // Needed because the canonical source of upstream truth is just the
     // upstream interface name, |mCurrentUpstreamIface|.  This is ripe for
     // future simplification, once the upstream Network is canonical.
@@ -952,10 +1014,10 @@
 
     class TetherMasterSM extends StateMachine {
         private static final int BASE_MASTER                    = Protocol.BASE_TETHERING;
-        // an interface SM has requested Tethering
-        static final int CMD_TETHER_MODE_REQUESTED              = BASE_MASTER + 1;
-        // an interface SM has unrequested Tethering
-        static final int CMD_TETHER_MODE_UNREQUESTED            = BASE_MASTER + 2;
+        // an interface SM has requested Tethering/Local Hotspot
+        static final int EVENT_IFACE_SERVING_STATE_ACTIVE       = BASE_MASTER + 1;
+        // an interface SM has unrequested Tethering/Local Hotspot
+        static final int EVENT_IFACE_SERVING_STATE_INACTIVE     = BASE_MASTER + 2;
         // upstream connection change - do the right thing
         static final int CMD_UPSTREAM_CHANGED                   = BASE_MASTER + 3;
         // we don't have a valid upstream conn, check again after a delay
@@ -1040,7 +1102,9 @@
                     transitionTo(mSetIpForwardingEnabledErrorState);
                     return false;
                 }
+                // TODO: Randomize DHCPv4 ranges, especially in hotspot mode.
                 try {
+                    // TODO: Find a more accurate method name (startDHCPv4()?).
                     mNMService.startTethering(cfg.dhcpRanges);
                 } catch (Exception e) {
                     try {
@@ -1342,26 +1406,41 @@
             }
         }
 
+        private void handleInterfaceServingStateActive(int mode, TetherInterfaceStateMachine who) {
+            if (mNotifyList.indexOf(who) < 0) {
+                mNotifyList.add(who);
+                mIPv6TetheringCoordinator.addActiveDownstream(who, mode);
+            }
+
+            if (mode == IControlsTethering.STATE_TETHERED) {
+                mForwardedDownstreams.add(who);
+            } else {
+                mForwardedDownstreams.remove(who);
+            }
+        }
+
+        private void handleInterfaceServingStateInactive(TetherInterfaceStateMachine who) {
+            mNotifyList.remove(who);
+            mIPv6TetheringCoordinator.removeActiveDownstream(who);
+            mForwardedDownstreams.remove(who);
+        }
+
         class InitialState extends TetherMasterUtilState {
             @Override
             public boolean processMessage(Message message) {
                 maybeLogMessage(this, message.what);
                 boolean retValue = true;
                 switch (message.what) {
-                    case CMD_TETHER_MODE_REQUESTED:
+                    case EVENT_IFACE_SERVING_STATE_ACTIVE:
                         TetherInterfaceStateMachine who = (TetherInterfaceStateMachine)message.obj;
                         if (VDBG) Log.d(TAG, "Tether Mode requested by " + who);
-                        if (mNotifyList.indexOf(who) < 0) {
-                            mNotifyList.add(who);
-                            mIPv6TetheringCoordinator.addActiveDownstream(who);
-                        }
+                        handleInterfaceServingStateActive(message.arg1, who);
                         transitionTo(mTetherModeAliveState);
                         break;
-                    case CMD_TETHER_MODE_UNREQUESTED:
+                    case EVENT_IFACE_SERVING_STATE_INACTIVE:
                         who = (TetherInterfaceStateMachine)message.obj;
                         if (VDBG) Log.d(TAG, "Tether Mode unrequested by " + who);
-                        mNotifyList.remove(who);
-                        mIPv6TetheringCoordinator.removeActiveDownstream(who);
+                        handleInterfaceServingStateInactive(who);
                         break;
                     default:
                         retValue = false;
@@ -1373,6 +1452,7 @@
 
         class TetherModeAliveState extends TetherMasterUtilState {
             final SimChangeListener simChange = new SimChangeListener(mContext);
+            boolean mUpstreamWanted = false;
             boolean mTryCell = true;
 
             @Override
@@ -1383,9 +1463,11 @@
                 mUpstreamNetworkMonitor.start();
                 mOffloadController.start();
 
-                // Better try something first pass or crazy tests cases will fail.
-                chooseUpstreamType(true);
-                mTryCell = false;
+                if (upstreamWanted()) {
+                    mUpstreamWanted = true;
+                    chooseUpstreamType(true);
+                    mTryCell = false;
+                }
             }
 
             @Override
@@ -1398,54 +1480,74 @@
                 handleNewUpstreamNetworkState(null);
             }
 
+            private boolean updateUpstreamWanted() {
+                final boolean previousUpstreamWanted = mUpstreamWanted;
+                mUpstreamWanted = upstreamWanted();
+                return previousUpstreamWanted;
+            }
+
             @Override
             public boolean processMessage(Message message) {
                 maybeLogMessage(this, message.what);
                 boolean retValue = true;
                 switch (message.what) {
-                    case CMD_TETHER_MODE_REQUESTED: {
+                    case EVENT_IFACE_SERVING_STATE_ACTIVE: {
                         TetherInterfaceStateMachine who = (TetherInterfaceStateMachine)message.obj;
                         if (VDBG) Log.d(TAG, "Tether Mode requested by " + who);
-                        if (mNotifyList.indexOf(who) < 0) {
-                            mNotifyList.add(who);
-                            mIPv6TetheringCoordinator.addActiveDownstream(who);
-                        }
+                        handleInterfaceServingStateActive(message.arg1, who);
                         who.sendMessage(TetherInterfaceStateMachine.CMD_TETHER_CONNECTION_CHANGED,
                                 mCurrentUpstreamIface);
+                        // If there has been a change and an upstream is now
+                        // desired, kick off the selection process.
+                        final boolean previousUpstreamWanted = updateUpstreamWanted();
+                        if (!previousUpstreamWanted && mUpstreamWanted) {
+                            chooseUpstreamType(true);
+                        }
                         break;
                     }
-                    case CMD_TETHER_MODE_UNREQUESTED: {
+                    case EVENT_IFACE_SERVING_STATE_INACTIVE: {
                         TetherInterfaceStateMachine who = (TetherInterfaceStateMachine)message.obj;
                         if (VDBG) Log.d(TAG, "Tether Mode unrequested by " + who);
-                        if (mNotifyList.remove(who)) {
-                            if (DBG) Log.d(TAG, "TetherModeAlive removing notifyee " + who);
-                            if (mNotifyList.isEmpty()) {
-                                turnOffMasterTetherSettings(); // transitions appropriately
-                            } else {
-                                if (DBG) {
-                                    Log.d(TAG, "TetherModeAlive still has " + mNotifyList.size() +
-                                            " live requests:");
-                                    for (TetherInterfaceStateMachine o : mNotifyList) {
-                                        Log.d(TAG, "  " + o);
-                                    }
+                        handleInterfaceServingStateInactive(who);
+
+                        if (mNotifyList.isEmpty()) {
+                            turnOffMasterTetherSettings(); // transitions appropriately
+                        } else {
+                            if (DBG) {
+                                Log.d(TAG, "TetherModeAlive still has " + mNotifyList.size() +
+                                        " live requests:");
+                                for (TetherInterfaceStateMachine o : mNotifyList) {
+                                    Log.d(TAG, "  " + o);
                                 }
                             }
-                        } else {
-                           Log.e(TAG, "TetherModeAliveState UNREQUESTED has unknown who: " + who);
                         }
-                        mIPv6TetheringCoordinator.removeActiveDownstream(who);
+                        // If there has been a change and an upstream is no
+                        // longer desired, release any mobile requests.
+                        final boolean previousUpstreamWanted = updateUpstreamWanted();
+                        if (previousUpstreamWanted && !mUpstreamWanted) {
+                            mUpstreamNetworkMonitor.releaseMobileNetworkRequest();
+                        }
                         break;
                     }
                     case CMD_UPSTREAM_CHANGED:
+                        updateUpstreamWanted();
+                        if (!mUpstreamWanted) break;
+
                         // Need to try DUN immediately if Wi-Fi goes down.
                         chooseUpstreamType(true);
                         mTryCell = false;
                         break;
                     case CMD_RETRY_UPSTREAM:
+                        updateUpstreamWanted();
+                        if (!mUpstreamWanted) break;
+
                         chooseUpstreamType(mTryCell);
                         mTryCell = !mTryCell;
                         break;
                     case EVENT_UPSTREAM_CALLBACK: {
+                        updateUpstreamWanted();
+                        if (!mUpstreamWanted) break;
+
                         final NetworkState ns = (NetworkState) message.obj;
 
                         if (ns == null || !pertainsToCurrentUpstream(ns)) {
@@ -1507,7 +1609,7 @@
             public boolean processMessage(Message message) {
                 boolean retValue = true;
                 switch (message.what) {
-                    case CMD_TETHER_MODE_REQUESTED:
+                    case EVENT_IFACE_SERVING_STATE_ACTIVE:
                         TetherInterfaceStateMachine who = (TetherInterfaceStateMachine)message.obj;
                         who.sendMessage(mErrorNotification);
                         break;
@@ -1615,12 +1717,16 @@
                     case IControlsTethering.STATE_TETHERED:
                         pw.print("TetheredState");
                         break;
+                    case IControlsTethering.STATE_LOCAL_HOTSPOT:
+                        pw.print("LocalHotspotState");
+                        break;
                     default:
                         pw.print("UnknownState");
                         break;
                 }
                 pw.println(" - lastError = " + tetherState.lastError);
             }
+            pw.println("Upstream wanted: " + upstreamWanted());
             pw.decreaseIndent();
         }
         pw.decreaseIndent();
@@ -1659,15 +1765,21 @@
         if (error == ConnectivityManager.TETHER_ERROR_MASTER_ERROR) {
             mTetherMasterSM.sendMessage(TetherMasterSM.CMD_CLEAR_ERROR, who);
         }
+        int which;
         switch (state) {
             case IControlsTethering.STATE_UNAVAILABLE:
             case IControlsTethering.STATE_AVAILABLE:
-                mTetherMasterSM.sendMessage(TetherMasterSM.CMD_TETHER_MODE_UNREQUESTED, who);
+                which = TetherMasterSM.EVENT_IFACE_SERVING_STATE_INACTIVE;
                 break;
             case IControlsTethering.STATE_TETHERED:
-                mTetherMasterSM.sendMessage(TetherMasterSM.CMD_TETHER_MODE_REQUESTED, who);
+            case IControlsTethering.STATE_LOCAL_HOTSPOT:
+                which = TetherMasterSM.EVENT_IFACE_SERVING_STATE_ACTIVE;
                 break;
+            default:
+                Log.wtf(TAG, "Unknown interface state: " + state);
+                return;
         }
+        mTetherMasterSM.sendMessage(which, state, 0, who);
         sendTetherStateChangedBroadcast();
     }
 
diff --git a/services/core/java/com/android/server/connectivity/tethering/IControlsTethering.java b/services/core/java/com/android/server/connectivity/tethering/IControlsTethering.java
index 449b8a8..f3914b7 100644
--- a/services/core/java/com/android/server/connectivity/tethering/IControlsTethering.java
+++ b/services/core/java/com/android/server/connectivity/tethering/IControlsTethering.java
@@ -25,6 +25,7 @@
     public final int STATE_UNAVAILABLE = 0;
     public final int STATE_AVAILABLE = 1;
     public final int STATE_TETHERED = 2;
+    public final int STATE_LOCAL_HOTSPOT = 3;
 
     /**
      * Notify that |who| has changed its tethering state.  This may be called from any thread.
diff --git a/services/core/java/com/android/server/connectivity/tethering/IPv6TetheringCoordinator.java b/services/core/java/com/android/server/connectivity/tethering/IPv6TetheringCoordinator.java
index 9173feb..5f496ca 100644
--- a/services/core/java/com/android/server/connectivity/tethering/IPv6TetheringCoordinator.java
+++ b/services/core/java/com/android/server/connectivity/tethering/IPv6TetheringCoordinator.java
@@ -24,12 +24,17 @@
 import android.net.NetworkCapabilities;
 import android.net.NetworkState;
 import android.net.RouteInfo;
+import android.net.util.NetworkConstants;
 import android.util.Log;
 
 import java.net.Inet6Address;
 import java.net.InetAddress;
+import java.net.UnknownHostException;
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
 import java.util.LinkedList;
+import java.util.Random;
 
 
 /**
@@ -45,29 +50,65 @@
     private static final boolean DBG = false;
     private static final boolean VDBG = false;
 
+    private static class Downstream {
+        public final TetherInterfaceStateMachine tism;
+        public final int mode;  // IControlsTethering.STATE_*
+        // Used to append to a ULA /48, constructing a ULA /64 for local use.
+        public final short subnetId;
+
+        Downstream(TetherInterfaceStateMachine tism, int mode, short subnetId) {
+            this.tism = tism;
+            this.mode = mode;
+            this.subnetId = subnetId;
+        }
+    }
+
     private final ArrayList<TetherInterfaceStateMachine> mNotifyList;
-    private final LinkedList<TetherInterfaceStateMachine> mActiveDownstreams;
+    // NOTE: mActiveDownstreams is a list and not a hash data structure because
+    // we keep active downstreams in arrival order.  This is done so /64s can
+    // be parceled out on a "first come, first served" basis and a /64 used by
+    // a downstream that is no longer active can be redistributed to any next
+    // waiting active downstream (again, in arrival order).
+    private final LinkedList<Downstream> mActiveDownstreams;
+    private final byte[] mUniqueLocalPrefix;
+    private short mNextSubnetId;
     private NetworkState mUpstreamNetworkState;
 
     public IPv6TetheringCoordinator(ArrayList<TetherInterfaceStateMachine> notifyList) {
         mNotifyList = notifyList;
         mActiveDownstreams = new LinkedList<>();
+        mUniqueLocalPrefix = generateUniqueLocalPrefix();
+        mNextSubnetId = 0;
     }
 
-    public void addActiveDownstream(TetherInterfaceStateMachine downstream) {
-        if (mActiveDownstreams.indexOf(downstream) == -1) {
+    public void addActiveDownstream(TetherInterfaceStateMachine downstream, int mode) {
+        if (findDownstream(downstream) == null) {
             // Adding a new downstream appends it to the list. Adding a
             // downstream a second time without first removing it has no effect.
-            mActiveDownstreams.offer(downstream);
+            // We never change the mode of a downstream except by first removing
+            // it and then re-adding it (with its new mode specified);
+            if (mActiveDownstreams.offer(new Downstream(downstream, mode, mNextSubnetId))) {
+                // Make sure subnet IDs are always positive. They are appended
+                // to a ULA /48 to make a ULA /64 for local use.
+                mNextSubnetId = (short) Math.max(0, mNextSubnetId + 1);
+            }
             updateIPv6TetheringInterfaces();
         }
     }
 
     public void removeActiveDownstream(TetherInterfaceStateMachine downstream) {
         stopIPv6TetheringOn(downstream);
-        if (mActiveDownstreams.remove(downstream)) {
+        if (mActiveDownstreams.remove(findDownstream(downstream))) {
             updateIPv6TetheringInterfaces();
         }
+
+        // When tethering is stopping we can reset the subnet counter.
+        if (mNotifyList.isEmpty()) {
+            if (!mActiveDownstreams.isEmpty()) {
+                Log.wtf(TAG, "Tethering notify list empty, IPv6 downstreams non-empty.");
+            }
+            mNextSubnetId = 0;
+        }
     }
 
     public void updateUpstreamNetworkState(NetworkState ns) {
@@ -123,20 +164,31 @@
     }
 
     private LinkProperties getInterfaceIPv6LinkProperties(TetherInterfaceStateMachine sm) {
-        if (mUpstreamNetworkState == null) return null;
-
         if (sm.interfaceType() == ConnectivityManager.TETHERING_BLUETOOTH) {
             // TODO: Figure out IPv6 support on PAN interfaces.
             return null;
         }
 
+        final Downstream ds = findDownstream(sm);
+        if (ds == null) return null;
+
+        if (ds.mode == IControlsTethering.STATE_LOCAL_HOTSPOT) {
+            // Build a Unique Locally-assigned Prefix configuration.
+            return getUniqueLocalConfig(mUniqueLocalPrefix, ds.subnetId);
+        }
+
+        // This downstream is in IControlsTethering.STATE_TETHERED mode.
+        if (mUpstreamNetworkState == null || mUpstreamNetworkState.linkProperties == null) {
+            return null;
+        }
+
         // NOTE: Here, in future, we would have policies to decide how to divvy
         // up the available dedicated prefixes among downstream interfaces.
         // At this time we have no such mechanism--we only support tethering
         // IPv6 toward the oldest (first requested) active downstream.
 
-        final TetherInterfaceStateMachine currentActive = mActiveDownstreams.peek();
-        if (currentActive != null && currentActive == sm) {
+        final Downstream currentActive = mActiveDownstreams.peek();
+        if (currentActive != null && currentActive.tism == sm) {
             final LinkProperties lp = getIPv6OnlyLinkProperties(
                     mUpstreamNetworkState.linkProperties);
             if (lp.hasIPv6DefaultRoute() && lp.hasGlobalIPv6Address()) {
@@ -147,6 +199,13 @@
         return null;
     }
 
+    Downstream findDownstream(TetherInterfaceStateMachine tism) {
+        for (Downstream ds : mActiveDownstreams) {
+            if (ds.tism == tism) return ds;
+        }
+        return null;
+    }
+
     private static boolean canTetherIPv6(NetworkState ns) {
         // Broadly speaking:
         //
@@ -263,6 +322,44 @@
                !ip.isMulticastAddress();
     }
 
+    private static LinkProperties getUniqueLocalConfig(byte[] ulp, short subnetId) {
+        final LinkProperties lp = new LinkProperties();
+
+        final IpPrefix local48 = makeUniqueLocalPrefix(ulp, (short) 0, 48);
+        lp.addRoute(new RouteInfo(local48, null, null));
+
+        final IpPrefix local64 = makeUniqueLocalPrefix(ulp, subnetId, 64);
+        // Because this is a locally-generated ULA, we don't have an upstream
+        // address. But because the downstream IP address management code gets
+        // its prefix from the upstream's IP address, we create a fake one here.
+        lp.addLinkAddress(new LinkAddress(local64.getAddress(), 64));
+
+        lp.setMtu(NetworkConstants.ETHER_MTU);
+        return lp;
+    }
+
+    private static IpPrefix makeUniqueLocalPrefix(byte[] in6addr, short subnetId, int prefixlen) {
+        final byte[] bytes = Arrays.copyOf(in6addr, in6addr.length);
+        bytes[7] = (byte) (subnetId >> 8);
+        bytes[8] = (byte) subnetId;
+        return new IpPrefix(bytes, prefixlen);
+    }
+
+    // Generates a Unique Locally-assigned Prefix:
+    //
+    //     https://tools.ietf.org/html/rfc4193#section-3.1
+    //
+    // The result is a /48 that can be used for local-only communications.
+    private static byte[] generateUniqueLocalPrefix() {
+        final byte[] ulp = new byte[6];  // 6 = 48bits / 8bits/byte
+        (new Random()).nextBytes(ulp);
+
+        final byte[] in6addr = Arrays.copyOf(ulp, NetworkConstants.IPV6_ADDR_LEN);
+        in6addr[0] = (byte) 0xfd;  // fc00::/7 and L=1
+
+        return in6addr;
+    }
+
     private static String toDebugString(NetworkState ns) {
         if (ns == null) {
             return "NetworkState{null}";
diff --git a/services/core/java/com/android/server/connectivity/tethering/IPv6TetheringInterfaceServices.java b/services/core/java/com/android/server/connectivity/tethering/IPv6TetheringInterfaceServices.java
index 8c6430c..c6a7925 100644
--- a/services/core/java/com/android/server/connectivity/tethering/IPv6TetheringInterfaceServices.java
+++ b/services/core/java/com/android/server/connectivity/tethering/IPv6TetheringInterfaceServices.java
@@ -42,6 +42,7 @@
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.Objects;
+import java.util.Random;
 
 
 /**
@@ -66,10 +67,17 @@
     }
 
     public boolean start() {
+        // TODO: Refactor for testability (perhaps passing an android.system.Os
+        // instance and calling getifaddrs() directly).
         try {
             mNetworkInterface = NetworkInterface.getByName(mIfName);
         } catch (SocketException e) {
-            Log.e(TAG, "Failed to find NetworkInterface for " + mIfName, e);
+            Log.e(TAG, "Error looking up NetworkInterfaces for " + mIfName, e);
+            stop();
+            return false;
+        }
+        if (mNetworkInterface == null) {
+            Log.e(TAG, "Failed to find NetworkInterface for " + mIfName);
             stop();
             return false;
         }
@@ -267,10 +275,10 @@
         return localRoutes;
     }
 
-    // Given a prefix like 2001:db8::/64 return 2001:db8::1.
+    // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
     private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
         final byte[] dnsBytes = localPrefix.getRawAddress();
-        dnsBytes[dnsBytes.length - 1] = 0x1;
+        dnsBytes[dnsBytes.length - 1] = getRandomNonZeroByte();
         try {
             return Inet6Address.getByAddress(null, dnsBytes, 0);
         } catch (UnknownHostException e) {
@@ -278,4 +286,11 @@
             return null;
         }
     }
+
+    private static byte getRandomNonZeroByte() {
+        final byte random = (byte) (new Random()).nextInt();
+        // Don't pick the subnet-router anycast address, since that might be
+        // in use on the upstream already.
+        return (random != 0) ? random : 0x1;
+    }
 }
diff --git a/services/core/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachine.java b/services/core/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachine.java
index 710ab33..1ffa864 100644
--- a/services/core/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachine.java
+++ b/services/core/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachine.java
@@ -78,6 +78,8 @@
     public static final int CMD_IPV6_TETHER_UPDATE          = BASE_IFACE + 13;
 
     private final State mInitialState;
+    private final State mServingState;
+    private final State mLocalHotspotState;
     private final State mTetheredState;
     private final State mUnavailableState;
 
@@ -105,10 +107,14 @@
         mLastError = ConnectivityManager.TETHER_ERROR_NO_ERROR;
 
         mInitialState = new InitialState();
-        addState(mInitialState);
+        mServingState = new ServingState();
+        mLocalHotspotState = new LocalHotspotState();
         mTetheredState = new TetheredState();
-        addState(mTetheredState);
         mUnavailableState = new UnavailableState();
+        addState(mInitialState);
+        addState(mServingState);
+            addState(mLocalHotspotState, mServingState);
+            addState(mTetheredState, mServingState);
         addState(mUnavailableState);
 
         setInitialState(mInitialState);
@@ -172,12 +178,15 @@
         }
     }
 
+    private void sendInterfaceState(int newInterfaceState) {
+        mTetherController.notifyInterfaceStateChange(
+                mIfaceName, TetherInterfaceStateMachine.this, newInterfaceState, mLastError);
+    }
+
     class InitialState extends State {
         @Override
         public void enter() {
-            mTetherController.notifyInterfaceStateChange(
-                    mIfaceName, TetherInterfaceStateMachine.this,
-                    IControlsTethering.STATE_AVAILABLE, mLastError);
+            sendInterfaceState(IControlsTethering.STATE_AVAILABLE);
         }
 
         @Override
@@ -187,7 +196,16 @@
             switch (message.what) {
                 case CMD_TETHER_REQUESTED:
                     mLastError = ConnectivityManager.TETHER_ERROR_NO_ERROR;
-                    transitionTo(mTetheredState);
+                    switch (message.arg1) {
+                        case IControlsTethering.STATE_LOCAL_HOTSPOT:
+                            transitionTo(mLocalHotspotState);
+                            break;
+                        case IControlsTethering.STATE_TETHERED:
+                            transitionTo(mTetheredState);
+                            break;
+                        default:
+                            Log.e(TAG, "Invalid tethering interface serving state specified.");
+                    }
                     break;
                 case CMD_INTERFACE_DOWN:
                     transitionTo(mUnavailableState);
@@ -204,7 +222,7 @@
         }
     }
 
-    class TetheredState extends State {
+    class ServingState extends State {
         @Override
         public void enter() {
             if (!configureIfaceIp(true)) {
@@ -225,11 +243,6 @@
             if (!mIPv6TetherSvc.start()) {
                 Log.e(TAG, "Failed to start IPv6TetheringInterfaceServices");
             }
-
-            if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
-            mTetherController.notifyInterfaceStateChange(
-                    mIfaceName, TetherInterfaceStateMachine.this,
-                    IControlsTethering.STATE_TETHERED, mLastError);
         }
 
         @Override
@@ -238,7 +251,6 @@
             // of these operations, but it doesn't really change that we have to try them
             // all in sequence.
             mIPv6TetherSvc.stop();
-            cleanupUpstream();
 
             try {
                 mNMService.untetherInterface(mIfaceName);
@@ -250,6 +262,73 @@
             configureIfaceIp(false);
         }
 
+        @Override
+        public boolean processMessage(Message message) {
+            maybeLogMessage(this, message.what);
+            switch (message.what) {
+                case CMD_TETHER_UNREQUESTED:
+                    transitionTo(mInitialState);
+                    if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
+                    break;
+                case CMD_INTERFACE_DOWN:
+                    transitionTo(mUnavailableState);
+                    if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
+                    break;
+                case CMD_IPV6_TETHER_UPDATE:
+                    mIPv6TetherSvc.updateUpstreamIPv6LinkProperties(
+                            (LinkProperties) message.obj);
+                    break;
+                case CMD_IP_FORWARDING_ENABLE_ERROR:
+                case CMD_IP_FORWARDING_DISABLE_ERROR:
+                case CMD_START_TETHERING_ERROR:
+                case CMD_STOP_TETHERING_ERROR:
+                case CMD_SET_DNS_FORWARDERS_ERROR:
+                    mLastError = ConnectivityManager.TETHER_ERROR_MASTER_ERROR;
+                    transitionTo(mInitialState);
+                    break;
+                default:
+                    return false;
+            }
+            return true;
+        }
+    }
+
+    class LocalHotspotState extends State {
+        @Override
+        public void enter() {
+            if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
+            sendInterfaceState(IControlsTethering.STATE_LOCAL_HOTSPOT);
+        }
+
+        @Override
+        public boolean processMessage(Message message) {
+            maybeLogMessage(this, message.what);
+            switch (message.what) {
+                case CMD_TETHER_REQUESTED:
+                    Log.e(TAG, "CMD_TETHER_REQUESTED while in local hotspot mode.");
+                    break;
+                case CMD_TETHER_CONNECTION_CHANGED:
+                    // Ignored in local hotspot state.
+                    break;
+                default:
+                    return false;
+            }
+            return true;
+        }
+    }
+
+    class TetheredState extends State {
+        @Override
+        public void enter() {
+            if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
+            sendInterfaceState(IControlsTethering.STATE_TETHERED);
+        }
+
+        @Override
+        public void exit() {
+            cleanupUpstream();
+        }
+
         private void cleanupUpstream() {
             if (mMyUpstreamIfaceName == null) return;
 
@@ -285,13 +364,8 @@
             maybeLogMessage(this, message.what);
             boolean retValue = true;
             switch (message.what) {
-                case CMD_TETHER_UNREQUESTED:
-                    transitionTo(mInitialState);
-                    if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
-                    break;
-                case CMD_INTERFACE_DOWN:
-                    transitionTo(mUnavailableState);
-                    if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
+                case CMD_TETHER_REQUESTED:
+                    Log.e(TAG, "CMD_TETHER_REQUESTED while already tethering.");
                     break;
                 case CMD_TETHER_CONNECTION_CHANGED:
                     String newUpstreamIfaceName = (String)(message.obj);
@@ -317,18 +391,6 @@
                     }
                     mMyUpstreamIfaceName = newUpstreamIfaceName;
                     break;
-                case CMD_IPV6_TETHER_UPDATE:
-                    mIPv6TetherSvc.updateUpstreamIPv6LinkProperties(
-                            (LinkProperties) message.obj);
-                    break;
-                case CMD_IP_FORWARDING_ENABLE_ERROR:
-                case CMD_IP_FORWARDING_DISABLE_ERROR:
-                case CMD_START_TETHERING_ERROR:
-                case CMD_STOP_TETHERING_ERROR:
-                case CMD_SET_DNS_FORWARDERS_ERROR:
-                    mLastError = ConnectivityManager.TETHER_ERROR_MASTER_ERROR;
-                    transitionTo(mInitialState);
-                    break;
                 default:
                     retValue = false;
                     break;
@@ -348,9 +410,7 @@
         @Override
         public void enter() {
             mLastError = ConnectivityManager.TETHER_ERROR_NO_ERROR;
-            mTetherController.notifyInterfaceStateChange(
-                    mIfaceName, TetherInterfaceStateMachine.this,
-                    IControlsTethering.STATE_UNAVAILABLE, mLastError);
+            sendInterfaceState(IControlsTethering.STATE_UNAVAILABLE);
         }
     }
 }
diff --git a/services/core/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitor.java b/services/core/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitor.java
index 6209929..97a2d5e 100644
--- a/services/core/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitor.java
+++ b/services/core/java/com/android/server/connectivity/tethering/UpstreamNetworkMonitor.java
@@ -308,7 +308,8 @@
     // Fetch (and cache) a ConnectivityManager only if and when we need one.
     private ConnectivityManager cm() {
         if (mCM == null) {
-            mCM = mContext.getSystemService(ConnectivityManager.class);
+            // MUST call the String variant to be able to write unittests.
+            mCM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
         }
         return mCM;
     }
diff --git a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
index c8028fe..2e499f1 100644
--- a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
+++ b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
@@ -1003,22 +1003,24 @@
             final boolean meteredHint = info.getMeteredHint();
 
             final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
-            synchronized (mNetworkPoliciesSecondLock) {
-                NetworkPolicy policy = mNetworkPolicy.get(template);
-                if (policy == null && meteredHint) {
-                    // policy doesn't exist, and AP is hinting that it's
-                    // metered: create an inferred policy.
-                    policy = newWifiPolicy(template, meteredHint);
-                    addNetworkPolicyNL(policy);
+            synchronized (mUidRulesFirstLock) {
+                synchronized (mNetworkPoliciesSecondLock) {
+                    NetworkPolicy policy = mNetworkPolicy.get(template);
+                    if (policy == null && meteredHint) {
+                        // policy doesn't exist, and AP is hinting that it's
+                        // metered: create an inferred policy.
+                        policy = newWifiPolicy(template, meteredHint);
+                        addNetworkPolicyAL(policy);
 
-                } else if (policy != null && policy.inferred) {
-                    // policy exists, and was inferred: update its current
-                    // metered state.
-                    policy.metered = meteredHint;
+                    } else if (policy != null && policy.inferred) {
+                        // policy exists, and was inferred: update its current
+                        // metered state.
+                        policy.metered = meteredHint;
 
-                    // since this is inferred for each wifi session, just update
-                    // rules without persisting.
-                    updateNetworkRulesNL();
+                        // since this is inferred for each wifi session, just update
+                        // rules without persisting.
+                        updateNetworkRulesNL();
+                    }
                 }
             }
         }
@@ -1289,12 +1291,14 @@
             // permission above.
 
             maybeRefreshTrustedTime();
-            synchronized (mNetworkPoliciesSecondLock) {
-                ensureActiveMobilePolicyNL();
-                normalizePoliciesNL();
-                updateNetworkEnabledNL();
-                updateNetworkRulesNL();
-                updateNotificationsNL();
+            synchronized (mUidRulesFirstLock) {
+                synchronized (mNetworkPoliciesSecondLock) {
+                    ensureActiveMobilePolicyAL();
+                    normalizePoliciesNL();
+                    updateNetworkEnabledNL();
+                    updateNetworkRulesNL();
+                    updateNotificationsNL();
+                }
             }
         }
     };
@@ -1477,7 +1481,7 @@
             maybeRefreshTrustedTime();
             synchronized (mUidRulesFirstLock) {
                 synchronized (mNetworkPoliciesSecondLock) {
-                    final boolean added = ensureActiveMobilePolicyNL(subId, subscriberId);
+                    final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
                     if (added) return;
                     final boolean updated = maybeUpdateMobilePolicyCycleNL(subId);
                     if (!updated) return;
@@ -1721,8 +1725,8 @@
      * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
      * have at least a default mobile policy defined.
      */
-    private void ensureActiveMobilePolicyNL() {
-        if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
+    private void ensureActiveMobilePolicyAL() {
+        if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
         if (mSuppressDefaultPolicy) return;
 
         final TelephonyManager tele = TelephonyManager.from(mContext);
@@ -1731,7 +1735,7 @@
         final int[] subIds = sub.getActiveSubscriptionIdList();
         for (int subId : subIds) {
             final String subscriberId = tele.getSubscriberId(subId);
-            ensureActiveMobilePolicyNL(subId, subscriberId);
+            ensureActiveMobilePolicyAL(subId, subscriberId);
         }
     }
 
@@ -1743,7 +1747,7 @@
      * @param subscriberId that we check for an existing policy
      * @return true if a mobile network policy was added, or false one already existed.
      */
-    private boolean ensureActiveMobilePolicyNL(int subId, String subscriberId) {
+    private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
         // Poke around to see if we already have a policy
         final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
                 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
@@ -1761,7 +1765,7 @@
         Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
                 + "; generating default policy");
         final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
-        addNetworkPolicyNL(policy);
+        addNetworkPolicyAL(policy);
         return true;
     }
 
@@ -2265,7 +2269,7 @@
         }
     }
 
-    void addNetworkPolicyNL(NetworkPolicy policy) {
+    void addNetworkPolicyAL(NetworkPolicy policy) {
         NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
         policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
         setNetworkPolicies(policies);
diff --git a/services/core/java/com/android/server/om/OverlayManagerService.java b/services/core/java/com/android/server/om/OverlayManagerService.java
index 2026c1b..818c3ad 100644
--- a/services/core/java/com/android/server/om/OverlayManagerService.java
+++ b/services/core/java/com/android/server/om/OverlayManagerService.java
@@ -193,13 +193,10 @@
  * </ul>
  */
 public final class OverlayManagerService extends SystemService {
-
     static final String TAG = "OverlayManager";
 
     static final boolean DEBUG = false;
 
-    static final String PERMISSION_DENIED = "Operation not permitted for user shell";
-
     /**
      * The system property that specifies the default overlays to apply.
      * This is a semicolon separated list of package names.
@@ -234,7 +231,7 @@
         IdmapManager im = new IdmapManager(installer);
         mSettings = new OverlayManagerSettings();
         mImpl = new OverlayManagerServiceImpl(mPackageManager, im, mSettings,
-                getDefaultOverlayPackages());
+                getDefaultOverlayPackages(), new OverlayChangeListener());
         mInitCompleteSignal = SystemServerInitThreadPool.get().submit(() -> {
             final IntentFilter packageFilter = new IntentFilter();
             packageFilter.addAction(ACTION_PACKAGE_ADDED);
@@ -251,9 +248,6 @@
 
             restoreSettings();
             onSwitchUser(UserHandle.USER_SYSTEM);
-            schedulePersistSettings();
-
-            mSettings.addChangeListener(new OverlayChangeListener());
 
             publishBinderService(Context.OVERLAY_SERVICE, mService);
             publishLocalService(OverlayManagerService.class, this);
@@ -281,8 +275,9 @@
         final List<String> targets;
         synchronized (mLock) {
             targets = mImpl.onSwitchUser(newUserId);
+            updateAssetsLocked(newUserId, targets);
         }
-        updateAssets(newUserId, targets);
+        schedulePersistSettings();
     }
 
     private static Set<String> getDefaultOverlayPackages() {
@@ -348,7 +343,8 @@
                 @NonNull final int[] userIds) {
             for (final int userId : userIds) {
                 synchronized (mLock) {
-                    final PackageInfo pi = mPackageManager.getPackageInfo(packageName, userId, false);
+                    final PackageInfo pi = mPackageManager.getPackageInfo(packageName, userId,
+                            false);
                     if (pi != null) {
                         mPackageManager.cachePackageInfo(packageName, userId, pi);
                         if (!isOverlayPackage(pi)) {
@@ -365,7 +361,8 @@
                 @NonNull final int[] userIds) {
             for (int userId : userIds) {
                 synchronized (mLock) {
-                    final PackageInfo pi = mPackageManager.getPackageInfo(packageName, userId, false);
+                    final PackageInfo pi = mPackageManager.getPackageInfo(packageName, userId,
+                            false);
                     if (pi != null) {
                         mPackageManager.cachePackageInfo(packageName, userId, pi);
                         if (!isOverlayPackage(pi)) {
@@ -397,7 +394,8 @@
                 @NonNull final int[] userIds) {
             for (int userId : userIds) {
                 synchronized (mLock) {
-                    final PackageInfo pi = mPackageManager.getPackageInfo(packageName, userId, false);
+                    final PackageInfo pi = mPackageManager.getPackageInfo(packageName, userId,
+                            false);
                     if (pi != null) {
                         mPackageManager.cachePackageInfo(packageName, userId, pi);
                         if (!isOverlayPackage(pi)) {
@@ -449,8 +447,7 @@
 
     private final IBinder mService = new IOverlayManager.Stub() {
         @Override
-        public Map<String, List<OverlayInfo>> getAllOverlays(int userId)
-                throws RemoteException {
+        public Map<String, List<OverlayInfo>> getAllOverlays(int userId) throws RemoteException {
             userId = handleIncomingUser(userId, "getAllOverlays");
 
             synchronized (mLock) {
@@ -508,14 +505,14 @@
                 int userId) throws RemoteException {
             enforceChangeOverlayPackagesPermission("setEnabled");
             userId = handleIncomingUser(userId, "setEnabled");
-            if (packageName == null) {
+            if (packageName == null || !enable) {
                 return false;
             }
 
             final long ident = Binder.clearCallingIdentity();
             try {
                 synchronized (mLock) {
-                    return mImpl.setEnabledExclusive(packageName, enable, userId);
+                    return mImpl.setEnabledExclusive(packageName, userId);
                 }
             } finally {
                 Binder.restoreCallingIdentity(ident);
@@ -643,68 +640,24 @@
         return pi != null && pi.overlayTarget != null;
     }
 
-    private final class OverlayChangeListener implements OverlayManagerSettings.ChangeListener {
+    private final class OverlayChangeListener
+            implements OverlayManagerServiceImpl.OverlayChangeListener {
         @Override
-        public void onSettingsChanged() {
+        public void onOverlaysChanged(@NonNull final String targetPackageName, final int userId) {
             schedulePersistSettings();
-        }
-
-        @Override
-        public void onOverlayAdded(@NonNull final OverlayInfo oi) {
-            scheduleBroadcast(Intent.ACTION_OVERLAY_ADDED, oi, oi.isEnabled());
-        }
-
-        @Override
-        public void onOverlayRemoved(@NonNull final OverlayInfo oi) {
-            scheduleBroadcast(Intent.ACTION_OVERLAY_REMOVED, oi, oi.isEnabled());
-        }
-
-        @Override
-        public void onOverlayChanged(@NonNull final OverlayInfo oi,
-                @NonNull final OverlayInfo oldOi) {
-            scheduleBroadcast(Intent.ACTION_OVERLAY_CHANGED, oi, oi.isEnabled() != oldOi.isEnabled());
-        }
-
-        @Override
-        public void onOverlayPriorityChanged(@NonNull final OverlayInfo oi) {
-            scheduleBroadcast(Intent.ACTION_OVERLAY_PRIORITY_CHANGED, oi, oi.isEnabled());
-        }
-
-        private void scheduleBroadcast(@NonNull final String action, @NonNull final OverlayInfo oi,
-                final boolean doUpdate) {
-            FgThread.getHandler().post(new BroadcastRunnable(action, oi, doUpdate));
-        }
-
-        private final class BroadcastRunnable implements Runnable {
-            private final String mAction;
-            private final OverlayInfo mOverlayInfo;
-            private final boolean mDoUpdate;
-
-            BroadcastRunnable(@NonNull final String action, @NonNull final OverlayInfo oi,
-                    final boolean doUpdate) {
-                mAction = action;
-                mOverlayInfo = oi;
-                mDoUpdate = doUpdate;
-            }
-
-            @Override
-            public void run() {
-                if (mDoUpdate) {
-                    updateAssets(mOverlayInfo.userId, mOverlayInfo.targetPackageName);
+            FgThread.getHandler().post(() -> {
+                synchronized (mLock) {
+                    updateAssetsLocked(userId, targetPackageName);
                 }
-                sendBroadcast(mAction, mOverlayInfo.targetPackageName, mOverlayInfo.packageName,
-                        mOverlayInfo.userId);
-            }
 
-            private void sendBroadcast(@NonNull final String action,
-                    @NonNull final String targetPackageName, @NonNull final String packageName,
-                    final int userId) {
-                final Intent intent = new Intent(action, Uri.fromParts("package",
-                            String.format("%s/%s", targetPackageName, packageName), null));
+                final Intent intent = new Intent(Intent.ACTION_OVERLAY_CHANGED,
+                        Uri.fromParts("package", targetPackageName, null));
                 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
+
                 if (DEBUG) {
-                    Slog.d(TAG, String.format("send broadcast %s", intent));
+                    Slog.d(TAG, "send broadcast " + intent);
                 }
+
                 try {
                     ActivityManager.getService().broadcastIntent(null, intent, null, null, 0,
                             null, null, null, android.app.AppOpsManager.OP_NONE, null, false, false,
@@ -712,18 +665,20 @@
                 } catch (RemoteException e) {
                     // Intentionally left empty.
                 }
-            }
-
+            });
         }
     }
 
-    private void updateAssets(final int userId, final String targetPackageName) {
+    private void updateAssetsLocked(final int userId, final String targetPackageName) {
         final List<String> list = new ArrayList<>();
         list.add(targetPackageName);
-        updateAssets(userId, list);
+        updateAssetsLocked(userId, list);
     }
 
-    private void updateAssets(final int userId, List<String> targetPackageNames) {
+    private void updateAssetsLocked(final int userId, List<String> targetPackageNames) {
+        if (DEBUG) {
+            Slog.d(TAG, "Updating overlay assets");
+        }
         final PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
         final boolean updateFrameworkRes = targetPackageNames.contains("android");
         if (updateFrameworkRes) {
@@ -743,6 +698,12 @@
         final int N = targetPackageNames.size();
         for (int i = 0; i < N; i++) {
             final String targetPackageName = targetPackageNames.get(i);
+            if (DEBUG) {
+                Slog.d(TAG, "-> Updating overlay: target=" + targetPackageName + " overlays=["
+                        + TextUtils.join(",", pendingChanges.get(targetPackageName))
+                        + "] userId=" + userId);
+            }
+
             if (!pm.setEnabledOverlayPackages(
                         userId, targetPackageName, pendingChanges.get(targetPackageName))) {
                 Slog.e(TAG, String.format("Failed to change enabled overlays for %s user %d",
@@ -762,20 +723,20 @@
         if (mPersistSettingsScheduled.getAndSet(true)) {
             return;
         }
-        IoThread.getHandler().post(new Runnable() {
-            @Override
-            public void run() {
-                mPersistSettingsScheduled.set(false);
-                synchronized (mLock) {
-                    FileOutputStream stream = null;
-                    try {
-                        stream = mSettingsFile.startWrite();
-                        mSettings.persist(stream);
-                        mSettingsFile.finishWrite(stream);
-                    } catch (IOException | XmlPullParserException e) {
-                        mSettingsFile.failWrite(stream);
-                        Slog.e(TAG, "failed to persist overlay state", e);
-                    }
+        IoThread.getHandler().post(() -> {
+            mPersistSettingsScheduled.set(false);
+            if (DEBUG) {
+                Slog.d(TAG, "Writing overlay settings");
+            }
+            synchronized (mLock) {
+                FileOutputStream stream = null;
+                try {
+                    stream = mSettingsFile.startWrite();
+                    mSettings.persist(stream);
+                    mSettingsFile.finishWrite(stream);
+                } catch (IOException | XmlPullParserException e) {
+                    mSettingsFile.failWrite(stream);
+                    Slog.e(TAG, "failed to persist overlay state", e);
                 }
             }
         });
@@ -862,7 +823,8 @@
             // The package manager does not support different versions of packages
             // to be installed for different users: ignore userId for now.
             try {
-                return mPackageManager.checkSignatures(packageName1, packageName2) == SIGNATURE_MATCH;
+                return mPackageManager.checkSignatures(
+                        packageName1, packageName2) == SIGNATURE_MATCH;
             } catch (RemoteException e) {
                 // Intentionally left blank
             }
diff --git a/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java b/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java
index 3705946..c536278 100644
--- a/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java
+++ b/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java
@@ -54,15 +54,18 @@
     private final IdmapManager mIdmapManager;
     private final OverlayManagerSettings mSettings;
     private final Set<String> mDefaultOverlays;
+    private final OverlayChangeListener mListener;
 
     OverlayManagerServiceImpl(@NonNull final PackageManagerHelper packageManager,
             @NonNull final IdmapManager idmapManager,
             @NonNull final OverlayManagerSettings settings,
-            @NonNull final Set<String> defaultOverlays) {
+            @NonNull final Set<String> defaultOverlays,
+            @NonNull final OverlayChangeListener listener) {
         mPackageManager = packageManager;
         mIdmapManager = idmapManager;
         mSettings = settings;
         mDefaultOverlays = defaultOverlays;
+        mListener = listener;
     }
 
     /*
@@ -145,7 +148,6 @@
                 iter.remove();
             }
         }
-
         return new ArrayList<>(packagesToUpdateAssets);
     }
 
@@ -199,25 +201,30 @@
         updateAllOverlaysForTarget(packageName, userId, null);
     }
 
-    private void updateAllOverlaysForTarget(@NonNull final String packageName, final int userId,
+    /**
+     * Returns true if the settings were modified for this target.
+     */
+    private boolean updateAllOverlaysForTarget(@NonNull final String packageName, final int userId,
             @Nullable final PackageInfo targetPackage) {
+        boolean modified = false;
         final List<OverlayInfo> ois = mSettings.getOverlaysForTarget(packageName, userId);
         final int N = ois.size();
         for (int i = 0; i < N; i++) {
             final OverlayInfo oi = ois.get(i);
             final PackageInfo overlayPackage = mPackageManager.getPackageInfo(oi.packageName, userId);
             if (overlayPackage == null) {
-                mSettings.remove(oi.packageName, oi.userId);
+                modified |= mSettings.remove(oi.packageName, oi.userId);
                 removeIdmapIfPossible(oi);
             } else {
                 try {
-                    updateState(targetPackage, overlayPackage, userId);
+                    modified |= updateState(targetPackage, overlayPackage, userId);
                 } catch (OverlayManagerSettings.BadKeyException e) {
                     Slog.e(TAG, "failed to update settings", e);
-                    mSettings.remove(oi.packageName, userId);
+                    modified |= mSettings.remove(oi.packageName, userId);
                 }
             }
         }
+        return modified;
     }
 
     void onOverlayPackageAdded(@NonNull final String packageName, final int userId) {
@@ -238,7 +245,9 @@
         mSettings.init(packageName, userId, overlayPackage.overlayTarget,
                 overlayPackage.applicationInfo.getBaseCodePath());
         try {
-            updateState(targetPackage, overlayPackage, userId);
+            if (updateState(targetPackage, overlayPackage, userId)) {
+                mListener.onOverlaysChanged(overlayPackage.overlayTarget, userId);
+            }
         } catch (OverlayManagerSettings.BadKeyException e) {
             Slog.e(TAG, "failed to update settings", e);
             mSettings.remove(packageName, userId);
@@ -289,8 +298,9 @@
         if (overlayPackage == null) {
             return false;
         }
-        // Static overlay is always being enabled.
-        if (!enable && overlayPackage.isStaticOverlay) {
+
+        // Ignore static overlays.
+        if (overlayPackage.isStaticOverlay) {
             return false;
         }
 
@@ -298,19 +308,21 @@
             final OverlayInfo oi = mSettings.getOverlayInfo(packageName, userId);
             final PackageInfo targetPackage =
                     mPackageManager.getPackageInfo(oi.targetPackageName, userId);
-            mSettings.setEnabled(packageName, userId, enable);
-            updateState(targetPackage, overlayPackage, userId);
+            boolean modified = mSettings.setEnabled(packageName, userId, enable);
+            modified |= updateState(targetPackage, overlayPackage, userId);
+
+            if (modified) {
+                mListener.onOverlaysChanged(oi.targetPackageName, userId);
+            }
             return true;
         } catch (OverlayManagerSettings.BadKeyException e) {
             return false;
         }
     }
 
-    boolean setEnabledExclusive(@NonNull final String packageName, final boolean enable,
-            final int userId) {
+    boolean setEnabledExclusive(@NonNull final String packageName, final int userId) {
         if (DEBUG) {
-            Slog.d(TAG, String.format("setEnabled packageName=%s enable=%s userId=%d",
-                        packageName, enable, userId));
+            Slog.d(TAG, String.format("setEnabledExclusive packageName=%s userId=%d", packageName, userId));
         }
 
         final PackageInfo overlayPackage = mPackageManager.getPackageInfo(packageName, userId);
@@ -320,23 +332,48 @@
 
         try {
             final OverlayInfo oi = mSettings.getOverlayInfo(packageName, userId);
+            final PackageInfo targetPackage =
+                    mPackageManager.getPackageInfo(oi.targetPackageName, userId);
+
             List<OverlayInfo> allOverlays = getOverlayInfosForTarget(oi.targetPackageName, userId);
 
+            boolean modified = false;
+
             // Disable all other overlays.
             allOverlays.remove(oi);
             for (int i = 0; i < allOverlays.size(); i++) {
-                // TODO: Optimize this to only send updates after all changes.
-                setEnabled(allOverlays.get(i).packageName, false, userId);
+                final String disabledOverlayPackageName = allOverlays.get(i).packageName;
+                final PackageInfo disabledOverlayPackageInfo = mPackageManager.getPackageInfo(
+                        disabledOverlayPackageName, userId);
+                if (disabledOverlayPackageInfo == null) {
+                    modified |= mSettings.remove(disabledOverlayPackageName, userId);
+                    continue;
+                }
+
+                if (disabledOverlayPackageInfo.isStaticOverlay) {
+                    // Don't touch static overlays.
+                    continue;
+                }
+
+                // Disable the overlay.
+                modified |= mSettings.setEnabled(disabledOverlayPackageName, userId, false);
+                modified |= updateState(targetPackage, disabledOverlayPackageInfo, userId);
             }
 
-            setEnabled(packageName, enable, userId);
+            // Enable the selected overlay.
+            modified |= mSettings.setEnabled(packageName, userId, true);
+            modified |= updateState(targetPackage, overlayPackage, userId);
+
+            if (modified) {
+                mListener.onOverlaysChanged(oi.targetPackageName, userId);
+            }
             return true;
         } catch (OverlayManagerSettings.BadKeyException e) {
             return false;
         }
     }
 
-    boolean isPackageUpdatableOverlay(@NonNull final String packageName, final int userId) {
+    private boolean isPackageUpdatableOverlay(@NonNull final String packageName, final int userId) {
         final PackageInfo overlayPackage = mPackageManager.getPackageInfo(packageName, userId);
         if (overlayPackage == null || overlayPackage.isStaticOverlay) {
             return false;
@@ -346,18 +383,64 @@
 
     boolean setPriority(@NonNull final String packageName,
             @NonNull final String newParentPackageName, final int userId) {
-        return isPackageUpdatableOverlay(packageName, userId) &&
-                mSettings.setPriority(packageName, newParentPackageName, userId);
+        if (DEBUG) {
+            Slog.d(TAG, "setPriority packageName=" + packageName + " newParentPackageName="
+                    + newParentPackageName + " userId=" + userId);
+        }
+
+        if (!isPackageUpdatableOverlay(packageName, userId)) {
+            return false;
+        }
+
+        final PackageInfo overlayPackage = mPackageManager.getPackageInfo(packageName, userId);
+        if (overlayPackage == null) {
+            return false;
+        }
+
+        if (mSettings.setPriority(packageName, newParentPackageName, userId)) {
+            mListener.onOverlaysChanged(overlayPackage.overlayTarget, userId);
+        }
+        return true;
     }
 
     boolean setHighestPriority(@NonNull final String packageName, final int userId) {
-        return isPackageUpdatableOverlay(packageName, userId) &&
-                mSettings.setHighestPriority(packageName, userId);
+        if (DEBUG) {
+            Slog.d(TAG, "setHighestPriority packageName=" + packageName + " userId=" + userId);
+        }
+
+        if (!isPackageUpdatableOverlay(packageName, userId)) {
+            return false;
+        }
+
+        final PackageInfo overlayPackage = mPackageManager.getPackageInfo(packageName, userId);
+        if (overlayPackage == null) {
+            return false;
+        }
+
+        if (mSettings.setHighestPriority(packageName, userId)) {
+            mListener.onOverlaysChanged(overlayPackage.overlayTarget, userId);
+        }
+        return true;
     }
 
     boolean setLowestPriority(@NonNull final String packageName, final int userId) {
-        return isPackageUpdatableOverlay(packageName, userId) &&
-                mSettings.setLowestPriority(packageName, userId);
+        if (DEBUG) {
+            Slog.d(TAG, "setLowestPriority packageName=" + packageName + " userId=" + userId);
+        }
+
+        if (!isPackageUpdatableOverlay(packageName, userId)) {
+            return false;
+        }
+
+        final PackageInfo overlayPackage = mPackageManager.getPackageInfo(packageName, userId);
+        if (overlayPackage == null) {
+            return false;
+        }
+
+        if (mSettings.setLowestPriority(packageName, userId)) {
+            mListener.onOverlaysChanged(overlayPackage.overlayTarget, userId);
+        }
+        return true;
     }
 
     void onDump(@NonNull final PrintWriter pw) {
@@ -379,16 +462,19 @@
         return paths;
     }
 
-    private void updateState(@Nullable final PackageInfo targetPackage,
+    /**
+     * Returns true if the settings/state was modified, false otherwise.
+     */
+    private boolean updateState(@Nullable final PackageInfo targetPackage,
             @NonNull final PackageInfo overlayPackage, final int userId)
-        throws OverlayManagerSettings.BadKeyException {
+            throws OverlayManagerSettings.BadKeyException {
         // Static RROs targeting to "android", ie framework-res.apk, are handled by native layers.
         if (targetPackage != null &&
                 !("android".equals(targetPackage.packageName) && overlayPackage.isStaticOverlay)) {
             mIdmapManager.createIdmap(targetPackage, overlayPackage, userId);
         }
 
-        mSettings.setBaseCodePath(overlayPackage.packageName, userId,
+        boolean modified = mSettings.setBaseCodePath(overlayPackage.packageName, userId,
                 overlayPackage.applicationInfo.getBaseCodePath());
 
         final int currentState = mSettings.getState(overlayPackage.packageName, userId);
@@ -400,8 +486,9 @@
                             OverlayInfo.stateToString(currentState),
                             OverlayInfo.stateToString(newState)));
             }
-            mSettings.setState(overlayPackage.packageName, userId, newState);
+            modified |= mSettings.setState(overlayPackage.packageName, userId, newState);
         }
+        return modified;
     }
 
     private int calculateNewState(@Nullable final PackageInfo targetPackage,
@@ -441,10 +528,8 @@
         if (!mIdmapManager.idmapExists(oi)) {
             return;
         }
-        final List<Integer> userIds = mSettings.getUsers();
-        final int N = userIds.size();
-        for (int i = 0; i < N; i++) {
-            final int userId = userIds.get(i);
+        final int[] userIds = mSettings.getUsers();
+        for (int userId : userIds) {
             try {
                 final OverlayInfo tmp = mSettings.getOverlayInfo(oi.packageName, userId);
                 if (tmp != null && tmp.isEnabled()) {
@@ -458,6 +543,10 @@
         mIdmapManager.removeIdmap(oi, oi.userId);
     }
 
+    interface OverlayChangeListener {
+        void onOverlaysChanged(@NonNull String targetPackage, int userId);
+    }
+
     interface PackageManagerHelper {
         PackageInfo getPackageInfo(@NonNull String packageName, int userId);
         boolean signaturesMatching(@NonNull String packageName1, @NonNull String packageName2,
diff --git a/services/core/java/com/android/server/om/OverlayManagerSettings.java b/services/core/java/com/android/server/om/OverlayManagerSettings.java
index 2262a2e..2cafa39 100644
--- a/services/core/java/com/android/server/om/OverlayManagerSettings.java
+++ b/services/core/java/com/android/server/om/OverlayManagerSettings.java
@@ -16,17 +16,11 @@
 
 package com.android.server.om;
 
-import static android.content.om.OverlayInfo.STATE_UNKNOWN;
-
-import static com.android.server.om.OverlayManagerService.DEBUG;
-import static com.android.server.om.OverlayManagerService.TAG;
-
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.content.om.OverlayInfo;
 import android.util.AndroidRuntimeException;
 import android.util.ArrayMap;
-import android.util.Slog;
 import android.util.Xml;
 
 import com.android.internal.util.FastXmlSerializer;
@@ -41,23 +35,28 @@
 import java.io.OutputStream;
 import java.io.PrintWriter;
 import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
 import java.util.List;
-import java.util.ListIterator;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
 
 /**
  * Data structure representing the current state of all overlay packages in the
  * system.
  *
- * Modifications to the data are exposed through the ChangeListener interface.
+ * Modifications to the data are signaled by returning true from any state mutating method.
  *
- * @see ChangeListener
  * @see OverlayManagerService
  */
 final class OverlayManagerSettings {
-    private final List<ChangeListener> mListeners = new ArrayList<>();
-
+    /**
+     * All overlay data for all users and target packages is stored in this list.
+     * This keeps memory down, while increasing the cost of running queries or mutating the
+     * data. This is ok, since changing of overlays is very rare and has larger costs associated
+     * with it.
+     *
+     * The order of the items in the list is important, those with a lower index having a lower
+     * priority.
+     */
     private final ArrayList<SettingsItem> mItems = new ArrayList<>();
 
     void init(@NonNull final String packageName, final int userId,
@@ -68,225 +67,176 @@
         mItems.add(item);
     }
 
-    void remove(@NonNull final String packageName, final int userId) {
-        final SettingsItem item = select(packageName, userId);
-        if (item == null) {
-            return;
+    /**
+     * Returns true if the settings were modified, false if they remain the same.
+     */
+    boolean remove(@NonNull final String packageName, final int userId) {
+        final int idx = select(packageName, userId);
+        if (idx < 0) {
+            return false;
         }
-        final OverlayInfo oi = item.getOverlayInfo();
-        mItems.remove(item);
-        if (oi != null) {
-            notifyOverlayRemoved(oi);
-        }
-    }
 
-    boolean contains(@NonNull final String packageName, final int userId) {
-        return select(packageName, userId) != null;
+        mItems.remove(idx);
+        return true;
     }
 
     OverlayInfo getOverlayInfo(@NonNull final String packageName, final int userId)
             throws BadKeyException {
-        final SettingsItem item = select(packageName, userId);
-        if (item == null) {
+        final int idx = select(packageName, userId);
+        if (idx < 0) {
             throw new BadKeyException(packageName, userId);
         }
-        return item.getOverlayInfo();
+        return mItems.get(idx).getOverlayInfo();
     }
 
-    String getTargetPackageName(@NonNull final String packageName, final int userId)
-            throws BadKeyException {
-        final SettingsItem item = select(packageName, userId);
-        if (item == null) {
-            throw new BadKeyException(packageName, userId);
-        }
-        return item.getTargetPackageName();
-    }
-
-    void setBaseCodePath(@NonNull final String packageName, final int userId,
+    /**
+     * Returns true if the settings were modified, false if they remain the same.
+     */
+    boolean setBaseCodePath(@NonNull final String packageName, final int userId,
             @NonNull final String path) throws BadKeyException {
-        final SettingsItem item = select(packageName, userId);
-        if (item == null) {
+        final int idx = select(packageName, userId);
+        if (idx < 0) {
             throw new BadKeyException(packageName, userId);
         }
-        item.setBaseCodePath(path);
-        notifySettingsChanged();
+        return mItems.get(idx).setBaseCodePath(path);
     }
 
     boolean getEnabled(@NonNull final String packageName, final int userId) throws BadKeyException {
-        final SettingsItem item = select(packageName, userId);
-        if (item == null) {
+        final int idx = select(packageName, userId);
+        if (idx < 0) {
             throw new BadKeyException(packageName, userId);
         }
-        return item.isEnabled();
+        return mItems.get(idx).isEnabled();
     }
 
-    void setEnabled(@NonNull final String packageName, final int userId, final boolean enable)
+    /**
+     * Returns true if the settings were modified, false if they remain the same.
+     */
+    boolean setEnabled(@NonNull final String packageName, final int userId, final boolean enable)
             throws BadKeyException {
-        final SettingsItem item = select(packageName, userId);
-        if (item == null) {
+        final int idx = select(packageName, userId);
+        if (idx < 0) {
             throw new BadKeyException(packageName, userId);
         }
-        if (enable == item.isEnabled()) {
-            return; // nothing to do
-        }
-
-        item.setEnabled(enable);
-        notifySettingsChanged();
+        return mItems.get(idx).setEnabled(enable);
     }
 
     int getState(@NonNull final String packageName, final int userId) throws BadKeyException {
-        final SettingsItem item = select(packageName, userId);
-        if (item == null) {
+        final int idx = select(packageName, userId);
+        if (idx < 0) {
             throw new BadKeyException(packageName, userId);
         }
-        return item.getState();
+        return mItems.get(idx).getState();
     }
 
-    void setState(@NonNull final String packageName, final int userId, final int state)
+    /**
+     * Returns true if the settings were modified, false if they remain the same.
+     */
+    boolean setState(@NonNull final String packageName, final int userId, final int state)
             throws BadKeyException {
-        final SettingsItem item = select(packageName, userId);
-        if (item == null) {
+        final int idx = select(packageName, userId);
+        if (idx < 0) {
             throw new BadKeyException(packageName, userId);
         }
-        final OverlayInfo previous = item.getOverlayInfo();
-        item.setState(state);
-        final OverlayInfo current = item.getOverlayInfo();
-        if (previous.state == STATE_UNKNOWN) {
-            notifyOverlayAdded(current);
-            notifySettingsChanged();
-        } else if (current.state != previous.state) {
-            notifyOverlayChanged(current, previous);
-            notifySettingsChanged();
-        }
+        return mItems.get(idx).setState(state);
     }
 
     List<OverlayInfo> getOverlaysForTarget(@NonNull final String targetPackageName,
             final int userId) {
-        final List<SettingsItem> items = selectWhereTarget(targetPackageName, userId);
-        if (items.isEmpty()) {
-            return Collections.emptyList();
-        }
-        final List<OverlayInfo> out = new ArrayList<>(items.size());
-        final int N = items.size();
-        for (int i = 0; i < N; i++) {
-            final SettingsItem item = items.get(i);
-            out.add(item.getOverlayInfo());
-        }
-        return out;
+        return selectWhereTarget(targetPackageName, userId)
+                .map(SettingsItem::getOverlayInfo)
+                .collect(Collectors.toList());
     }
 
     ArrayMap<String, List<OverlayInfo>> getOverlaysForUser(final int userId) {
-        final List<SettingsItem> items = selectWhereUser(userId);
-        if (items.isEmpty()) {
-            return ArrayMap.EMPTY;
-        }
-        final ArrayMap<String, List<OverlayInfo>> out = new ArrayMap<>(items.size());
-        final int N = items.size();
-        for (int i = 0; i < N; i++) {
-            final SettingsItem item = items.get(i);
-            final String targetPackageName = item.getTargetPackageName();
-            if (!out.containsKey(targetPackageName)) {
-                out.put(targetPackageName, new ArrayList<OverlayInfo>());
-            }
-            final List<OverlayInfo> overlays = out.get(targetPackageName);
-            overlays.add(item.getOverlayInfo());
-        }
-        return out;
+        return selectWhereUser(userId)
+                .map(SettingsItem::getOverlayInfo)
+                .collect(Collectors.groupingBy(info -> info.targetPackageName, ArrayMap::new,
+                        Collectors.toList()));
     }
 
-    List<String> getTargetPackageNamesForUser(final int userId) {
-        final List<SettingsItem> items = selectWhereUser(userId);
-        if (items.isEmpty()) {
-            return Collections.emptyList();
-        }
-        final List<String> out = new ArrayList<>();
-        final int N = items.size();
-        for (int i = 0; i < N; i++) {
-            final SettingsItem item = items.get(i);
-            final String targetPackageName = item.getTargetPackageName();
-            if (!out.contains(targetPackageName)) {
-                out.add(targetPackageName);
-            }
-        }
-        return out;
+    int[] getUsers() {
+        return mItems.stream().mapToInt(SettingsItem::getUserId).distinct().toArray();
     }
 
-    List<Integer> getUsers() {
-        final ArrayList<Integer> users = new ArrayList<>();
-        final int N = mItems.size();
-        for (int i = 0; i < N; i++) {
+    /**
+     * Returns true if the settings were modified, false if they remain the same.
+     */
+    boolean removeUser(final int userId) {
+        boolean removed = false;
+        for (int i = 0; i < mItems.size(); i++) {
             final SettingsItem item = mItems.get(i);
-            if (!users.contains(item.userId)) {
-                users.add(item.userId);
+            if (item.getUserId() == userId) {
+                mItems.remove(i);
+                removed = true;
+                i--;
             }
         }
-        return users;
+        return removed;
     }
 
-    void removeUser(final int userId) {
-        final Iterator<SettingsItem> iter = mItems.iterator();
-        while (iter.hasNext()) {
-            final SettingsItem item = iter.next();
-            if (item.userId == userId) {
-                iter.remove();
-            }
-        }
-    }
-
+    /**
+     * Returns true if the settings were modified, false if they remain the same.
+     */
     boolean setPriority(@NonNull final String packageName,
             @NonNull final String newParentPackageName, final int userId) {
         if (packageName.equals(newParentPackageName)) {
             return false;
         }
-        final SettingsItem rowToMove = select(packageName, userId);
-        if (rowToMove == null) {
-            return false;
-        }
-        final SettingsItem newParentRow = select(newParentPackageName, userId);
-        if (newParentRow == null) {
-            return false;
-        }
-        if (!rowToMove.getTargetPackageName().equals(newParentRow.getTargetPackageName())) {
+        final int moveIdx = select(packageName, userId);
+        if (moveIdx < 0) {
             return false;
         }
 
-        mItems.remove(rowToMove);
-        final ListIterator<SettingsItem> iter = mItems.listIterator();
-        while (iter.hasNext()) {
-            final SettingsItem item = iter.next();
-            if (item.userId == userId && item.packageName.equals(newParentPackageName)) {
-                iter.add(rowToMove);
-                notifyOverlayPriorityChanged(rowToMove.getOverlayInfo());
-                notifySettingsChanged();
-                return true;
-            }
+        final int parentIdx = select(newParentPackageName, userId);
+        if (parentIdx < 0) {
+            return false;
         }
 
-        Slog.wtf(TAG, "failed to find the parent item a second time");
-        return false;
+        final SettingsItem itemToMove = mItems.get(moveIdx);
+
+        // Make sure both packages are targeting the same package.
+        if (!itemToMove.getTargetPackageName().equals(
+                mItems.get(parentIdx).getTargetPackageName())) {
+            return false;
+        }
+
+        mItems.remove(moveIdx);
+        final int newParentIdx = select(newParentPackageName, userId);
+        mItems.add(newParentIdx, itemToMove);
+        return moveIdx != newParentIdx;
     }
 
+    /**
+     * Returns true if the settings were modified, false if they remain the same.
+     */
     boolean setLowestPriority(@NonNull final String packageName, final int userId) {
-        final SettingsItem item = select(packageName, userId);
-        if (item == null) {
+        final int idx = select(packageName, userId);
+        if (idx <= 0) {
+            // If the item doesn't exist or is already the lowest, don't change anything.
             return false;
         }
+
+        final SettingsItem item = mItems.get(idx);
         mItems.remove(item);
         mItems.add(0, item);
-        notifyOverlayPriorityChanged(item.getOverlayInfo());
-        notifySettingsChanged();
         return true;
     }
 
+    /**
+     * Returns true if the settings were modified, false if they remain the same.
+     */
     boolean setHighestPriority(@NonNull final String packageName, final int userId) {
-        final SettingsItem item = select(packageName, userId);
-        if (item == null) {
+        final int idx = select(packageName, userId);
+
+        // If the item doesn't exist or is already the highest, don't change anything.
+        if (idx < 0 || idx == mItems.size() - 1) {
             return false;
         }
-        mItems.remove(item);
+
+        final SettingsItem item = mItems.get(idx);
+        mItems.remove(idx);
         mItems.add(item);
-        notifyOverlayPriorityChanged(item.getOverlayInfo());
-        notifySettingsChanged();
         return true;
     }
 
@@ -296,11 +246,6 @@
 
     void dump(@NonNull final PrintWriter pw) {
         pw.println("Settings");
-        dumpItems(pw);
-        dumpListeners(pw);
-    }
-
-    private void dumpItems(@NonNull final PrintWriter pw) {
         pw.println(TAB1 + "Items");
 
         if (mItems.isEmpty()) {
@@ -312,34 +257,18 @@
         for (int i = 0; i < N; i++) {
             final SettingsItem item = mItems.get(i);
             final StringBuilder sb = new StringBuilder();
-            sb.append(TAB2 + item.packageName + ":" + item.userId + " {\n");
-            sb.append(TAB3 + "packageName.......: " + item.packageName + "\n");
-            sb.append(TAB3 + "userId............: " + item.userId + "\n");
-            sb.append(TAB3 + "targetPackageName.: " + item.getTargetPackageName() + "\n");
-            sb.append(TAB3 + "baseCodePath......: " + item.getBaseCodePath() + "\n");
-            sb.append(TAB3 + "state.............: " + OverlayInfo.stateToString(item.getState()) + "\n");
-            sb.append(TAB3 + "isEnabled.........: " + item.isEnabled() + "\n");
+            sb.append(TAB2 + item.mPackageName + ":" + item.getUserId() + " {\n");
+            sb.append(TAB3 + "mPackageName.......: " + item.mPackageName + "\n");
+            sb.append(TAB3 + "mUserId............: " + item.getUserId() + "\n");
+            sb.append(TAB3 + "mTargetPackageName.: " + item.getTargetPackageName() + "\n");
+            sb.append(TAB3 + "mBaseCodePath......: " + item.getBaseCodePath() + "\n");
+            sb.append(TAB3 + "mState.............: " + OverlayInfo.stateToString(item.getState()) + "\n");
+            sb.append(TAB3 + "mIsEnabled.........: " + item.isEnabled() + "\n");
             sb.append(TAB2 + "}");
             pw.println(sb.toString());
         }
     }
 
-    private void dumpListeners(@NonNull final PrintWriter pw) {
-        pw.println(TAB1 + "Change listeners");
-
-        if (mListeners.isEmpty()) {
-            pw.println(TAB2 + "<none>");
-            return;
-        }
-
-        final int N = mListeners.size();
-        for (int i = 0; i < N; i++) {
-            final ChangeListener ch = mListeners.get(i);
-            pw.println(TAB2 + ch);
-        }
-
-    }
-
     void restore(@NonNull final InputStream is) throws IOException, XmlPullParserException {
         Serializer.restore(mItems, is);
     }
@@ -434,127 +363,122 @@
         private static void persistRow(@NonNull final FastXmlSerializer xml,
                 @NonNull final SettingsItem item) throws IOException {
             xml.startTag(null, TAG_ITEM);
-            XmlUtils.writeStringAttribute(xml, ATTR_PACKAGE_NAME, item.packageName);
-            XmlUtils.writeIntAttribute(xml, ATTR_USER_ID, item.userId);
-            XmlUtils.writeStringAttribute(xml, ATTR_TARGET_PACKAGE_NAME, item.targetPackageName);
-            XmlUtils.writeStringAttribute(xml, ATTR_BASE_CODE_PATH, item.baseCodePath);
-            XmlUtils.writeIntAttribute(xml, ATTR_STATE, item.state);
-            XmlUtils.writeBooleanAttribute(xml, ATTR_IS_ENABLED, item.isEnabled);
+            XmlUtils.writeStringAttribute(xml, ATTR_PACKAGE_NAME, item.mPackageName);
+            XmlUtils.writeIntAttribute(xml, ATTR_USER_ID, item.mUserId);
+            XmlUtils.writeStringAttribute(xml, ATTR_TARGET_PACKAGE_NAME, item.mTargetPackageName);
+            XmlUtils.writeStringAttribute(xml, ATTR_BASE_CODE_PATH, item.mBaseCodePath);
+            XmlUtils.writeIntAttribute(xml, ATTR_STATE, item.mState);
+            XmlUtils.writeBooleanAttribute(xml, ATTR_IS_ENABLED, item.mIsEnabled);
             xml.endTag(null, TAG_ITEM);
         }
     }
 
     private static final class SettingsItem {
-        private final int userId;
-        private final String packageName;
-        private final String targetPackageName;
-        private String baseCodePath;
-        private int state;
-        private boolean isEnabled;
-        private OverlayInfo cache;
+        private final int mUserId;
+        private final String mPackageName;
+        private final String mTargetPackageName;
+        private String mBaseCodePath;
+        private int mState;
+        private boolean mIsEnabled;
+        private OverlayInfo mCache;
 
         SettingsItem(@NonNull final String packageName, final int userId,
                 @NonNull final String targetPackageName, @NonNull final String baseCodePath,
                 final int state, final boolean isEnabled) {
-            this.packageName = packageName;
-            this.userId = userId;
-            this.targetPackageName = targetPackageName;
-            this.baseCodePath = baseCodePath;
-            this.state = state;
-            this.isEnabled = isEnabled;
-            cache = null;
+            mPackageName = packageName;
+            mUserId = userId;
+            mTargetPackageName = targetPackageName;
+            mBaseCodePath = baseCodePath;
+            mState = state;
+            mIsEnabled = isEnabled;
+            mCache = null;
         }
 
         SettingsItem(@NonNull final String packageName, final int userId,
                 @NonNull final String targetPackageName, @NonNull final String baseCodePath) {
-            this(packageName, userId, targetPackageName, baseCodePath, STATE_UNKNOWN,
+            this(packageName, userId, targetPackageName, baseCodePath, OverlayInfo.STATE_UNKNOWN,
                     false);
         }
 
         private String getTargetPackageName() {
-            return targetPackageName;
+            return mTargetPackageName;
+        }
+
+        private int getUserId() {
+            return mUserId;
         }
 
         private String getBaseCodePath() {
-            return baseCodePath;
+            return mBaseCodePath;
         }
 
-        private void setBaseCodePath(@NonNull final String path) {
-            if (!baseCodePath.equals(path)) {
-                baseCodePath = path;
+        private boolean setBaseCodePath(@NonNull final String path) {
+            if (!mBaseCodePath.equals(path)) {
+                mBaseCodePath = path;
                 invalidateCache();
+                return true;
             }
+            return false;
         }
 
         private int getState() {
-            return state;
+            return mState;
         }
 
-        private void setState(final int state) {
-            if (this.state != state) {
-                this.state = state;
+        private boolean setState(final int state) {
+            if (mState != state) {
+                mState = state;
                 invalidateCache();
+                return true;
             }
+            return false;
         }
 
         private boolean isEnabled() {
-            return isEnabled;
+            return mIsEnabled;
         }
 
-        private void setEnabled(final boolean enable) {
-            if (isEnabled != enable) {
-                isEnabled = enable;
+        private boolean setEnabled(final boolean enable) {
+            if (mIsEnabled != enable) {
+                mIsEnabled = enable;
                 invalidateCache();
+                return true;
             }
+            return false;
         }
 
         private OverlayInfo getOverlayInfo() {
-            if (cache == null) {
-                cache = new OverlayInfo(packageName, targetPackageName, baseCodePath,
-                        state, userId);
+            if (mCache == null) {
+                mCache = new OverlayInfo(mPackageName, mTargetPackageName, mBaseCodePath, mState,
+                        mUserId);
             }
-            return cache;
+            return mCache;
         }
 
         private void invalidateCache() {
-            cache = null;
+            mCache = null;
         }
     }
 
-    private SettingsItem select(@NonNull final String packageName, final int userId) {
+    private int select(@NonNull final String packageName, final int userId) {
         final int N = mItems.size();
         for (int i = 0; i < N; i++) {
             final SettingsItem item = mItems.get(i);
-            if (item.userId == userId && item.packageName.equals(packageName)) {
-                return item;
+            if (item.mUserId == userId && item.mPackageName.equals(packageName)) {
+                return i;
             }
         }
-        return null;
+        return -1;
     }
 
-    private List<SettingsItem> selectWhereUser(final int userId) {
-        final ArrayList<SettingsItem> items = new ArrayList<>();
-        final int N = mItems.size();
-        for (int i = 0; i < N; i++) {
-            final SettingsItem item = mItems.get(i);
-            if (item.userId == userId) {
-                items.add(item);
-            }
-        }
-        return items;
+    private Stream<SettingsItem> selectWhereUser(final int userId) {
+        return mItems.stream().filter(item -> item.mUserId == userId);
     }
 
-    private List<SettingsItem> selectWhereTarget(@NonNull final String targetPackageName,
+    private Stream<SettingsItem> selectWhereTarget(@NonNull final String targetPackageName,
             final int userId) {
-        final ArrayList<SettingsItem> items = new ArrayList<>();
-        final int N = mItems.size();
-        for (int i = 0; i < N; i++) {
-            final SettingsItem item = mItems.get(i);
-            if (item.userId == userId && item.getTargetPackageName().equals(targetPackageName)) {
-                items.add(item);
-            }
-        }
-        return items;
+        return selectWhereUser(userId)
+                .filter(item -> item.getTargetPackageName().equals(targetPackageName));
     }
 
     private void assertNotNull(@Nullable final Object o) {
@@ -563,79 +487,9 @@
         }
     }
 
-    void addChangeListener(@NonNull final ChangeListener listener) {
-        mListeners.add(listener);
-    }
-
-    void removeChangeListener(@NonNull final ChangeListener listener) {
-        mListeners.remove(listener);
-    }
-
-    private void notifySettingsChanged() {
-        final int N = mListeners.size();
-        for (int i = 0; i < N; i++) {
-            final ChangeListener listener = mListeners.get(i);
-            listener.onSettingsChanged();
-        }
-    }
-
-    private void notifyOverlayAdded(@NonNull final OverlayInfo oi) {
-        if (DEBUG) {
-            assertNotNull(oi);
-        }
-        final int N = mListeners.size();
-        for (int i = 0; i < N; i++) {
-            final ChangeListener listener = mListeners.get(i);
-            listener.onOverlayAdded(oi);
-        }
-    }
-
-    private void notifyOverlayRemoved(@NonNull final OverlayInfo oi) {
-        if (DEBUG) {
-            assertNotNull(oi);
-        }
-        final int N = mListeners.size();
-        for (int i = 0; i < N; i++) {
-            final ChangeListener listener = mListeners.get(i);
-            listener.onOverlayRemoved(oi);
-        }
-    }
-
-    private void notifyOverlayChanged(@NonNull final OverlayInfo oi,
-            @NonNull final OverlayInfo oldOi) {
-        if (DEBUG) {
-            assertNotNull(oi);
-            assertNotNull(oldOi);
-        }
-        final int N = mListeners.size();
-        for (int i = 0; i < N; i++) {
-            final ChangeListener listener = mListeners.get(i);
-            listener.onOverlayChanged(oi, oldOi);
-        }
-    }
-
-    private void notifyOverlayPriorityChanged(@NonNull final OverlayInfo oi) {
-        if (DEBUG) {
-            assertNotNull(oi);
-        }
-        final int N = mListeners.size();
-        for (int i = 0; i < N; i++) {
-            final ChangeListener listener = mListeners.get(i);
-            listener.onOverlayPriorityChanged(oi);
-        }
-    }
-
-    interface ChangeListener {
-        void onSettingsChanged();
-        void onOverlayAdded(@NonNull OverlayInfo oi);
-        void onOverlayRemoved(@NonNull OverlayInfo oi);
-        void onOverlayChanged(@NonNull OverlayInfo oi, @NonNull OverlayInfo oldOi);
-        void onOverlayPriorityChanged(@NonNull OverlayInfo oi);
-    }
-
     static final class BadKeyException extends RuntimeException {
         BadKeyException(@NonNull final String packageName, final int userId) {
-            super("Bad key packageName=" + packageName + " userId=" + userId);
+            super("Bad key mPackageName=" + packageName + " mUserId=" + userId);
         }
     }
 }
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index dd39590..15b4d85 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -173,6 +173,7 @@
 import android.content.pm.VerifierInfo;
 import android.content.pm.VersionedPackage;
 import android.content.res.Resources;
+import android.database.ContentObserver;
 import android.graphics.Bitmap;
 import android.hardware.display.DisplayManager;
 import android.net.Uri;
@@ -396,7 +397,6 @@
     /** REMOVE. According to Svet, this was only used to reset permissions during development. */
     static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
 
-    private static final boolean DISABLE_EPHEMERAL_APPS = false;
     private static final boolean HIDE_EPHEMERAL_APIS = false;
 
     private static final boolean ENABLE_FREE_CACHE_V2 =
@@ -829,6 +829,7 @@
     volatile boolean mSystemReady;
     volatile boolean mSafeMode;
     volatile boolean mHasSystemUidErrors;
+    private volatile boolean mEphemeralAppsDisabled;
 
     ApplicationInfo mAndroidApplication;
     final ActivityInfo mResolveActivity = new ActivityInfo();
@@ -5703,24 +5704,9 @@
 
     /**
      * Returns whether or not instant apps have been disabled remotely.
-     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
-     * held. Otherwise we run the risk of deadlock.
      */
     private boolean isEphemeralDisabled() {
-        // ephemeral apps have been disabled across the board
-        if (DISABLE_EPHEMERAL_APPS) {
-            return true;
-        }
-        // system isn't up yet; can't read settings, so, assume no ephemeral apps
-        if (!mSystemReady) {
-            return true;
-        }
-        // we can't get a content resolver until the system is ready; these checks must happen last
-        final ContentResolver resolver = mContext.getContentResolver();
-        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
-            return true;
-        }
-        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
+        return mEphemeralAppsDisabled;
     }
 
     private boolean isEphemeralAllowed(
@@ -13391,6 +13377,7 @@
         final PackageRemovedInfo info = new PackageRemovedInfo();
         info.removedPackage = packageName;
         info.removedUsers = new int[] {userId};
+        info.broadcastUsers = new int[] {userId};
         info.uid = UserHandle.getUid(userId, pkgSetting.appId);
         info.sendPackageRemovedBroadcasts(true /*killApp*/);
     }
@@ -18432,6 +18419,7 @@
             outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
             outInfo.removedAppId = ps.appId;
             outInfo.removedUsers = userIds;
+            outInfo.broadcastUsers = userIds;
         }
 
         return true;
@@ -20174,6 +20162,21 @@
     @Override
     public void systemReady() {
         mSystemReady = true;
+        final ContentResolver resolver = mContext.getContentResolver();
+        ContentObserver co = new ContentObserver(mHandler) {
+            @Override
+            public void onChange(boolean selfChange) {
+                mEphemeralAppsDisabled =
+                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
+                                (Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0);
+            }
+        };
+        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
+                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
+                false, co, UserHandle.USER_SYSTEM);
+        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
+                        .getUriFor(Secure.WEB_ACTION_ENABLED), false, co, UserHandle.USER_SYSTEM);
+        co.onChange(true);
 
         // Disable any carrier apps. We do this very early in boot to prevent the apps from being
         // disabled after already being started.
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index 21be742..23058bd 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -1662,7 +1662,7 @@
         return stack;
     }
 
-    void moveStackToDisplay(TaskStack stack) {
+    void moveStackToDisplay(TaskStack stack, boolean onTop) {
         final DisplayContent prevDc = stack.getDisplayContent();
         if (prevDc == null) {
             throw new IllegalStateException("Trying to move stackId=" + stack.mStackId
@@ -1674,7 +1674,7 @@
         }
 
         prevDc.mTaskStackContainers.removeStackFromDisplay(stack);
-        mTaskStackContainers.addStackToDisplay(stack, true /* onTop */);
+        mTaskStackContainers.addStackToDisplay(stack, onTop);
     }
 
     @Override
diff --git a/services/core/java/com/android/server/wm/StackWindowController.java b/services/core/java/com/android/server/wm/StackWindowController.java
index 5d0384e..bf024cf 100644
--- a/services/core/java/com/android/server/wm/StackWindowController.java
+++ b/services/core/java/com/android/server/wm/StackWindowController.java
@@ -100,7 +100,7 @@
         }
     }
 
-    public void reparent(int displayId, Rect outStackBounds) {
+    public void reparent(int displayId, Rect outStackBounds, boolean onTop) {
         synchronized (mWindowMap) {
             if (mContainer == null) {
                 throw new IllegalArgumentException("Trying to move unknown stackId=" + mStackId
@@ -113,7 +113,7 @@
                         + " to unknown displayId=" + displayId);
             }
 
-            targetDc.moveStackToDisplay(mContainer);
+            targetDc.moveStackToDisplay(mContainer, onTop);
             getRawBounds(outStackBounds);
         }
     }
diff --git a/services/net/java/android/net/ip/RouterAdvertisementDaemon.java b/services/net/java/android/net/ip/RouterAdvertisementDaemon.java
index ba1621d..cb3123c 100644
--- a/services/net/java/android/net/ip/RouterAdvertisementDaemon.java
+++ b/services/net/java/android/net/ip/RouterAdvertisementDaemon.java
@@ -16,6 +16,8 @@
 
 package android.net.ip;
 
+import static android.net.util.NetworkConstants.IPV6_MIN_MTU;
+import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH;
 import static android.system.OsConstants.*;
 
 import android.net.IpPrefix;
@@ -69,7 +71,6 @@
     private static final String TAG = RouterAdvertisementDaemon.class.getSimpleName();
     private static final byte ICMPV6_ND_ROUTER_SOLICIT = asByte(133);
     private static final byte ICMPV6_ND_ROUTER_ADVERT  = asByte(134);
-    private static final int IPV6_MIN_MTU = 1280;
     private static final int MIN_RA_HEADER_SIZE = 16;
 
     // Summary of various timers and lifetimes.
@@ -543,6 +544,14 @@
             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
          */
 
+        final HashSet<Inet6Address> filteredDnses = new HashSet<>();
+        for (Inet6Address dns : dnses) {
+            if ((new LinkAddress(dns, RFC7421_PREFIX_LENGTH)).isGlobalPreferred()) {
+                filteredDnses.add(dns);
+            }
+        }
+        if (filteredDnses.isEmpty()) return;
+
         final byte ND_OPTION_RDNSS = 25;
         final byte RDNSS_NUM_8OCTETS = asByte(dnses.size() * 2 + 1);
         ra.put(ND_OPTION_RDNSS)
@@ -550,7 +559,7 @@
           .putShort(asShort(0))
           .putInt(lifetime);
 
-        for (Inet6Address dns : dnses) {
+        for (Inet6Address dns : filteredDnses) {
             // NOTE: If the full of list DNS servers doesn't fit in the packet,
             // this code will cause a buffer overflow and the RA won't include
             // this instance of the option at all.
diff --git a/services/net/java/android/net/util/NetworkConstants.java b/services/net/java/android/net/util/NetworkConstants.java
index 26f3050..a012e0c 100644
--- a/services/net/java/android/net/util/NetworkConstants.java
+++ b/services/net/java/android/net/util/NetworkConstants.java
@@ -36,6 +36,7 @@
      *
      * See also:
      *     - https://tools.ietf.org/html/rfc894
+     *     - https://tools.ietf.org/html/rfc2464
      *     - https://tools.ietf.org/html/rfc7042
      *     - http://www.iana.org/assignments/ethernet-numbers/ethernet-numbers.xhtml
      *     - http://www.iana.org/assignments/ieee-802-numbers/ieee-802-numbers.xhtml
@@ -57,6 +58,8 @@
         FF, FF, FF, FF, FF, FF
     };
 
+    public static final int ETHER_MTU = 1500;
+
     /**
      * ARP constants.
      *
@@ -97,6 +100,7 @@
     public static final int IPV6_SRC_ADDR_OFFSET = 8;
     public static final int IPV6_DST_ADDR_OFFSET = 24;
     public static final int IPV6_ADDR_LEN = 16;
+    public static final int IPV6_MIN_MTU = 1280;
     public static final int RFC7421_PREFIX_LENGTH = 64;
 
     /**
diff --git a/services/print/java/com/android/server/print/CompanionDeviceManagerService.java b/services/print/java/com/android/server/print/CompanionDeviceManagerService.java
index 7790698..d0dfc6c 100644
--- a/services/print/java/com/android/server/print/CompanionDeviceManagerService.java
+++ b/services/print/java/com/android/server/print/CompanionDeviceManagerService.java
@@ -17,6 +17,7 @@
 
 package com.android.server.print;
 
+import static com.android.internal.util.Preconditions.checkArgument;
 import static com.android.internal.util.Preconditions.checkNotNull;
 
 import android.Manifest;
@@ -50,6 +51,7 @@
 import android.util.Slog;
 import android.util.Xml;
 
+import com.android.internal.app.IAppOpsService;
 import com.android.internal.content.PackageMonitor;
 import com.android.internal.util.ArrayUtils;
 import com.android.internal.util.CollectionUtils;
@@ -98,12 +100,15 @@
     private IDeviceIdleController mIdleController;
     private IFindDeviceCallback mFindDeviceCallback;
     private ServiceConnection mServiceConnection;
+    private IAppOpsService mAppOpsManager;
 
     public CompanionDeviceManagerService(Context context) {
         super(context);
         mImpl = new CompanionDeviceManagerImpl();
         mIdleController = IDeviceIdleController.Stub.asInterface(
                 ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
+        mAppOpsManager = IAppOpsService.Stub.asInterface(
+                ServiceManager.getService(Context.APP_OPS_SERVICE));
         registerPackageMonitor();
     }
 
@@ -182,13 +187,14 @@
         public void associate(
                 AssociationRequest request,
                 IFindDeviceCallback callback,
-                String callingPackage) {
+                String callingPackage) throws RemoteException {
             if (DEBUG) {
                 Slog.i(LOG_TAG, "associate(request = " + request + ", callback = " + callback
                         + ", callingPackage = " + callingPackage + ")");
             }
             checkNotNull(request, "Request cannot be null");
             checkNotNull(callback, "Callback cannot be null");
+            checkCallerIsSystemOr(callingPackage);
             final long callingIdentity = Binder.clearCallingIdentity();
             try {
                 //TODO bindServiceAsUser
@@ -203,20 +209,40 @@
 
 
         @Override
-        public List<String> getAssociations(String callingPackage) {
+        public List<String> getAssociations(String callingPackage, int userId)
+                throws RemoteException {
+            checkCallerIsSystemOr(callingPackage, userId);
             return CollectionUtils.map(
-                    readAllAssociations(getUserId(), callingPackage),
+                    readAllAssociations(userId, callingPackage),
                     a -> a.deviceAddress);
         }
 
         @Override
-        public void disassociate(String deviceMacAddress, String callingPackage) {
-            updateAssociations((associations) -> ArrayUtils.remove(associations,
-                    new Association(getUserId(), checkNotNull(deviceMacAddress), callingPackage)));
+        public void disassociate(String deviceMacAddress, String callingPackage)
+                throws RemoteException {
+            checkNotNull(deviceMacAddress);
+            checkCallerIsSystemOr(callingPackage);
+            updateAssociations(associations -> ArrayUtils.remove(associations,
+                    new Association(getCallingUserId(), deviceMacAddress, callingPackage)));
+        }
+
+        private void checkCallerIsSystemOr(String pkg) throws RemoteException {
+            checkCallerIsSystemOr(pkg, getCallingUserId());
+        }
+
+        private void checkCallerIsSystemOr(String pkg, int userId) throws RemoteException {
+            if (getCallingUserId() == UserHandle.USER_SYSTEM) {
+                return;
+            }
+
+            checkArgument(getCallingUserId() == userId,
+                    "Must be called by either same user or system");
+
+            mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
         }
     }
 
-    private int getUserId() {
+    private int getCallingUserId() {
         return UserHandle.getUserId(Binder.getCallingUid());
     }
 
@@ -320,11 +346,11 @@
 
     private void recordAssociation(String priviledgedPackage, String deviceAddress) {
         updateAssociations((associations) -> ArrayUtils.add(associations,
-                new Association(getUserId(), deviceAddress, priviledgedPackage)));
+                new Association(getCallingUserId(), deviceAddress, priviledgedPackage)));
     }
 
     private void updateAssociations(Function<ArrayList<Association>, List<Association>> update) {
-        updateAssociations(update, getUserId());
+        updateAssociations(update, getCallingUserId());
     }
 
     private void updateAssociations(Function<ArrayList<Association>, List<Association>> update,
diff --git a/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java b/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java
index d7d365e..0270bb9 100644
--- a/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java
@@ -181,7 +181,7 @@
         assertEquals(dc, token.getDisplayContent());
 
         // Move stack to first display.
-        sDisplayContent.moveStackToDisplay(stack);
+        sDisplayContent.moveStackToDisplay(stack, true /* onTop */);
         assertEquals(sDisplayContent.getDisplayId(), stack.getDisplayContent().getDisplayId());
         assertEquals(sDisplayContent, stack.getParent().getParent());
         assertEquals(sDisplayContent, stack.getDisplayContent());
diff --git a/services/tests/servicestests/src/com/android/server/wm/StackWindowControllerTests.java b/services/tests/servicestests/src/com/android/server/wm/StackWindowControllerTests.java
index 13098f6..61f7f57 100644
--- a/services/tests/servicestests/src/com/android/server/wm/StackWindowControllerTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/StackWindowControllerTests.java
@@ -103,7 +103,7 @@
         final TaskStack stack2 = stack2Controller.mContainer;
 
         // Reparent
-        stack1Controller.reparent(dc.getDisplayId(), new Rect());
+        stack1Controller.reparent(dc.getDisplayId(), new Rect(), true /* onTop */);
         assertEquals(dc, stack1.getDisplayContent());
         final int stack1PositionInParent = stack1.getParent().mChildren.indexOf(stack1);
         final int stack2PositionInParent = stack1.getParent().mChildren.indexOf(stack2);
diff --git a/services/usage/java/com/android/server/usage/StorageStatsService.java b/services/usage/java/com/android/server/usage/StorageStatsService.java
index 3f39e4f..5ad7f80 100644
--- a/services/usage/java/com/android/server/usage/StorageStatsService.java
+++ b/services/usage/java/com/android/server/usage/StorageStatsService.java
@@ -162,6 +162,9 @@
             return FileUtils.roundStorageSize(mStorage.getPrimaryStorageSize());
         } else {
             final VolumeInfo vol = mStorage.findVolumeByUuid(volumeUuid);
+            if (vol == null) {
+                throw new IllegalStateException("Volume was unexpected null");
+            }
             return FileUtils.roundStorageSize(vol.disk.size);
         }
     }
@@ -185,6 +188,9 @@
             return Environment.getDataDirectory().getUsableSpace() + cacheBytes;
         } else {
             final VolumeInfo vol = mStorage.findVolumeByUuid(volumeUuid);
+            if (vol == null) {
+                throw new IllegalStateException("Volume was unexpected null");
+            }
             return vol.getPath().getUsableSpace() + cacheBytes;
         }
     }
diff --git a/services/usb/java/com/android/server/usb/UsbDeviceManager.java b/services/usb/java/com/android/server/usb/UsbDeviceManager.java
index b5a87ca..80b73d3 100644
--- a/services/usb/java/com/android/server/usb/UsbDeviceManager.java
+++ b/services/usb/java/com/android/server/usb/UsbDeviceManager.java
@@ -640,8 +640,11 @@
                 // Set the new USB configuration.
                 setUsbConfig(oemFunctions);
 
-                // Start up dependent services.
-                updateUsbStateBroadcastIfNeeded(true);
+                if (UsbManager.containsFunction(functions, UsbManager.USB_FUNCTION_MTP)
+                        || UsbManager.containsFunction(functions, UsbManager.USB_FUNCTION_PTP)) {
+                    // Start up dependent services.
+                    updateUsbStateBroadcastIfNeeded(true);
+                }
 
                 if (!waitForState(oemFunctions)) {
                     Slog.e(TAG, "Failed to switch USB config to " + functions);
diff --git a/tests/net/java/com/android/server/connectivity/TetheringTest.java b/tests/net/java/com/android/server/connectivity/TetheringTest.java
index a9f68c8..e527d57 100644
--- a/tests/net/java/com/android/server/connectivity/TetheringTest.java
+++ b/tests/net/java/com/android/server/connectivity/TetheringTest.java
@@ -16,22 +16,43 @@
 
 package com.android.server.connectivity;
 
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.any;
 import static org.mockito.Matchers.anyBoolean;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyString;
 import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
 import static org.mockito.Mockito.when;
 
 import android.content.Context;
+import android.content.ContextWrapper;
+import android.content.Intent;
 import android.content.res.Resources;
+import android.hardware.usb.UsbManager;
+import android.net.ConnectivityManager;
+import android.net.ConnectivityManager.NetworkCallback;
 import android.net.INetworkPolicyManager;
 import android.net.INetworkStatsService;
+import android.net.InterfaceConfiguration;
+import android.net.NetworkRequest;
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiManager;
+import android.os.Handler;
 import android.os.INetworkManagementService;
 import android.os.PersistableBundle;
 import android.os.test.TestLooper;
+import android.os.UserHandle;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
 import android.telephony.CarrierConfigManager;
 
+import com.android.internal.util.test.BroadcastInterceptingContext;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -44,34 +65,60 @@
     private static final String[] PROVISIONING_APP_NAME = {"some", "app"};
 
     @Mock private Context mContext;
+    @Mock private ConnectivityManager mConnectivityManager;
     @Mock private INetworkManagementService mNMService;
     @Mock private INetworkStatsService mStatsService;
     @Mock private INetworkPolicyManager mPolicyManager;
     @Mock private MockableSystemProperties mSystemProperties;
     @Mock private Resources mResources;
+    @Mock private UsbManager mUsbManager;
+    @Mock private WifiManager mWifiManager;
     @Mock private CarrierConfigManager mCarrierConfigManager;
 
     // Like so many Android system APIs, these cannot be mocked because it is marked final.
     // We have to use the real versions.
     private final PersistableBundle mCarrierConfig = new PersistableBundle();
     private final TestLooper mLooper = new TestLooper();
+    private final String mTestIfname = "test_wlan0";
 
+    private BroadcastInterceptingContext mServiceContext;
     private Tethering mTethering;
 
+    private class MockContext extends BroadcastInterceptingContext {
+        MockContext(Context base) {
+            super(base);
+        }
+
+        @Override
+        public Resources getResources() { return mResources; }
+
+        @Override
+        public Object getSystemService(String name) {
+            if (Context.CONNECTIVITY_SERVICE.equals(name)) return mConnectivityManager;
+            if (Context.WIFI_SERVICE.equals(name)) return mWifiManager;
+            return super.getSystemService(name);
+        }
+    }
+
     @Before public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
-        when(mContext.getResources()).thenReturn(mResources);
         when(mResources.getStringArray(com.android.internal.R.array.config_tether_dhcp_range))
                 .thenReturn(new String[0]);
         when(mResources.getStringArray(com.android.internal.R.array.config_tether_usb_regexs))
                 .thenReturn(new String[0]);
         when(mResources.getStringArray(com.android.internal.R.array.config_tether_wifi_regexs))
-                .thenReturn(new String[0]);
+                .thenReturn(new String[]{ "test_wlan\\d" });
         when(mResources.getStringArray(com.android.internal.R.array.config_tether_bluetooth_regexs))
                 .thenReturn(new String[0]);
         when(mResources.getIntArray(com.android.internal.R.array.config_tether_upstream_types))
                 .thenReturn(new int[0]);
-        mTethering = new Tethering(mContext, mNMService, mStatsService, mPolicyManager,
+        when(mNMService.listInterfaces())
+                .thenReturn(new String[]{ "test_rmnet_data0", mTestIfname });
+        when(mNMService.getInterfaceConfig(anyString()))
+                .thenReturn(new InterfaceConfiguration());
+
+        mServiceContext = new MockContext(mContext);
+        mTethering = new Tethering(mServiceContext, mNMService, mStatsService, mPolicyManager,
                                    mLooper.getLooper(), mSystemProperties);
     }
 
@@ -126,4 +173,144 @@
                 .thenReturn(new String[] {"malformedApp"});
         assertTrue(!mTethering.isTetherProvisioningRequired());
     }
+
+    private void sendWifiApStateChanged(int state) {
+        final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
+        intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, state);
+        mServiceContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
+    }
+
+    @Test
+    public void workingLocalOnlyHotspot() throws Exception {
+        when(mConnectivityManager.isTetheringSupported()).thenReturn(true);
+        when(mWifiManager.setWifiApEnabled(any(WifiConfiguration.class), anyBoolean()))
+                .thenReturn(true);
+
+        // Emulate externally-visible WifiManager effects, causing the
+        // per-interface state machine to start up, and telling us that
+        // hotspot mode is to be started.
+        mTethering.interfaceStatusChanged(mTestIfname, true);
+        sendWifiApStateChanged(WifiManager.WIFI_AP_STATE_ENABLED);
+        mLooper.dispatchAll();
+
+        verify(mNMService, times(1)).listInterfaces();
+        verify(mNMService, times(1)).getInterfaceConfig(mTestIfname);
+        verify(mNMService, times(1))
+                .setInterfaceConfig(eq(mTestIfname), any(InterfaceConfiguration.class));
+        verify(mNMService, times(1)).tetherInterface(mTestIfname);
+        verify(mNMService, times(1)).setIpForwardingEnabled(true);
+        verify(mNMService, times(1)).startTethering(any(String[].class));
+        verifyNoMoreInteractions(mNMService);
+        // UpstreamNetworkMonitor will be started, and will register two callbacks:
+        // a "listen all" and a "track default".
+        verify(mConnectivityManager, times(1)).registerNetworkCallback(
+                any(NetworkRequest.class), any(NetworkCallback.class), any(Handler.class));
+        verify(mConnectivityManager, times(1)).registerDefaultNetworkCallback(
+                any(NetworkCallback.class), any(Handler.class));
+        // TODO: Figure out why this isn't exactly once, for sendTetherStateChangedBroadcast().
+        verify(mConnectivityManager, atLeastOnce()).isTetheringSupported();
+        verifyNoMoreInteractions(mConnectivityManager);
+
+        // Emulate externally-visible WifiManager effects, when hotspot mode
+        // is being torn down.
+        sendWifiApStateChanged(WifiManager.WIFI_AP_STATE_DISABLED);
+        mTethering.interfaceRemoved(mTestIfname);
+        mLooper.dispatchAll();
+
+        verify(mNMService, times(1)).untetherInterface(mTestIfname);
+        // TODO: Why is {g,s}etInterfaceConfig() called more than once?
+        verify(mNMService, atLeastOnce()).getInterfaceConfig(mTestIfname);
+        verify(mNMService, atLeastOnce())
+                .setInterfaceConfig(eq(mTestIfname), any(InterfaceConfiguration.class));
+        verify(mNMService, times(1)).stopTethering();
+        verify(mNMService, times(1)).setIpForwardingEnabled(false);
+        verifyNoMoreInteractions(mNMService);
+        // Asking for the last error after the per-interface state machine
+        // has been reaped yields an unknown interface error.
+        assertEquals(ConnectivityManager.TETHER_ERROR_UNKNOWN_IFACE,
+                mTethering.getLastTetherError(mTestIfname));
+    }
+
+    @Test
+    public void workingWifiTethering() throws Exception {
+        when(mConnectivityManager.isTetheringSupported()).thenReturn(true);
+        when(mWifiManager.setWifiApEnabled(any(WifiConfiguration.class), anyBoolean()))
+                .thenReturn(true);
+
+        // Emulate pressing the WiFi tethering button.
+        mTethering.startTethering(ConnectivityManager.TETHERING_WIFI, null, false);
+        mLooper.dispatchAll();
+        verify(mWifiManager, times(1)).setWifiApEnabled(null, true);
+        verifyNoMoreInteractions(mWifiManager);
+        verifyNoMoreInteractions(mConnectivityManager);
+        verifyNoMoreInteractions(mNMService);
+
+        // Emulate externally-visible WifiManager effects, causing the
+        // per-interface state machine to start up, and telling us that
+        // tethering mode is to be started.
+        mTethering.interfaceStatusChanged(mTestIfname, true);
+        sendWifiApStateChanged(WifiManager.WIFI_AP_STATE_ENABLED);
+        mLooper.dispatchAll();
+
+        verify(mNMService, times(1)).listInterfaces();
+        verify(mNMService, times(1)).getInterfaceConfig(mTestIfname);
+        verify(mNMService, times(1))
+                .setInterfaceConfig(eq(mTestIfname), any(InterfaceConfiguration.class));
+        verify(mNMService, times(1)).tetherInterface(mTestIfname);
+        verify(mNMService, times(1)).setIpForwardingEnabled(true);
+        verify(mNMService, times(1)).startTethering(any(String[].class));
+        verifyNoMoreInteractions(mNMService);
+        // UpstreamNetworkMonitor will be started, and will register two callbacks:
+        // a "listen all" and a "track default".
+        verify(mConnectivityManager, times(1)).registerNetworkCallback(
+                any(NetworkRequest.class), any(NetworkCallback.class), any(Handler.class));
+        verify(mConnectivityManager, times(1)).registerDefaultNetworkCallback(
+                any(NetworkCallback.class), any(Handler.class));
+        // In tethering mode, in the default configuration, an explicit request
+        // for a mobile network is also made.
+        verify(mConnectivityManager, atLeastOnce()).getNetworkInfo(anyInt());
+        verify(mConnectivityManager, times(1)).requestNetwork(
+                any(NetworkRequest.class), any(NetworkCallback.class), eq(0), anyInt(),
+                any(Handler.class));
+        // TODO: Figure out why this isn't exactly once, for sendTetherStateChangedBroadcast().
+        verify(mConnectivityManager, atLeastOnce()).isTetheringSupported();
+        verifyNoMoreInteractions(mConnectivityManager);
+
+        /////
+        // We do not currently emulate any upstream being found.
+        //
+        // This is why there are no calls to verify mNMService.enableNat() or
+        // mNMService.startInterfaceForwarding().
+        /////
+
+        // Emulate pressing the WiFi tethering button.
+        mTethering.stopTethering(ConnectivityManager.TETHERING_WIFI);
+        mLooper.dispatchAll();
+        verify(mWifiManager, times(1)).setWifiApEnabled(null, false);
+        verifyNoMoreInteractions(mWifiManager);
+        verifyNoMoreInteractions(mConnectivityManager);
+        verifyNoMoreInteractions(mNMService);
+
+        // Emulate externally-visible WifiManager effects, when tethering mode
+        // is being torn down.
+        sendWifiApStateChanged(WifiManager.WIFI_AP_STATE_DISABLED);
+        mTethering.interfaceRemoved(mTestIfname);
+        mLooper.dispatchAll();
+
+        verify(mNMService, times(1)).untetherInterface(mTestIfname);
+        // TODO: Why is {g,s}etInterfaceConfig() called more than once?
+        verify(mNMService, atLeastOnce()).getInterfaceConfig(mTestIfname);
+        verify(mNMService, atLeastOnce())
+                .setInterfaceConfig(eq(mTestIfname), any(InterfaceConfiguration.class));
+        verify(mNMService, times(1)).stopTethering();
+        verify(mNMService, times(1)).setIpForwardingEnabled(false);
+        verifyNoMoreInteractions(mNMService);
+        // Asking for the last error after the per-interface state machine
+        // has been reaped yields an unknown interface error.
+        assertEquals(ConnectivityManager.TETHER_ERROR_UNKNOWN_IFACE,
+                mTethering.getLastTetherError(mTestIfname));
+    }
+
+    // TODO: Test that a request for hotspot mode doesn't interface with an
+    // already operating tethering mode interface.
 }
diff --git a/tests/net/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachineTest.java b/tests/net/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachineTest.java
index 32e1b96..caf1a55 100644
--- a/tests/net/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachineTest.java
+++ b/tests/net/java/com/android/server/connectivity/tethering/TetherInterfaceStateMachineTest.java
@@ -32,6 +32,7 @@
 import static android.net.ConnectivityManager.TETHERING_USB;
 import static android.net.ConnectivityManager.TETHERING_WIFI;
 import static com.android.server.connectivity.tethering.IControlsTethering.STATE_AVAILABLE;
+import static com.android.server.connectivity.tethering.IControlsTethering.STATE_LOCAL_HOTSPOT;
 import static com.android.server.connectivity.tethering.IControlsTethering.STATE_TETHERED;
 import static com.android.server.connectivity.tethering.IControlsTethering.STATE_UNAVAILABLE;
 
@@ -80,7 +81,7 @@
 
     private void initTetheredStateMachine(int interfaceType, String upstreamIface) throws Exception {
         initStateMachine(interfaceType);
-        dispatchCommand(TetherInterfaceStateMachine.CMD_TETHER_REQUESTED);
+        dispatchCommand(TetherInterfaceStateMachine.CMD_TETHER_REQUESTED, STATE_TETHERED);
         if (upstreamIface != null) {
             dispatchTetherConnectionChanged(upstreamIface);
         }
@@ -138,7 +139,7 @@
     public void canBeTethered() throws Exception {
         initStateMachine(TETHERING_BLUETOOTH);
 
-        dispatchCommand(TetherInterfaceStateMachine.CMD_TETHER_REQUESTED);
+        dispatchCommand(TetherInterfaceStateMachine.CMD_TETHER_REQUESTED, STATE_TETHERED);
         InOrder inOrder = inOrder(mTetherHelper, mNMService);
         inOrder.verify(mNMService).tetherInterface(IFACE_NAME);
         inOrder.verify(mTetherHelper).notifyInterfaceStateChange(
@@ -162,7 +163,7 @@
     public void canBeTetheredAsUsb() throws Exception {
         initStateMachine(TETHERING_USB);
 
-        dispatchCommand(TetherInterfaceStateMachine.CMD_TETHER_REQUESTED);
+        dispatchCommand(TetherInterfaceStateMachine.CMD_TETHER_REQUESTED, STATE_TETHERED);
         InOrder inOrder = inOrder(mTetherHelper, mNMService);
         inOrder.verify(mNMService).getInterfaceConfig(IFACE_NAME);
         inOrder.verify(mNMService).setInterfaceConfig(IFACE_NAME, mInterfaceConfiguration);
@@ -272,7 +273,7 @@
         initStateMachine(TETHERING_USB);
 
         doThrow(RemoteException.class).when(mNMService).tetherInterface(IFACE_NAME);
-        dispatchCommand(TetherInterfaceStateMachine.CMD_TETHER_REQUESTED);
+        dispatchCommand(TetherInterfaceStateMachine.CMD_TETHER_REQUESTED, STATE_TETHERED);
         InOrder usbTeardownOrder = inOrder(mNMService, mInterfaceConfiguration, mTetherHelper);
         usbTeardownOrder.verify(mInterfaceConfiguration).setInterfaceDown();
         usbTeardownOrder.verify(mNMService).setInterfaceConfig(
@@ -310,6 +311,17 @@
      * Send a command to the state machine under test, and run the event loop to idle.
      *
      * @param command One of the TetherInterfaceStateMachine.CMD_* constants.
+     * @param obj An additional argument to pass.
+     */
+    private void dispatchCommand(int command, int arg1) {
+        mTestedSm.sendMessage(command, arg1);
+        mLooper.dispatchAll();
+    }
+
+    /**
+     * Send a command to the state machine under test, and run the event loop to idle.
+     *
+     * @param command One of the TetherInterfaceStateMachine.CMD_* constants.
      */
     private void dispatchCommand(int command) {
         mTestedSm.sendMessage(command);
diff --git a/tools/aapt2/Android.bp b/tools/aapt2/Android.bp
index ef3797c..b460258 100644
--- a/tools/aapt2/Android.bp
+++ b/tools/aapt2/Android.bp
@@ -15,11 +15,12 @@
 //
 
 toolSources = [
-    "compile/Compile.cpp",
-    "diff/Diff.cpp",
-    "dump/Dump.cpp",
-    "link/Link.cpp",
-    "optimize/Optimize.cpp",
+    "cmd/Compile.cpp",
+    "cmd/Diff.cpp",
+    "cmd/Dump.cpp",
+    "cmd/Link.cpp",
+    "cmd/Optimize.cpp",
+    "cmd/Util.cpp",
 ]
 
 cc_defaults {
@@ -90,7 +91,7 @@
         "io/BigBufferStreams.cpp",
         "io/File.cpp",
         "io/FileSystem.cpp",
-        "io/Io.cpp",
+        "io/Util.cpp",
         "io/ZipArchive.cpp",
         "link/AutoVersioner.cpp",
         "link/ManifestFixer.cpp",
diff --git a/tools/aapt2/AppInfo.h b/tools/aapt2/AppInfo.h
index 9db21aa..d6f5995 100644
--- a/tools/aapt2/AppInfo.h
+++ b/tools/aapt2/AppInfo.h
@@ -29,7 +29,7 @@
   std::string package;
 
   // The app's minimum SDK version, if it is defined.
-  Maybe<std::string> min_sdk_version;
+  Maybe<int> min_sdk_version;
 
   // The app's version code, if it is defined.
   Maybe<uint32_t> version_code;
diff --git a/tools/aapt2/LoadedApk.cpp b/tools/aapt2/LoadedApk.cpp
index b855f8f..8a8f8be 100644
--- a/tools/aapt2/LoadedApk.cpp
+++ b/tools/aapt2/LoadedApk.cpp
@@ -21,6 +21,7 @@
 #include "flatten/Archive.h"
 #include "flatten/TableFlattener.h"
 #include "io/BigBufferInputStream.h"
+#include "io/Util.h"
 
 namespace aapt {
 
@@ -47,11 +48,10 @@
   }
 
   std::unique_ptr<ResourceTable> table = util::make_unique<ResourceTable>();
-  BinaryResourceParser parser(context, table.get(), source, data->data(), data->size());
+  BinaryResourceParser parser(context, table.get(), source, data->data(), data->size(), apk.get());
   if (!parser.Parse()) {
     return {};
   }
-
   return util::make_unique<LoadedApk>(source, std::move(apk), std::move(table));
 }
 
@@ -100,20 +100,16 @@
       }
 
       io::BigBufferInputStream input_stream(&buffer);
-      if (!writer->WriteFile(path, ArchiveEntry::kAlign, &input_stream)) {
-        context->GetDiagnostics()->Error(DiagMessage()
-                                         << "Error when writing file '" << path << "' in APK.");
+      if (!io::CopyInputStreamToArchive(context, &input_stream, path, ArchiveEntry::kAlign,
+                                        writer)) {
         return false;
       }
-      continue;
-    }
 
-    std::unique_ptr<io::IData> data = file->OpenAsData();
-    uint32_t compression_flags = file->WasCompressed() ? ArchiveEntry::kCompress : 0u;
-    if (!writer->WriteFile(path, compression_flags, data.get())) {
-      context->GetDiagnostics()->Error(DiagMessage()
-                                       << "Error when writing file '" << path << "' in APK.");
-      return false;
+    } else {
+      uint32_t compression_flags = file->WasCompressed() ? ArchiveEntry::kCompress : 0u;
+      if (!io::CopyFileToArchive(context, file, path, compression_flags, writer)) {
+        return false;
+      }
     }
   }
   return true;
diff --git a/tools/aapt2/Main.cpp b/tools/aapt2/Main.cpp
index 36c1de6..87fda16 100644
--- a/tools/aapt2/Main.cpp
+++ b/tools/aapt2/Main.cpp
@@ -25,7 +25,7 @@
 static const char* sMajorVersion = "2";
 
 // Update minor version whenever a feature or flag is added.
-static const char* sMinorVersion = "12";
+static const char* sMinorVersion = "13";
 
 int PrintVersion() {
   std::cerr << "Android Asset Packaging Tool (aapt) " << sMajorVersion << "."
diff --git a/tools/aapt2/ResourceUtils.cpp b/tools/aapt2/ResourceUtils.cpp
index ca6738b..1bb7d9b 100644
--- a/tools/aapt2/ResourceUtils.cpp
+++ b/tools/aapt2/ResourceUtils.cpp
@@ -675,5 +675,65 @@
   return out.str();
 }
 
+std::unique_ptr<Item> ParseBinaryResValue(const ResourceType& type, const ConfigDescription& config,
+                                          const android::ResStringPool& src_pool,
+                                          const android::Res_value& res_value,
+                                          StringPool* dst_pool) {
+  if (type == ResourceType::kId) {
+    return util::make_unique<Id>();
+  }
+
+  const uint32_t data = util::DeviceToHost32(res_value.data);
+  switch (res_value.dataType) {
+    case android::Res_value::TYPE_STRING: {
+      const std::string str = util::GetString(src_pool, data);
+      const android::ResStringPool_span* spans = src_pool.styleAt(data);
+
+      // Check if the string has a valid style associated with it.
+      if (spans != nullptr && spans->name.index != android::ResStringPool_span::END) {
+        StyleString style_str = {str};
+        while (spans->name.index != android::ResStringPool_span::END) {
+          style_str.spans.push_back(Span{util::GetString(src_pool, spans->name.index),
+                                         spans->firstChar, spans->lastChar});
+          spans++;
+        }
+        return util::make_unique<StyledString>(dst_pool->MakeRef(
+            style_str, StringPool::Context(StringPool::Context::kStylePriority, config)));
+      } else {
+        if (type != ResourceType::kString && util::StartsWith(str, "res/")) {
+          // This must be a FileReference.
+          return util::make_unique<FileReference>(dst_pool->MakeRef(
+              str, StringPool::Context(StringPool::Context::kHighPriority, config)));
+        }
+
+        // There are no styles associated with this string, so treat it as a simple string.
+        return util::make_unique<String>(dst_pool->MakeRef(str, StringPool::Context(config)));
+      }
+    } break;
+
+    case android::Res_value::TYPE_REFERENCE:
+    case android::Res_value::TYPE_ATTRIBUTE:
+    case android::Res_value::TYPE_DYNAMIC_REFERENCE:
+    case android::Res_value::TYPE_DYNAMIC_ATTRIBUTE: {
+      Reference::Type ref_type = Reference::Type::kResource;
+      if (res_value.dataType == android::Res_value::TYPE_ATTRIBUTE ||
+          res_value.dataType == android::Res_value::TYPE_DYNAMIC_ATTRIBUTE) {
+        ref_type = Reference::Type::kAttribute;
+      }
+
+      if (data == 0) {
+        // A reference of 0, must be the magic @null reference.
+        return util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_REFERENCE, 0u);
+      }
+
+      // This is a normal reference.
+      return util::make_unique<Reference>(data, ref_type);
+    } break;
+  }
+
+  // Treat this as a raw binary primitive.
+  return util::make_unique<BinaryPrimitive>(res_value);
+}
+
 }  // namespace ResourceUtils
 }  // namespace aapt
diff --git a/tools/aapt2/ResourceUtils.h b/tools/aapt2/ResourceUtils.h
index 59b78f4..48922b7 100644
--- a/tools/aapt2/ResourceUtils.h
+++ b/tools/aapt2/ResourceUtils.h
@@ -20,11 +20,13 @@
 #include <functional>
 #include <memory>
 
+#include "androidfw/ResourceTypes.h"
 #include "androidfw/StringPiece.h"
 
 #include "NameMangler.h"
 #include "Resource.h"
 #include "ResourceValues.h"
+#include "StringPool.h"
 
 namespace aapt {
 namespace ResourceUtils {
@@ -200,6 +202,13 @@
 std::string BuildResourceFileName(const ResourceFile& res_file,
                                   const NameMangler* mangler = nullptr);
 
+// Parses the binary form of a resource value. `type` is used as a hint to know when a value is
+// an ID versus a False boolean value, etc. `config` is for sorting strings in the string pool.
+std::unique_ptr<Item> ParseBinaryResValue(const ResourceType& type, const ConfigDescription& config,
+                                          const android::ResStringPool& src_pool,
+                                          const android::Res_value& res_value,
+                                          StringPool* dst_pool);
+
 }  // namespace ResourceUtils
 }  // namespace aapt
 
diff --git a/tools/aapt2/StringPool.h b/tools/aapt2/StringPool.h
index a626d37..d1232a2 100644
--- a/tools/aapt2/StringPool.h
+++ b/tools/aapt2/StringPool.h
@@ -23,6 +23,7 @@
 #include <unordered_map>
 #include <vector>
 
+#include "android-base/macros.h"
 #include "androidfw/StringPiece.h"
 
 #include "ConfigDescription.h"
@@ -148,7 +149,8 @@
   static bool FlattenUtf16(BigBuffer* out, const StringPool& pool);
 
   StringPool() = default;
-  StringPool(const StringPool&) = delete;
+  StringPool(StringPool&&) = default;
+  StringPool& operator=(StringPool&&) = default;
 
   /**
    * Adds a string to the pool, unless it already exists. Returns
@@ -208,6 +210,8 @@
   void Prune();
 
  private:
+  DISALLOW_COPY_AND_ASSIGN(StringPool);
+
   friend const_iterator begin(const StringPool& pool);
   friend const_iterator end(const StringPool& pool);
 
diff --git a/tools/aapt2/compile/Compile.cpp b/tools/aapt2/cmd/Compile.cpp
similarity index 83%
rename from tools/aapt2/compile/Compile.cpp
rename to tools/aapt2/cmd/Compile.cpp
index 1fe30f0..578a8fb 100644
--- a/tools/aapt2/compile/Compile.cpp
+++ b/tools/aapt2/cmd/Compile.cpp
@@ -38,6 +38,7 @@
 #include "flatten/Archive.h"
 #include "flatten/XmlFlattener.h"
 #include "io/BigBufferOutputStream.h"
+#include "io/Util.h"
 #include "proto/ProtoSerialize.h"
 #include "util/Files.h"
 #include "util/Maybe.h"
@@ -138,9 +139,8 @@
 /**
  * Walks the res directory structure, looking for resource files.
  */
-static bool LoadInputFilesFromDir(
-    IAaptContext* context, const CompileOptions& options,
-    std::vector<ResourcePathData>* out_path_data) {
+static bool LoadInputFilesFromDir(IAaptContext* context, const CompileOptions& options,
+                                  std::vector<ResourcePathData>* out_path_data) {
   const std::string& root_dir = options.res_dir.value();
   std::unique_ptr<DIR, decltype(closedir)*> d(opendir(root_dir.data()), closedir);
   if (!d) {
@@ -190,8 +190,7 @@
 }
 
 static bool CompileTable(IAaptContext* context, const CompileOptions& options,
-                         const ResourcePathData& path_data,
-                         IArchiveWriter* writer,
+                         const ResourcePathData& path_data, IArchiveWriter* writer,
                          const std::string& output_path) {
   ResourceTable table;
   {
@@ -210,11 +209,9 @@
 
     // If the filename includes donottranslate, then the default translatable is
     // false.
-    parser_options.translatable =
-        path_data.name.find("donottranslate") == std::string::npos;
+    parser_options.translatable = path_data.name.find("donottranslate") == std::string::npos;
 
-    ResourceParser res_parser(context->GetDiagnostics(), &table,
-                              path_data.source, path_data.config,
+    ResourceParser res_parser(context->GetDiagnostics(), &table, path_data.source, path_data.config,
                               parser_options);
     if (!res_parser.Parse(&xml_parser)) {
       return false;
@@ -273,10 +270,8 @@
   return true;
 }
 
-static bool WriteHeaderAndBufferToWriter(const StringPiece& output_path,
-                                         const ResourceFile& file,
-                                         const BigBuffer& buffer,
-                                         IArchiveWriter* writer,
+static bool WriteHeaderAndBufferToWriter(const StringPiece& output_path, const ResourceFile& file,
+                                         const BigBuffer& buffer, IArchiveWriter* writer,
                                          IDiagnostics* diag) {
   // Start the entry so we can write the header.
   if (!writer->StartEntry(output_path, 0)) {
@@ -312,10 +307,8 @@
   return true;
 }
 
-static bool WriteHeaderAndMmapToWriter(const StringPiece& output_path,
-                                       const ResourceFile& file,
-                                       const android::FileMap& map,
-                                       IArchiveWriter* writer,
+static bool WriteHeaderAndMmapToWriter(const StringPiece& output_path, const ResourceFile& file,
+                                       const android::FileMap& map, IArchiveWriter* writer,
                                        IDiagnostics* diag) {
   // Start the entry so we can write the header.
   if (!writer->StartEntry(output_path, 0)) {
@@ -334,8 +327,7 @@
     // Number of CompiledFiles.
     output_stream.WriteLittleEndian32(1);
 
-    std::unique_ptr<pb::CompiledFile> compiled_file =
-        SerializeCompiledFileToPb(file);
+    std::unique_ptr<pb::CompiledFile> compiled_file = SerializeCompiledFileToPb(file);
     output_stream.WriteCompiledFile(compiled_file.get());
     output_stream.WriteData(map.getDataPtr(), map.getDataLength());
 
@@ -352,10 +344,8 @@
   return true;
 }
 
-static bool FlattenXmlToOutStream(IAaptContext* context,
-                                  const StringPiece& output_path,
-                                  xml::XmlResource* xmlres,
-                                  CompiledFileOutputStream* out) {
+static bool FlattenXmlToOutStream(IAaptContext* context, const StringPiece& output_path,
+                                  xml::XmlResource* xmlres, CompiledFileOutputStream* out) {
   BigBuffer buffer(1024);
   XmlFlattenerOptions xml_flattener_options;
   xml_flattener_options.keep_raw_values = true;
@@ -376,8 +366,8 @@
 }
 
 static bool CompileXml(IAaptContext* context, const CompileOptions& options,
-                       const ResourcePathData& path_data,
-                       IArchiveWriter* writer, const std::string& output_path) {
+                       const ResourcePathData& path_data, IArchiveWriter* writer,
+                       const std::string& output_path) {
   if (context->IsVerbose()) {
     context->GetDiagnostics()->Note(DiagMessage(path_data.source) << "compiling XML");
   }
@@ -400,8 +390,7 @@
     return false;
   }
 
-  xmlres->file.name = ResourceName(
-      {}, *ParseResourceType(path_data.resource_dir), path_data.name);
+  xmlres->file.name = ResourceName({}, *ParseResourceType(path_data.resource_dir), path_data.name);
   xmlres->file.config = path_data.config;
   xmlres->file.source = path_data.source;
 
@@ -419,8 +408,7 @@
 
   // Start the entry so we can write the header.
   if (!writer->StartEntry(output_path, 0)) {
-    context->GetDiagnostics()->Error(DiagMessage(output_path)
-                                     << "failed to open file");
+    context->GetDiagnostics()->Error(DiagMessage(output_path) << "failed to open file");
     return false;
   }
 
@@ -439,48 +427,42 @@
     // Number of CompiledFiles.
     output_stream.WriteLittleEndian32(1 + inline_documents.size());
 
-    if (!FlattenXmlToOutStream(context, output_path, xmlres.get(),
-                               &output_stream)) {
+    if (!FlattenXmlToOutStream(context, output_path, xmlres.get(), &output_stream)) {
       return false;
     }
 
     for (auto& inline_xml_doc : inline_documents) {
-      if (!FlattenXmlToOutStream(context, output_path, inline_xml_doc.get(),
-                                 &output_stream)) {
+      if (!FlattenXmlToOutStream(context, output_path, inline_xml_doc.get(), &output_stream)) {
         return false;
       }
     }
   }
 
   if (!writer->FinishEntry()) {
-    context->GetDiagnostics()->Error(DiagMessage(output_path)
-                                     << "failed to finish writing data");
+    context->GetDiagnostics()->Error(DiagMessage(output_path) << "failed to finish writing data");
     return false;
   }
   return true;
 }
 
 static bool CompilePng(IAaptContext* context, const CompileOptions& options,
-                       const ResourcePathData& path_data,
-                       IArchiveWriter* writer, const std::string& output_path) {
+                       const ResourcePathData& path_data, IArchiveWriter* writer,
+                       const std::string& output_path) {
   if (context->IsVerbose()) {
-    context->GetDiagnostics()->Note(DiagMessage(path_data.source)
-                                    << "compiling PNG");
+    context->GetDiagnostics()->Note(DiagMessage(path_data.source) << "compiling PNG");
   }
 
   BigBuffer buffer(4096);
   ResourceFile res_file;
-  res_file.name = ResourceName({}, *ParseResourceType(path_data.resource_dir),
-                               path_data.name);
+  res_file.name = ResourceName({}, *ParseResourceType(path_data.resource_dir), path_data.name);
   res_file.config = path_data.config;
   res_file.source = path_data.source;
 
   {
     std::string content;
     if (!android::base::ReadFileToString(path_data.source.path, &content)) {
-      context->GetDiagnostics()->Error(
-          DiagMessage(path_data.source)
-          << android::base::SystemErrorCodeToString(errno));
+      context->GetDiagnostics()->Error(DiagMessage(path_data.source)
+                                       << android::base::SystemErrorCodeToString(errno));
       return false;
     }
 
@@ -517,8 +499,8 @@
       }
 
       if (context->IsVerbose()) {
-        context->GetDiagnostics()->Note(DiagMessage(path_data.source)
-                                        << "9-patch: " << *nine_patch);
+        context->GetDiagnostics()->Note(DiagMessage(path_data.source) << "9-patch: "
+                                                                      << *nine_patch);
       }
     }
 
@@ -572,26 +554,22 @@
 }
 
 static bool CompileFile(IAaptContext* context, const CompileOptions& options,
-                        const ResourcePathData& path_data,
-                        IArchiveWriter* writer,
+                        const ResourcePathData& path_data, IArchiveWriter* writer,
                         const std::string& output_path) {
   if (context->IsVerbose()) {
-    context->GetDiagnostics()->Note(DiagMessage(path_data.source)
-                                    << "compiling file");
+    context->GetDiagnostics()->Note(DiagMessage(path_data.source) << "compiling file");
   }
 
   BigBuffer buffer(256);
   ResourceFile res_file;
-  res_file.name = ResourceName({}, *ParseResourceType(path_data.resource_dir),
-                               path_data.name);
+  res_file.name = ResourceName({}, *ParseResourceType(path_data.resource_dir), path_data.name);
   res_file.config = path_data.config;
   res_file.source = path_data.source;
 
   std::string error_str;
   Maybe<android::FileMap> f = file::MmapPath(path_data.source.path, &error_str);
   if (!f) {
-    context->GetDiagnostics()->Error(DiagMessage(path_data.source)
-                                     << error_str);
+    context->GetDiagnostics()->Error(DiagMessage(path_data.source) << error_str);
     return false;
   }
 
@@ -604,11 +582,17 @@
 
 class CompileContext : public IAaptContext {
  public:
-  void SetVerbose(bool val) { verbose_ = val; }
+  void SetVerbose(bool val) {
+    verbose_ = val;
+  }
 
-  bool IsVerbose() override { return verbose_; }
+  bool IsVerbose() override {
+    return verbose_;
+  }
 
-  IDiagnostics* GetDiagnostics() override { return &diagnostics_; }
+  IDiagnostics* GetDiagnostics() override {
+    return &diagnostics_;
+  }
 
   NameMangler* GetNameMangler() override {
     abort();
@@ -620,14 +604,18 @@
     return empty;
   }
 
-  uint8_t GetPackageId() override { return 0x0; }
+  uint8_t GetPackageId() override {
+    return 0x0;
+  }
 
   SymbolTable* GetExternalSymbols() override {
     abort();
     return nullptr;
   }
 
-  int GetMinSdkVersion() override { return 0; }
+  int GetMinSdkVersion() override {
+    return 0;
+  }
 
  private:
   StdErrDiagnostics diagnostics_;
@@ -646,16 +634,13 @@
   Flags flags =
       Flags()
           .RequiredFlag("-o", "Output path", &options.output_path)
-          .OptionalFlag("--dir", "Directory to scan for resources",
-                        &options.res_dir)
+          .OptionalFlag("--dir", "Directory to scan for resources", &options.res_dir)
           .OptionalSwitch("--pseudo-localize",
                           "Generate resources for pseudo-locales "
                           "(en-XA and ar-XB)",
                           &options.pseudolocalize)
-          .OptionalSwitch(
-              "--legacy",
-              "Treat errors that used to be valid in AAPT as warnings",
-              &options.legacy_mode)
+          .OptionalSwitch("--legacy", "Treat errors that used to be valid in AAPT as warnings",
+                          &options.legacy_mode)
           .OptionalSwitch("-v", "Enables verbose logging", &verbose);
   if (!flags.Parse("aapt2 compile", args, &std::cerr)) {
     return 1;
@@ -669,8 +654,7 @@
   if (options.res_dir) {
     if (!flags.GetArgs().empty()) {
       // Can't have both files and a resource directory.
-      context.GetDiagnostics()->Error(DiagMessage()
-                                      << "files given but --dir specified");
+      context.GetDiagnostics()->Error(DiagMessage() << "files given but --dir specified");
       flags.Usage("aapt2 compile", &std::cerr);
       return 1;
     }
@@ -679,8 +663,7 @@
       return 1;
     }
 
-    archive_writer = CreateZipFileArchiveWriter(context.GetDiagnostics(),
-                                                options.output_path);
+    archive_writer = CreateZipFileArchiveWriter(context.GetDiagnostics(), options.output_path);
 
   } else {
     input_data.reserve(flags.GetArgs().size());
@@ -688,18 +671,15 @@
     // Collect data from the path for each input file.
     for (const std::string& arg : flags.GetArgs()) {
       std::string error_str;
-      if (Maybe<ResourcePathData> path_data =
-              ExtractResourcePathData(arg, &error_str)) {
+      if (Maybe<ResourcePathData> path_data = ExtractResourcePathData(arg, &error_str)) {
         input_data.push_back(std::move(path_data.value()));
       } else {
-        context.GetDiagnostics()->Error(DiagMessage() << error_str << " ("
-                                                      << arg << ")");
+        context.GetDiagnostics()->Error(DiagMessage() << error_str << " (" << arg << ")");
         return 1;
       }
     }
 
-    archive_writer = CreateDirectoryArchiveWriter(context.GetDiagnostics(),
-                                                  options.output_path);
+    archive_writer = CreateDirectoryArchiveWriter(context.GetDiagnostics(), options.output_path);
   }
 
   if (!archive_writer) {
@@ -709,8 +689,7 @@
   bool error = false;
   for (ResourcePathData& path_data : input_data) {
     if (options.verbose) {
-      context.GetDiagnostics()->Note(DiagMessage(path_data.source)
-                                     << "processing");
+      context.GetDiagnostics()->Note(DiagMessage(path_data.source) << "processing");
     }
 
     if (path_data.resource_dir == "values") {
@@ -718,42 +697,35 @@
       path_data.extension = "arsc";
 
       const std::string output_filename = BuildIntermediateFilename(path_data);
-      if (!CompileTable(&context, options, path_data, archive_writer.get(),
-                        output_filename)) {
+      if (!CompileTable(&context, options, path_data, archive_writer.get(), output_filename)) {
         error = true;
       }
 
     } else {
       const std::string output_filename = BuildIntermediateFilename(path_data);
-      if (const ResourceType* type =
-              ParseResourceType(path_data.resource_dir)) {
+      if (const ResourceType* type = ParseResourceType(path_data.resource_dir)) {
         if (*type != ResourceType::kRaw) {
           if (path_data.extension == "xml") {
-            if (!CompileXml(&context, options, path_data, archive_writer.get(),
-                            output_filename)) {
+            if (!CompileXml(&context, options, path_data, archive_writer.get(), output_filename)) {
               error = true;
             }
-          } else if (path_data.extension == "png" ||
-                     path_data.extension == "9.png") {
-            if (!CompilePng(&context, options, path_data, archive_writer.get(),
-                            output_filename)) {
+          } else if (path_data.extension == "png" || path_data.extension == "9.png") {
+            if (!CompilePng(&context, options, path_data, archive_writer.get(), output_filename)) {
               error = true;
             }
           } else {
-            if (!CompileFile(&context, options, path_data, archive_writer.get(),
-                             output_filename)) {
+            if (!CompileFile(&context, options, path_data, archive_writer.get(), output_filename)) {
               error = true;
             }
           }
         } else {
-          if (!CompileFile(&context, options, path_data, archive_writer.get(),
-                           output_filename)) {
+          if (!CompileFile(&context, options, path_data, archive_writer.get(), output_filename)) {
             error = true;
           }
         }
       } else {
-        context.GetDiagnostics()->Error(
-            DiagMessage() << "invalid file path '" << path_data.source << "'");
+        context.GetDiagnostics()->Error(DiagMessage() << "invalid file path '" << path_data.source
+                                                      << "'");
         error = true;
       }
     }
diff --git a/tools/aapt2/diff/Diff.cpp b/tools/aapt2/cmd/Diff.cpp
similarity index 72%
rename from tools/aapt2/diff/Diff.cpp
rename to tools/aapt2/cmd/Diff.cpp
index dacf8d9..fdc89b2 100644
--- a/tools/aapt2/diff/Diff.cpp
+++ b/tools/aapt2/cmd/Diff.cpp
@@ -28,21 +28,36 @@
 
 class DiffContext : public IAaptContext {
  public:
-  DiffContext() : name_mangler_({}), symbol_table_(&name_mangler_) {}
+  DiffContext() : name_mangler_({}), symbol_table_(&name_mangler_) {
+  }
 
-  const std::string& GetCompilationPackage() override { return empty_; }
+  const std::string& GetCompilationPackage() override {
+    return empty_;
+  }
 
-  uint8_t GetPackageId() override { return 0x0; }
+  uint8_t GetPackageId() override {
+    return 0x0;
+  }
 
-  IDiagnostics* GetDiagnostics() override { return &diagnostics_; }
+  IDiagnostics* GetDiagnostics() override {
+    return &diagnostics_;
+  }
 
-  NameMangler* GetNameMangler() override { return &name_mangler_; }
+  NameMangler* GetNameMangler() override {
+    return &name_mangler_;
+  }
 
-  SymbolTable* GetExternalSymbols() override { return &symbol_table_; }
+  SymbolTable* GetExternalSymbols() override {
+    return &symbol_table_;
+  }
 
-  bool IsVerbose() override { return false; }
+  bool IsVerbose() override {
+    return false;
+  }
 
-  int GetMinSdkVersion() override { return 0; }
+  int GetMinSdkVersion() override {
+    return 0;
+  }
 
  private:
   std::string empty_;
@@ -55,34 +70,31 @@
   std::cerr << source << ": " << message << "\n";
 }
 
-static bool IsSymbolVisibilityDifferent(const Symbol& symbol_a,
-                                        const Symbol& symbol_b) {
+static bool IsSymbolVisibilityDifferent(const Symbol& symbol_a, const Symbol& symbol_b) {
   return symbol_a.state != symbol_b.state;
 }
 
 template <typename Id>
-static bool IsIdDiff(const Symbol& symbol_a, const Maybe<Id>& id_a,
-                     const Symbol& symbol_b, const Maybe<Id>& id_b) {
-  if (symbol_a.state == SymbolState::kPublic ||
-      symbol_b.state == SymbolState::kPublic) {
+static bool IsIdDiff(const Symbol& symbol_a, const Maybe<Id>& id_a, const Symbol& symbol_b,
+                     const Maybe<Id>& id_b) {
+  if (symbol_a.state == SymbolState::kPublic || symbol_b.state == SymbolState::kPublic) {
     return id_a != id_b;
   }
   return false;
 }
 
-static bool EmitResourceConfigValueDiff(
-    IAaptContext* context, LoadedApk* apk_a, ResourceTablePackage* pkg_a,
-    ResourceTableType* type_a, ResourceEntry* entry_a,
-    ResourceConfigValue* config_value_a, LoadedApk* apk_b,
-    ResourceTablePackage* pkg_b, ResourceTableType* type_b,
-    ResourceEntry* entry_b, ResourceConfigValue* config_value_b) {
+static bool EmitResourceConfigValueDiff(IAaptContext* context, LoadedApk* apk_a,
+                                        ResourceTablePackage* pkg_a, ResourceTableType* type_a,
+                                        ResourceEntry* entry_a, ResourceConfigValue* config_value_a,
+                                        LoadedApk* apk_b, ResourceTablePackage* pkg_b,
+                                        ResourceTableType* type_b, ResourceEntry* entry_b,
+                                        ResourceConfigValue* config_value_b) {
   Value* value_a = config_value_a->value.get();
   Value* value_b = config_value_b->value.get();
   if (!value_a->Equals(value_b)) {
     std::stringstream str_stream;
-    str_stream << "value " << pkg_a->name << ":" << type_a->type << "/"
-               << entry_a->name << " config=" << config_value_a->config
-               << " does not match:\n";
+    str_stream << "value " << pkg_a->name << ":" << type_a->type << "/" << entry_a->name
+               << " config=" << config_value_a->config << " does not match:\n";
     value_a->Print(&str_stream);
     str_stream << "\n vs \n";
     value_b->Print(&str_stream);
@@ -93,37 +105,33 @@
 }
 
 static bool EmitResourceEntryDiff(IAaptContext* context, LoadedApk* apk_a,
-                                  ResourceTablePackage* pkg_a,
-                                  ResourceTableType* type_a,
+                                  ResourceTablePackage* pkg_a, ResourceTableType* type_a,
                                   ResourceEntry* entry_a, LoadedApk* apk_b,
-                                  ResourceTablePackage* pkg_b,
-                                  ResourceTableType* type_b,
+                                  ResourceTablePackage* pkg_b, ResourceTableType* type_b,
                                   ResourceEntry* entry_b) {
   bool diff = false;
   for (std::unique_ptr<ResourceConfigValue>& config_value_a : entry_a->values) {
-    ResourceConfigValue* config_value_b =
-        entry_b->FindValue(config_value_a->config);
+    ResourceConfigValue* config_value_b = entry_b->FindValue(config_value_a->config);
     if (!config_value_b) {
       std::stringstream str_stream;
-      str_stream << "missing " << pkg_a->name << ":" << type_a->type << "/"
-                 << entry_a->name << " config=" << config_value_a->config;
+      str_stream << "missing " << pkg_a->name << ":" << type_a->type << "/" << entry_a->name
+                 << " config=" << config_value_a->config;
       EmitDiffLine(apk_b->GetSource(), str_stream.str());
       diff = true;
     } else {
-      diff |= EmitResourceConfigValueDiff(
-          context, apk_a, pkg_a, type_a, entry_a, config_value_a.get(), apk_b,
-          pkg_b, type_b, entry_b, config_value_b);
+      diff |=
+          EmitResourceConfigValueDiff(context, apk_a, pkg_a, type_a, entry_a, config_value_a.get(),
+                                      apk_b, pkg_b, type_b, entry_b, config_value_b);
     }
   }
 
   // Check for any newly added config values.
   for (std::unique_ptr<ResourceConfigValue>& config_value_b : entry_b->values) {
-    ResourceConfigValue* config_value_a =
-        entry_a->FindValue(config_value_b->config);
+    ResourceConfigValue* config_value_a = entry_a->FindValue(config_value_b->config);
     if (!config_value_a) {
       std::stringstream str_stream;
-      str_stream << "new config " << pkg_b->name << ":" << type_b->type << "/"
-                 << entry_b->name << " config=" << config_value_b->config;
+      str_stream << "new config " << pkg_b->name << ":" << type_b->type << "/" << entry_b->name
+                 << " config=" << config_value_b->config;
       EmitDiffLine(apk_b->GetSource(), str_stream.str());
       diff = true;
     }
@@ -132,22 +140,19 @@
 }
 
 static bool EmitResourceTypeDiff(IAaptContext* context, LoadedApk* apk_a,
-                                 ResourceTablePackage* pkg_a,
-                                 ResourceTableType* type_a, LoadedApk* apk_b,
-                                 ResourceTablePackage* pkg_b,
+                                 ResourceTablePackage* pkg_a, ResourceTableType* type_a,
+                                 LoadedApk* apk_b, ResourceTablePackage* pkg_b,
                                  ResourceTableType* type_b) {
   bool diff = false;
   for (std::unique_ptr<ResourceEntry>& entry_a : type_a->entries) {
     ResourceEntry* entry_b = type_b->FindEntry(entry_a->name);
     if (!entry_b) {
       std::stringstream str_stream;
-      str_stream << "missing " << pkg_a->name << ":" << type_a->type << "/"
-                 << entry_a->name;
+      str_stream << "missing " << pkg_a->name << ":" << type_a->type << "/" << entry_a->name;
       EmitDiffLine(apk_b->GetSource(), str_stream.str());
       diff = true;
     } else {
-      if (IsSymbolVisibilityDifferent(entry_a->symbol_status,
-                                      entry_b->symbol_status)) {
+      if (IsSymbolVisibilityDifferent(entry_a->symbol_status, entry_b->symbol_status)) {
         std::stringstream str_stream;
         str_stream << pkg_a->name << ":" << type_a->type << "/" << entry_a->name
                    << " has different visibility (";
@@ -165,8 +170,8 @@
         str_stream << ")";
         EmitDiffLine(apk_b->GetSource(), str_stream.str());
         diff = true;
-      } else if (IsIdDiff(entry_a->symbol_status, entry_a->id,
-                          entry_b->symbol_status, entry_b->id)) {
+      } else if (IsIdDiff(entry_a->symbol_status, entry_a->id, entry_b->symbol_status,
+                          entry_b->id)) {
         std::stringstream str_stream;
         str_stream << pkg_a->name << ":" << type_a->type << "/" << entry_a->name
                    << " has different public ID (";
@@ -185,9 +190,8 @@
         EmitDiffLine(apk_b->GetSource(), str_stream.str());
         diff = true;
       }
-      diff |=
-          EmitResourceEntryDiff(context, apk_a, pkg_a, type_a, entry_a.get(),
-                                apk_b, pkg_b, type_b, entry_b);
+      diff |= EmitResourceEntryDiff(context, apk_a, pkg_a, type_a, entry_a.get(), apk_b, pkg_b,
+                                    type_b, entry_b);
     }
   }
 
@@ -196,8 +200,7 @@
     ResourceEntry* entry_a = type_a->FindEntry(entry_b->name);
     if (!entry_a) {
       std::stringstream str_stream;
-      str_stream << "new entry " << pkg_b->name << ":" << type_b->type << "/"
-                 << entry_b->name;
+      str_stream << "new entry " << pkg_b->name << ":" << type_b->type << "/" << entry_b->name;
       EmitDiffLine(apk_b->GetSource(), str_stream.str());
       diff = true;
     }
@@ -206,8 +209,7 @@
 }
 
 static bool EmitResourcePackageDiff(IAaptContext* context, LoadedApk* apk_a,
-                                    ResourceTablePackage* pkg_a,
-                                    LoadedApk* apk_b,
+                                    ResourceTablePackage* pkg_a, LoadedApk* apk_b,
                                     ResourceTablePackage* pkg_b) {
   bool diff = false;
   for (std::unique_ptr<ResourceTableType>& type_a : pkg_a->types) {
@@ -218,11 +220,9 @@
       EmitDiffLine(apk_a->GetSource(), str_stream.str());
       diff = true;
     } else {
-      if (IsSymbolVisibilityDifferent(type_a->symbol_status,
-                                      type_b->symbol_status)) {
+      if (IsSymbolVisibilityDifferent(type_a->symbol_status, type_b->symbol_status)) {
         std::stringstream str_stream;
-        str_stream << pkg_a->name << ":" << type_a->type
-                   << " has different visibility (";
+        str_stream << pkg_a->name << ":" << type_a->type << " has different visibility (";
         if (type_b->symbol_status.state == SymbolState::kPublic) {
           str_stream << "PUBLIC";
         } else {
@@ -237,11 +237,9 @@
         str_stream << ")";
         EmitDiffLine(apk_b->GetSource(), str_stream.str());
         diff = true;
-      } else if (IsIdDiff(type_a->symbol_status, type_a->id,
-                          type_b->symbol_status, type_b->id)) {
+      } else if (IsIdDiff(type_a->symbol_status, type_a->id, type_b->symbol_status, type_b->id)) {
         std::stringstream str_stream;
-        str_stream << pkg_a->name << ":" << type_a->type
-                   << " has different public ID (";
+        str_stream << pkg_a->name << ":" << type_a->type << " has different public ID (";
         if (type_b->id) {
           str_stream << "0x" << std::hex << type_b->id.value();
         } else {
@@ -257,8 +255,7 @@
         EmitDiffLine(apk_b->GetSource(), str_stream.str());
         diff = true;
       }
-      diff |= EmitResourceTypeDiff(context, apk_a, pkg_a, type_a.get(), apk_b,
-                                   pkg_b, type_b);
+      diff |= EmitResourceTypeDiff(context, apk_a, pkg_a, type_a.get(), apk_b, pkg_b, type_b);
     }
   }
 
@@ -275,8 +272,7 @@
   return diff;
 }
 
-static bool EmitResourceTableDiff(IAaptContext* context, LoadedApk* apk_a,
-                                  LoadedApk* apk_b) {
+static bool EmitResourceTableDiff(IAaptContext* context, LoadedApk* apk_a, LoadedApk* apk_b) {
   ResourceTable* table_a = apk_a->GetResourceTable();
   ResourceTable* table_b = apk_b->GetResourceTable();
 
@@ -307,8 +303,7 @@
         EmitDiffLine(apk_b->GetSource(), str_stream.str());
         diff = true;
       }
-      diff |=
-          EmitResourcePackageDiff(context, apk_a, pkg_a.get(), apk_b, pkg_b);
+      diff |= EmitResourcePackageDiff(context, apk_a, pkg_a.get(), apk_b, pkg_b);
     }
   }
 
@@ -357,10 +352,8 @@
     return 1;
   }
 
-  std::unique_ptr<LoadedApk> apk_a =
-      LoadedApk::LoadApkFromPath(&context, flags.GetArgs()[0]);
-  std::unique_ptr<LoadedApk> apk_b =
-      LoadedApk::LoadApkFromPath(&context, flags.GetArgs()[1]);
+  std::unique_ptr<LoadedApk> apk_a = LoadedApk::LoadApkFromPath(&context, flags.GetArgs()[0]);
+  std::unique_ptr<LoadedApk> apk_b = LoadedApk::LoadApkFromPath(&context, flags.GetArgs()[1]);
   if (!apk_a || !apk_b) {
     return 1;
   }
diff --git a/tools/aapt2/dump/Dump.cpp b/tools/aapt2/cmd/Dump.cpp
similarity index 71%
rename from tools/aapt2/dump/Dump.cpp
rename to tools/aapt2/cmd/Dump.cpp
index bcede72..1bbfb28 100644
--- a/tools/aapt2/dump/Dump.cpp
+++ b/tools/aapt2/cmd/Dump.cpp
@@ -31,13 +31,12 @@
 
 namespace aapt {
 
-void DumpCompiledFile(const pb::CompiledFile& pb_file, const void* data,
-                      size_t len, const Source& source, IAaptContext* context) {
+void DumpCompiledFile(const pb::CompiledFile& pb_file, const void* data, size_t len,
+                      const Source& source, IAaptContext* context) {
   std::unique_ptr<ResourceFile> file =
       DeserializeCompiledFileFromPb(pb_file, source, context->GetDiagnostics());
   if (!file) {
-    context->GetDiagnostics()->Warn(DiagMessage()
-                                    << "failed to read compiled file");
+    context->GetDiagnostics()->Warn(DiagMessage() << "failed to read compiled file");
     return;
   }
 
@@ -50,27 +49,24 @@
   std::unique_ptr<ResourceTable> table;
 
   std::string err;
-  std::unique_ptr<io::ZipFileCollection> zip =
-      io::ZipFileCollection::Create(file_path, &err);
+  std::unique_ptr<io::ZipFileCollection> zip = io::ZipFileCollection::Create(file_path, &err);
   if (zip) {
     io::IFile* file = zip->FindFile("resources.arsc.flat");
     if (file) {
       std::unique_ptr<io::IData> data = file->OpenAsData();
       if (!data) {
-        context->GetDiagnostics()->Error(
-            DiagMessage(file_path) << "failed to open resources.arsc.flat");
+        context->GetDiagnostics()->Error(DiagMessage(file_path)
+                                         << "failed to open resources.arsc.flat");
         return;
       }
 
       pb::ResourceTable pb_table;
       if (!pb_table.ParseFromArray(data->data(), data->size())) {
-        context->GetDiagnostics()->Error(DiagMessage(file_path)
-                                         << "invalid resources.arsc.flat");
+        context->GetDiagnostics()->Error(DiagMessage(file_path) << "invalid resources.arsc.flat");
         return;
       }
 
-      table = DeserializeTableFromPb(pb_table, Source(file_path),
-                                     context->GetDiagnostics());
+      table = DeserializeTableFromPb(pb_table, Source(file_path), context->GetDiagnostics());
       if (!table) {
         return;
       }
@@ -87,8 +83,8 @@
         }
 
         table = util::make_unique<ResourceTable>();
-        BinaryResourceParser parser(context, table.get(), Source(file_path),
-                                    data->data(), data->size());
+        BinaryResourceParser parser(context, table.get(), Source(file_path), data->data(),
+                                    data->size());
         if (!parser.Parse()) {
           return;
         }
@@ -107,16 +103,13 @@
 
     // Try as a compiled table.
     pb::ResourceTable pb_table;
-    if (pb_table.ParseFromArray(file_map->getDataPtr(),
-                                file_map->getDataLength())) {
-      table = DeserializeTableFromPb(pb_table, Source(file_path),
-                                     context->GetDiagnostics());
+    if (pb_table.ParseFromArray(file_map->getDataPtr(), file_map->getDataLength())) {
+      table = DeserializeTableFromPb(pb_table, Source(file_path), context->GetDiagnostics());
     }
 
     if (!table) {
       // Try as a compiled file.
-      CompiledFileInputStream input(file_map->getDataPtr(),
-                                    file_map->getDataLength());
+      CompiledFileInputStream input(file_map->getDataPtr(), file_map->getDataLength());
 
       uint32_t num_files = 0;
       if (!input.ReadLittleEndian32(&num_files)) {
@@ -126,20 +119,17 @@
       for (uint32_t i = 0; i < num_files; i++) {
         pb::CompiledFile compiled_file;
         if (!input.ReadCompiledFile(&compiled_file)) {
-          context->GetDiagnostics()->Warn(DiagMessage()
-                                          << "failed to read compiled file");
+          context->GetDiagnostics()->Warn(DiagMessage() << "failed to read compiled file");
           return;
         }
 
         uint64_t offset, len;
         if (!input.ReadDataMetaData(&offset, &len)) {
-          context->GetDiagnostics()->Warn(DiagMessage()
-                                          << "failed to read meta data");
+          context->GetDiagnostics()->Warn(DiagMessage() << "failed to read meta data");
           return;
         }
 
-        const void* data =
-            static_cast<const uint8_t*>(file_map->getDataPtr()) + offset;
+        const void* data = static_cast<const uint8_t*>(file_map->getDataPtr()) + offset;
         DumpCompiledFile(compiled_file, data, len, Source(file_path), context);
       }
     }
@@ -154,7 +144,9 @@
 
 class DumpContext : public IAaptContext {
  public:
-  IDiagnostics* GetDiagnostics() override { return &diagnostics_; }
+  IDiagnostics* GetDiagnostics() override {
+    return &diagnostics_;
+  }
 
   NameMangler* GetNameMangler() override {
     abort();
@@ -166,18 +158,26 @@
     return empty;
   }
 
-  uint8_t GetPackageId() override { return 0; }
+  uint8_t GetPackageId() override {
+    return 0;
+  }
 
   SymbolTable* GetExternalSymbols() override {
     abort();
     return nullptr;
   }
 
-  bool IsVerbose() override { return verbose_; }
+  bool IsVerbose() override {
+    return verbose_;
+  }
 
-  void SetVerbose(bool val) { verbose_ = val; }
+  void SetVerbose(bool val) {
+    verbose_ = val;
+  }
 
-  int GetMinSdkVersion() override { return 0; }
+  int GetMinSdkVersion() override {
+    return 0;
+  }
 
  private:
   StdErrDiagnostics diagnostics_;
@@ -189,8 +189,7 @@
  */
 int Dump(const std::vector<StringPiece>& args) {
   bool verbose = false;
-  Flags flags =
-      Flags().OptionalSwitch("-v", "increase verbosity of output", &verbose);
+  Flags flags = Flags().OptionalSwitch("-v", "increase verbosity of output", &verbose);
   if (!flags.Parse("aapt2 dump", args, &std::cerr)) {
     return 1;
   }
diff --git a/tools/aapt2/link/Link.cpp b/tools/aapt2/cmd/Link.cpp
similarity index 72%
rename from tools/aapt2/link/Link.cpp
rename to tools/aapt2/cmd/Link.cpp
index 407eb52..6e0809e 100644
--- a/tools/aapt2/link/Link.cpp
+++ b/tools/aapt2/cmd/Link.cpp
@@ -33,6 +33,7 @@
 #include "Locale.h"
 #include "NameMangler.h"
 #include "ResourceUtils.h"
+#include "cmd/Util.h"
 #include "compile/IdAssigner.h"
 #include "filter/ConfigFilter.h"
 #include "flatten/Archive.h"
@@ -40,6 +41,7 @@
 #include "flatten/XmlFlattener.h"
 #include "io/BigBufferInputStream.h"
 #include "io/FileSystem.h"
+#include "io/Util.h"
 #include "io/ZipArchive.h"
 #include "java/JavaClassGenerator.h"
 #include "java/ManifestClassGenerator.h"
@@ -60,7 +62,6 @@
 
 using android::StringPiece;
 using android::base::StringPrintf;
-using ::google::protobuf::io::CopyingOutputStreamAdaptor;
 
 namespace aapt {
 
@@ -125,11 +126,16 @@
 
 class LinkContext : public IAaptContext {
  public:
-  LinkContext() : name_mangler_({}), symbols_(&name_mangler_) {}
+  LinkContext() : name_mangler_({}), symbols_(&name_mangler_) {
+  }
 
-  IDiagnostics* GetDiagnostics() override { return &diagnostics_; }
+  IDiagnostics* GetDiagnostics() override {
+    return &diagnostics_;
+  }
 
-  NameMangler* GetNameMangler() override { return &name_mangler_; }
+  NameMangler* GetNameMangler() override {
+    return &name_mangler_;
+  }
 
   void SetNameManglerPolicy(const NameManglerPolicy& policy) {
     name_mangler_ = NameMangler(policy);
@@ -143,19 +149,33 @@
     compilation_package_ = package_name.to_string();
   }
 
-  uint8_t GetPackageId() override { return package_id_; }
+  uint8_t GetPackageId() override {
+    return package_id_;
+  }
 
-  void SetPackageId(uint8_t id) { package_id_ = id; }
+  void SetPackageId(uint8_t id) {
+    package_id_ = id;
+  }
 
-  SymbolTable* GetExternalSymbols() override { return &symbols_; }
+  SymbolTable* GetExternalSymbols() override {
+    return &symbols_;
+  }
 
-  bool IsVerbose() override { return verbose_; }
+  bool IsVerbose() override {
+    return verbose_;
+  }
 
-  void SetVerbose(bool val) { verbose_ = val; }
+  void SetVerbose(bool val) {
+    verbose_ = val;
+  }
 
-  int GetMinSdkVersion() override { return min_sdk_version_; }
+  int GetMinSdkVersion() override {
+    return min_sdk_version_;
+  }
 
-  void SetMinSdkVersion(int minSdk) { min_sdk_version_ = minSdk; }
+  void SetMinSdkVersion(int minSdk) {
+    min_sdk_version_ = minSdk;
+  }
 
  private:
   DISALLOW_COPY_AND_ASSIGN(LinkContext);
@@ -169,63 +189,9 @@
   int min_sdk_version_ = 0;
 };
 
-static bool CopyInputStreamToArchive(io::InputStream* in, const std::string& out_path,
-                                     uint32_t compression_flags, IArchiveWriter* writer,
-                                     IAaptContext* context) {
-  if (context->IsVerbose()) {
-    context->GetDiagnostics()->Note(DiagMessage() << "writing " << out_path << " to archive");
-  }
-
-  if (!writer->WriteFile(out_path, compression_flags, in)) {
-    context->GetDiagnostics()->Error(DiagMessage() << "failed to write " << out_path
-                                                   << " to archive: " << writer->GetError());
-    return false;
-  }
-  return true;
-}
-
-static bool CopyFileToArchive(io::IFile* file, const std::string& out_path,
-                              uint32_t compression_flags,
-                              IArchiveWriter* writer, IAaptContext* context) {
-  std::unique_ptr<io::IData> data = file->OpenAsData();
-  if (!data) {
-    context->GetDiagnostics()->Error(DiagMessage(file->GetSource()) << "failed to open file");
-    return false;
-  }
-  return CopyInputStreamToArchive(data.get(), out_path, compression_flags, writer, context);
-}
-
-static bool CopyProtoToArchive(::google::protobuf::MessageLite* proto_msg,
-                               const std::string& out_path, uint32_t compression_flags,
-                               IArchiveWriter* writer, IAaptContext* context) {
-  if (context->IsVerbose()) {
-    context->GetDiagnostics()->Note(DiagMessage() << "writing " << out_path << " to archive");
-  }
-
-  if (writer->StartEntry(out_path, compression_flags)) {
-    // Make sure CopyingOutputStreamAdaptor is deleted before we call writer->FinishEntry().
-    {
-      // Wrap our IArchiveWriter with an adaptor that implements the ZeroCopyOutputStream interface.
-      ::google::protobuf::io::CopyingOutputStreamAdaptor adaptor(writer);
-      if (!proto_msg->SerializeToZeroCopyStream(&adaptor)) {
-        context->GetDiagnostics()->Error(DiagMessage()
-                                         << "failed to write " << out_path << " to archive");
-        return false;
-      }
-    }
-
-    if (writer->FinishEntry()) {
-      return true;
-    }
-  }
-  context->GetDiagnostics()->Error(DiagMessage() << "failed to write " << out_path
-                                                 << " to archive: " << writer->GetError());
-  return false;
-}
-
 static bool FlattenXml(xml::XmlResource* xml_res, const StringPiece& path,
-                       Maybe<size_t> max_sdk_level, bool keep_raw_values,
-                       IArchiveWriter* writer, IAaptContext* context) {
+                       Maybe<size_t> max_sdk_level, bool keep_raw_values, IArchiveWriter* writer,
+                       IAaptContext* context) {
   BigBuffer buffer(1024);
   XmlFlattenerOptions options = {};
   options.keep_raw_values = keep_raw_values;
@@ -239,21 +205,18 @@
     DiagMessage msg;
     msg << "writing " << path << " to archive";
     if (max_sdk_level) {
-      msg << " maxSdkLevel=" << max_sdk_level.value()
-          << " keepRawValues=" << keep_raw_values;
+      msg << " maxSdkLevel=" << max_sdk_level.value() << " keepRawValues=" << keep_raw_values;
     }
     context->GetDiagnostics()->Note(msg);
   }
 
   io::BigBufferInputStream input_stream(&buffer);
-  return CopyInputStreamToArchive(&input_stream, path.to_string(), ArchiveEntry::kCompress, writer,
-                                  context);
+  return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
+                                      ArchiveEntry::kCompress, writer);
 }
 
-static std::unique_ptr<ResourceTable> LoadTableFromPb(const Source& source,
-                                                      const void* data,
-                                                      size_t len,
-                                                      IDiagnostics* diag) {
+static std::unique_ptr<ResourceTable> LoadTableFromPb(const Source& source, const void* data,
+                                                      size_t len, IDiagnostics* diag) {
   pb::ResourceTable pb_table;
   if (!pb_table.ParseFromArray(data, len)) {
     diag->Error(DiagMessage(source) << "invalid compiled table");
@@ -270,8 +233,7 @@
 /**
  * Inflates an XML file from the source path.
  */
-static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path,
-                                                 IDiagnostics* diag) {
+static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
   std::ifstream fin(path, std::ifstream::binary);
   if (!fin) {
     diag->Error(DiagMessage(path) << strerror(errno));
@@ -293,9 +255,10 @@
 
 class ResourceFileFlattener {
  public:
-  ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
-                        IAaptContext* context, proguard::KeepSet* keep_set)
-      : options_(options), context_(context), keep_set_(keep_set) {}
+  ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
+                        proguard::KeepSet* keep_set)
+      : options_(options), context_(context), keep_set_(keep_set) {
+  }
 
   bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
 
@@ -341,25 +304,15 @@
 }
 
 static bool IsTransitionElement(const std::string& name) {
-  return
-    name == "fade" ||
-    name == "changeBounds" ||
-    name == "slide" ||
-    name == "explode" ||
-    name == "changeImageTransform" ||
-    name == "changeTransform" ||
-    name == "changeClipBounds" ||
-    name == "autoTransition" ||
-    name == "recolor" ||
-    name == "changeScroll" ||
-    name == "transitionSet" ||
-    name == "transition" ||
-    name == "transitionManager";
+  return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
+         name == "changeImageTransform" || name == "changeTransform" ||
+         name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
+         name == "changeScroll" || name == "transitionSet" || name == "transition" ||
+         name == "transitionManager";
 }
 
-bool ResourceFileFlattener::LinkAndVersionXmlFile(
-    ResourceTable* table, FileOperation* file_op,
-    std::queue<FileOperation>* out_file_op_queue) {
+bool ResourceFileFlattener::LinkAndVersionXmlFile(ResourceTable* table, FileOperation* file_op,
+                                                  std::queue<FileOperation>* out_file_op_queue) {
   xml::XmlResource* doc = file_op->xml_to_flatten.get();
   const Source& src = doc->file.source;
 
@@ -372,8 +325,7 @@
     return false;
   }
 
-  if (options_.update_proguard_spec &&
-      !proguard::CollectProguardRules(src, doc, keep_set_)) {
+  if (options_.update_proguard_spec && !proguard::CollectProguardRules(src, doc, keep_set_)) {
     return false;
   }
 
@@ -415,8 +367,7 @@
     const int min_sdk_version = context_->GetMinSdkVersion();
     for (int sdk_level : xml_linker.sdk_levels()) {
       if (sdk_level > min_sdk_version && sdk_level > config.sdkVersion) {
-        if (!ShouldGenerateVersionedResource(file_op->entry, config,
-                                             sdk_level)) {
+        if (!ShouldGenerateVersionedResource(file_op->entry, config, sdk_level)) {
           // If we shouldn't generate a versioned resource, stop checking.
           break;
         }
@@ -425,24 +376,22 @@
         versioned_file_desc.config.sdkVersion = (uint16_t)sdk_level;
 
         FileOperation new_file_op;
-        new_file_op.xml_to_flatten = util::make_unique<xml::XmlResource>(
-            versioned_file_desc, doc->root->Clone());
+        new_file_op.xml_to_flatten =
+            util::make_unique<xml::XmlResource>(versioned_file_desc, doc->root->Clone());
         new_file_op.config = versioned_file_desc.config;
         new_file_op.entry = file_op->entry;
-        new_file_op.dst_path = ResourceUtils::BuildResourceFileName(
-            versioned_file_desc, context_->GetNameMangler());
+        new_file_op.dst_path =
+            ResourceUtils::BuildResourceFileName(versioned_file_desc, context_->GetNameMangler());
 
         if (context_->IsVerbose()) {
-          context_->GetDiagnostics()->Note(
-              DiagMessage(versioned_file_desc.source)
-              << "auto-versioning resource from config '" << config << "' -> '"
-              << versioned_file_desc.config << "'");
+          context_->GetDiagnostics()->Note(DiagMessage(versioned_file_desc.source)
+                                           << "auto-versioning resource from config '" << config
+                                           << "' -> '" << versioned_file_desc.config << "'");
         }
 
         bool added = table->AddFileReferenceAllowMangled(
-            versioned_file_desc.name, versioned_file_desc.config,
-            versioned_file_desc.source, new_file_op.dst_path, nullptr,
-            context_->GetDiagnostics());
+            versioned_file_desc.name, versioned_file_desc.config, versioned_file_desc.source,
+            new_file_op.dst_path, nullptr, context_->GetDiagnostics());
         if (!added) {
           return false;
         }
@@ -460,11 +409,9 @@
  * will
  * corrupt the iteration order.
  */
-bool ResourceFileFlattener::Flatten(ResourceTable* table,
-                                    IArchiveWriter* archive_writer) {
+bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
   bool error = false;
-  std::map<std::pair<ConfigDescription, StringPiece>, FileOperation>
-      config_sorted_files;
+  std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
 
   for (auto& pkg : table->packages) {
     for (auto& type : pkg->types) {
@@ -476,8 +423,7 @@
       // Populate the queue with all files in the ResourceTable.
       for (auto& entry : type->entries) {
         for (auto& config_value : entry->values) {
-          FileReference* file_ref =
-              ValueCast<FileReference>(config_value->value.get());
+          FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
           if (!file_ref) {
             continue;
           }
@@ -496,8 +442,7 @@
 
           const StringPiece src_path = file->GetSource().path;
           if (type->type != ResourceType::kRaw &&
-              (util::EndsWith(src_path, ".xml.flat") ||
-               util::EndsWith(src_path, ".xml"))) {
+              (util::EndsWith(src_path, ".xml.flat") || util::EndsWith(src_path, ".xml"))) {
             std::unique_ptr<io::IData> data = file->OpenAsData();
             if (!data) {
               context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
@@ -505,9 +450,8 @@
               return false;
             }
 
-            file_op.xml_to_flatten =
-                xml::Inflate(data->data(), data->size(),
-                             context_->GetDiagnostics(), file->GetSource());
+            file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(),
+                                                  context_->GetDiagnostics(), file->GetSource());
 
             if (!file_op.xml_to_flatten) {
               return false;
@@ -515,8 +459,7 @@
 
             file_op.xml_to_flatten->file.config = config_value->config;
             file_op.xml_to_flatten->file.source = file_ref->GetSource();
-            file_op.xml_to_flatten->file.name =
-                ResourceName(pkg->name, type->type, entry->name);
+            file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
 
             // Enqueue the XML files to be processed.
             file_operations.push(std::move(file_op));
@@ -528,8 +471,8 @@
             // then creating a StringPiece from the copy, which would cause us
             // to end up referencing garbage in the map.
             const StringPiece entry_name(entry->name);
-            config_sorted_files[std::make_pair(
-                config_value->config, entry_name)] = std::move(file_op);
+            config_sorted_files[std::make_pair(config_value->config, entry_name)] =
+                std::move(file_op);
           }
         }
       }
@@ -548,8 +491,7 @@
         // creating a StringPiece from the copy, which would cause us to end up
         // referencing garbage in the map.
         const StringPiece entry_name(file_op.entry->name);
-        config_sorted_files[std::make_pair(file_op.config, entry_name)] =
-            std::move(file_op);
+        config_sorted_files[std::make_pair(file_op.config, entry_name)] = std::move(file_op);
       }
 
       if (error) {
@@ -564,21 +506,19 @@
         if (file_op.xml_to_flatten) {
           Maybe<size_t> max_sdk_level;
           if (!options_.no_auto_version && !file_op.skip_version) {
-            max_sdk_level =
-                std::max<size_t>(std::max<size_t>(config.sdkVersion, 1u),
-                                 context_->GetMinSdkVersion());
+            max_sdk_level = std::max<size_t>(std::max<size_t>(config.sdkVersion, 1u),
+                                             context_->GetMinSdkVersion());
           }
 
-          bool result = FlattenXml(
-              file_op.xml_to_flatten.get(), file_op.dst_path, max_sdk_level,
-              options_.keep_raw_values, archive_writer, context_);
+          bool result = FlattenXml(file_op.xml_to_flatten.get(), file_op.dst_path, max_sdk_level,
+                                   options_.keep_raw_values, archive_writer, context_);
           if (!result) {
             error = true;
           }
         } else {
-          bool result = CopyFileToArchive(
-              file_op.file_to_copy, file_op.dst_path,
-              GetCompressionFlags(file_op.dst_path), archive_writer, context_);
+          bool result =
+              io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
+                                    GetCompressionFlags(file_op.dst_path), archive_writer);
           if (!result) {
             error = true;
           }
@@ -589,10 +529,9 @@
   return !error;
 }
 
-static bool WriteStableIdMapToPath(
-    IDiagnostics* diag,
-    const std::unordered_map<ResourceName, ResourceId>& id_map,
-    const std::string& id_map_path) {
+static bool WriteStableIdMapToPath(IDiagnostics* diag,
+                                   const std::unordered_map<ResourceName, ResourceId>& id_map,
+                                   const std::string& id_map_path) {
   std::ofstream fout(id_map_path, std::ofstream::binary);
   if (!fout) {
     diag->Error(DiagMessage(id_map_path) << strerror(errno));
@@ -606,18 +545,16 @@
   }
 
   if (!fout) {
-    diag->Error(DiagMessage(id_map_path)
-                << "failed writing to file: "
-                << android::base::SystemErrorCodeToString(errno));
+    diag->Error(DiagMessage(id_map_path) << "failed writing to file: "
+                                         << android::base::SystemErrorCodeToString(errno));
     return false;
   }
 
   return true;
 }
 
-static bool LoadStableIdMap(
-    IDiagnostics* diag, const std::string& path,
-    std::unordered_map<ResourceName, ResourceId>* out_id_map) {
+static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
+                            std::unordered_map<ResourceName, ResourceId>* out_id_map) {
   std::string content;
   if (!android::base::ReadFileToString(path, &content)) {
     diag->Error(DiagMessage(path) << "failed reading stable ID file");
@@ -643,20 +580,19 @@
     StringPiece res_name_str =
         util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
     if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
-      diag->Error(DiagMessage(Source(path, line_no))
-                  << "invalid resource name '" << res_name_str << "'");
+      diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
+                                                     << "'");
       return false;
     }
 
     const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
     const size_t res_id_str_len = line.size() - res_id_start_idx;
-    StringPiece res_id_str =
-        util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
+    StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
 
     Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
     if (!maybe_id) {
-      diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '"
-                                                     << res_id_str << "'");
+      diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
+                                                     << "'");
       return false;
     }
 
@@ -665,38 +601,14 @@
   return true;
 }
 
-static bool ParseSplitParameter(const StringPiece& arg, IDiagnostics* diag,
-                                std::string* out_path,
-                                SplitConstraints* out_split) {
-  std::vector<std::string> parts = util::Split(arg, ':');
-  if (parts.size() != 2) {
-    diag->Error(DiagMessage() << "invalid split parameter '" << arg << "'");
-    diag->Note(
-        DiagMessage()
-        << "should be --split path/to/output.apk:<config>[,<config>...]");
-    return false;
-  }
-  *out_path = parts[0];
-  std::vector<ConfigDescription> configs;
-  for (const StringPiece& config_str : util::Tokenize(parts[1], ',')) {
-    configs.push_back({});
-    if (!ConfigDescription::Parse(config_str, &configs.back())) {
-      diag->Error(DiagMessage() << "invalid config '" << config_str
-                                << "' in split parameter '" << arg << "'");
-      return false;
-    }
-  }
-  out_split->configs.insert(configs.begin(), configs.end());
-  return true;
-}
-
 class LinkCommand {
  public:
   LinkCommand(LinkContext* context, const LinkOptions& options)
       : options_(options),
         context_(context),
         final_table_(),
-        file_collection_(util::make_unique<io::FileCollection>()) {}
+        file_collection_(util::make_unique<io::FileCollection>()) {
+  }
 
   /**
    * Creates a SymbolTable that loads symbols from the various APKs and caches
@@ -707,8 +619,7 @@
         util::make_unique<AssetManagerSymbolSource>();
     for (const std::string& path : options_.include_paths) {
       if (context_->IsVerbose()) {
-        context_->GetDiagnostics()->Note(DiagMessage(path)
-                                         << "loading include path");
+        context_->GetDiagnostics()->Note(DiagMessage(path) << "loading include path");
       }
 
       // First try to load the file as a static lib.
@@ -820,7 +731,7 @@
     if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
       if (xml::Attribute* min_sdk =
               uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
-        app_info.min_sdk_version = min_sdk->value;
+        app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
       }
     }
     return app_info;
@@ -832,8 +743,7 @@
    * stripped, or there is an error and false is returned.
    */
   bool VerifyNoExternalPackages() {
-    auto is_ext_package_func =
-        [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
+    auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
       return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
              pkg->id.value() != context_->GetPackageId();
     };
@@ -849,17 +759,16 @@
             for (const auto& config_value : entry->values) {
               // Special case the occurrence of an ID that is being generated
               // for the 'android' package. This is due to legacy reasons.
-              if (ValueCast<Id>(config_value->value.get()) &&
-                  package->name == "android") {
-                context_->GetDiagnostics()->Warn(
-                    DiagMessage(config_value->value->GetSource())
-                    << "generated id '" << res_name
-                    << "' for external package '" << package->name << "'");
+              if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
+                context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
+                                                 << "generated id '" << res_name
+                                                 << "' for external package '" << package->name
+                                                 << "'");
               } else {
-                context_->GetDiagnostics()->Error(
-                    DiagMessage(config_value->value->GetSource())
-                    << "defined resource '" << res_name
-                    << "' for external package '" << package->name << "'");
+                context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
+                                                  << "defined resource '" << res_name
+                                                  << "' for external package '" << package->name
+                                                  << "'");
                 error = true;
               }
             }
@@ -868,9 +777,8 @@
       }
     }
 
-    auto new_end_iter =
-        std::remove_if(final_table_.packages.begin(),
-                       final_table_.packages.end(), is_ext_package_func);
+    auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
+                                       is_ext_package_func);
     final_table_.packages.erase(new_end_iter, final_table_.packages.end());
     return !error;
   }
@@ -919,17 +827,16 @@
     }
 
     io::BigBufferInputStream input_stream(&buffer);
-    return CopyInputStreamToArchive(&input_stream, "resources.arsc", ArchiveEntry::kAlign, writer,
-                                    context_);
+    return io::CopyInputStreamToArchive(context_, &input_stream, "resources.arsc",
+                                        ArchiveEntry::kAlign, writer);
   }
 
   bool FlattenTableToPb(ResourceTable* table, IArchiveWriter* writer) {
     std::unique_ptr<pb::ResourceTable> pb_table = SerializeTableToPb(table);
-    return CopyProtoToArchive(pb_table.get(), "resources.arsc.flat", 0, writer, context_);
+    return io::CopyProtoToArchive(context_, pb_table.get(), "resources.arsc.flat", 0, writer);
   }
 
-  bool WriteJavaFile(ResourceTable* table,
-                     const StringPiece& package_name_to_generate,
+  bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
                      const StringPiece& out_package,
                      const JavaClassGeneratorOptions& java_options) {
     if (!options_.generate_java_class_path) {
@@ -939,8 +846,8 @@
     std::string out_path = options_.generate_java_class_path.value();
     file::AppendPath(&out_path, file::PackageToPath(out_package));
     if (!file::mkdirs(out_path)) {
-      context_->GetDiagnostics()->Error(
-          DiagMessage() << "failed to create directory '" << out_path << "'");
+      context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
+                                                      << "'");
       return false;
     }
 
@@ -948,9 +855,9 @@
 
     std::ofstream fout(out_path, std::ofstream::binary);
     if (!fout) {
-      context_->GetDiagnostics()->Error(
-          DiagMessage() << "failed writing to '" << out_path << "': "
-                        << android::base::SystemErrorCodeToString(errno));
+      context_->GetDiagnostics()->Error(DiagMessage()
+                                        << "failed writing to '" << out_path
+                                        << "': " << android::base::SystemErrorCodeToString(errno));
       return false;
     }
 
@@ -961,9 +868,9 @@
     }
 
     if (!fout) {
-      context_->GetDiagnostics()->Error(
-          DiagMessage() << "failed writing to '" << out_path << "': "
-                        << android::base::SystemErrorCodeToString(errno));
+      context_->GetDiagnostics()->Error(DiagMessage()
+                                        << "failed writing to '" << out_path
+                                        << "': " << android::base::SystemErrorCodeToString(errno));
     }
     return true;
   }
@@ -999,8 +906,8 @@
     file::AppendPath(&out_path, file::PackageToPath(package_utf8));
 
     if (!file::mkdirs(out_path)) {
-      context_->GetDiagnostics()->Error(
-          DiagMessage() << "failed to create directory '" << out_path << "'");
+      context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
+                                                      << "'");
       return false;
     }
 
@@ -1008,24 +915,22 @@
 
     std::ofstream fout(out_path, std::ofstream::binary);
     if (!fout) {
-      context_->GetDiagnostics()->Error(
-          DiagMessage() << "failed writing to '" << out_path << "': "
-                        << android::base::SystemErrorCodeToString(errno));
+      context_->GetDiagnostics()->Error(DiagMessage()
+                                        << "failed writing to '" << out_path
+                                        << "': " << android::base::SystemErrorCodeToString(errno));
       return false;
     }
 
-    if (!ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8,
-                                        true, &fout)) {
-      context_->GetDiagnostics()->Error(
-          DiagMessage() << "failed writing to '" << out_path << "': "
-                        << android::base::SystemErrorCodeToString(errno));
+    if (!ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout)) {
+      context_->GetDiagnostics()->Error(DiagMessage()
+                                        << "failed writing to '" << out_path
+                                        << "': " << android::base::SystemErrorCodeToString(errno));
       return false;
     }
     return true;
   }
 
-  bool WriteProguardFile(const Maybe<std::string>& out,
-                         const proguard::KeepSet& keep_set) {
+  bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
     if (!out) {
       return true;
     }
@@ -1033,17 +938,17 @@
     const std::string& out_path = out.value();
     std::ofstream fout(out_path, std::ofstream::binary);
     if (!fout) {
-      context_->GetDiagnostics()->Error(
-          DiagMessage() << "failed to open '" << out_path << "': "
-                        << android::base::SystemErrorCodeToString(errno));
+      context_->GetDiagnostics()->Error(DiagMessage()
+                                        << "failed to open '" << out_path
+                                        << "': " << android::base::SystemErrorCodeToString(errno));
       return false;
     }
 
     proguard::WriteKeepSet(&fout, keep_set);
     if (!fout) {
-      context_->GetDiagnostics()->Error(
-          DiagMessage() << "failed writing to '" << out_path << "': "
-                        << android::base::SystemErrorCodeToString(errno));
+      context_->GetDiagnostics()->Error(DiagMessage()
+                                        << "failed writing to '" << out_path
+                                        << "': " << android::base::SystemErrorCodeToString(errno));
       return false;
     }
     return true;
@@ -1059,8 +964,7 @@
     return LoadTablePbFromCollection(collection.get());
   }
 
-  std::unique_ptr<ResourceTable> LoadTablePbFromCollection(
-      io::IFileCollection* collection) {
+  std::unique_ptr<ResourceTable> LoadTablePbFromCollection(io::IFileCollection* collection) {
     io::IFile* file = collection->FindFile("resources.arsc.flat");
     if (!file) {
       return {};
@@ -1073,8 +977,7 @@
 
   bool MergeStaticLibrary(const std::string& input, bool override) {
     if (context_->IsVerbose()) {
-      context_->GetDiagnostics()->Note(DiagMessage()
-                                       << "merging static library " << input);
+      context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
     }
 
     std::string error_str;
@@ -1118,8 +1021,8 @@
     } else {
       // This is the proper way to merge libraries, where the package name is
       // preserved and resource names are mangled.
-      result = table_merger_->MergeAndMangle(Source(input), pkg->name,
-                                             table.get(), collection.get());
+      result =
+          table_merger_->MergeAndMangle(Source(input), pkg->name, table.get(), collection.get());
     }
 
     if (!result) {
@@ -1133,20 +1036,18 @@
 
   bool MergeResourceTable(io::IFile* file, bool override) {
     if (context_->IsVerbose()) {
-      context_->GetDiagnostics()->Note(
-          DiagMessage() << "merging resource table " << file->GetSource());
+      context_->GetDiagnostics()->Note(DiagMessage() << "merging resource table "
+                                                     << file->GetSource());
     }
 
     std::unique_ptr<io::IData> data = file->OpenAsData();
     if (!data) {
-      context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
-                                        << "failed to open file");
+      context_->GetDiagnostics()->Error(DiagMessage(file->GetSource()) << "failed to open file");
       return false;
     }
 
     std::unique_ptr<ResourceTable> table =
-        LoadTableFromPb(file->GetSource(), data->data(), data->size(),
-                        context_->GetDiagnostics());
+        LoadTableFromPb(file->GetSource(), data->data(), data->size(), context_->GetDiagnostics());
     if (!table) {
       return false;
     }
@@ -1160,12 +1061,11 @@
     return result;
   }
 
-  bool MergeCompiledFile(io::IFile* file, ResourceFile* file_desc,
-                         bool override) {
+  bool MergeCompiledFile(io::IFile* file, ResourceFile* file_desc, bool override) {
     if (context_->IsVerbose()) {
-      context_->GetDiagnostics()->Note(
-          DiagMessage() << "merging '" << file_desc->name
-                        << "' from compiled file " << file->GetSource());
+      context_->GetDiagnostics()->Note(DiagMessage() << "merging '" << file_desc->name
+                                                     << "' from compiled file "
+                                                     << file->GetSource());
     }
 
     bool result = false;
@@ -1196,8 +1096,8 @@
       std::unique_ptr<Id> id = util::make_unique<Id>();
       id->SetSource(file_desc->source.WithLine(exported_symbol.line));
       bool result = final_table_.AddResourceAllowMangled(
-          res_name, ConfigDescription::DefaultConfig(), std::string(),
-          std::move(id), context_->GetDiagnostics());
+          res_name, ConfigDescription::DefaultConfig(), std::string(), std::move(id),
+          context_->GetDiagnostics());
       if (!result) {
         return false;
       }
@@ -1216,8 +1116,7 @@
    */
   bool MergeArchive(const std::string& input, bool override) {
     if (context_->IsVerbose()) {
-      context_->GetDiagnostics()->Note(DiagMessage() << "merging archive "
-                                                     << input);
+      context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
     }
 
     std::string error_str;
@@ -1296,49 +1195,43 @@
       CompiledFileInputStream input_stream(data->data(), data->size());
       uint32_t num_files = 0;
       if (!input_stream.ReadLittleEndian32(&num_files)) {
-        context_->GetDiagnostics()->Error(DiagMessage(src)
-                                          << "failed read num files");
+        context_->GetDiagnostics()->Error(DiagMessage(src) << "failed read num files");
         return false;
       }
 
       for (uint32_t i = 0; i < num_files; i++) {
         pb::CompiledFile compiled_file;
         if (!input_stream.ReadCompiledFile(&compiled_file)) {
-          context_->GetDiagnostics()->Error(
-              DiagMessage(src) << "failed to read compiled file header");
+          context_->GetDiagnostics()->Error(DiagMessage(src)
+                                            << "failed to read compiled file header");
           return false;
         }
 
         uint64_t offset, len;
         if (!input_stream.ReadDataMetaData(&offset, &len)) {
-          context_->GetDiagnostics()->Error(DiagMessage(src)
-                                            << "failed to read data meta data");
+          context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read data meta data");
           return false;
         }
 
-        std::unique_ptr<ResourceFile> resource_file =
-            DeserializeCompiledFileFromPb(compiled_file, file->GetSource(),
-                                          context_->GetDiagnostics());
+        std::unique_ptr<ResourceFile> resource_file = DeserializeCompiledFileFromPb(
+            compiled_file, file->GetSource(), context_->GetDiagnostics());
         if (!resource_file) {
           return false;
         }
 
-        if (!MergeCompiledFile(file->CreateFileSegment(offset, len),
-                               resource_file.get(), override)) {
+        if (!MergeCompiledFile(file->CreateFileSegment(offset, len), resource_file.get(),
+                               override)) {
           return false;
         }
       }
       return true;
-    } else if (util::EndsWith(src.path, ".xml") ||
-               util::EndsWith(src.path, ".png")) {
+    } else if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
       // Since AAPT compiles these file types and appends .flat to them, seeing
       // their raw extensions is a sign that they weren't compiled.
-      const StringPiece file_type =
-          util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
-      context_->GetDiagnostics()->Error(DiagMessage(src)
-                                        << "uncompiled " << file_type
-                                        << " file passed as argument. Must be "
-                                           "compiled first into .flat file.");
+      const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
+      context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
+                                                         << " file passed as argument. Must be "
+                                                            "compiled first into .flat file.");
       return false;
     }
 
@@ -1348,51 +1241,6 @@
     return true;
   }
 
-  std::unique_ptr<xml::XmlResource> GenerateSplitManifest(const AppInfo& app_info,
-                                                          const SplitConstraints& constraints) {
-    std::unique_ptr<xml::XmlResource> doc = util::make_unique<xml::XmlResource>();
-
-    std::unique_ptr<xml::Namespace> namespace_android = util::make_unique<xml::Namespace>();
-    namespace_android->namespace_uri = xml::kSchemaAndroid;
-    namespace_android->namespace_prefix = "android";
-
-    std::unique_ptr<xml::Element> manifest_el = util::make_unique<xml::Element>();
-    manifest_el->name = "manifest";
-    manifest_el->attributes.push_back(xml::Attribute{"", "package", app_info.package});
-
-    if (app_info.version_code) {
-      manifest_el->attributes.push_back(xml::Attribute{
-          xml::kSchemaAndroid, "versionCode", std::to_string(app_info.version_code.value())});
-    }
-
-    if (app_info.revision_code) {
-      manifest_el->attributes.push_back(xml::Attribute{
-          xml::kSchemaAndroid, "revisionCode", std::to_string(app_info.revision_code.value())});
-    }
-
-    std::stringstream split_name;
-    if (app_info.split_name) {
-      split_name << app_info.split_name.value() << ".";
-    }
-    split_name << "config." << util::Joiner(constraints.configs, "_");
-
-    manifest_el->attributes.push_back(xml::Attribute{"", "split", split_name.str()});
-
-    if (app_info.split_name) {
-      manifest_el->attributes.push_back(
-          xml::Attribute{"", "configForSplit", app_info.split_name.value()});
-    }
-
-    std::unique_ptr<xml::Element> application_el = util::make_unique<xml::Element>();
-    application_el->name = "application";
-    application_el->attributes.push_back(xml::Attribute{xml::kSchemaAndroid, "hasCode", "false"});
-
-    manifest_el->AppendChild(std::move(application_el));
-    namespace_android->AppendChild(std::move(manifest_el));
-    doc->root = std::move(namespace_android);
-    return doc;
-  }
-
   bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
     std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
     for (const std::string& assets_dir : options_.assets_dirs) {
@@ -1425,8 +1273,8 @@
         compression_flags = 0u;
       }
 
-      if (!CopyFileToArchive(entry.second.get(), entry.first, compression_flags, writer,
-                             context_)) {
+      if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
+                                 writer)) {
         return false;
       }
     }
@@ -1437,21 +1285,19 @@
    * Writes the AndroidManifest, ResourceTable, and all XML files referenced by
    * the ResourceTable to the IArchiveWriter.
    */
-  bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set,
-                xml::XmlResource* manifest, ResourceTable* table) {
+  bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
+                ResourceTable* table) {
     const bool keep_raw_values = options_.package_type == PackageType::kStaticLib;
-    bool result = FlattenXml(manifest, "AndroidManifest.xml", {},
-                             keep_raw_values, writer, context_);
+    bool result =
+        FlattenXml(manifest, "AndroidManifest.xml", {}, keep_raw_values, writer, context_);
     if (!result) {
       return false;
     }
 
     ResourceFileFlattenerOptions file_flattener_options;
     file_flattener_options.keep_raw_values = keep_raw_values;
-    file_flattener_options.do_not_compress_anything =
-        options_.do_not_compress_anything;
-    file_flattener_options.extensions_to_not_compress =
-        options_.extensions_to_not_compress;
+    file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
+    file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
     file_flattener_options.no_auto_version = options_.no_auto_version;
     file_flattener_options.no_version_vectors = options_.no_version_vectors;
     file_flattener_options.no_version_transitions = options_.no_version_transitions;
@@ -1487,10 +1333,9 @@
       return 1;
     }
 
-    // First extract the Package name without modifying it (via
-    // --rename-manifest-package).
-    if (Maybe<AppInfo> maybe_app_info = ExtractAppInfoFromManifest(
-            manifest_xml.get(), context_->GetDiagnostics())) {
+    // First extract the Package name without modifying it (via --rename-manifest-package).
+    if (Maybe<AppInfo> maybe_app_info =
+            ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
       const AppInfo& app_info = maybe_app_info.value();
       context_->SetCompilationPackage(app_info.package);
     }
@@ -1500,22 +1345,16 @@
       return 1;
     }
 
-    Maybe<AppInfo> maybe_app_info = ExtractAppInfoFromManifest(
-        manifest_xml.get(), context_->GetDiagnostics());
+    Maybe<AppInfo> maybe_app_info =
+        ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
     if (!maybe_app_info) {
       return 1;
     }
 
     const AppInfo& app_info = maybe_app_info.value();
-    if (app_info.min_sdk_version) {
-      if (Maybe<int> maybe_min_sdk_version = ResourceUtils::ParseSdkVersion(
-              app_info.min_sdk_version.value())) {
-        context_->SetMinSdkVersion(maybe_min_sdk_version.value());
-      }
-    }
+    context_->SetMinSdkVersion(app_info.min_sdk_version.value_or_default(0));
 
-    context_->SetNameManglerPolicy(
-        NameManglerPolicy{context_->GetCompilationPackage()});
+    context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
 
     // Override the package ID when it is "android".
     if (context_->GetCompilationPackage() == "android") {
@@ -1535,8 +1374,7 @@
 
     TableMergerOptions table_merger_options;
     table_merger_options.auto_add_overlay = options_.auto_add_overlay;
-    table_merger_ = util::make_unique<TableMerger>(context_, &final_table_,
-                                                   table_merger_options);
+    table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
 
     if (context_->IsVerbose()) {
       context_->GetDiagnostics()->Note(DiagMessage()
@@ -1547,16 +1385,14 @@
 
     for (const std::string& input : input_files) {
       if (!MergePath(input, false)) {
-        context_->GetDiagnostics()->Error(DiagMessage()
-                                          << "failed parsing input");
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
         return 1;
       }
     }
 
     for (const std::string& input : options_.overlay_files) {
       if (!MergePath(input, true)) {
-        context_->GetDiagnostics()->Error(DiagMessage()
-                                          << "failed parsing overlays");
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
         return 1;
       }
     }
@@ -1568,8 +1404,7 @@
     if (options_.package_type != PackageType::kStaticLib) {
       PrivateAttributeMover mover;
       if (!mover.Consume(context_, &final_table_)) {
-        context_->GetDiagnostics()->Error(
-            DiagMessage() << "failed moving private attributes");
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
         return 1;
       }
 
@@ -1587,14 +1422,13 @@
             for (auto& entry : type->entries) {
               ResourceName name(package->name, type->type, entry->name);
               // The IDs are guaranteed to exist.
-              options_.stable_id_map[std::move(name)] = ResourceId(
-                  package->id.value(), type->id.value(), entry->id.value());
+              options_.stable_id_map[std::move(name)] =
+                  ResourceId(package->id.value(), type->id.value(), entry->id.value());
             }
           }
         }
 
-        if (!WriteStableIdMapToPath(context_->GetDiagnostics(),
-                                    options_.stable_id_map,
+        if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
                                     options_.resource_id_map_path.value())) {
           return 1;
         }
@@ -1609,8 +1443,8 @@
     }
 
     // Add the names to mangle based on our source merge earlier.
-    context_->SetNameManglerPolicy(NameManglerPolicy{
-        context_->GetCompilationPackage(), table_merger_->merged_packages()});
+    context_->SetNameManglerPolicy(
+        NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
 
     // Add our table to the symbol table.
     context_->GetExternalSymbols()->PrependSource(
@@ -1618,8 +1452,7 @@
 
     ReferenceLinker linker;
     if (!linker.Consume(context_, &final_table_)) {
-      context_->GetDiagnostics()->Error(DiagMessage()
-                                        << "failed linking references");
+      context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
       return 1;
     }
 
@@ -1639,17 +1472,16 @@
     if (!options_.no_auto_version) {
       AutoVersioner versioner;
       if (!versioner.Consume(context_, &final_table_)) {
-        context_->GetDiagnostics()->Error(DiagMessage()
-                                          << "failed versioning styles");
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
         return 1;
       }
     }
 
     if (options_.package_type != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
       if (context_->IsVerbose()) {
-        context_->GetDiagnostics()->Note(
-            DiagMessage() << "collapsing resource versions for minimum SDK "
-                          << context_->GetMinSdkVersion());
+        context_->GetDiagnostics()->Note(DiagMessage()
+                                         << "collapsing resource versions for minimum SDK "
+                                         << context_->GetMinSdkVersion());
       }
 
       VersionCollapser collapser;
@@ -1676,27 +1508,12 @@
                                          << "can't strip resources when building static library");
       }
     } else {
-      // Adjust the SplitConstraints so that their SDK version is stripped if it
-      // is less
-      // than or equal to the minSdk. Otherwise the resources that have had
-      // their SDK version
-      // stripped due to minSdk won't ever match.
-      std::vector<SplitConstraints> adjusted_constraints_list;
-      adjusted_constraints_list.reserve(options_.split_constraints.size());
-      for (const SplitConstraints& constraints : options_.split_constraints) {
-        SplitConstraints adjusted_constraints;
-        for (const ConfigDescription& config : constraints.configs) {
-          if (config.sdkVersion <= context_->GetMinSdkVersion()) {
-            adjusted_constraints.configs.insert(config.CopyWithoutSdkVersion());
-          } else {
-            adjusted_constraints.configs.insert(config);
-          }
-        }
-        adjusted_constraints_list.push_back(std::move(adjusted_constraints));
-      }
+      // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
+      // equal to the minSdk.
+      options_.split_constraints =
+          AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
 
-      TableSplitter table_splitter(adjusted_constraints_list,
-                                   options_.table_splitter_options);
+      TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
       if (!table_splitter.VerifySplitConstraints(context_)) {
         return 1;
       }
@@ -1704,21 +1521,18 @@
 
       // Now we need to write out the Split APKs.
       auto path_iter = options_.split_paths.begin();
-      auto split_constraints_iter = adjusted_constraints_list.begin();
-      for (std::unique_ptr<ResourceTable>& split_table :
-           table_splitter.splits()) {
+      auto split_constraints_iter = options_.split_constraints.begin();
+      for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
         if (context_->IsVerbose()) {
-          context_->GetDiagnostics()->Note(
-              DiagMessage(*path_iter)
-              << "generating split with configurations '"
-              << util::Joiner(split_constraints_iter->configs, ", ") << "'");
+          context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
+                                           << "generating split with configurations '"
+                                           << util::Joiner(split_constraints_iter->configs, ", ")
+                                           << "'");
         }
 
-        std::unique_ptr<IArchiveWriter> archive_writer =
-            MakeArchiveWriter(*path_iter);
+        std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
         if (!archive_writer) {
-          context_->GetDiagnostics()->Error(DiagMessage()
-                                            << "failed to create archive");
+          context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
           return 1;
         }
 
@@ -1728,13 +1542,13 @@
 
         XmlReferenceLinker linker;
         if (!linker.Consume(context_, split_manifest.get())) {
-          context_->GetDiagnostics()->Error(
-              DiagMessage() << "failed to create Split AndroidManifest.xml");
+          context_->GetDiagnostics()->Error(DiagMessage()
+                                            << "failed to create Split AndroidManifest.xml");
           return 1;
         }
 
-        if (!WriteApk(archive_writer.get(), &proguard_keep_set,
-                      split_manifest.get(), split_table.get())) {
+        if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
+                      split_table.get())) {
           return 1;
         }
 
@@ -1925,10 +1739,10 @@
   std::vector<std::string> split_args;
   Flags flags =
       Flags()
-          .RequiredFlag("-o", "Output path", &options.output_path)
-          .RequiredFlag("--manifest", "Path to the Android manifest to build",
+          .RequiredFlag("-o", "Output path.", &options.output_path)
+          .RequiredFlag("--manifest", "Path to the Android manifest to build.",
                         &options.manifest_path)
-          .OptionalFlagList("-I", "Adds an Android APK to link against", &options.include_paths)
+          .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
           .OptionalFlagList("-A",
                             "An assets directory to include in the APK. These are unprocessed.",
                             &options.assets_dirs)
@@ -1940,24 +1754,23 @@
                         "Specify the package ID to use for this app. Must be greater or equal to\n"
                         "0x7f and can't be used with --static-lib or --shared-lib.",
                         &package_id)
-          .OptionalFlag("--java", "Directory in which to generate R.java",
+          .OptionalFlag("--java", "Directory in which to generate R.java.",
                         &options.generate_java_class_path)
-          .OptionalFlag("--proguard", "Output file for generated Proguard rules",
+          .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
                         &options.generate_proguard_rules_path)
           .OptionalFlag("--proguard-main-dex",
-                        "Output file for generated Proguard rules for the main dex",
+                        "Output file for generated Proguard rules for the main dex.",
                         &options.generate_main_dex_proguard_rules_path)
-          .OptionalSwitch("--no-auto-version", "Disables automatic style and layout SDK versioning",
+          .OptionalSwitch("--no-auto-version",
+                          "Disables automatic style and layout SDK versioning.",
                           &options.no_auto_version)
           .OptionalSwitch("--no-version-vectors",
-                          "Disables automatic versioning of vector drawables. "
-                          "Use this only\n"
-                          "when building with vector drawable support library",
+                          "Disables automatic versioning of vector drawables. Use this only\n"
+                          "when building with vector drawable support library.",
                           &options.no_version_vectors)
           .OptionalSwitch("--no-version-transitions",
-                          "Disables automatic versioning of transition resources. "
-                          "Use this only\n"
-                          "when building with transition support library",
+                          "Disables automatic versioning of transition resources. Use this only\n"
+                          "when building with transition support library.",
                           &options.no_version_transitions)
           .OptionalSwitch("--no-resource-deduping",
                           "Disables automatic deduping of resources with\n"
@@ -1967,100 +1780,90 @@
                           "Enables encoding sparse entries using a binary search tree.\n"
                           "This decreases APK size at the cost of resource retrieval performance.",
                           &options.table_flattener_options.use_sparse_entries)
-          .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01",
+          .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
                           &legacy_x_flag)
-          .OptionalSwitch("-z", "Require localization of strings marked 'suggested'",
+          .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
                           &require_localization)
           .OptionalFlagList("-c",
                         "Comma separated list of configurations to include. The default\n"
-                        "is all configurations",
+                        "is all configurations.",
                         &configs)
           .OptionalFlag("--preferred-density",
                         "Selects the closest matching density and strips out all others.",
                         &preferred_density)
           .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
           .OptionalSwitch("--output-to-dir",
-                          "Outputs the APK contents to a directory specified "
-                          "by -o",
+                          "Outputs the APK contents to a directory specified by -o.",
                           &options.output_to_directory)
           .OptionalSwitch("--no-xml-namespaces",
-                          "Removes XML namespace prefix and URI "
-                          "information from AndroidManifest.xml\nand XML "
-                          "binaries in res/*.",
+                          "Removes XML namespace prefix and URI information from\n"
+                          "AndroidManifest.xml and XML binaries in res/*.",
                           &options.no_xml_namespaces)
           .OptionalFlag("--min-sdk-version",
-                        "Default minimum SDK version to use for "
-                        "AndroidManifest.xml",
+                        "Default minimum SDK version to use for AndroidManifest.xml.",
                         &options.manifest_fixer_options.min_sdk_version_default)
           .OptionalFlag("--target-sdk-version",
-                        "Default target SDK version to use for "
-                        "AndroidManifest.xml",
+                        "Default target SDK version to use for AndroidManifest.xml.",
                         &options.manifest_fixer_options.target_sdk_version_default)
           .OptionalFlag("--version-code",
-                        "Version code (integer) to inject into the "
-                        "AndroidManifest.xml if none is present",
+                        "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
+                        "present.",
                         &options.manifest_fixer_options.version_code_default)
           .OptionalFlag("--version-name",
-                        "Version name to inject into the AndroidManifest.xml "
-                        "if none is present",
+                        "Version name to inject into the AndroidManifest.xml if none is present.",
                         &options.manifest_fixer_options.version_name_default)
-          .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library", &shared_lib)
-          .OptionalSwitch("--static-lib", "Generate a static Android library", &static_lib)
+          .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
+                          &shared_lib)
+          .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
           .OptionalSwitch("--no-static-lib-packages",
-                          "Merge all library resources under the app's package",
+                          "Merge all library resources under the app's package.",
                           &options.no_static_lib_packages)
           .OptionalSwitch("--non-final-ids",
-                          "Generates R.java without the final modifier.\n"
-                          "This is implied when --static-lib is specified.",
+                          "Generates R.java without the final modifier. This is implied when\n"
+                          "--static-lib is specified.",
                           &options.generate_non_final_ids)
           .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
                         &stable_id_file_path)
           .OptionalFlag("--emit-ids",
-                        "Emit a file at the given path with a list of name to ID\n"
-                        "mappings, suitable for use with --stable-ids.",
+                        "Emit a file at the given path with a list of name to ID mappings,\n"
+                        "suitable for use with --stable-ids.",
                         &options.resource_id_map_path)
           .OptionalFlag("--private-symbols",
-                        "Package name to use when generating R.java for "
-                        "private symbols.\n"
-                        "If not specified, public and private symbols will use "
-                        "the application's "
-                        "package name",
+                        "Package name to use when generating R.java for private symbols.\n"
+                        "If not specified, public and private symbols will use the application's\n"
+                        "package name.",
                         &options.private_symbols)
-          .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java",
+          .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
                         &options.custom_java_package)
           .OptionalFlagList("--extra-packages",
-                            "Generate the same R.java but with different "
-                            "package names",
+                            "Generate the same R.java but with different package names.",
                             &extra_java_packages)
           .OptionalFlagList("--add-javadoc-annotation",
-                            "Adds a JavaDoc annotation to all "
-                            "generated Java classes",
+                            "Adds a JavaDoc annotation to all generated Java classes.",
                             &options.javadoc_annotations)
           .OptionalSwitch("--auto-add-overlay",
-                          "Allows the addition of new resources in "
-                          "overlays without <add-resource> tags",
+                          "Allows the addition of new resources in overlays without\n"
+                          "<add-resource> tags.",
                           &options.auto_add_overlay)
-          .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml",
+          .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
                         &options.manifest_fixer_options.rename_manifest_package)
           .OptionalFlag("--rename-instrumentation-target-package",
-                        "Changes the name of the target package for instrumentation. "
-                        "Most useful "
-                        "when used\nin conjunction with --rename-manifest-package",
+                        "Changes the name of the target package for instrumentation. Most useful\n"
+                        "when used in conjunction with --rename-manifest-package.",
                         &options.manifest_fixer_options.rename_instrumentation_target_package)
-          .OptionalFlagList("-0", "File extensions not to compress",
+          .OptionalFlagList("-0", "File extensions not to compress.",
                             &options.extensions_to_not_compress)
           .OptionalFlagList("--split",
-                            "Split resources matching a set of configs out to a "
-                            "Split APK.\nSyntax: path/to/output.apk:<config>[,<config>[...]]",
+                            "Split resources matching a set of configs out to a Split APK.\n"
+                            "Syntax: path/to/output.apk:<config>[,<config>[...]].",
                             &split_args)
-          .OptionalSwitch("-v", "Enables verbose logging", &verbose);
+          .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
 
   if (!flags.Parse("aapt2 link", args, &std::cerr)) {
     return 1;
   }
 
-  // Expand all argument-files passed into the command line. These start with
-  // '@'.
+  // Expand all argument-files passed into the command line. These start with '@'.
   std::vector<std::string> arg_list;
   for (const std::string& arg : flags.GetArgs()) {
     if (util::StartsWith(arg, "@")) {
@@ -2150,55 +1953,32 @@
     }
   }
 
-  AxisConfigFilter filter;
+  std::unique_ptr<IConfigFilter> filter;
   if (!configs.empty()) {
-    for (const std::string& config_arg : configs) {
-      for (const StringPiece& config_str : util::Tokenize(config_arg, ',')) {
-        ConfigDescription config;
-        LocaleValue lv;
-        if (lv.InitFromFilterString(config_str)) {
-          lv.WriteTo(&config);
-        } else if (!ConfigDescription::Parse(config_str, &config)) {
-          context.GetDiagnostics()->Error(DiagMessage() << "invalid config '"
-                                                        << config_str
-                                                        << "' for -c option");
-          return 1;
-        }
-
-        if (config.density != 0) {
-          context.GetDiagnostics()->Warn(DiagMessage() << "ignoring density '"
-                                                       << config
-                                                       << "' for -c option");
-        } else {
-          filter.AddConfig(config);
-        }
-      }
+    filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
+    if (filter == nullptr) {
+      return 1;
     }
-    options.table_splitter_options.config_filter = &filter;
+    options.table_splitter_options.config_filter = filter.get();
   }
 
   if (preferred_density) {
-    ConfigDescription preferred_density_config;
-    if (!ConfigDescription::Parse(preferred_density.value(),
-                                  &preferred_density_config)) {
-      context.GetDiagnostics()->Error(
-          DiagMessage() << "invalid density '" << preferred_density.value()
-                        << "' for --preferred-density option");
+    Maybe<uint16_t> density =
+        ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
+    if (!density) {
       return 1;
     }
+    options.table_splitter_options.preferred_densities.push_back(density.value());
+  }
 
-    // Clear the version that can be automatically added.
-    preferred_density_config.sdkVersion = 0;
-
-    if (preferred_density_config.diff(ConfigDescription::DefaultConfig()) !=
-        ConfigDescription::CONFIG_DENSITY) {
-      context.GetDiagnostics()->Error(
-          DiagMessage() << "invalid preferred density '"
-                        << preferred_density.value() << "'. "
-                        << "Preferred density must only be a density value");
+  // Parse the split parameters.
+  for (const std::string& split_arg : split_args) {
+    options.split_paths.push_back({});
+    options.split_constraints.push_back({});
+    if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
+                             &options.split_constraints.back())) {
       return 1;
     }
-    options.table_splitter_options.preferred_densities.push_back(preferred_density_config.density);
   }
 
   if (options.package_type != PackageType::kStaticLib && stable_id_file_path) {
@@ -2215,17 +1995,6 @@
        ".imy",   ".xmf",  ".mp4",  ".m4a", ".m4v",  ".3gp",  ".3gpp", ".3g2",
        ".3gpp2", ".amr",  ".awb",  ".wma", ".wmv",  ".webm", ".mkv"});
 
-  // Parse the split parameters.
-  for (const std::string& split_arg : split_args) {
-    options.split_paths.push_back({});
-    options.split_constraints.push_back({});
-    if (!ParseSplitParameter(split_arg, context.GetDiagnostics(),
-                             &options.split_paths.back(),
-                             &options.split_constraints.back())) {
-      return 1;
-    }
-  }
-
   // Turn off auto versioning for static-libs.
   if (options.package_type == PackageType::kStaticLib) {
     options.no_auto_version = true;
diff --git a/tools/aapt2/cmd/Optimize.cpp b/tools/aapt2/cmd/Optimize.cpp
new file mode 100644
index 0000000..8f8e0c8
--- /dev/null
+++ b/tools/aapt2/cmd/Optimize.cpp
@@ -0,0 +1,369 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <memory>
+#include <vector>
+
+#include "androidfw/StringPiece.h"
+
+#include "Diagnostics.h"
+#include "Flags.h"
+#include "LoadedApk.h"
+#include "ResourceUtils.h"
+#include "SdkConstants.h"
+#include "ValueVisitor.h"
+#include "cmd/Util.h"
+#include "flatten/TableFlattener.h"
+#include "flatten/XmlFlattener.h"
+#include "io/BigBufferInputStream.h"
+#include "io/Util.h"
+#include "optimize/ResourceDeduper.h"
+#include "optimize/VersionCollapser.h"
+#include "split/TableSplitter.h"
+
+using android::StringPiece;
+
+namespace aapt {
+
+struct OptimizeOptions {
+  // Path to the output APK.
+  std::string output_path;
+
+  // Details of the app extracted from the AndroidManifest.xml
+  AppInfo app_info;
+
+  // Split APK options.
+  TableSplitterOptions table_splitter_options;
+
+  // List of output split paths. These are in the same order as `split_constraints`.
+  std::vector<std::string> split_paths;
+
+  // List of SplitConstraints governing what resources go into each split. Ordered by `split_paths`.
+  std::vector<SplitConstraints> split_constraints;
+
+  TableFlattenerOptions table_flattener_options;
+};
+
+class OptimizeContext : public IAaptContext {
+ public:
+  IDiagnostics* GetDiagnostics() override {
+    return &diagnostics_;
+  }
+
+  NameMangler* GetNameMangler() override {
+    UNIMPLEMENTED(FATAL);
+    return nullptr;
+  }
+
+  const std::string& GetCompilationPackage() override {
+    static std::string empty;
+    return empty;
+  }
+
+  uint8_t GetPackageId() override {
+    return 0;
+  }
+
+  SymbolTable* GetExternalSymbols() override {
+    UNIMPLEMENTED(FATAL);
+    return nullptr;
+  }
+
+  bool IsVerbose() override {
+    return verbose_;
+  }
+
+  void SetVerbose(bool val) {
+    verbose_ = val;
+  }
+
+  void SetMinSdkVersion(int sdk_version) {
+    sdk_version_ = sdk_version;
+  }
+
+  int GetMinSdkVersion() override {
+    return sdk_version_;
+  }
+
+ private:
+  StdErrDiagnostics diagnostics_;
+  bool verbose_ = false;
+  int sdk_version_ = 0;
+};
+
+class OptimizeCommand {
+ public:
+  OptimizeCommand(OptimizeContext* context, const OptimizeOptions& options)
+      : options_(options), context_(context) {
+  }
+
+  int Run(std::unique_ptr<LoadedApk> apk) {
+    if (context_->IsVerbose()) {
+      context_->GetDiagnostics()->Note(DiagMessage() << "Optimizing APK...");
+    }
+
+    VersionCollapser collapser;
+    if (!collapser.Consume(context_, apk->GetResourceTable())) {
+      return 1;
+    }
+
+    ResourceDeduper deduper;
+    if (!deduper.Consume(context_, apk->GetResourceTable())) {
+      context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
+      return 1;
+    }
+
+    // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
+    // equal to the minSdk.
+    options_.split_constraints =
+        AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
+
+    // Stripping the APK using the TableSplitter. The resource table is modified in place in the
+    // LoadedApk.
+    TableSplitter splitter(options_.split_constraints, options_.table_splitter_options);
+    if (!splitter.VerifySplitConstraints(context_)) {
+      return 1;
+    }
+    splitter.SplitTable(apk->GetResourceTable());
+
+    auto path_iter = options_.split_paths.begin();
+    auto split_constraints_iter = options_.split_constraints.begin();
+    for (std::unique_ptr<ResourceTable>& split_table : splitter.splits()) {
+      if (context_->IsVerbose()) {
+        context_->GetDiagnostics()->Note(
+            DiagMessage(*path_iter) << "generating split with configurations '"
+                                    << util::Joiner(split_constraints_iter->configs, ", ") << "'");
+      }
+
+      // Generate an AndroidManifest.xml for each split.
+      std::unique_ptr<xml::XmlResource> split_manifest =
+          GenerateSplitManifest(options_.app_info, *split_constraints_iter);
+      std::unique_ptr<IArchiveWriter> split_writer =
+          CreateZipFileArchiveWriter(context_->GetDiagnostics(), *path_iter);
+      if (!split_writer) {
+        return 1;
+      }
+
+      if (!WriteSplitApk(split_table.get(), split_manifest.get(), split_writer.get())) {
+        return 1;
+      }
+
+      ++path_iter;
+      ++split_constraints_iter;
+    }
+
+    std::unique_ptr<IArchiveWriter> writer =
+        CreateZipFileArchiveWriter(context_->GetDiagnostics(), options_.output_path);
+    if (!apk->WriteToArchive(context_, options_.table_flattener_options, writer.get())) {
+      return 1;
+    }
+
+    return 0;
+  }
+
+ private:
+  bool WriteSplitApk(ResourceTable* table, xml::XmlResource* manifest, IArchiveWriter* writer) {
+    BigBuffer manifest_buffer(4096);
+    XmlFlattener xml_flattener(&manifest_buffer, {});
+    if (!xml_flattener.Consume(context_, manifest)) {
+      return false;
+    }
+
+    io::BigBufferInputStream manifest_buffer_in(&manifest_buffer);
+    if (!io::CopyInputStreamToArchive(context_, &manifest_buffer_in, "AndroidManifest.xml",
+                                      ArchiveEntry::kCompress, writer)) {
+      return false;
+    }
+
+    std::map<std::pair<ConfigDescription, StringPiece>, FileReference*> config_sorted_files;
+    for (auto& pkg : table->packages) {
+      for (auto& type : pkg->types) {
+        // Sort by config and name, so that we get better locality in the zip file.
+        config_sorted_files.clear();
+
+        for (auto& entry : type->entries) {
+          for (auto& config_value : entry->values) {
+            FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
+            if (file_ref == nullptr) {
+              continue;
+            }
+
+            if (file_ref->file == nullptr) {
+              ResourceNameRef name(pkg->name, type->type, entry->name);
+              context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
+                                                << "file for resource " << name << " with config '"
+                                                << config_value->config << "' not found");
+              return false;
+            }
+
+            const StringPiece entry_name = entry->name;
+            config_sorted_files[std::make_pair(config_value->config, entry_name)] = file_ref;
+          }
+        }
+
+        for (auto& entry : config_sorted_files) {
+          FileReference* file_ref = entry.second;
+          uint32_t compression_flags =
+              file_ref->file->WasCompressed() ? ArchiveEntry::kCompress : 0u;
+          if (!io::CopyFileToArchive(context_, file_ref->file, *file_ref->path, compression_flags,
+                                     writer)) {
+            return false;
+          }
+        }
+      }
+    }
+
+    BigBuffer table_buffer(4096);
+    TableFlattener table_flattener(options_.table_flattener_options, &table_buffer);
+    if (!table_flattener.Consume(context_, table)) {
+      return false;
+    }
+
+    io::BigBufferInputStream table_buffer_in(&table_buffer);
+    if (!io::CopyInputStreamToArchive(context_, &table_buffer_in, "resources.arsc",
+                                      ArchiveEntry::kAlign, writer)) {
+      return false;
+    }
+    return true;
+  }
+
+  OptimizeOptions options_;
+  OptimizeContext* context_;
+};
+
+bool ExtractAppDataFromManifest(OptimizeContext* context, LoadedApk* apk,
+                                OptimizeOptions* out_options) {
+  io::IFile* manifest_file = apk->GetFileCollection()->FindFile("AndroidManifest.xml");
+  if (manifest_file == nullptr) {
+    context->GetDiagnostics()->Error(DiagMessage(apk->GetSource())
+                                     << "missing AndroidManifest.xml");
+    return false;
+  }
+
+  std::unique_ptr<io::IData> data = manifest_file->OpenAsData();
+  if (data == nullptr) {
+    context->GetDiagnostics()->Error(DiagMessage(manifest_file->GetSource())
+                                     << "failed to open file");
+    return false;
+  }
+
+  std::unique_ptr<xml::XmlResource> manifest = xml::Inflate(
+      data->data(), data->size(), context->GetDiagnostics(), manifest_file->GetSource());
+  if (manifest == nullptr) {
+    context->GetDiagnostics()->Error(DiagMessage() << "failed to read binary AndroidManifest.xml");
+    return false;
+  }
+
+  Maybe<AppInfo> app_info =
+      ExtractAppInfoFromBinaryManifest(manifest.get(), context->GetDiagnostics());
+  if (!app_info) {
+    context->GetDiagnostics()->Error(DiagMessage()
+                                     << "failed to extract data from AndroidManifest.xml");
+    return false;
+  }
+
+  out_options->app_info = std::move(app_info.value());
+  context->SetMinSdkVersion(out_options->app_info.min_sdk_version.value_or_default(0));
+  return true;
+}
+
+int Optimize(const std::vector<StringPiece>& args) {
+  OptimizeContext context;
+  OptimizeOptions options;
+  Maybe<std::string> target_densities;
+  std::vector<std::string> configs;
+  std::vector<std::string> split_args;
+  bool verbose = false;
+  Flags flags =
+      Flags()
+          .RequiredFlag("-o", "Path to the output APK.", &options.output_path)
+          .OptionalFlag(
+              "--target-densities",
+              "Comma separated list of the screen densities that the APK will be optimized for.\n"
+              "All the resources that would be unused on devices of the given densities will be \n"
+              "removed from the APK.",
+              &target_densities)
+          .OptionalFlagList("-c",
+                            "Comma separated list of configurations to include. The default\n"
+                            "is all configurations.",
+                            &configs)
+          .OptionalFlagList("--split",
+                            "Split resources matching a set of configs out to a "
+                            "Split APK.\nSyntax: path/to/output.apk:<config>[,<config>[...]].",
+                            &split_args)
+          .OptionalSwitch("--enable-sparse-encoding",
+                          "Enables encoding sparse entries using a binary search tree.\n"
+                          "This decreases APK size at the cost of resource retrieval performance.",
+                          &options.table_flattener_options.use_sparse_entries)
+          .OptionalSwitch("-v", "Enables verbose logging", &verbose);
+
+  if (!flags.Parse("aapt2 optimize", args, &std::cerr)) {
+    return 1;
+  }
+
+  if (flags.GetArgs().size() != 1u) {
+    std::cerr << "must have one APK as argument.\n\n";
+    flags.Usage("aapt2 optimize", &std::cerr);
+    return 1;
+  }
+
+  std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(&context, flags.GetArgs()[0]);
+  if (!apk) {
+    return 1;
+  }
+
+  context.SetVerbose(verbose);
+
+  if (target_densities) {
+    // Parse the target screen densities.
+    for (const StringPiece& config_str : util::Tokenize(target_densities.value(), ',')) {
+      Maybe<uint16_t> target_density =
+          ParseTargetDensityParameter(config_str, context.GetDiagnostics());
+      if (!target_density) {
+        return 1;
+      }
+      options.table_splitter_options.preferred_densities.push_back(target_density.value());
+    }
+  }
+
+  std::unique_ptr<IConfigFilter> filter;
+  if (!configs.empty()) {
+    filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
+    if (filter == nullptr) {
+      return 1;
+    }
+    options.table_splitter_options.config_filter = filter.get();
+  }
+
+  // Parse the split parameters.
+  for (const std::string& split_arg : split_args) {
+    options.split_paths.push_back({});
+    options.split_constraints.push_back({});
+    if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
+                             &options.split_constraints.back())) {
+      return 1;
+    }
+  }
+
+  if (!ExtractAppDataFromManifest(&context, apk.get(), &options)) {
+    return 1;
+  }
+
+  OptimizeCommand cmd(&context, options);
+  return cmd.Run(std::move(apk));
+}
+
+}  // namespace aapt
diff --git a/tools/aapt2/cmd/Util.cpp b/tools/aapt2/cmd/Util.cpp
new file mode 100644
index 0000000..fd94bbc
--- /dev/null
+++ b/tools/aapt2/cmd/Util.cpp
@@ -0,0 +1,347 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "cmd/Util.h"
+
+#include <vector>
+
+#include "android-base/logging.h"
+
+#include "ConfigDescription.h"
+#include "Locale.h"
+#include "ResourceUtils.h"
+#include "ValueVisitor.h"
+#include "split/TableSplitter.h"
+#include "util/Maybe.h"
+#include "util/Util.h"
+
+using android::StringPiece;
+
+namespace aapt {
+
+Maybe<uint16_t> ParseTargetDensityParameter(const StringPiece& arg, IDiagnostics* diag) {
+  ConfigDescription preferred_density_config;
+  if (!ConfigDescription::Parse(arg, &preferred_density_config)) {
+    diag->Error(DiagMessage() << "invalid density '" << arg << "' for --preferred-density option");
+    return {};
+  }
+
+  // Clear the version that can be automatically added.
+  preferred_density_config.sdkVersion = 0;
+
+  if (preferred_density_config.diff(ConfigDescription::DefaultConfig()) !=
+      ConfigDescription::CONFIG_DENSITY) {
+    diag->Error(DiagMessage() << "invalid preferred density '" << arg << "'. "
+                              << "Preferred density must only be a density value");
+    return {};
+  }
+  return preferred_density_config.density;
+}
+
+bool ParseSplitParameter(const StringPiece& arg, IDiagnostics* diag, std::string* out_path,
+                         SplitConstraints* out_split) {
+  CHECK(diag != nullptr);
+  CHECK(out_path != nullptr);
+  CHECK(out_split != nullptr);
+
+  std::vector<std::string> parts = util::Split(arg, ':');
+  if (parts.size() != 2) {
+    diag->Error(DiagMessage() << "invalid split parameter '" << arg << "'");
+    diag->Note(DiagMessage() << "should be --split path/to/output.apk:<config>[,<config>...]");
+    return false;
+  }
+
+  *out_path = parts[0];
+  std::vector<ConfigDescription> configs;
+  for (const StringPiece& config_str : util::Tokenize(parts[1], ',')) {
+    ConfigDescription config;
+    if (!ConfigDescription::Parse(config_str, &config)) {
+      diag->Error(DiagMessage() << "invalid config '" << config_str << "' in split parameter '"
+                                << arg << "'");
+      return false;
+    }
+    out_split->configs.insert(config);
+  }
+  return true;
+}
+
+std::unique_ptr<IConfigFilter> ParseConfigFilterParameters(const std::vector<std::string>& args,
+                                                           IDiagnostics* diag) {
+  std::unique_ptr<AxisConfigFilter> filter = util::make_unique<AxisConfigFilter>();
+  for (const std::string& config_arg : args) {
+    for (const StringPiece& config_str : util::Tokenize(config_arg, ',')) {
+      ConfigDescription config;
+      LocaleValue lv;
+      if (lv.InitFromFilterString(config_str)) {
+        lv.WriteTo(&config);
+      } else if (!ConfigDescription::Parse(config_str, &config)) {
+        diag->Error(DiagMessage() << "invalid config '" << config_str << "' for -c option");
+        return {};
+      }
+
+      if (config.density != 0) {
+        diag->Warn(DiagMessage() << "ignoring density '" << config << "' for -c option");
+      } else {
+        filter->AddConfig(config);
+      }
+    }
+  }
+  return std::move(filter);
+}
+
+// Adjust the SplitConstraints so that their SDK version is stripped if it
+// is less than or equal to the minSdk. Otherwise the resources that have had
+// their SDK version stripped due to minSdk won't ever match.
+std::vector<SplitConstraints> AdjustSplitConstraintsForMinSdk(
+    int min_sdk, const std::vector<SplitConstraints>& split_constraints) {
+  std::vector<SplitConstraints> adjusted_constraints;
+  adjusted_constraints.reserve(split_constraints.size());
+  for (const SplitConstraints& constraints : split_constraints) {
+    SplitConstraints constraint;
+    for (const ConfigDescription& config : constraints.configs) {
+      if (config.sdkVersion <= min_sdk) {
+        constraint.configs.insert(config.CopyWithoutSdkVersion());
+      } else {
+        constraint.configs.insert(config);
+      }
+    }
+    adjusted_constraints.push_back(std::move(constraint));
+  }
+  return adjusted_constraints;
+}
+
+static xml::AaptAttribute CreateAttributeWithId(const ResourceId& id) {
+  return xml::AaptAttribute{id, Attribute(true)};
+}
+
+std::unique_ptr<xml::XmlResource> GenerateSplitManifest(const AppInfo& app_info,
+                                                        const SplitConstraints& constraints) {
+  const ResourceId kVersionCode(0x0101021b);
+  const ResourceId kRevisionCode(0x010104d5);
+  const ResourceId kHasCode(0x0101000c);
+
+  std::unique_ptr<xml::XmlResource> doc = util::make_unique<xml::XmlResource>();
+
+  std::unique_ptr<xml::Namespace> namespace_android = util::make_unique<xml::Namespace>();
+  namespace_android->namespace_uri = xml::kSchemaAndroid;
+  namespace_android->namespace_prefix = "android";
+
+  std::unique_ptr<xml::Element> manifest_el = util::make_unique<xml::Element>();
+  manifest_el->name = "manifest";
+  manifest_el->attributes.push_back(xml::Attribute{"", "package", app_info.package});
+
+  if (app_info.version_code) {
+    const uint32_t version_code = app_info.version_code.value();
+    manifest_el->attributes.push_back(xml::Attribute{
+        xml::kSchemaAndroid, "versionCode", std::to_string(version_code),
+        CreateAttributeWithId(kVersionCode),
+        util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_INT_DEC, version_code)});
+  }
+
+  if (app_info.revision_code) {
+    const uint32_t revision_code = app_info.revision_code.value();
+    manifest_el->attributes.push_back(xml::Attribute{
+        xml::kSchemaAndroid, "revisionCode", std::to_string(revision_code),
+        CreateAttributeWithId(kRevisionCode),
+        util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_INT_DEC, revision_code)});
+  }
+
+  std::stringstream split_name;
+  if (app_info.split_name) {
+    split_name << app_info.split_name.value() << ".";
+  }
+  split_name << "config." << util::Joiner(constraints.configs, "_");
+
+  manifest_el->attributes.push_back(xml::Attribute{"", "split", split_name.str()});
+
+  if (app_info.split_name) {
+    manifest_el->attributes.push_back(
+        xml::Attribute{"", "configForSplit", app_info.split_name.value()});
+  }
+
+  std::unique_ptr<xml::Element> application_el = util::make_unique<xml::Element>();
+  application_el->name = "application";
+  application_el->attributes.push_back(
+      xml::Attribute{xml::kSchemaAndroid, "hasCode", "false", CreateAttributeWithId(kHasCode),
+                     util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_INT_BOOLEAN, 0u)});
+
+  manifest_el->AppendChild(std::move(application_el));
+  namespace_android->AppendChild(std::move(manifest_el));
+  doc->root = std::move(namespace_android);
+  return doc;
+}
+
+static Maybe<std::string> ExtractCompiledString(xml::Attribute* attr, std::string* out_error) {
+  if (attr->compiled_value != nullptr) {
+    String* compiled_str = ValueCast<String>(attr->compiled_value.get());
+    if (compiled_str != nullptr) {
+      if (!compiled_str->value->empty()) {
+        return *compiled_str->value;
+      } else {
+        *out_error = "compiled value is an empty string";
+        return {};
+      }
+    }
+    *out_error = "compiled value is not a string";
+    return {};
+  }
+
+  // Fallback to the plain text value if there is one.
+  if (!attr->value.empty()) {
+    return attr->value;
+  }
+  *out_error = "value is an empty string";
+  return {};
+}
+
+static Maybe<uint32_t> ExtractCompiledInt(xml::Attribute* attr, std::string* out_error) {
+  if (attr->compiled_value != nullptr) {
+    BinaryPrimitive* compiled_prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get());
+    if (compiled_prim != nullptr) {
+      if (compiled_prim->value.dataType >= android::Res_value::TYPE_FIRST_INT &&
+          compiled_prim->value.dataType <= android::Res_value::TYPE_LAST_INT) {
+        return compiled_prim->value.data;
+      }
+    }
+    *out_error = "compiled value is not an integer";
+    return {};
+  }
+
+  // Fallback to the plain text value if there is one.
+  Maybe<uint32_t> integer = ResourceUtils::ParseInt(attr->value);
+  if (integer) {
+    return integer;
+  }
+  std::stringstream error_msg;
+  error_msg << "'" << attr->value << "' is not a valid integer";
+  *out_error = error_msg.str();
+  return {};
+}
+
+static Maybe<int> ExtractSdkVersion(xml::Attribute* attr, std::string* out_error) {
+  if (attr->compiled_value != nullptr) {
+    BinaryPrimitive* compiled_prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get());
+    if (compiled_prim != nullptr) {
+      if (compiled_prim->value.dataType >= android::Res_value::TYPE_FIRST_INT &&
+          compiled_prim->value.dataType <= android::Res_value::TYPE_LAST_INT) {
+        return compiled_prim->value.data;
+      }
+      *out_error = "compiled value is not an integer or string";
+      return {};
+    }
+
+    String* compiled_str = ValueCast<String>(attr->compiled_value.get());
+    if (compiled_str != nullptr) {
+      Maybe<int> sdk_version = ResourceUtils::ParseSdkVersion(*compiled_str->value);
+      if (sdk_version) {
+        return sdk_version;
+      }
+
+      *out_error = "compiled string value is not a valid SDK version";
+      return {};
+    }
+    *out_error = "compiled value is not an integer or string";
+    return {};
+  }
+
+  // Fallback to the plain text value if there is one.
+  Maybe<int> sdk_version = ResourceUtils::ParseSdkVersion(attr->value);
+  if (sdk_version) {
+    return sdk_version;
+  }
+  std::stringstream error_msg;
+  error_msg << "'" << attr->value << "' is not a valid SDK version";
+  *out_error = error_msg.str();
+  return {};
+}
+
+Maybe<AppInfo> ExtractAppInfoFromBinaryManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
+  // Make sure the first element is <manifest> with package attribute.
+  xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
+  if (manifest_el == nullptr) {
+    return {};
+  }
+
+  AppInfo app_info;
+
+  if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
+    diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
+    return {};
+  }
+
+  xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
+  if (!package_attr) {
+    diag->Error(DiagMessage(xml_res->file.source) << "<manifest> must have a 'package' attribute");
+    return {};
+  }
+
+  std::string error_msg;
+  Maybe<std::string> maybe_package = ExtractCompiledString(package_attr, &error_msg);
+  if (!maybe_package) {
+    diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
+                << "invalid package name: " << error_msg);
+    return {};
+  }
+  app_info.package = maybe_package.value();
+
+  if (xml::Attribute* version_code_attr =
+          manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
+    Maybe<uint32_t> maybe_code = ExtractCompiledInt(version_code_attr, &error_msg);
+    if (!maybe_code) {
+      diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
+                  << "invalid android:versionCode: " << error_msg);
+      return {};
+    }
+    app_info.version_code = maybe_code.value();
+  }
+
+  if (xml::Attribute* revision_code_attr =
+          manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
+    Maybe<uint32_t> maybe_code = ExtractCompiledInt(revision_code_attr, &error_msg);
+    if (!maybe_code) {
+      diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
+                  << "invalid android:revisionCode: " << error_msg);
+      return {};
+    }
+    app_info.revision_code = maybe_code.value();
+  }
+
+  if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
+    Maybe<std::string> maybe_split_name = ExtractCompiledString(split_name_attr, &error_msg);
+    if (!maybe_split_name) {
+      diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
+                  << "invalid split name: " << error_msg);
+      return {};
+    }
+    app_info.split_name = maybe_split_name.value();
+  }
+
+  if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
+    if (xml::Attribute* min_sdk =
+            uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
+      Maybe<int> maybe_sdk = ExtractSdkVersion(min_sdk, &error_msg);
+      if (!maybe_sdk) {
+        diag->Error(DiagMessage(xml_res->file.source.WithLine(uses_sdk_el->line_number))
+                    << "invalid android:minSdkVersion: " << error_msg);
+        return {};
+      }
+      app_info.min_sdk_version = maybe_sdk.value();
+    }
+  }
+  return app_info;
+}
+
+}  // namespace aapt
diff --git a/tools/aapt2/cmd/Util.h b/tools/aapt2/cmd/Util.h
new file mode 100644
index 0000000..fd9b39c
--- /dev/null
+++ b/tools/aapt2/cmd/Util.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef AAPT_SPLIT_UTIL_H
+#define AAPT_SPLIT_UTIL_H
+
+#include "androidfw/StringPiece.h"
+
+#include "AppInfo.h"
+#include "Diagnostics.h"
+#include "SdkConstants.h"
+#include "filter/ConfigFilter.h"
+#include "split/TableSplitter.h"
+#include "util/Maybe.h"
+#include "xml/XmlDom.h"
+
+namespace aapt {
+
+// Parses a configuration density (ex. hdpi, xxhdpi, 234dpi, anydpi, etc).
+// Returns Nothing and logs a human friendly error message if the string was not legal.
+Maybe<uint16_t> ParseTargetDensityParameter(const android::StringPiece& arg, IDiagnostics* diag);
+
+// Parses a string of the form 'path/to/output.apk:<config>[,<config>...]' and fills in
+// `out_path` with the path and `out_split` with the set of ConfigDescriptions.
+// Returns false and logs a human friendly error message if the string was not legal.
+bool ParseSplitParameter(const android::StringPiece& arg, IDiagnostics* diag, std::string* out_path,
+                         SplitConstraints* out_split);
+
+// Parses a set of config filter strings of the form 'en,fr-rFR' and returns an IConfigFilter.
+// Returns nullptr and logs a human friendly error message if the string was not legal.
+std::unique_ptr<IConfigFilter> ParseConfigFilterParameters(const std::vector<std::string>& args,
+                                                           IDiagnostics* diag);
+
+// Adjust the SplitConstraints so that their SDK version is stripped if it
+// is less than or equal to the min_sdk. Otherwise the resources that have had
+// their SDK version stripped due to min_sdk won't ever match.
+std::vector<SplitConstraints> AdjustSplitConstraintsForMinSdk(
+    int min_sdk, const std::vector<SplitConstraints>& split_constraints);
+
+// Generates a split AndroidManifest.xml given the split constraints and app info. The resulting
+// XmlResource does not need to be linked via XmlReferenceLinker.
+// This will never fail/return nullptr.
+std::unique_ptr<xml::XmlResource> GenerateSplitManifest(const AppInfo& app_info,
+                                                        const SplitConstraints& constraints);
+
+// Extracts relevant info from the AndroidManifest.xml.
+Maybe<AppInfo> ExtractAppInfoFromBinaryManifest(xml::XmlResource* xml_res, IDiagnostics* diag);
+
+}  // namespace aapt
+
+#endif /* AAPT_SPLIT_UTIL_H */
diff --git a/tools/aapt2/io/Io.cpp b/tools/aapt2/io/Io.cpp
deleted file mode 100644
index f5c5737..0000000
--- a/tools/aapt2/io/Io.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "io/Io.h"
-
-#include <cstring>
-
-namespace aapt {
-namespace io {
-
-bool Copy(OutputStream* out, InputStream* in) {
-  const void* in_buffer;
-  size_t in_len;
-  while (in->Next(&in_buffer, &in_len)) {
-    void* out_buffer;
-    size_t out_len;
-    if (!out->Next(&out_buffer, &out_len)) {
-      return !out->HadError();
-    }
-
-    const size_t bytes_to_copy = in_len < out_len ? in_len : out_len;
-    memcpy(out_buffer, in_buffer, bytes_to_copy);
-    out->BackUp(out_len - bytes_to_copy);
-    in->BackUp(in_len - bytes_to_copy);
-  }
-  return !in->HadError();
-}
-
-}  // namespace io
-}  // namespace aapt
diff --git a/tools/aapt2/io/Io.h b/tools/aapt2/io/Io.h
index 2a34d4d..a656740 100644
--- a/tools/aapt2/io/Io.h
+++ b/tools/aapt2/io/Io.h
@@ -87,10 +87,6 @@
   virtual bool HadError() const = 0;
 };
 
-// Copies the data from in to out. Returns false if there was an error.
-// If there was an error, check the individual streams' HadError/GetError methods.
-bool Copy(OutputStream* out, InputStream* in);
-
 }  // namespace io
 }  // namespace aapt
 
diff --git a/tools/aapt2/io/Util.cpp b/tools/aapt2/io/Util.cpp
new file mode 100644
index 0000000..15114e8
--- /dev/null
+++ b/tools/aapt2/io/Util.cpp
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "io/Util.h"
+
+#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
+
+namespace aapt {
+namespace io {
+
+bool CopyInputStreamToArchive(IAaptContext* context, InputStream* in, const std::string& out_path,
+                              uint32_t compression_flags, IArchiveWriter* writer) {
+  if (context->IsVerbose()) {
+    context->GetDiagnostics()->Note(DiagMessage() << "writing " << out_path << " to archive");
+  }
+
+  if (!writer->WriteFile(out_path, compression_flags, in)) {
+    context->GetDiagnostics()->Error(DiagMessage() << "failed to write " << out_path
+                                                   << " to archive: " << writer->GetError());
+    return false;
+  }
+  return true;
+}
+
+bool CopyFileToArchive(IAaptContext* context, io::IFile* file, const std::string& out_path,
+                       uint32_t compression_flags, IArchiveWriter* writer) {
+  std::unique_ptr<io::IData> data = file->OpenAsData();
+  if (!data) {
+    context->GetDiagnostics()->Error(DiagMessage(file->GetSource()) << "failed to open file");
+    return false;
+  }
+  return CopyInputStreamToArchive(context, data.get(), out_path, compression_flags, writer);
+}
+
+bool CopyProtoToArchive(IAaptContext* context, ::google::protobuf::MessageLite* proto_msg,
+                        const std::string& out_path, uint32_t compression_flags,
+                        IArchiveWriter* writer) {
+  if (context->IsVerbose()) {
+    context->GetDiagnostics()->Note(DiagMessage() << "writing " << out_path << " to archive");
+  }
+
+  if (writer->StartEntry(out_path, compression_flags)) {
+    // Make sure CopyingOutputStreamAdaptor is deleted before we call writer->FinishEntry().
+    {
+      // Wrap our IArchiveWriter with an adaptor that implements the ZeroCopyOutputStream interface.
+      ::google::protobuf::io::CopyingOutputStreamAdaptor adaptor(writer);
+      if (!proto_msg->SerializeToZeroCopyStream(&adaptor)) {
+        context->GetDiagnostics()->Error(DiagMessage() << "failed to write " << out_path
+                                                       << " to archive");
+        return false;
+      }
+    }
+
+    if (writer->FinishEntry()) {
+      return true;
+    }
+  }
+  context->GetDiagnostics()->Error(DiagMessage() << "failed to write " << out_path
+                                                 << " to archive: " << writer->GetError());
+  return false;
+}
+
+bool Copy(OutputStream* out, InputStream* in) {
+  const void* in_buffer;
+  size_t in_len;
+  while (in->Next(&in_buffer, &in_len)) {
+    void* out_buffer;
+    size_t out_len;
+    if (!out->Next(&out_buffer, &out_len)) {
+      return !out->HadError();
+    }
+
+    const size_t bytes_to_copy = in_len < out_len ? in_len : out_len;
+    memcpy(out_buffer, in_buffer, bytes_to_copy);
+    out->BackUp(out_len - bytes_to_copy);
+    in->BackUp(in_len - bytes_to_copy);
+  }
+  return !in->HadError();
+}
+
+}  // namespace io
+}  // namespace aapt
diff --git a/tools/aapt2/io/Util.h b/tools/aapt2/io/Util.h
new file mode 100644
index 0000000..ec1ddb8
--- /dev/null
+++ b/tools/aapt2/io/Util.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef AAPT_IO_UTIL_H
+#define AAPT_IO_UTIL_H
+
+#include <string>
+
+#include "google/protobuf/message_lite.h"
+
+#include "flatten/Archive.h"
+#include "io/File.h"
+#include "io/Io.h"
+#include "process/IResourceTableConsumer.h"
+
+namespace aapt {
+namespace io {
+
+bool CopyInputStreamToArchive(IAaptContext* context, InputStream* in, const std::string& out_path,
+                              uint32_t compression_flags, IArchiveWriter* writer);
+
+bool CopyFileToArchive(IAaptContext* context, IFile* file, const std::string& out_path,
+                       uint32_t compression_flags, IArchiveWriter* writer);
+
+bool CopyProtoToArchive(IAaptContext* context, ::google::protobuf::MessageLite* proto_msg,
+                        const std::string& out_path, uint32_t compression_flags,
+                        IArchiveWriter* writer);
+
+// Copies the data from in to out. Returns false if there was an error.
+// If there was an error, check the individual streams' HadError/GetError methods.
+bool Copy(OutputStream* out, InputStream* in);
+
+}  // namespace io
+}  // namespace aapt
+
+#endif /* AAPT_IO_UTIL_H */
diff --git a/tools/aapt2/optimize/Optimize.cpp b/tools/aapt2/optimize/Optimize.cpp
deleted file mode 100644
index 9615962..0000000
--- a/tools/aapt2/optimize/Optimize.cpp
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <memory>
-#include <vector>
-
-#include "androidfw/StringPiece.h"
-
-#include "Diagnostics.h"
-#include "Flags.h"
-#include "LoadedApk.h"
-#include "SdkConstants.h"
-#include "flatten/TableFlattener.h"
-#include "optimize/ResourceDeduper.h"
-#include "optimize/VersionCollapser.h"
-#include "split/TableSplitter.h"
-
-using android::StringPiece;
-
-namespace aapt {
-
-struct OptimizeOptions {
-  // Path to the output APK.
-  std::string output_path;
-
-  // List of screen density configurations the APK will be optimized for.
-  std::vector<ConfigDescription> target_configs;
-
-  TableFlattenerOptions table_flattener_options;
-};
-
-class OptimizeContext : public IAaptContext {
- public:
-  IDiagnostics* GetDiagnostics() override { return &diagnostics_; }
-
-  NameMangler* GetNameMangler() override {
-    abort();
-    return nullptr;
-  }
-
-  const std::string& GetCompilationPackage() override {
-    static std::string empty;
-    return empty;
-  }
-
-  uint8_t GetPackageId() override { return 0; }
-
-  SymbolTable* GetExternalSymbols() override {
-    abort();
-    return nullptr;
-  }
-
-  bool IsVerbose() override { return verbose_; }
-
-  void SetVerbose(bool val) { verbose_ = val; }
-
-  void SetMinSdkVersion(int sdk_version) { sdk_version_ = sdk_version; }
-
-  int GetMinSdkVersion() override { return sdk_version_; }
-
- private:
-  StdErrDiagnostics diagnostics_;
-  bool verbose_ = false;
-  int sdk_version_ = 0;
-};
-
-class OptimizeCommand {
- public:
-  OptimizeCommand(OptimizeContext* context, const OptimizeOptions& options)
-      : options_(options),
-        context_(context) {}
-
-  int Run(std::unique_ptr<LoadedApk> apk) {
-    if (context_->IsVerbose()) {
-      context_->GetDiagnostics()->Note(DiagMessage() << "Optimizing APK...");
-    }
-
-    VersionCollapser collapser;
-    if (!collapser.Consume(context_, apk->GetResourceTable())) {
-      return 1;
-    }
-
-    ResourceDeduper deduper;
-    if (!deduper.Consume(context_, apk->GetResourceTable())) {
-      context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
-      return 1;
-    }
-
-    // Stripping the APK using the TableSplitter with no splits and the target
-    // densities as the preferred densities. The resource table is modified in
-    // place in the LoadedApk.
-    TableSplitterOptions splitter_options;
-    for (auto& config : options_.target_configs) {
-      splitter_options.preferred_densities.push_back(config.density);
-    }
-    std::vector<SplitConstraints> splits;
-    TableSplitter splitter(splits, splitter_options);
-    splitter.SplitTable(apk->GetResourceTable());
-
-    std::unique_ptr<IArchiveWriter> writer =
-        CreateZipFileArchiveWriter(context_->GetDiagnostics(), options_.output_path);
-    if (!apk->WriteToArchive(context_, options_.table_flattener_options, writer.get())) {
-      return 1;
-    }
-
-    return 0;
-  }
-
- private:
-  OptimizeOptions options_;
-  OptimizeContext* context_;
-};
-
-int Optimize(const std::vector<StringPiece>& args) {
-  OptimizeContext context;
-  OptimizeOptions options;
-  Maybe<std::string> target_densities;
-  bool verbose = false;
-  Flags flags =
-      Flags()
-          .RequiredFlag("-o", "Path to the output APK.", &options.output_path)
-          .OptionalFlag(
-              "--target-densities",
-              "Comma separated list of the screen densities that the APK will "
-              "be optimized for. All the resources that would be unused on "
-              "devices of the given densities will be removed from the APK.",
-              &target_densities)
-          .OptionalSwitch("--enable-sparse-encoding",
-                          "Enables encoding sparse entries using a binary search tree.\n"
-                          "This decreases APK size at the cost of resource retrieval performance.",
-                          &options.table_flattener_options.use_sparse_entries)
-          .OptionalSwitch("-v", "Enables verbose logging", &verbose);
-
-  if (!flags.Parse("aapt2 optimize", args, &std::cerr)) {
-    return 1;
-  }
-
-  if (flags.GetArgs().size() != 1u) {
-    std::cerr << "must have one APK as argument.\n\n";
-    flags.Usage("aapt2 optimize", &std::cerr);
-    return 1;
-  }
-
-  std::unique_ptr<LoadedApk> apk =
-      LoadedApk::LoadApkFromPath(&context, flags.GetArgs()[0]);
-  if (!apk) {
-    return 1;
-  }
-
-  if (verbose) {
-    context.SetVerbose(verbose);
-  }
-
-  if (target_densities) {
-    // Parse the target screen densities.
-    for (const StringPiece& config_str : util::Tokenize(target_densities.value(), ',')) {
-      ConfigDescription config;
-      if (!ConfigDescription::Parse(config_str, &config) || config.density == 0) {
-        context.GetDiagnostics()->Error(
-            DiagMessage() << "invalid density '" << config_str
-                          << "' for --target-densities option");
-        return 1;
-      }
-
-      // Clear the version that can be automatically added.
-      config.sdkVersion = 0;
-
-      if (config.diff(ConfigDescription::DefaultConfig()) !=
-          ConfigDescription::CONFIG_DENSITY) {
-        context.GetDiagnostics()->Error(
-            DiagMessage() << "invalid density '" << config_str
-                          << "' for --target-densities option. Must be only a "
-                          << "density value.");
-        return 1;
-      }
-
-      options.target_configs.push_back(config);
-    }
-  }
-
-  // TODO(adamlesinski): Read manfiest and set the proper minSdkVersion.
-  // context.SetMinSdkVersion(SDK_O);
-
-  OptimizeCommand cmd(&context, options);
-  return cmd.Run(std::move(apk));
-}
-
-}  // namespace aapt
diff --git a/tools/aapt2/readme.md b/tools/aapt2/readme.md
index 2e674bd..daf1ebc 100644
--- a/tools/aapt2/readme.md
+++ b/tools/aapt2/readme.md
@@ -1,5 +1,10 @@
 # Android Asset Packaging Tool 2.0 (AAPT2) release notes
 
+## Version 2.13
+### `aapt2 optimize ...`
+- aapt2 optimize can now split a binary APK with the same --split parameters as the link
+  phase.
+
 ## Version 2.12
 ### `aapt2 optimize ...`
 - aapt2 optimize now understands map (complex) values under the type `id`. It ignores their
diff --git a/tools/aapt2/unflatten/BinaryResourceParser.cpp b/tools/aapt2/unflatten/BinaryResourceParser.cpp
index 35bf618..20a4531 100644
--- a/tools/aapt2/unflatten/BinaryResourceParser.cpp
+++ b/tools/aapt2/unflatten/BinaryResourceParser.cpp
@@ -73,15 +73,16 @@
 
 }  // namespace
 
-BinaryResourceParser::BinaryResourceParser(IAaptContext* context,
-                                           ResourceTable* table,
-                                           const Source& source,
-                                           const void* data, size_t len)
+BinaryResourceParser::BinaryResourceParser(IAaptContext* context, ResourceTable* table,
+                                           const Source& source, const void* data, size_t len,
+                                           io::IFileCollection* files)
     : context_(context),
       table_(table),
       source_(source),
       data_(data),
-      data_len_(len) {}
+      data_len_(len),
+      files_(files) {
+}
 
 bool BinaryResourceParser::Parse() {
   ResChunkPullParser parser(data_, data_len_);
@@ -359,16 +360,14 @@
 
     std::unique_ptr<Value> resource_value;
     if (entry->flags & ResTable_entry::FLAG_COMPLEX) {
-      const ResTable_map_entry* mapEntry =
-          static_cast<const ResTable_map_entry*>(entry);
+      const ResTable_map_entry* mapEntry = static_cast<const ResTable_map_entry*>(entry);
 
       // TODO(adamlesinski): Check that the entry count is valid.
       resource_value = ParseMapEntry(name, config, mapEntry);
     } else {
       const Res_value* value =
-          (const Res_value*)((const uint8_t*)entry +
-                             util::DeviceToHost32(entry->size));
-      resource_value = ParseValue(name, config, value, entry->flags);
+          (const Res_value*)((const uint8_t*)entry + util::DeviceToHost32(entry->size));
+      resource_value = ParseValue(name, config, *value);
     }
 
     if (!resource_value) {
@@ -388,8 +387,7 @@
       Symbol symbol;
       symbol.state = SymbolState::kPublic;
       symbol.source = source_.WithLine(0);
-      if (!table_->SetSymbolStateAllowMangled(name, res_id, symbol,
-                                              context_->GetDiagnostics())) {
+      if (!table_->SetSymbolStateAllowMangled(name, res_id, symbol, context_->GetDiagnostics())) {
         return false;
       }
     }
@@ -419,70 +417,25 @@
   return true;
 }
 
-std::unique_ptr<Item> BinaryResourceParser::ParseValue(
-    const ResourceNameRef& name, const ConfigDescription& config,
-    const Res_value* value, uint16_t flags) {
-  if (name.type == ResourceType::kId) {
-    return util::make_unique<Id>();
-  }
-
-  const uint32_t data = util::DeviceToHost32(value->data);
-
-  if (value->dataType == Res_value::TYPE_STRING) {
-    const std::string str = util::GetString(value_pool_, data);
-
-    const ResStringPool_span* spans = value_pool_.styleAt(data);
-
-    // Check if the string has a valid style associated with it.
-    if (spans != nullptr && spans->name.index != ResStringPool_span::END) {
-      StyleString style_str = {str};
-      while (spans->name.index != ResStringPool_span::END) {
-        style_str.spans.push_back(
-            Span{util::GetString(value_pool_, spans->name.index),
-                 spans->firstChar, spans->lastChar});
-        spans++;
+std::unique_ptr<Item> BinaryResourceParser::ParseValue(const ResourceNameRef& name,
+                                                       const ConfigDescription& config,
+                                                       const android::Res_value& value) {
+  std::unique_ptr<Item> item = ResourceUtils::ParseBinaryResValue(name.type, config, value_pool_,
+                                                                  value, &table_->string_pool);
+  if (files_ != nullptr && item != nullptr) {
+    FileReference* file_ref = ValueCast<FileReference>(item.get());
+    if (file_ref != nullptr) {
+      file_ref->file = files_->FindFile(*file_ref->path);
+      if (file_ref->file == nullptr) {
+        context_->GetDiagnostics()->Error(DiagMessage() << "resource " << name << " for config '"
+                                                        << config << "' is a file reference to '"
+                                                        << *file_ref->path
+                                                        << "' but no such path exists");
+        return {};
       }
-      return util::make_unique<StyledString>(table_->string_pool.MakeRef(
-          style_str,
-          StringPool::Context(StringPool::Context::kStylePriority, config)));
-    } else {
-      if (name.type != ResourceType::kString && util::StartsWith(str, "res/")) {
-        // This must be a FileReference.
-        return util::make_unique<FileReference>(table_->string_pool.MakeRef(
-            str,
-            StringPool::Context(StringPool::Context::kHighPriority, config)));
-      }
-
-      // There are no styles associated with this string, so treat it as
-      // a simple string.
-      return util::make_unique<String>(
-          table_->string_pool.MakeRef(str, StringPool::Context(config)));
     }
   }
-
-  if (value->dataType == Res_value::TYPE_REFERENCE ||
-      value->dataType == Res_value::TYPE_ATTRIBUTE ||
-      value->dataType == Res_value::TYPE_DYNAMIC_REFERENCE ||
-      value->dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE) {
-    Reference::Type type = Reference::Type::kResource;
-    if (value->dataType == Res_value::TYPE_ATTRIBUTE ||
-        value->dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE) {
-      type = Reference::Type::kAttribute;
-    }
-
-    if (data == 0) {
-      // A reference of 0, must be the magic @null reference.
-      Res_value null_type = {};
-      null_type.dataType = Res_value::TYPE_REFERENCE;
-      return util::make_unique<BinaryPrimitive>(null_type);
-    }
-
-    // This is a normal reference.
-    return util::make_unique<Reference>(data, type);
-  }
-
-  // Treat this as a raw binary primitive.
-  return util::make_unique<BinaryPrimitive>(*value);
+  return item;
 }
 
 std::unique_ptr<Value> BinaryResourceParser::ParseMapEntry(
@@ -528,7 +481,7 @@
 
     Style::Entry style_entry;
     style_entry.key = Reference(util::DeviceToHost32(map_entry.name.ident));
-    style_entry.value = ParseValue(name, config, &map_entry.value, 0);
+    style_entry.value = ParseValue(name, config, map_entry.value);
     if (!style_entry.value) {
       return {};
     }
@@ -586,7 +539,7 @@
     const ResTable_map_entry* map) {
   std::unique_ptr<Array> array = util::make_unique<Array>();
   for (const ResTable_map& map_entry : map) {
-    array->items.push_back(ParseValue(name, config, &map_entry.value, 0));
+    array->items.push_back(ParseValue(name, config, map_entry.value));
   }
   return array;
 }
@@ -596,7 +549,7 @@
     const ResTable_map_entry* map) {
   std::unique_ptr<Plural> plural = util::make_unique<Plural>();
   for (const ResTable_map& map_entry : map) {
-    std::unique_ptr<Item> item = ParseValue(name, config, &map_entry.value, 0);
+    std::unique_ptr<Item> item = ParseValue(name, config, map_entry.value);
     if (!item) {
       return {};
     }
diff --git a/tools/aapt2/unflatten/BinaryResourceParser.h b/tools/aapt2/unflatten/BinaryResourceParser.h
index e3dd802..c41ada0 100644
--- a/tools/aapt2/unflatten/BinaryResourceParser.h
+++ b/tools/aapt2/unflatten/BinaryResourceParser.h
@@ -45,8 +45,8 @@
    * Creates a parser, which will read `len` bytes from `data`, and
    * add any resources parsed to `table`. `source` is for logging purposes.
    */
-  BinaryResourceParser(IAaptContext* context, ResourceTable* table,
-                       const Source& source, const void* data, size_t data_len);
+  BinaryResourceParser(IAaptContext* context, ResourceTable* table, const Source& source,
+                       const void* data, size_t data_len, io::IFileCollection* files = nullptr);
 
   /*
    * Parses the binary resource table and returns true if successful.
@@ -63,10 +63,8 @@
                  const android::ResChunk_header* chunk);
   bool ParseLibrary(const android::ResChunk_header* chunk);
 
-  std::unique_ptr<Item> ParseValue(const ResourceNameRef& name,
-                                   const ConfigDescription& config,
-                                   const android::Res_value* value,
-                                   uint16_t flags);
+  std::unique_ptr<Item> ParseValue(const ResourceNameRef& name, const ConfigDescription& config,
+                                   const android::Res_value& value);
 
   std::unique_ptr<Value> ParseMapEntry(const ResourceNameRef& name,
                                        const ConfigDescription& config,
@@ -104,6 +102,9 @@
   const void* data_;
   const size_t data_len_;
 
+  // Optional file collection from which to create io::IFile objects.
+  io::IFileCollection* files_;
+
   // The standard value string pool for resource values.
   android::ResStringPool value_pool_;
 
diff --git a/tools/aapt2/util/Util.h b/tools/aapt2/util/Util.h
index 7210d21..30b9af6 100644
--- a/tools/aapt2/util/Util.h
+++ b/tools/aapt2/util/Util.h
@@ -99,8 +99,7 @@
                                               const android::StringPiece& class_name);
 
 /**
- * Makes a std::unique_ptr<> with the template parameter inferred by the
- * compiler.
+ * Makes a std::unique_ptr<> with the template parameter inferred by the compiler.
  * This will be present in C++14 and can be removed then.
  */
 template <typename T, class... Args>
diff --git a/tools/aapt2/xml/XmlDom.cpp b/tools/aapt2/xml/XmlDom.cpp
index d9ea1bc..4a278f63 100644
--- a/tools/aapt2/xml/XmlDom.cpp
+++ b/tools/aapt2/xml/XmlDom.cpp
@@ -25,6 +25,7 @@
 
 #include "android-base/logging.h"
 
+#include "ResourceUtils.h"
 #include "XmlPullParser.h"
 #include "util/Util.h"
 
@@ -193,16 +194,14 @@
   stack->pending_comment += comment;
 }
 
-std::unique_ptr<XmlResource> Inflate(std::istream* in, IDiagnostics* diag,
-                                     const Source& source) {
+std::unique_ptr<XmlResource> Inflate(std::istream* in, IDiagnostics* diag, const Source& source) {
   Stack stack;
 
   XML_Parser parser = XML_ParserCreateNS(nullptr, kXmlNamespaceSep);
   XML_SetUserData(parser, &stack);
   XML_UseParserAsHandlerArg(parser);
   XML_SetElementHandler(parser, StartElementHandler, EndElementHandler);
-  XML_SetNamespaceDeclHandler(parser, StartNamespaceHandler,
-                              EndNamespaceHandler);
+  XML_SetNamespaceDeclHandler(parser, StartNamespaceHandler, EndNamespaceHandler);
   XML_SetCharacterDataHandler(parser, CharacterDataHandler);
   XML_SetCommentHandler(parser, CommentDataHandler);
 
@@ -215,8 +214,7 @@
       break;
     }
 
-    if (XML_Parse(parser, buffer, in->gcount(), in->eof()) ==
-        XML_STATUS_ERROR) {
+    if (XML_Parse(parser, buffer, in->gcount(), in->eof()) == XML_STATUS_ERROR) {
       stack.root = {};
       diag->Error(DiagMessage(source.WithLine(XML_GetCurrentLineNumber(parser)))
                   << XML_ErrorString(XML_GetErrorCode(parser)));
@@ -226,13 +224,12 @@
 
   XML_ParserFree(parser);
   if (stack.root) {
-    return util::make_unique<XmlResource>(ResourceFile{{}, {}, source},
-                                          std::move(stack.root));
+    return util::make_unique<XmlResource>(ResourceFile{{}, {}, source}, std::move(stack.root));
   }
   return {};
 }
 
-static void CopyAttributes(Element* el, android::ResXMLParser* parser) {
+static void CopyAttributes(Element* el, android::ResXMLParser* parser, StringPool* out_pool) {
   const size_t attr_count = parser->getAttributeCount();
   if (attr_count > 0) {
     el->attributes.reserve(attr_count);
@@ -253,18 +250,26 @@
       if (str16) {
         attr.value = util::Utf16ToUtf8(StringPiece16(str16, len));
       }
+
+      android::Res_value res_value;
+      if (parser->getAttributeValue(i, &res_value) > 0) {
+        attr.compiled_value = ResourceUtils::ParseBinaryResValue(
+            ResourceType::kAnim, {}, parser->getStrings(), res_value, out_pool);
+      }
+
       el->attributes.push_back(std::move(attr));
     }
   }
 }
 
-std::unique_ptr<XmlResource> Inflate(const void* data, size_t data_len,
-                                     IDiagnostics* diag, const Source& source) {
+std::unique_ptr<XmlResource> Inflate(const void* data, size_t data_len, IDiagnostics* diag,
+                                     const Source& source) {
   // We import the android namespace because on Windows NO_ERROR is a macro, not
   // an enum, which
   // causes errors when qualifying it with android::
   using namespace android;
 
+  StringPool string_pool;
   std::unique_ptr<Node> root;
   std::stack<Node*> node_stack;
 
@@ -307,7 +312,7 @@
           node->name = util::Utf16ToUtf8(StringPiece16(str16, len));
         }
 
-        CopyAttributes(node.get(), &tree);
+        CopyAttributes(node.get(), &tree, &string_pool);
 
         new_node = std::move(node);
         break;
@@ -352,7 +357,7 @@
       }
     }
   }
-  return util::make_unique<XmlResource>(ResourceFile{}, std::move(root));
+  return util::make_unique<XmlResource>(ResourceFile{}, std::move(root), std::move(string_pool));
 }
 
 std::unique_ptr<Node> Namespace::Clone() {
diff --git a/tools/aapt2/xml/XmlDom.h b/tools/aapt2/xml/XmlDom.h
index 90cdfb6..f1d0953 100644
--- a/tools/aapt2/xml/XmlDom.h
+++ b/tools/aapt2/xml/XmlDom.h
@@ -129,21 +129,21 @@
  public:
   ResourceFile file;
   std::unique_ptr<xml::Node> root;
+  StringPool string_pool;
 };
 
 /**
  * Inflates an XML DOM from a text stream, logging errors to the logger.
  * Returns the root node on success, or nullptr on failure.
  */
-std::unique_ptr<XmlResource> Inflate(std::istream* in, IDiagnostics* diag,
-                                     const Source& source);
+std::unique_ptr<XmlResource> Inflate(std::istream* in, IDiagnostics* diag, const Source& source);
 
 /**
  * Inflates an XML DOM from a binary ResXMLTree, logging errors to the logger.
  * Returns the root node on success, or nullptr on failure.
  */
-std::unique_ptr<XmlResource> Inflate(const void* data, size_t data_len,
-                                     IDiagnostics* diag, const Source& source);
+std::unique_ptr<XmlResource> Inflate(const void* data, size_t data_len, IDiagnostics* diag,
+                                     const Source& source);
 
 Element* FindRootElement(XmlResource* doc);
 Element* FindRootElement(Node* node);